@trustware/sdk-staging 1.1.4-staging.35 → 1.1.4-staging.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config/defaults.ts","../src/types/config.ts","../src/constants.ts","../src/config/merge.ts","../src/config/store.ts","../src/config/index.ts","../src/core/http.ts","../src/utils/chains.ts","../src/registry.ts","../src/core.ts","../src/core/index.ts","../src/wallets/eipWallets.ts","../src/wallets/solana.ts","../src/core/sdkRpc.ts","../src/wallets/adapters.ts","../src/wallets/connect.ts","../src/validation/address.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/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","../src/identity/index.ts","../src/wallets/manager.ts","../src/core/routes.ts","../src/core/balances.ts","../src/core/tx.ts","../src/core/useChains.ts","../src/core/registryClient.ts","../src/widget/helpers/chainHelpers.ts","../src/core/useTokens.ts","../src/widget/data/chainPopularity.json","../src/widget/helpers/chainPopularity.ts","../src/widget/helpers/tokenPopularity.ts","../src/errors/TrustwareError.ts"],"sourcesContent":["import { TrustwareWidgetTheme, TrustwareWidgetMessages } from \"../types/\";\n\nexport const DEFAULT_SLIPPAGE = 1;\nexport const DEFAULT_AUTO_DETECT_PROVIDER = false;\n\nexport const DEFAULT_THEME: TrustwareWidgetTheme = {\n primaryColor: \"#4F46E5\",\n secondaryColor: \"#6366F1\",\n backgroundColor: \"#FFFFFF\",\n textColor: \"#111827\",\n borderColor: \"#E5E7EB\",\n radius: 8,\n};\n\nexport const DEFAULT_MESSAGES: TrustwareWidgetMessages = {\n title: \"Trustware SDK\",\n description: \"Seamlessly bridge assets across chains with Trustware.\",\n};\n","import { TrustwareError } from \"src/errors/TrustwareError\";\nimport { TrustwareWidgetTheme, TrustwareWidgetMessages } from \"./theme\";\nimport { TrustwareEvent } from \"src/events/events\";\nimport { Transaction } from \"./routes\";\n\n/** WalletConnect configuration options (all optional - SDK has built-in defaults) */\nexport type WalletConnectConfig = {\n /** Override the built-in WalletConnect project ID (optional - SDK includes one) */\n projectId?: string;\n /** Chain IDs to support (defaults to [1] for Ethereum mainnet) */\n chains?: number[];\n /** Optional chain IDs (chains that can be switched to) */\n optionalChains?: number[];\n /** dApp metadata shown in wallet */\n metadata?: {\n name: string;\n description?: string;\n url: string;\n icons?: string[];\n };\n /** Custom relay URL (defaults to WalletConnect's relay) */\n relayUrl?: string;\n /** Whether to show our custom QR modal (default: true) */\n showQrModal?: boolean;\n /** Disable WalletConnect entirely (default: false) */\n disabled?: boolean;\n};\n\n/** Resolved WalletConnect config with defaults applied */\nexport type ResolvedWalletConnectConfig = {\n projectId: string;\n chains: number[];\n optionalChains: number[];\n metadata: {\n name: string;\n description: string;\n url: string;\n icons: string[];\n };\n relayUrl?: string;\n showQrModal: boolean;\n};\n\nexport type TrustwareConfigOptions = {\n apiKey: string; // Required API key for authentication\n routes: {\n toChain: string; // Default destination chain\n toToken: string; // Default destination token\n fromToken?: string; // Default source token (optional)\n fromAddress?: string; // Default source address (optional)\n toAddress?: string; // Default destination address (optional; can be updated later via Trustware.setDestinationAddress)\n defaultSlippage?: number; // Default slippage percentage (optional) defautts to 1\n routeType?: string; // Route type: \"swap\" | \"deposit\" | \"withdraw\" | \"cross\" (default: \"swap\")\n options?: {\n routeRefreshMs?: number; // Route refresh interval in milliseconds (optional)\n fixedFromAmount?: string | number;\n minAmountOut?: string | number;\n maxAmountOut?: string | number;\n };\n };\n autoDetectProvider?: boolean; // Whether to auto-detect wallet provider (optional, default: false.)\n theme?: TrustwareWidgetTheme; // Optional theme customization\n messages?: Partial<TrustwareWidgetMessages>; // Optional message customization\n retry?: RetryConfig; // Optional retry configuration for rate-limited requests\n walletConnect?: WalletConnectConfig; // Optional WalletConnect configuration\n features?: FeatureFlags; // Optional feature rollout controls\n\n onError?: (error: TrustwareError) => void;\n onSuccess?: (transaction: Transaction) => void;\n onEvent?: (event: TrustwareEvent) => void;\n};\n\nexport type ResolvedTrustwareConfig = {\n apiKey: string;\n routes: {\n toChain: string;\n toToken: string;\n fromToken?: string;\n fromAddress?: string;\n toAddress?: string;\n defaultSlippage: number; // resolved\n routeType: string; // resolved\n options: {\n routeRefreshMs?: number;\n fixedFromAmount?: string | number;\n minAmountOut?: string | number;\n maxAmountOut?: string | number;\n };\n };\n autoDetectProvider: boolean;\n theme: TrustwareWidgetTheme;\n messages: TrustwareWidgetMessages;\n retry: ResolvedRetryConfig;\n walletConnect?: ResolvedWalletConnectConfig; // Optional WalletConnect config\n features: ResolvedFeatureFlags;\n onError?: (error: TrustwareError) => void;\n onSuccess?: (transaction: Transaction) => void;\n onEvent?: (event: TrustwareEvent) => void;\n};\n\nexport type FeatureFlags = {\n tokensPagination?: boolean;\n balanceStreaming?: boolean;\n shouldAllowGA4?: boolean;\n};\n\nexport type ResolvedFeatureFlags = {\n tokensPagination: boolean;\n balanceStreaming: boolean;\n shouldAllowGA4: boolean;\n};\n\nexport const DEFAULT_SLIPPAGE = 1; // Default slippage percentage\nexport const DEFAULT_AUTO_DETECT_PROVIDER = false; // Default auto-detect provider setting\n\n// Rate limit types for SDK rate limit handling\nexport type RateLimitInfo = {\n /** Maximum requests allowed in the current window */\n limit: number;\n /** Requests remaining in the current window */\n remaining: number;\n /** Unix timestamp when the rate limit window resets */\n reset: number;\n /** Seconds until rate limit resets (only present on 429 responses) */\n retryAfter?: number;\n};\n\nexport type RetryConfig = {\n /** Enable automatic retry on 429 responses (default: true). Note: This does NOT disable backend rate limits, only client-side retry behavior. */\n autoRetry?: boolean;\n /** Maximum number of retries on 429 (default: 3) */\n maxRetries?: number;\n /** Base delay in ms for exponential backoff (default: 1000) */\n baseDelayMs?: number;\n /** Callback when rate limit info is received from server */\n onRateLimitInfo?: (info: RateLimitInfo) => void;\n /** Callback when rate limit is hit (429 received) */\n onRateLimited?: (info: RateLimitInfo, retryCount: number) => void;\n /** Callback when remaining requests fall below threshold */\n onRateLimitApproaching?: (info: RateLimitInfo, threshold: number) => void;\n /** Threshold for onRateLimitApproaching callback (default: 5) */\n approachingThreshold?: number;\n};\n\nexport type ResolvedRetryConfig = {\n autoRetry: boolean;\n maxRetries: number;\n baseDelayMs: number;\n approachingThreshold: number;\n onRateLimitInfo?: (info: RateLimitInfo) => void;\n onRateLimited?: (info: RateLimitInfo, retryCount: number) => void;\n onRateLimitApproaching?: (info: RateLimitInfo, threshold: number) => void;\n};\n\nexport const DEFAULT_RETRY_CONFIG: ResolvedRetryConfig = {\n autoRetry: true,\n maxRetries: 3,\n baseDelayMs: 1000,\n approachingThreshold: 5,\n};\n\nexport const DEFAULT_FEATURE_FLAGS: ResolvedFeatureFlags = {\n tokensPagination: false,\n balanceStreaming: false,\n shouldAllowGA4: true,\n};\n","// constants.ts\ndeclare const __SDK_VERSION__: string;\ndeclare const __API_ROOT__: string;\ndeclare const __GTM_ID__: string;\n\nexport const SDK_NAME = \"@trustware/sdk\";\nexport const SDK_VERSION: string = __SDK_VERSION__;\nexport const API_ROOT: string = __API_ROOT__;\nexport const GTM_ID: string = __GTM_ID__;\nexport const API_PREFIX = \"/api\";\n\n// Assets base URL for wallet logos and other static assets\nexport const ASSETS_BASE_URL = \"https://app.trustware.io\";\n\n// WalletConnect Cloud project ID - built into the SDK for seamless wallet connections\n// This is a public identifier (not a secret) registered with WalletConnect Cloud\nexport const WALLETCONNECT_PROJECT_ID = \"4ead125c-63be-4b1a-a835-cef2dce67b84\";\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n TrustwareConfigOptions,\n ResolvedTrustwareConfig,\n ResolvedWalletConnectConfig,\n WalletConnectConfig,\n} from \"../types/\";\nimport {\n DEFAULT_AUTO_DETECT_PROVIDER,\n DEFAULT_SLIPPAGE,\n DEFAULT_THEME,\n DEFAULT_MESSAGES,\n} from \"./defaults\";\nimport { DEFAULT_FEATURE_FLAGS, DEFAULT_RETRY_CONFIG } from \"../types/config\";\nimport { WALLETCONNECT_PROJECT_ID } from \"../constants\";\n\n/**\n * Resolve WalletConnect config with built-in defaults.\n * WalletConnect is ENABLED by default - no user configuration required.\n */\nfunction resolveWalletConnectConfig(\n input?: WalletConnectConfig\n): ResolvedWalletConnectConfig | undefined {\n // Allow users to explicitly disable WalletConnect\n if (input?.disabled) return undefined;\n\n // Use built-in project ID by default, allow override\n const projectId = input?.projectId ?? WALLETCONNECT_PROJECT_ID;\n\n return {\n projectId,\n chains: input?.chains ?? [1], // Default to Ethereum mainnet\n optionalChains: input?.optionalChains ?? [\n 1, 10, 56, 137, 8453, 42161, 43114,\n ], // ETH, OP, BSC, Polygon, Base, Arbitrum, Avalanche\n metadata: {\n name: input?.metadata?.name ?? \"Trustware\",\n description:\n input?.metadata?.description ?? \"Cross-chain bridge & top-up\",\n url: input?.metadata?.url ?? \"https://trustware.io\",\n icons: input?.metadata?.icons ?? [\"https://app.trustware.io/icon.png\"],\n },\n relayUrl: input?.relayUrl,\n showQrModal: input?.showQrModal ?? true,\n };\n}\n\n// tiny deep merge for plain objects\nfunction deepMerge<T extends Record<string, any>>(\n base: T,\n patch?: Partial<T>\n): T {\n if (!patch) return { ...base };\n const out: any = Array.isArray(base) ? [...(base as any)] : { ...base };\n for (const [k, v] of Object.entries(patch)) {\n if (v && typeof v === \"object\" && !Array.isArray(v)) {\n (out as any)[k] = deepMerge((base as any)[k] ?? {}, v as any);\n } else {\n (out as any)[k] = v;\n }\n }\n return out;\n}\n\nfunction normalizeSlippage(v: unknown): number {\n const n = Number(v);\n if (!Number.isFinite(n)) return DEFAULT_SLIPPAGE;\n // clamp sane range 0.01%..5% (0.0001..0.05)\n if (n <= 0) return DEFAULT_SLIPPAGE;\n if (n > 5) return 5;\n return n;\n}\n\nexport function resolveConfig(\n input: TrustwareConfigOptions\n): ResolvedTrustwareConfig {\n if (!input?.apiKey) {\n throw new Error(\"TrustwareConfig: 'apiKey' is required.\");\n }\n if (!input.routes?.toChain || !input.routes?.toToken) {\n throw new Error(\n \"TrustwareConfig: 'routes.toChain' and 'routes.toToken' are required.\"\n );\n }\n\n const autoDetectProvider =\n typeof input.autoDetectProvider === \"boolean\"\n ? input.autoDetectProvider\n : DEFAULT_AUTO_DETECT_PROVIDER;\n\n const routes = {\n toChain: input.routes.toChain,\n toToken: input.routes.toToken,\n fromToken: input.routes.fromToken,\n fromAddress: input.routes.fromAddress,\n toAddress: input.routes.toAddress,\n defaultSlippage: normalizeSlippage(\n input.routes.defaultSlippage ?? DEFAULT_SLIPPAGE\n ),\n routeType: input.routes.routeType ?? \"swap\",\n options: {\n ...input.routes.options,\n },\n };\n\n const theme = deepMerge(DEFAULT_THEME, input.theme);\n const messages = deepMerge(DEFAULT_MESSAGES, input.messages);\n\n // Merge retry config with defaults\n const retry = {\n autoRetry: input.retry?.autoRetry ?? DEFAULT_RETRY_CONFIG.autoRetry,\n maxRetries: input.retry?.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries,\n baseDelayMs: input.retry?.baseDelayMs ?? DEFAULT_RETRY_CONFIG.baseDelayMs,\n approachingThreshold:\n input.retry?.approachingThreshold ??\n DEFAULT_RETRY_CONFIG.approachingThreshold,\n onRateLimitInfo: input.retry?.onRateLimitInfo,\n onRateLimited: input.retry?.onRateLimited,\n onRateLimitApproaching: input.retry?.onRateLimitApproaching,\n };\n\n // Resolve WalletConnect config (optional)\n const walletConnect = resolveWalletConnectConfig(input.walletConnect);\n const features = {\n tokensPagination:\n input.features?.tokensPagination ??\n DEFAULT_FEATURE_FLAGS.tokensPagination,\n balanceStreaming:\n input.features?.balanceStreaming ??\n DEFAULT_FEATURE_FLAGS.balanceStreaming,\n shouldAllowGA4:\n input.features?.shouldAllowGA4 ?? DEFAULT_FEATURE_FLAGS.shouldAllowGA4,\n };\n\n return {\n apiKey: input.apiKey,\n routes,\n autoDetectProvider,\n theme,\n messages,\n retry,\n walletConnect,\n features,\n onError: input.onError,\n onSuccess: input.onSuccess,\n onEvent: input.onEvent,\n };\n}\n","import type {\n ResolvedTrustwareConfig,\n TrustwareConfigOptions,\n} from \"../types/\";\nimport { resolveConfig } from \"./merge\";\n\ntype Listener = (cfg: ResolvedTrustwareConfig) => void;\n\nclass ConfigStore {\n private _cfg: ResolvedTrustwareConfig | null = null;\n private _listeners = new Set<Listener>();\n\n isInitialized(): boolean {\n return this._cfg != null;\n }\n\n peek(): ResolvedTrustwareConfig | null {\n return this._cfg;\n }\n\n /** Initialize or replace the config */\n init(opts: TrustwareConfigOptions) {\n this._cfg = resolveConfig(opts);\n this.emit();\n }\n\n /** Partially update by re-resolving from last + patch */\n update(patch: Partial<TrustwareConfigOptions>) {\n if (!this._cfg) throw new Error(\"TrustwareConfig: call init() first.\");\n const next = resolveConfig({\n ...this._cfg,\n ...patch,\n routes: { ...this._cfg.routes, ...(patch.routes ?? {}) },\n theme: {\n ...this._cfg.theme,\n ...(patch.theme ?? {}),\n } as ResolvedTrustwareConfig[\"theme\"],\n messages: {\n ...this._cfg.messages,\n ...(patch.messages ?? {}),\n } as ResolvedTrustwareConfig[\"messages\"],\n retry: { ...this._cfg.retry, ...(patch.retry ?? {}) },\n features: { ...this._cfg.features, ...(patch.features ?? {}) },\n walletConnect: patch.walletConnect\n ? { ...this._cfg.walletConnect, ...patch.walletConnect }\n : this._cfg.walletConnect,\n } as TrustwareConfigOptions);\n this._cfg = next;\n this.emit();\n }\n\n get(): ResolvedTrustwareConfig {\n if (!this._cfg) throw new Error(\"TrustwareConfig: not initialized.\");\n return this._cfg;\n }\n\n getTheme() {\n return this.get().theme;\n }\n\n getMessages() {\n return this.get().messages;\n }\n\n subscribe(fn: (cfg: ResolvedTrustwareConfig) => void) {\n this._listeners.add(fn);\n if (this._cfg) fn(this._cfg);\n return () => {\n this._listeners.delete(fn);\n };\n }\n\n private emit() {\n if (!this._cfg) return;\n for (const fn of this._listeners) fn(this._cfg);\n }\n}\nexport const TrustwareConfigStore = new ConfigStore();\n\n/** Convenience for non-React environments */\nexport const TrustwareConfig = {\n init: (opts: TrustwareConfigOptions) => TrustwareConfigStore.init(opts),\n update: (patch: Partial<TrustwareConfigOptions>) =>\n TrustwareConfigStore.update(patch),\n get: () => TrustwareConfigStore.get(),\n getTheme: () => TrustwareConfigStore.get().theme,\n getMessages: () => TrustwareConfigStore.get().messages,\n subscribe: (fn: (cfg: ResolvedTrustwareConfig) => void) =>\n TrustwareConfigStore.subscribe(fn),\n};\n","export * from \"./defaults\";\nexport * from \"./merge\";\nexport * from \"./store\";\n// walletconnect.ts is excluded: depends on @reown/appkit-universal-connector (not installed)\n","/* core/http.ts */\nimport { SDK_NAME, SDK_VERSION, API_ROOT, API_PREFIX } from \"../constants\";\nimport { TrustwareConfigStore } from \"../config/\";\nimport type { RateLimitInfo } from \"../types/config\";\n\nexport function apiBase() {\n return `${API_ROOT}${API_PREFIX}`;\n}\n\nexport function jsonHeaders(extra?: Record<string, string>): HeadersInit {\n const cfg = TrustwareConfigStore.get();\n const h: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"X-API-Key\": cfg.apiKey,\n \"X-SDK-Name\": SDK_NAME,\n \"X-SDK-Version\": SDK_VERSION,\n \"X-API-Version\": \"2025-10-01\",\n };\n return { ...h, ...(extra || {}) };\n}\n\nexport async function assertOK(r: Response) {\n if (r.ok) return;\n let msg = r.statusText;\n try {\n const j = await r.json();\n if (j?.error) msg = j.error;\n } catch {\n // response body not JSON, use statusText\n }\n throw new Error(`HTTP ${r.status}: ${msg}`);\n}\n\n///sdk/validate\nexport async function validateSdkAccess() {\n const r = await fetch(`${apiBase()}/sdk/validate`, {\n method: \"GET\",\n headers: jsonHeaders(),\n });\n await assertOK(r);\n const j = await r.json();\n return j.data;\n}\n\n/** Parse rate limit headers from a response */\nexport function parseRateLimitHeaders(r: Response): RateLimitInfo | null {\n const limit = r.headers.get(\"X-RateLimit-Limit\");\n const remaining = r.headers.get(\"X-RateLimit-Remaining\");\n const reset = r.headers.get(\"X-RateLimit-Reset\");\n\n if (!limit || !remaining || !reset) {\n return null;\n }\n\n const info: RateLimitInfo = {\n limit: parseInt(limit, 10),\n remaining: parseInt(remaining, 10),\n reset: parseInt(reset, 10),\n };\n\n // Add retryAfter if present (only on 429 responses)\n const retryAfter = r.headers.get(\"Retry-After\");\n if (retryAfter) {\n info.retryAfter = parseInt(retryAfter, 10);\n }\n\n return info;\n}\n\n/** Notify rate limit callbacks based on response */\nfunction notifyRateLimitCallbacks(\n info: RateLimitInfo,\n isRateLimited: boolean,\n retryCount: number\n) {\n const cfg = TrustwareConfigStore.get();\n const { retry } = cfg;\n\n // Always notify onRateLimitInfo if configured\n if (retry.onRateLimitInfo) {\n retry.onRateLimitInfo(info);\n }\n\n // Notify when rate limited\n if (isRateLimited && retry.onRateLimited) {\n retry.onRateLimited(info, retryCount);\n }\n\n // Notify when approaching limit\n if (\n !isRateLimited &&\n retry.onRateLimitApproaching &&\n info.remaining <= retry.approachingThreshold\n ) {\n retry.onRateLimitApproaching(info, retry.approachingThreshold);\n }\n}\n\n/** Calculate delay for exponential backoff */\nfunction calculateBackoffDelay(\n baseDelayMs: number,\n retryCount: number,\n retryAfter?: number\n): number {\n // If server specified retry-after, use that (in seconds, convert to ms)\n if (retryAfter && retryAfter > 0) {\n return retryAfter * 1000;\n }\n // Otherwise use exponential backoff: base * 2^retryCount\n return baseDelayMs * Math.pow(2, retryCount);\n}\n\n/** Sleep for specified milliseconds */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport class RateLimitError extends Error {\n public readonly rateLimitInfo: RateLimitInfo;\n public readonly retriesExhausted: boolean;\n\n constructor(info: RateLimitInfo, retriesExhausted: boolean) {\n const message = retriesExhausted\n ? `Rate limit exceeded after max retries. Try again in ${info.retryAfter ?? Math.ceil((info.reset * 1000 - Date.now()) / 1000)} seconds.`\n : `Rate limit exceeded. Try again in ${info.retryAfter} seconds.`;\n super(message);\n this.name = \"RateLimitError\";\n this.rateLimitInfo = info;\n this.retriesExhausted = retriesExhausted;\n }\n}\n\ntype FetchOptions = RequestInit & {\n /** Skip rate limit handling for this request */\n skipRateLimit?: boolean;\n};\n\n/**\n * Rate-limit-aware fetch wrapper.\n * Automatically handles 429 responses with exponential backoff retry.\n * Notifies callbacks on rate limit events.\n */\nexport async function rateLimitedFetch(\n url: string,\n options: FetchOptions = {}\n): Promise<Response> {\n const { skipRateLimit, ...fetchOptions } = options;\n\n // If auto-retry is disabled or skipped, just do a normal fetch\n const cfg = TrustwareConfigStore.get();\n if (!cfg.retry.autoRetry || skipRateLimit) {\n return fetch(url, fetchOptions);\n }\n\n const { maxRetries, baseDelayMs } = cfg.retry;\n let retryCount = 0;\n\n while (true) {\n const response = await fetch(url, fetchOptions);\n\n // Parse rate limit headers\n const rateLimitInfo = parseRateLimitHeaders(response);\n\n if (response.status === 429) {\n // Rate limited\n if (rateLimitInfo) {\n notifyRateLimitCallbacks(rateLimitInfo, true, retryCount);\n }\n\n // Check if we should retry\n if (retryCount >= maxRetries) {\n // Max retries exhausted\n throw new RateLimitError(\n rateLimitInfo || { limit: 0, remaining: 0, reset: 0 },\n true\n );\n }\n\n // Calculate delay and retry\n const delay = calculateBackoffDelay(\n baseDelayMs,\n retryCount,\n rateLimitInfo?.retryAfter\n );\n await sleep(delay);\n retryCount++;\n continue;\n }\n\n // Not rate limited - notify callbacks if we have info\n if (rateLimitInfo) {\n notifyRateLimitCallbacks(rateLimitInfo, false, 0);\n }\n\n return response;\n }\n}\n","import type { ChainDef, ChainType } from \"../types\";\n\nexport const NATIVE_EVM = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\";\nexport const NATIVE_SOLANA = \"So11111111111111111111111111111111111111111\";\n\nconst CHAIN_TYPE_ALIASES: Record<string, ChainType> = {\n btc: \"bitcoin\",\n bitcoin: \"bitcoin\",\n sei: \"cosmos\",\n \"pacific-1\": \"cosmos\",\n};\n\nfunction inferChainTypeFromValue(normalized: string): ChainType | undefined {\n if (!normalized) return undefined;\n\n const aliased = CHAIN_TYPE_ALIASES[normalized];\n if (aliased) return aliased;\n\n if (\n normalized === \"evm\" ||\n normalized === \"solana\" ||\n normalized === \"cosmos\" ||\n normalized === \"bitcoin\"\n ) {\n return normalized;\n }\n\n if (/^eip155:\\d+$/.test(normalized) || /^\\d+$/.test(normalized)) {\n return \"evm\";\n }\n\n if (normalized.startsWith(\"solana:\") || normalized.includes(\"solana\")) {\n return \"solana\";\n }\n\n if (\n normalized.startsWith(\"cosmos:\") ||\n normalized.startsWith(\"sei:\") ||\n normalized === \"sei-evm\"\n ) {\n return \"cosmos\";\n }\n\n return undefined;\n}\n\nexport function normalizeChainKey(\n value: string | number | null | undefined\n): string {\n if (value === undefined || value === null) return \"\";\n return String(value).trim().toLowerCase();\n}\n\nexport function normalizeChainType(\n chain?: ChainDef | ChainType | string | null\n): ChainType | undefined {\n if (!chain) return undefined;\n const raw =\n typeof chain === \"string\"\n ? chain\n : (chain.type ??\n chain.chainType ??\n chain.networkIdentifier ??\n chain.chainId ??\n chain.id ??\n chain.networkName ??\n chain.axelarChainName);\n if (!raw) return undefined;\n const normalized = String(raw).trim().toLowerCase();\n return inferChainTypeFromValue(normalized) ?? normalized;\n}\n\nexport function getNativeTokenAddress(chainType?: ChainType | null) {\n return normalizeChainType(chainType) === \"solana\"\n ? NATIVE_SOLANA\n : NATIVE_EVM;\n}\n\nexport function isSolanaNativeTokenAlias(address?: string | null) {\n if (!address) return false;\n const trimmed = address.trim();\n if (!trimmed) return false;\n return trimmed === NATIVE_SOLANA || trimmed.toLowerCase() === NATIVE_EVM;\n}\n\nexport function normalizeAddress(\n address: string,\n chainType?: ChainType | null\n) {\n const trimmed = address.trim();\n if (normalizeChainType(chainType) === \"solana\") {\n if (isSolanaNativeTokenAlias(trimmed)) {\n return NATIVE_SOLANA;\n }\n return trimmed;\n }\n return trimmed.toLowerCase();\n}\n\nexport function isZeroAddressLike(\n address?: string | null,\n chainType?: ChainType | null\n) {\n if (!address) return true;\n const normalized = normalizeAddress(address, chainType);\n return (\n normalized ===\n normalizeAddress(getNativeTokenAddress(chainType), chainType) ||\n normalized === \"0x0000000000000000000000000000000000000000\"\n );\n}\n","import { TrustwareConfigStore } from \"./config/store\";\nimport type {\n ChainDef,\n TokenDef,\n TokenPageOptions,\n TokenPageResult,\n} from \"./types/\";\nimport {\n getNativeTokenAddress,\n normalizeAddress,\n normalizeChainKey,\n normalizeChainType,\n} from \"./utils/chains\";\n\nexport const NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\n\nconst PAGE_CACHE_TTL_MS = 5 * 60 * 1000;\nconst PAGE_CACHE_LIMIT = 100;\n\ntype CachedTokenPage = TokenPageResult & { storedAt: number };\n\nfunction getChainAliases(chain: ChainDef): string[] {\n const values = [\n chain.chainId,\n chain.id,\n chain.networkIdentifier,\n chain.axelarChainName,\n chain.networkName,\n ];\n return values.map((value) => normalizeChainKey(value)).filter(Boolean);\n}\n\nfunction tokenKey(token: TokenDef): string {\n return `${normalizeChainKey(token.chainId)}:${token.address.toLowerCase()}`;\n}\n\nfunction parseTokenPage(payload: unknown): TokenPageResult {\n if (Array.isArray(payload)) {\n return {\n data: payload as TokenDef[],\n pageInfo: { hasNextPage: false },\n };\n }\n\n const parsed = (payload ?? {}) as {\n data?: TokenDef[];\n results?: TokenDef[];\n tokens?: TokenDef[];\n pageInfo?: { hasNextPage?: boolean; nextCursor?: string };\n pagination?: { hasNextPage?: boolean; nextCursor?: string };\n nextCursor?: string;\n hasNextPage?: boolean;\n };\n\n const data = parsed.data ?? parsed.results ?? parsed.tokens ?? [];\n const info = parsed.pageInfo ?? parsed.pagination;\n return {\n data: Array.isArray(data) ? data : [],\n pageInfo: {\n hasNextPage:\n info?.hasNextPage ?? parsed.hasNextPage ?? Boolean(info?.nextCursor),\n nextCursor: info?.nextCursor ?? parsed.nextCursor,\n },\n };\n}\n\nfunction normalizeToken(token: TokenDef): TokenDef {\n return {\n ...token,\n chainId: token.chainId,\n };\n}\n\nexport class Registry {\n private _chainsById = new Map<string, ChainDef>();\n private _chainAliases = new Map<string, string>();\n private _tokensByChain = new Map<string, TokenDef[]>();\n private _tokensByChainKey = new Map<string, Map<string, TokenDef>>();\n private _pageCache = new Map<string, CachedTokenPage>();\n private _loaded = false;\n private _chainsLoaded = false;\n private _loadingPromise: Promise<void> | null = null;\n private _chainsLoadingPromise: Promise<void> | null = null;\n\n constructor(private baseURL: string) {}\n\n async ensureLoaded() {\n if (this._loaded) return;\n if (this._loadingPromise) {\n await this._loadingPromise;\n return;\n }\n\n this._loadingPromise = this.loadAllTokens();\n try {\n await this._loadingPromise;\n } finally {\n this._loadingPromise = null;\n }\n }\n\n async ensureChainsLoaded() {\n if (this._chainsLoaded) return;\n if (this._chainsLoadingPromise) {\n await this._chainsLoadingPromise;\n return;\n }\n\n this._chainsLoadingPromise = this.loadChains();\n try {\n await this._chainsLoadingPromise;\n } finally {\n this._chainsLoadingPromise = null;\n }\n }\n\n private get config() {\n return TrustwareConfigStore.get();\n }\n\n private emitPageLoaded(\n chainRef: string | number,\n query: string | undefined,\n result: TokenPageResult,\n cursor?: string\n ) {\n this.config.onEvent?.({\n type: \"token_page_loaded\",\n chainRef: String(chainRef),\n query,\n count: result.data.length,\n hasNextPage: result.pageInfo.hasNextPage,\n cursor,\n });\n }\n\n private emitPageError(\n chainRef: string | number,\n query: string | undefined,\n cursor: string | undefined,\n error: unknown\n ) {\n const message = error instanceof Error ? error.message : String(error);\n this.config.onEvent?.({\n type: \"token_page_error\",\n chainRef: String(chainRef),\n query,\n cursor,\n message,\n });\n }\n\n private storeChain(chain: ChainDef) {\n const canonical = chain?.chainId ?? chain?.id;\n if (canonical == null) return;\n const normalized: ChainDef = {\n ...chain,\n id: chain.id ?? canonical,\n chainId: chain.chainId ?? canonical,\n };\n const canonicalKey = normalizeChainKey(canonical);\n this._chainsById.set(canonicalKey, normalized);\n for (const alias of getChainAliases(normalized)) {\n this._chainAliases.set(alias, canonicalKey);\n }\n }\n\n private storeTokenForAlias(chainKey: string, token: TokenDef) {\n const key = tokenKey(token);\n const existingByKey = this._tokensByChainKey.get(chainKey) ?? new Map();\n existingByKey.set(key, token);\n this._tokensByChainKey.set(chainKey, existingByKey);\n this._tokensByChain.set(chainKey, Array.from(existingByKey.values()));\n }\n\n private storeToken(token: TokenDef) {\n const chainRef = token?.chainId;\n if (chainRef == null) return;\n const normalized = normalizeToken(token);\n const resolvedChain = this.chain(chainRef);\n const aliases = resolvedChain\n ? getChainAliases(resolvedChain)\n : [normalizeChainKey(chainRef)];\n for (const alias of aliases) {\n this.storeTokenForAlias(alias, normalized);\n }\n }\n\n private async loadChains() {\n const chainsRes = await fetch(`${this.baseURL}/v1/routes/chains`, {\n headers: { Accept: \"application/json\", \"X-API-Key\": this.config.apiKey },\n });\n if (!chainsRes.ok) throw new Error(`chains: HTTP ${chainsRes.status}`);\n\n const chains = await chainsRes.json();\n const chainsArr: ChainDef[] = Array.isArray(chains)\n ? chains\n : (chains.data ?? []);\n\n for (const chain of chainsArr) {\n this.storeChain(chain);\n }\n\n this._chainsLoaded = true;\n }\n\n private async loadAllTokens() {\n await this.ensureChainsLoaded();\n\n const tokensRes = await fetch(`${this.baseURL}/v1/routes/tokens`, {\n headers: { Accept: \"application/json\", \"X-API-Key\": this.config.apiKey },\n });\n if (!tokensRes.ok) throw new Error(`tokens: HTTP ${tokensRes.status}`);\n\n const tokens = await tokensRes.json();\n const tokensArr: TokenDef[] = Array.isArray(tokens)\n ? tokens\n : (tokens.data ?? []);\n for (const token of tokensArr) {\n this.storeToken(token);\n }\n\n this._loaded = true;\n }\n\n private prunePageCache() {\n const now = Date.now();\n for (const [key, value] of this._pageCache.entries()) {\n if (now - value.storedAt > PAGE_CACHE_TTL_MS) {\n this._pageCache.delete(key);\n }\n }\n\n while (this._pageCache.size > PAGE_CACHE_LIMIT) {\n const oldestKey = this._pageCache.keys().next().value;\n if (!oldestKey) {\n break;\n }\n this._pageCache.delete(oldestKey);\n }\n }\n\n private pageCacheKey(\n chainRef: string | number,\n opts: TokenPageOptions = {}\n ): string {\n const chain = this.chain(chainRef);\n const canonical = normalizeChainKey(chain?.chainId ?? chainRef);\n return `${canonical}::${opts.q ?? \"\"}::${opts.limit ?? \"\"}::${opts.cursor ?? \"\"}`;\n }\n\n private filterTokens(\n tokens: TokenDef[],\n chainRef: string | number,\n query?: string\n ): TokenDef[] {\n const normalizedChain = normalizeChainKey(chainRef);\n const normalizedQuery = query?.trim().toLowerCase();\n return tokens.filter((token) => {\n if (normalizeChainKey(token.chainId) !== normalizedChain) {\n return false;\n }\n if (!normalizedQuery) {\n return true;\n }\n return (\n token.symbol?.toLowerCase().includes(normalizedQuery) ||\n token.name?.toLowerCase().includes(normalizedQuery) ||\n token.address?.toLowerCase().includes(normalizedQuery)\n );\n });\n }\n\n chains(): ChainDef[] {\n return Array.from(this._chainsById.values());\n }\n\n chain(chainRef: string | number): ChainDef | undefined {\n const normalized = normalizeChainKey(chainRef);\n const canonicalKey = this._chainAliases.get(normalized) ?? normalized;\n return this._chainsById.get(canonicalKey);\n }\n\n allTokens(): TokenDef[] {\n const unique = new Map<string, TokenDef>();\n for (const list of this._tokensByChain.values()) {\n for (const token of list) {\n unique.set(tokenKey(token), token);\n }\n }\n return Array.from(unique.values());\n }\n\n tokens(chainRef: string | number): TokenDef[] {\n return this._tokensByChain.get(normalizeChainKey(chainRef)) ?? [];\n }\n\n async tokensPage(\n chainRef: string | number,\n opts: TokenPageOptions = {}\n ): Promise<TokenPageResult> {\n await this.ensureChainsLoaded();\n\n if (!this.config.features.tokensPagination) {\n await this.ensureLoaded();\n const all = this.filterTokens(this.allTokens(), chainRef, opts.q);\n const start = opts.cursor ? Number(opts.cursor) || 0 : 0;\n const limit = opts.limit ?? all.length;\n const data = all.slice(start, start + limit);\n return {\n data,\n pageInfo: {\n hasNextPage: start + limit < all.length,\n nextCursor:\n start + limit < all.length ? String(start + limit) : undefined,\n },\n };\n }\n\n const cacheKey = this.pageCacheKey(chainRef, opts);\n const cached = this._pageCache.get(cacheKey);\n if (cached && Date.now() - cached.storedAt <= PAGE_CACHE_TTL_MS) {\n return { data: cached.data, pageInfo: cached.pageInfo };\n }\n\n const chain = this.chain(chainRef);\n const chainKey = normalizeChainKey(chain?.chainId ?? chainRef);\n const url = new URL(`${this.baseURL}/v1/routes/tokens`);\n url.searchParams.set(\"chainId\", chainKey);\n if (opts.cursor) url.searchParams.set(\"cursor\", opts.cursor);\n if (opts.limit != null) url.searchParams.set(\"limit\", String(opts.limit));\n if (opts.q) url.searchParams.set(\"q\", opts.q);\n\n try {\n const res = await fetch(url.toString(), {\n headers: {\n Accept: \"application/json\",\n \"X-API-Key\": this.config.apiKey,\n },\n });\n\n if (!res.ok) {\n throw new Error(`tokens page: HTTP ${res.status}`);\n }\n\n const parsed = parseTokenPage(await res.json());\n const deduped = new Map<string, TokenDef>();\n for (const token of parsed.data) {\n const normalized = normalizeToken(token);\n this.storeToken(normalized);\n deduped.set(tokenKey(normalized), normalized);\n }\n\n const result = {\n data: Array.from(deduped.values()),\n pageInfo: parsed.pageInfo,\n };\n\n this._pageCache.set(cacheKey, { ...result, storedAt: Date.now() });\n this.prunePageCache();\n this.emitPageLoaded(chainRef, opts.q, result, opts.cursor);\n return result;\n } catch (error) {\n this.emitPageError(chainRef, opts.q, opts.cursor, error);\n await this.ensureLoaded();\n const fallback = this.filterTokens(this.allTokens(), chainRef, opts.q);\n return {\n data: fallback,\n pageInfo: { hasNextPage: false },\n };\n }\n }\n\n async *iterateTokens(\n chainRef: string | number,\n opts: Omit<TokenPageOptions, \"cursor\"> = {}\n ): AsyncGenerator<TokenPageResult, void, void> {\n let cursor: string | undefined;\n do {\n const page = await this.tokensPage(chainRef, { ...opts, cursor });\n yield page;\n cursor = page.pageInfo.nextCursor;\n if (!page.pageInfo.hasNextPage) {\n break;\n }\n } while (cursor);\n }\n\n findToken(chainRef: string | number, address: string): TokenDef | undefined {\n const chain = this.chain(chainRef);\n const chainType = normalizeChainType(chain);\n const normalizedAddress = normalizeAddress(address, chainType);\n return this.tokens(chainRef).find((token) => {\n return normalizeAddress(token.address, chainType) === normalizedAddress;\n });\n }\n\n resolveToken(\n chainRef: string | number,\n input?: string | null\n ): string | undefined {\n if (!input) return undefined;\n const s = String(input).trim();\n const chain = this.chain(chainRef);\n const chainType = normalizeChainType(chain);\n\n if (/^0x[0-9a-fA-F]{40}$/.test(s)) return s;\n if (chainType === \"solana\" && s.length > 20) return s;\n\n const nativeAddress = getNativeTokenAddress(chainType);\n const nativeSymbol = chain?.nativeCurrency?.symbol?.toUpperCase?.();\n if (\n (nativeSymbol && s.toUpperCase() === nativeSymbol) ||\n [\"ETH\", \"MATIC\", \"AVAX\", \"BNB\", \"SOL\", \"NATIVE\"].includes(s.toUpperCase())\n ) {\n return chainType === \"solana\" ? nativeAddress : NATIVE;\n }\n\n const hit = this.tokens(chainRef).find((token) => {\n if (!token.symbol) return false;\n return token.symbol.toUpperCase() === s.toUpperCase();\n });\n if (hit) return hit.address;\n\n return s;\n }\n}\n","export * from \"./core/index\";\n","/* core/index.ts */\nimport type {\n TrustwareConfigOptions,\n ResolvedTrustwareConfig,\n WalletInterFaceAPI,\n} from \"../types\";\nimport { TrustwareConfigStore } from \"../config/store\";\nimport { walletManager } from \"../wallets/manager\";\nimport {\n buildRoute,\n buildDepositAddress,\n submitReceipt,\n getStatus,\n pollStatus,\n} from \"./routes\";\nimport {\n getBalances,\n getBalancesByAddress,\n getBalancesByAddressStream,\n} from \"./balances\";\nimport { sendRouteTransaction, runTopUp } from \"./tx\";\nimport { validateSdkAccess } from \"./http\";\nimport { useChains } from \"./useChains\";\nimport { useTokens } from \"./useTokens\";\nimport { TrustwareError } from \"../errors/TrustwareError\";\nimport { TrustwareErrorCode } from \"../errors/errorCodes\";\nimport {\n validateAddressForChain,\n validateRouteAddresses,\n} from \"../validation/address\";\n\n// simple memo to avoid re-validating same key repeatedly\nlet _lastValidatedKey: string | null = null;\n\nexport const Trustware = {\n /** Initialize config */\n async init(cfg: TrustwareConfigOptions) {\n TrustwareConfigStore.init(cfg);\n const key = TrustwareConfigStore.get().apiKey;\n\n if (_lastValidatedKey !== key) {\n try {\n await validateSdkAccess();\n _lastValidatedKey = key;\n } catch (err: unknown) {\n const reason =\n err instanceof Error && err.message ? `: ${err.message}` : \"\";\n const error = new TrustwareError({\n code: TrustwareErrorCode.INVALID_API_KEY,\n message: `Trustware.init: API key validation failed${reason}`,\n userMessage:\n \"API key validation failed. Please verify your Trustware API key.\",\n cause: err,\n });\n const config = TrustwareConfigStore.get();\n config.onError?.(error);\n config.onEvent?.({ type: \"error\", error });\n throw error;\n }\n }\n return Trustware;\n },\n\n /** Attach a wallet interface directly (skips detection) */\n useWallet(w: WalletInterFaceAPI) {\n walletManager.attachWallet(w);\n return Trustware;\n },\n\n /** Best-effort background attach to detected wallet(s) (detection hook should be running in the app) */\n async autoDetect(_timeoutMs?: number) {\n await walletManager.autoAttach();\n return walletManager.wallet != null;\n },\n\n /** Read resolved config */\n getConfig(): ResolvedTrustwareConfig {\n return TrustwareConfigStore.get();\n },\n\n setDestinationAddress(address?: string | null) {\n const prev = TrustwareConfigStore.get();\n TrustwareConfigStore.update({\n routes: {\n ...prev.routes,\n toAddress: address ?? undefined,\n },\n });\n return Trustware;\n },\n\n setDestinationChain(chain: string) {\n const prev = TrustwareConfigStore.get();\n TrustwareConfigStore.update({\n routes: {\n ...prev.routes,\n toChain: chain,\n },\n });\n return Trustware;\n },\n\n setDestinationToken(token: string) {\n const prev = TrustwareConfigStore.get();\n TrustwareConfigStore.update({\n routes: {\n ...prev.routes,\n toToken: token,\n },\n });\n return Trustware;\n },\n\n /** Read active wallet */\n getWallet(): WalletInterFaceAPI | null {\n return walletManager.wallet;\n },\n\n getIdentity() {\n return walletManager.identity;\n },\n\n resolveAddressForChain(\n chain: Parameters<typeof walletManager.resolveAddressForChain>[0]\n ) {\n return walletManager.resolveAddressForChain(chain);\n },\n\n addIdentityAddress(\n address: Parameters<typeof walletManager.addIdentityAddress>[0]\n ) {\n walletManager.addIdentityAddress(address);\n return Trustware;\n },\n\n /** Simple helpers */\n async getAddress(): Promise<string> {\n const w = walletManager.wallet;\n if (!w) throw new Error(\"Trustware.wallet not configured\");\n return w.getAddress();\n },\n\n // ---- REST methods (re-export) ----\n buildRoute,\n buildDepositAddress,\n submitReceipt,\n getStatus,\n pollStatus,\n getBalances,\n getBalancesByAddress,\n getBalancesByAddressStream,\n useChains,\n useTokens,\n validateAddressForChain,\n validateRouteAddresses,\n\n // ---- Tx helpers ----\n sendRouteTransaction,\n runTopUp,\n};\n\nexport type TrustwareCore = typeof Trustware;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n// src/wallet.ts\nimport type { WalletInterFaceAPI, EIP1193 } from \"../types/\";\n\n/* ---------------- chain params for addChain fallback ---------------- */\nconst CHAIN_PARAMS: Record<\n number,\n {\n chainIdHex: `0x${string}`;\n chainName: string;\n rpcUrls: string[];\n nativeCurrency: { name: string; symbol: string; decimals: number };\n blockExplorerUrls?: string[];\n }\n> = {\n 8453: {\n chainIdHex: \"0x2105\",\n chainName: \"Base\",\n rpcUrls: [\"https://mainnet.base.org\"],\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n blockExplorerUrls: [\"https://basescan.org\"],\n },\n 42161: {\n chainIdHex: \"0xa4b1\",\n chainName: \"Arbitrum One\",\n rpcUrls: [\"https://arb1.arbitrum.io/rpc\"],\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n blockExplorerUrls: [\"https://arbiscan.io\"],\n },\n 43114: {\n chainIdHex: \"0xa86a\",\n chainName: \"Avalanche C-Chain\",\n rpcUrls: [\"https://api.avax.network/ext/bc/C/rpc\"],\n nativeCurrency: { name: \"Avalanche\", symbol: \"AVAX\", decimals: 18 },\n blockExplorerUrls: [\"https://snowtrace.io\"],\n },\n};\n\nasync function addThenSwitch(eth: EIP1193, chainId: number) {\n const p = CHAIN_PARAMS[chainId];\n if (!p) throw new Error(`Unknown chain ${chainId} (no params to add)`);\n await eth.request({ method: \"wallet_addEthereumChain\", params: [p] as any });\n await eth.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: p.chainIdHex }] as any,\n });\n}\n\n/* ---------------- EIP-1193 adapter (safe switching) ---------------- */\nexport function useEIP1193(eth: EIP1193): WalletInterFaceAPI {\n if (!eth?.request) throw new Error(\"useEIP1193: invalid provider\");\n let switching = false;\n\n return {\n ecosystem: \"evm\",\n type: \"eip1193\",\n async getAddress() {\n const [a] = (await eth.request({\n method: \"eth_requestAccounts\",\n })) as string[];\n if (!a) throw new Error(\"No connected address\");\n return a;\n },\n async getChainId() {\n const hex = await eth.request({ method: \"eth_chainId\" });\n return parseInt(String(hex), 16);\n },\n async switchChain(chainId: number) {\n if (switching) return; // prevent 4001: already in progress\n switching = true;\n const hex =\n CHAIN_PARAMS[chainId]?.chainIdHex ?? `0x${chainId.toString(16)}`;\n try {\n await eth.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: hex }],\n });\n } catch (e: any) {\n if (e?.code === 4902) {\n await addThenSwitch(eth, chainId);\n } else if (e?.code === 4001) {\n // user rejected or wallet busy; don’t crash the flow\n } else {\n throw e;\n }\n } finally {\n switching = false;\n }\n },\n request: (args) => eth.request(args),\n };\n}\n\n/* ---------------- Wagmi/Viem client adapter (version-agnostic) ---------------- */\nexport function useWagmi(client: any): WalletInterFaceAPI {\n if (!client) throw new Error(\"useWagmi: missing client\");\n let switching = false;\n\n async function getAddress(): Promise<`0x${string}`> {\n const addr = client.account?.address as `0x${string}` | undefined;\n if (addr) return addr;\n if (typeof client.getAddresses === \"function\") {\n const arr = await client.getAddresses();\n if (arr?.[0]) return arr[0];\n }\n throw new Error(\"No connected address\");\n }\n\n async function getChainId(): Promise<number> {\n const id = client.chain?.id ?? (await client.getChainId?.());\n return typeof id === \"number\" ? id : 0;\n }\n\n async function switchChain(target: number) {\n if (switching) return;\n switching = true;\n try {\n if (typeof client.switchChain === \"function\") {\n try {\n await client.switchChain({ id: target });\n } catch {\n await client.switchChain({ chainId: target });\n }\n return;\n }\n const eth = (globalThis as any).ethereum as EIP1193 | undefined;\n if (!eth?.request) throw new Error(\"switchChain not available\");\n try {\n const hex =\n CHAIN_PARAMS[target]?.chainIdHex ?? `0x${target.toString(16)}`;\n await eth.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: hex }],\n });\n } catch (e: any) {\n if (e?.code === 4902) await addThenSwitch(eth, target);\n else if (e?.code === 4001)\n void 0; // switchChain rejected/in-progress — non-fatal\n else throw e;\n }\n } finally {\n switching = false;\n }\n }\n\n async function sendTransaction(tx: {\n to: `0x${string}`;\n data: `0x${string}`;\n value?: bigint;\n chainId?: number;\n }) {\n if (typeof client.sendTransaction !== \"function\")\n throw new Error(\"sendTransaction not available\");\n const account = await getAddress();\n const chainId = tx.chainId ?? (await getChainId());\n try {\n const res = await client.sendTransaction({\n account,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n chain: { id: chainId },\n });\n return { hash: res.hash as `0x${string}` };\n } catch {\n const res = await client.sendTransaction({\n account,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n chainId,\n });\n return { hash: res.hash as `0x${string}` };\n }\n }\n\n return {\n ecosystem: \"evm\",\n type: \"wagmi\",\n getAddress,\n getChainId,\n switchChain,\n sendTransaction,\n };\n}\n\n/* ---------------- Provider discovery (prefer Rabby) ---------------- */\n\ntype Detected = { id: string; name: string; provider: EIP1193 };\n\nfunction nameOf(p: any): string {\n return (\n p?.providerInfo?.name ||\n p?.info?.name ||\n (p?.isRabby && \"Rabby\") ||\n (p?.isMetaMask && \"MetaMask\") ||\n (p?.isBraveWallet && \"Brave Wallet\") ||\n (p?.isCoinbaseWallet && \"Coinbase Wallet\") ||\n \"Injected Wallet\"\n );\n}\nfunction idOf(p: any): string {\n return nameOf(p).toLowerCase().replace(/\\s+/g, \"-\") || \"injected\";\n}\n\nfunction rank(list: Detected[]): Detected[] {\n const score = (n: string) => {\n const s = n.toLowerCase();\n if (s.includes(\"rabby\")) return 0;\n if (s.includes(\"metamask\")) return 1;\n if (s.includes(\"coinbase\")) return 2;\n if (s.includes(\"okx\")) return 3;\n if (s.includes(\"brave\")) return 99; // de-prioritize Brave\n return 50;\n };\n return [...list].sort((a, b) => score(a.name) - score(b.name));\n}\n\n/** Prefer Rabby automatically; fallback to others (no browser setting needed) */\nexport async function autoDetectWallet(\n timeoutMs = 400\n): Promise<{ kind: \"eip1193\"; wallet: WalletInterFaceAPI } | null> {\n if (typeof window === \"undefined\") return null;\n const w = window as any;\n\n const announced: any[] = [];\n const handler = (e: any) => {\n if (e?.detail?.provider?.request) announced.push(e.detail.provider);\n };\n w.addEventListener?.(\"eip6963:announceProvider\", handler);\n w.dispatchEvent?.(new Event(\"eip6963:requestProvider\"));\n await new Promise((res) => setTimeout(res, timeoutMs));\n w.removeEventListener?.(\"eip6963:announceProvider\", handler);\n\n const candidates: any[] = [];\n if (w.ethereum?.request) {\n const multi = Array.isArray(w.ethereum.providers)\n ? w.ethereum.providers\n : [w.ethereum];\n for (const p of multi) if (p?.request) candidates.push(p);\n }\n for (const p of announced)\n if (p?.request && !candidates.includes(p)) candidates.push(p);\n\n if (candidates.length === 0) return null;\n\n const dedup = new Map<string, Detected>();\n for (const p of candidates) {\n const det = { id: idOf(p), name: nameOf(p), provider: p as EIP1193 };\n dedup.set(det.id, det);\n }\n\n const best = rank(Array.from(dedup.values()))[0];\n return { kind: \"eip1193\", wallet: useEIP1193(best.provider) };\n}\n","import { Transaction, VersionedTransaction } from \"@solana/web3.js\";\nimport { getSolanaTxStatus, sendSolanaSerialized } from \"../core/sdkRpc\";\n\nimport type {\n DetectedWallet,\n SolanaProviderLike,\n SolanaWalletInterface,\n WalletId,\n WalletMeta,\n} from \"../types\";\n\ntype SolanaEventHandlers = {\n onConnect?: () => void;\n onAccountChanged?: () => void;\n onDisconnect?: () => void;\n};\n\nconst SOLANA_WALLET_IDS: WalletId[] = [\n \"phantom-solana\",\n \"solflare\",\n \"backpack\",\n];\n\nfunction getPublicKeyString(provider?: SolanaProviderLike | null) {\n const publicKey = provider?.publicKey;\n if (!publicKey) return null;\n const text = publicKey.toString().trim();\n return text || null;\n}\n\nfunction decodeBase64(serializedTransaction: string) {\n const trimmed = serializedTransaction.trim();\n if (typeof Buffer !== \"undefined\") {\n return Uint8Array.from(Buffer.from(trimmed, \"base64\"));\n }\n const binary = globalThis.atob(trimmed);\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n}\n\nfunction decodeBase64Transaction(serializedTransaction: string) {\n const bytes = decodeBase64(serializedTransaction);\n try {\n return VersionedTransaction.deserialize(bytes);\n } catch {\n return Transaction.from(bytes);\n }\n}\n\nfunction encodeBase64(bytes: Uint8Array) {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(bytes).toString(\"base64\");\n }\n\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return globalThis.btoa(binary);\n}\n\nasync function waitForSolanaConfirmation(chainId: string, signature: string) {\n const started = Date.now();\n const timeoutMs = 120000;\n const intervalMs = 2000;\n\n while (Date.now() - started < timeoutMs) {\n const status = await getSolanaTxStatus({ chainId, signature });\n if (status.status === \"success\") return signature;\n if (status.status === \"failed\") {\n throw new Error(\"Solana transaction failed\");\n }\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n\n throw new Error(\"Timed out waiting for Solana transaction confirmation\");\n}\n\nexport function getSolanaProviders(): Partial<\n Record<WalletId, SolanaProviderLike>\n> {\n if (typeof window === \"undefined\") return {};\n\n const win = window as typeof window & {\n solana?: SolanaProviderLike;\n phantom?: { solana?: SolanaProviderLike };\n solflare?: SolanaProviderLike;\n backpack?: { solana?: SolanaProviderLike };\n };\n\n const providers: Partial<Record<WalletId, SolanaProviderLike>> = {};\n const phantom =\n win.phantom?.solana ?? (win.solana?.isPhantom ? win.solana : undefined);\n const solflare =\n win.solflare ?? (win.solana?.isSolflare ? win.solana : undefined);\n const backpack =\n win.backpack?.solana ?? (win.solana?.isBackpack ? win.solana : undefined);\n\n if (phantom) providers[\"phantom-solana\"] = phantom;\n if (solflare) providers.solflare = solflare;\n if (backpack) providers.backpack = backpack;\n\n return providers;\n}\n\nexport function detectSolanaWallets(wallets: WalletMeta[]): DetectedWallet[] {\n const providers = getSolanaProviders();\n return SOLANA_WALLET_IDS.flatMap((walletId) => {\n const provider = providers[walletId];\n const meta = wallets.find((item) => item.id === walletId);\n if (!provider || !meta) return [];\n return [{ meta, provider, via: \"solana-window\" as const }];\n });\n}\n\nexport function bindSolanaProviderEvents(\n provider: SolanaProviderLike,\n handlers: SolanaEventHandlers\n) {\n const onConnect = () => handlers.onConnect?.();\n const onAccountChanged = () => handlers.onAccountChanged?.();\n const onDisconnect = () => handlers.onDisconnect?.();\n\n provider.on?.(\"connect\", onConnect);\n provider.on?.(\"accountChanged\", onAccountChanged);\n provider.on?.(\"disconnect\", onDisconnect);\n\n return () => {\n provider.off?.(\"connect\", onConnect);\n provider.off?.(\"accountChanged\", onAccountChanged);\n provider.off?.(\"disconnect\", onDisconnect);\n provider.removeListener?.(\"connect\", onConnect);\n provider.removeListener?.(\"accountChanged\", onAccountChanged);\n provider.removeListener?.(\"disconnect\", onDisconnect);\n };\n}\n\nexport function toSolanaWalletInterface(\n provider: SolanaProviderLike\n): SolanaWalletInterface {\n return {\n ecosystem: \"solana\",\n type: \"solana\",\n async getAddress() {\n const current = getPublicKeyString(provider);\n if (current) return current;\n if (!provider.connect) {\n throw new Error(\"Selected Solana wallet cannot connect\");\n }\n await provider.connect();\n const next = getPublicKeyString(provider);\n if (!next) throw new Error(\"No connected Solana address\");\n return next;\n },\n async disconnect() {\n await provider.disconnect?.();\n },\n async getChainKey() {\n return \"solana-mainnet-beta\";\n },\n async sendSerializedTransaction(\n serializedTransactionBase64: string,\n chainId?: string\n ) {\n const transaction = decodeBase64Transaction(serializedTransactionBase64);\n\n if (provider.signAndSendTransaction) {\n const result = await provider.signAndSendTransaction(transaction, {\n preflightCommitment: \"confirmed\",\n });\n\n if (typeof result === \"string\") return result;\n if (result?.signature) return result.signature;\n }\n\n if (!provider.signTransaction) {\n throw new Error(\"Connected Solana wallet cannot sign transactions\");\n }\n\n const signed = await provider.signTransaction(transaction);\n const resolvedChainId = chainId?.trim() || \"solana-mainnet\";\n const serializedSigned = encodeBase64(signed.serialize());\n const { signature } = await sendSolanaSerialized({\n chainId: resolvedChainId,\n serializedTransaction: serializedSigned,\n });\n await waitForSolanaConfirmation(resolvedChainId, signature);\n return signature;\n },\n };\n}\n","import { apiBase, jsonHeaders, rateLimitedFetch } from \"./http\";\n\ntype SDKRPCErrorPayload = {\n code?: string;\n message?: string;\n context?: Record<string, unknown>;\n};\n\ntype SDKRPCEnvelope<T> = {\n success?: boolean;\n data?: T;\n error?: SDKRPCErrorPayload;\n};\n\nexport class SDKRPCError extends Error {\n code?: string;\n context?: Record<string, unknown>;\n status?: number;\n\n constructor(\n message: string,\n options?: {\n code?: string;\n context?: Record<string, unknown>;\n status?: number;\n }\n ) {\n super(message);\n this.name = \"SDKRPCError\";\n this.code = options?.code;\n this.context = options?.context;\n this.status = options?.status;\n }\n}\n\nasync function requestSDKRPC<T>(\n path: string,\n init: RequestInit = {}\n): Promise<T> {\n const response = await rateLimitedFetch(`${apiBase()}/v1/sdk/rpc${path}`, {\n ...init,\n headers: jsonHeaders(),\n });\n\n let payload: SDKRPCEnvelope<T> | null = null;\n try {\n payload = (await response.json()) as SDKRPCEnvelope<T>;\n } catch {\n payload = null;\n }\n\n if (response.ok && payload?.success && payload.data !== undefined) {\n return payload.data;\n }\n\n throw new SDKRPCError(\n payload?.error?.message ||\n `HTTP ${response.status}: ${response.statusText || \"SDK RPC request failed\"}`,\n {\n code: payload?.error?.code,\n context: payload?.error?.context,\n status: response.status,\n }\n );\n}\n\nexport type EVMAllowanceResponse = {\n chainId: string;\n tokenAddress: string;\n ownerAddress: string;\n spenderAddress: string;\n allowance: string;\n rpcHost?: string;\n};\n\nexport type EVMTxStatusResponse = {\n chainId: string;\n txHash: string;\n found: boolean;\n confirmed: boolean;\n status: \"pending\" | \"success\" | \"reverted\" | \"not_found\";\n blockNumber?: string;\n gasUsed?: string;\n effectiveGasPrice?: string;\n confirmations?: string;\n rpcHost?: string;\n};\n\nexport type EVMFeeDataResponse = {\n chainId: string;\n gasPrice?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n supportsEip1559?: boolean;\n rpcHost?: string;\n};\n\nexport type EVMEstimateGasResponse = {\n chainId: string;\n gasLimit: string;\n rpcHost?: string;\n};\n\nexport type SolanaSendSerializedResponse = {\n chainId: string;\n signature: string;\n rpcHost?: string;\n};\n\nexport type SolanaTxStatusResponse = {\n chainId: string;\n signature: string;\n found: boolean;\n confirmed: boolean;\n status: \"pending\" | \"success\" | \"failed\" | \"not_found\";\n slot?: number;\n err?: unknown;\n rpcHost?: string;\n};\n\nexport async function getEVMAllowance(params: {\n chainId: string;\n tokenAddress: string;\n ownerAddress: string;\n spenderAddress: string;\n}) {\n const search = new URLSearchParams(params);\n return requestSDKRPC<EVMAllowanceResponse>(\n `/evm/allowance?${search.toString()}`,\n { method: \"GET\" }\n );\n}\n\nexport async function getEVMTxStatus(params: {\n chainId: string;\n txHash: string;\n}) {\n const search = new URLSearchParams(params);\n return requestSDKRPC<EVMTxStatusResponse>(\n `/evm/tx-status?${search.toString()}`,\n { method: \"GET\" }\n );\n}\n\nexport async function getEVMFeeData(params: { chainId: string }) {\n const search = new URLSearchParams(params);\n return requestSDKRPC<EVMFeeDataResponse>(\n `/evm/fee-data?${search.toString()}`,\n { method: \"GET\" }\n );\n}\n\nexport async function estimateEVMGas(body: {\n chainId: string;\n fromAddress: string;\n to: string;\n data: string;\n value: string;\n}) {\n return requestSDKRPC<EVMEstimateGasResponse>(\"/evm/estimate-gas\", {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n}\n\nexport async function sendSolanaSerialized(body: {\n chainId: string;\n serializedTransaction: string;\n}) {\n return requestSDKRPC<SolanaSendSerializedResponse>(\n \"/solana/send-serialized\",\n {\n method: \"POST\",\n body: JSON.stringify(body),\n }\n );\n}\n\nexport async function getSolanaTxStatus(params: {\n chainId: string;\n signature: string;\n}) {\n const search = new URLSearchParams(params);\n return requestSDKRPC<SolanaTxStatusResponse>(\n `/solana/tx-status?${search.toString()}`,\n { method: \"GET\" }\n );\n}\n","import type { WalletInterFaceAPI, DetectedWallet, EIP1193 } from \"../types/\";\nimport { useEIP1193, useWagmi } from \"./eipWallets\";\nimport { toSolanaWalletInterface } from \"./solana\";\n\nexport { useEIP1193, useWagmi };\n\nexport function toWalletInterfaceFromDetected(\n dw: DetectedWallet\n): WalletInterFaceAPI {\n if (!dw?.provider) throw new Error(\"No provider on detected wallet\");\n if (dw.via === \"solana-window\" || dw.meta.ecosystem === \"solana\") {\n return toSolanaWalletInterface(dw.provider);\n }\n const eth = dw.provider as EIP1193;\n return useEIP1193(eth);\n}\n","import type { DetectedWallet, WalletInterFaceAPI } from \"../types\";\nimport type { WagmiBridge } from \"./bridges\";\nimport { toWalletInterfaceFromDetected } from \"./adapters\";\n// import { connectWalletConnect } from \"./walletconnect\";\n\nfunction pickWagmiConnector(\n wagmi: WagmiBridge,\n metaName: string,\n metaId: string,\n metaCategory: string\n) {\n const lower = metaName.toLowerCase();\n const cons = wagmi.connectors();\n return (\n cons.find((c) => c.name.toLowerCase().includes(lower)) ||\n (metaId === \"coinbase\" &&\n cons.find((c) => c.name.toLowerCase().includes(\"coinbase\"))) ||\n (metaId === \"walletconnect\" &&\n cons.find((c) => (c.type ?? \"\").toLowerCase() === \"walletconnect\")) ||\n (metaCategory === \"injected\" &&\n cons.find((c) => (c.type ?? \"\").toLowerCase() === \"injected\")) ||\n null\n );\n}\n\n/** Try wagmi bridge first (if provided), otherwise return EIP-1193 adapter. */\nexport async function connectDetectedWallet(\n dw: DetectedWallet,\n opts?: { wagmi?: WagmiBridge; touchAddress?: boolean }\n): Promise<{\n via: \"wagmi\" | \"eip1193\" | \"walletconnect\";\n api: WalletInterFaceAPI | null;\n error?: string | null;\n}> {\n const { wagmi, touchAddress = true } = opts ?? {};\n\n // Handle WalletConnect specially\n if (dw.meta.id === \"walletconnect\" || dw.via === \"walletconnect\") {\n // First try wagmi if available (host may have WC configured in wagmi)\n if (wagmi) {\n const conn = pickWagmiConnector(\n wagmi,\n dw.meta.name,\n dw.meta.id,\n dw.meta.category\n );\n if (conn) {\n await wagmi.connect(conn);\n return { via: \"wagmi\", api: null };\n }\n }\n\n // Use our native WalletConnect integration (built-in, always available)\n // const api = await connectWalletConnect();\n // if (api) {\n // if (touchAddress) await api.getAddress();\n // return { via: \"walletconnect\", api };\n // }\n\n throw new Error(\"WalletConnect connection failed. Please try again.\");\n }\n\n if (dw.via === \"solana-window\" || dw.meta.ecosystem === \"solana\") {\n try {\n const provider = dw.provider;\n await provider.connect();\n return {\n via: \"eip1193\",\n api: toWalletInterfaceFromDetected(dw),\n error: null,\n };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n return { via: \"eip1193\", api: null, error: errorMsg };\n }\n }\n\n if (wagmi) {\n const conn = pickWagmiConnector(\n wagmi,\n dw.meta.name,\n dw.meta.id,\n dw.meta.category\n );\n if (conn) {\n await wagmi.connect(conn);\n // when the host uses wagmi, you can later wrap the host client using your old useWagmi adapter\n return { via: \"wagmi\", api: null, error: null };\n }\n }\n\n // fallback: raw EIP-1193\n const api = toWalletInterfaceFromDetected(dw);\n if (touchAddress) await api.getAddress(); // triggers permission prompt\n return { via: \"eip1193\", api, error: null };\n}\n","import { isAddress as isEvmAddress } from \"viem\";\nimport { isAddress as isSolanaAddress } from \"@solana/addresses\";\n\nimport type { ChainDef, ChainType } from \"../types\";\nimport { normalizeChainType } from \"../utils/chains\";\n\ntype AddressValidationResult = { isValid: boolean; error?: string };\n\nconst BECH32_CHARSET = /^[023456789acdefghjklmnpqrstuvwxyz]+$/i;\n\nfunction hasMixedCase(value: string) {\n return value !== value.toLowerCase() && value !== value.toUpperCase();\n}\n\nfunction validateBech32LikeAddress(\n address: string,\n prefix: string\n): AddressValidationResult {\n const trimmed = address.trim();\n if (!trimmed) {\n return { isValid: false, error: \"Address is required.\" };\n }\n if (hasMixedCase(trimmed)) {\n return { isValid: false, error: \"Bech32 addresses cannot mix case.\" };\n }\n\n const lower = trimmed.toLowerCase();\n const expectedPrefix = `${prefix.toLowerCase()}1`;\n if (!lower.startsWith(expectedPrefix)) {\n return {\n isValid: false,\n error: `Address must start with ${expectedPrefix}.`,\n };\n }\n\n const dataPart = lower.slice(expectedPrefix.length);\n if (dataPart.length < 6 || !BECH32_CHARSET.test(dataPart)) {\n return {\n isValid: false,\n error: \"Bech32 address format is invalid.\",\n };\n }\n\n return { isValid: true };\n}\n\nexport function validateEvmAddress(address: string): AddressValidationResult {\n if (!isEvmAddress(address.trim())) {\n return {\n isValid: false,\n error: \"EVM addresses must be 0x-prefixed 20-byte hex strings.\",\n };\n }\n return { isValid: true };\n}\n\nexport function validateSeiAddress(address: string): AddressValidationResult {\n const trimmed = address.trim();\n if (isEvmAddress(trimmed)) {\n return { isValid: true };\n }\n const result = validateBech32LikeAddress(trimmed, \"sei\");\n if (result.isValid) return result;\n return {\n isValid: false,\n error: \"SEI addresses must be 0x-prefixed EVM or sei1 bech32 strings.\",\n };\n}\n\nexport function validateSolanaAddress(\n address: string\n): AddressValidationResult {\n const trimmed = address.trim();\n if (trimmed.startsWith(\"0x\") || isEvmAddress(trimmed)) {\n return {\n isValid: false,\n error: \"Solana addresses must be base58-encoded strings.\",\n };\n }\n if (\n trimmed.toLowerCase().startsWith(\"bc1\") ||\n trimmed.toLowerCase().startsWith(\"sei1\")\n ) {\n return {\n isValid: false,\n error: \"Solana addresses cannot be bech32 strings.\",\n };\n }\n if (!isSolanaAddress(trimmed)) {\n return {\n isValid: false,\n error: \"Solana addresses must be base58-encoded strings.\",\n };\n }\n return { isValid: true };\n}\n\nexport function validateBtcAddress(address: string): AddressValidationResult {\n const trimmed = address.trim();\n if (hasMixedCase(trimmed)) {\n return { isValid: false, error: \"Bitcoin addresses cannot mix case.\" };\n }\n const result = validateBech32LikeAddress(trimmed, \"bc\");\n if (result.isValid) return result;\n return {\n isValid: false,\n error: \"Bitcoin addresses must use native SegWit (bc1...) format.\",\n };\n}\n\nexport function validateAddressForChain(\n address: string,\n chain?: ChainDef | ChainType | string | null\n): AddressValidationResult {\n const trimmed = address.trim();\n if (!trimmed) return { isValid: true };\n const chainType = normalizeChainType(chain);\n const chainDef = typeof chain === \"object\" && chain ? chain : undefined;\n\n switch (chainType) {\n case \"evm\":\n return validateEvmAddress(trimmed);\n case \"solana\":\n return validateSolanaAddress(trimmed);\n case \"bitcoin\":\n return validateBtcAddress(trimmed);\n case \"cosmos\":\n if (chainDef?.networkIdentifier?.toLowerCase() === \"sei\") {\n return validateSeiAddress(trimmed);\n }\n return validateBech32LikeAddress(trimmed, \"sei\");\n default:\n return { isValid: false, error: \"Unsupported or unknown chain type.\" };\n }\n}\n\nfunction validateAddressForRouteChain(address: string, chainType: ChainType) {\n switch (normalizeChainType(chainType)) {\n case \"evm\":\n return validateEvmAddress(address);\n case \"solana\":\n return validateSolanaAddress(address);\n case \"bitcoin\":\n return validateBtcAddress(address);\n case \"cosmos\":\n return validateSeiAddress(address);\n default:\n return { isValid: false, error: \"Unsupported chain type.\" };\n }\n}\n\nexport function validateRouteAddresses(params: {\n fromChain?: ChainDef | ChainType | string | null;\n toChain?: ChainDef | ChainType | string | null;\n fromAddress: string;\n toAddress: string;\n refundAddress?: string;\n direction?: string;\n}): AddressValidationResult {\n const fromType = normalizeChainType(params.fromChain);\n const toType = normalizeChainType(params.toChain);\n\n if (!fromType || !toType) {\n return {\n isValid: false,\n error: \"Missing chain types for route validation.\",\n };\n }\n\n const fromAddress = params.fromAddress.trim();\n const toAddress = params.toAddress.trim();\n if (!fromAddress || !toAddress) {\n return { isValid: false, error: \"Route addresses are required.\" };\n }\n\n const normalizedDirection = params.direction?.trim().toLowerCase();\n const isDepositFlow =\n normalizedDirection === \"deposit\" ||\n ((toType === \"evm\" || toType === \"cosmos\") &&\n (fromType === \"bitcoin\" || fromType === \"solana\"));\n\n if (isDepositFlow) {\n const fromResult = validateAddressForRouteChain(fromAddress, fromType);\n if (!fromResult.isValid) {\n return {\n isValid: false,\n error: `From address: ${fromResult.error ?? \"Invalid address.\"}`,\n };\n }\n const toResult =\n toType === \"cosmos\"\n ? validateSeiAddress(toAddress)\n : validateEvmAddress(toAddress);\n if (!toResult.isValid) {\n return {\n isValid: false,\n error: `To address: ${toResult.error ?? \"Invalid address.\"}`,\n };\n }\n if (fromType === \"bitcoin\") {\n const refundAddress = params.refundAddress?.trim();\n if (!refundAddress) {\n return {\n isValid: false,\n error: \"Refund address is required for BTC deposit routes.\",\n };\n }\n const refundResult = validateBtcAddress(refundAddress);\n if (!refundResult.isValid) {\n return {\n isValid: false,\n error: `Refund address: ${refundResult.error ?? \"Invalid address.\"}`,\n };\n }\n }\n return { isValid: true };\n }\n\n const fromResult = validateAddressForRouteChain(fromAddress, fromType);\n if (!fromResult.isValid) {\n return {\n isValid: false,\n error: `From address: ${fromResult.error ?? \"Invalid address.\"}`,\n };\n }\n\n const toResult = validateAddressForRouteChain(toAddress, toType);\n if (!toResult.isValid) {\n return {\n isValid: false,\n error: `To address: ${toResult.error ?? \"Invalid address.\"}`,\n };\n }\n\n return { isValid: true };\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<T extends SolanaErrorCode> = { [P in T]: { index: number } };\n\ntype DefaultUnspecifiedErrorContextToUndefined<T> = {\n [P in SolanaErrorCode]: P extends keyof T ? T[P] : undefined;\n};\n\ntype ReadonlyContextValue<T> = {\n [P in keyof T]: Readonly<T[P]>;\n};\n\ntype TypedArrayMutableProperties = 'copyWithin' | 'fill' | 'reverse' | 'set' | 'sort';\ninterface ReadonlyUint8Array extends Omit<Uint8Array, TypedArrayMutableProperties> {\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<TErrorCode extends SolanaErrorCode>(\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<TErrorCode extends SolanaErrorCode>(\n code: TErrorCode,\n context: Record<string, unknown> = {},\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<SolanaError<TErrorCode>, '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<TErrorCode extends SolanaErrorCodeWithDeprecatedCause>(\n e: unknown,\n code: TErrorCode,\n): e is SolanaErrorWithDeprecatedCause<TErrorCode>;\nexport function isSolanaError<TErrorCode extends SolanaErrorCode>(\n e: unknown,\n code?: TErrorCode,\n): e is SolanaError<TErrorCode>;\nexport function isSolanaError<TErrorCode extends SolanaErrorCode>(\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<TErrorCode> {\n const isSolanaError = e instanceof Error && e.name === 'SolanaError';\n if (isSolanaError) {\n if (code !== undefined) {\n return (e as SolanaError<TErrorCode>).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<TErrorCode extends SolanaErrorCode = SolanaErrorCode> 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<typeof Error.captureStackTrace>): 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<typeof getSolanaErrorFromInstructionError>),\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<TFrom> = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => ReadonlyUint8Array<ArrayBuffer>;\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<number, 4>;\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<TFrom, TSize extends number = number> = BaseEncoder<TFrom> & {\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<string>;\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<TFrom> = BaseEncoder<TFrom> & {\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<string>;\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<string>;\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<Person> =>\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<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>;\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<TTo> = {\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<number, 4>;\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<TTo, TSize extends number = number> = BaseDecoder<TTo> & {\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<number>;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type VariableSizeDecoder<TTo> = BaseDecoder<TTo> & {\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<string>;\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<string>;\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<Person> =>\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<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>;\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<number | bigint, bigint, 8>;\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<TFrom, TTo extends TFrom = TFrom, TSize extends number = number> = FixedSizeDecoder<\n TTo,\n TSize\n> &\n FixedSizeEncoder<TFrom, TSize>;\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<number | bigint, bigint>;\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<TFrom, TTo extends TFrom = TFrom> = VariableSizeDecoder<TTo> & VariableSizeEncoder<TFrom>;\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<string>;\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<bigint | number, bigint>` can encode both\n * `bigint` and `number` values, but will always decode to a `bigint`.\n *\n * ```ts\n * const codec: Codec<bigint | number, bigint>;\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<TFrom, TTo>` can be combined from an `Encoder<TFrom>`\n * and a `Decoder<TTo>` 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<bigint | number>;\n * const decoder: Decoder<bigint>;\n * const codec: Codec<bigint | number, bigint> = 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<Person> =>\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<TFrom, TTo extends TFrom = TFrom> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>;\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<TFrom>(\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<Person> = 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<TFrom, TSize extends number>(\n encoder: Omit<FixedSizeEncoder<TFrom, TSize>, 'encode'>,\n): FixedSizeEncoder<TFrom, TSize>;\nexport function createEncoder<TFrom>(encoder: Omit<VariableSizeEncoder<TFrom>, 'encode'>): VariableSizeEncoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom> {\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<Person> = 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<TTo, TSize extends number>(\n decoder: Omit<FixedSizeDecoder<TTo, TSize>, 'decode'>,\n): FixedSizeDecoder<TTo, TSize>;\nexport function createDecoder<TTo>(decoder: Omit<VariableSizeDecoder<TTo>, 'decode'>): VariableSizeDecoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo> {\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<PersonInput, Person> = 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<TFrom, TTo extends TFrom = TFrom, TSize extends number = number>(\n codec: Omit<FixedSizeCodec<TFrom, TTo, TSize>, 'decode' | 'encode'>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec: Omit<VariableSizeCodec<TFrom, TTo>, 'decode' | 'encode'>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'decode' | 'encode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'decode' | 'encode'>,\n): Codec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'decode' | 'encode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'decode' | 'encode'>,\n): Codec<TFrom, TTo> {\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<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function isFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n): decoder is FixedSizeDecoder<TTo, TSize>;\nexport function isFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n): codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function isFixedSize<TSize extends number>(\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<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): asserts encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function assertIsFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n): asserts decoder is FixedSizeDecoder<TTo, TSize>;\nexport function assertIsFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n): asserts codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function assertIsFixedSize<TSize extends number>(\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<TFrom>(encoder: Encoder<TFrom>): encoder is VariableSizeEncoder<TFrom>;\nexport function isVariableSize<TTo>(decoder: Decoder<TTo>): decoder is VariableSizeDecoder<TTo>;\nexport function isVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): codec is VariableSizeCodec<TFrom, TTo>;\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<TFrom>(encoder: Encoder<TFrom>): asserts encoder is VariableSizeEncoder<TFrom>;\nexport function assertIsVariableSize<TTo>(decoder: Decoder<TTo>): asserts decoder is VariableSizeDecoder<TTo>;\nexport function assertIsVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): asserts codec is VariableSizeCodec<TFrom, TTo>;\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<TFrom>` and a `Decoder<TTo>`, this function returns a `Codec<TFrom, TTo>`.\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<MyType> => { \\/* ... *\\/ };\n * const getMyTypeDecoder = (): Decoder<MyType> => { \\/* ... *\\/ };\n * const getMyTypeCodec = (): Codec<MyType> =>\n * combineCodec(getMyTypeEncoder(), getMyTypeDecoder());\n * ```\n *\n * @see {@link Codec}\n * @see {@link Encoder}\n * @see {@link Decoder}\n */\nexport function combineCodec<TFrom, TTo extends TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n decoder: FixedSizeDecoder<TTo, TSize>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: VariableSizeEncoder<TFrom>,\n decoder: VariableSizeDecoder<TTo>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>,\n): Codec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>,\n): Codec<TFrom, TTo> {\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<TFrom>(\n encoder: FixedSizeEncoder<TFrom>,\n sentinel: ReadonlyUint8Array,\n): FixedSizeEncoder<TFrom>;\nexport function addEncoderSentinel<TFrom>(\n encoder: Encoder<TFrom>,\n sentinel: ReadonlyUint8Array,\n): VariableSizeEncoder<TFrom>;\nexport function addEncoderSentinel<TFrom>(encoder: Encoder<TFrom>, sentinel: ReadonlyUint8Array): Encoder<TFrom> {\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<TFrom>['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<TTo>(\n decoder: FixedSizeDecoder<TTo>,\n sentinel: ReadonlyUint8Array,\n): FixedSizeDecoder<TTo>;\nexport function addDecoderSentinel<TTo>(decoder: Decoder<TTo>, sentinel: ReadonlyUint8Array): VariableSizeDecoder<TTo>;\nexport function addDecoderSentinel<TTo>(decoder: Decoder<TTo>, sentinel: ReadonlyUint8Array): Decoder<TTo> {\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<TTo>['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<TFrom, TTo extends TFrom>(\n codec: FixedSizeCodec<TFrom, TTo>,\n sentinel: ReadonlyUint8Array,\n): FixedSizeCodec<TFrom, TTo>;\nexport function addCodecSentinel<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n sentinel: ReadonlyUint8Array,\n): VariableSizeCodec<TFrom, TTo>;\nexport function addCodecSentinel<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n sentinel: ReadonlyUint8Array,\n): Codec<TFrom, TTo> {\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<bigint | number> | Encoder<number>;\ntype FixedSizeNumberEncoder<TSize extends number = number> =\n | FixedSizeEncoder<bigint | number, TSize>\n | FixedSizeEncoder<number, TSize>;\ntype NumberDecoder = Decoder<bigint> | Decoder<number>;\ntype FixedSizeNumberDecoder<TSize extends number = number> =\n | FixedSizeDecoder<bigint, TSize>\n | FixedSizeDecoder<number, TSize>;\ntype NumberCodec = Codec<bigint | number, bigint> | Codec<number>;\ntype FixedSizeNumberCodec<TSize extends number = number> =\n | FixedSizeCodec<bigint | number, bigint, TSize>\n | FixedSizeCodec<number, number, TSize>;\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<TFrom>(\n encoder: FixedSizeEncoder<TFrom>,\n prefix: FixedSizeNumberEncoder,\n): FixedSizeEncoder<TFrom>;\nexport function addEncoderSizePrefix<TFrom>(encoder: Encoder<TFrom>, prefix: NumberEncoder): VariableSizeEncoder<TFrom>;\nexport function addEncoderSizePrefix<TFrom>(encoder: Encoder<TFrom>, prefix: NumberEncoder): Encoder<TFrom> {\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<TFrom>['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<TTo>(\n decoder: FixedSizeDecoder<TTo>,\n prefix: FixedSizeNumberDecoder,\n): FixedSizeDecoder<TTo>;\nexport function addDecoderSizePrefix<TTo>(decoder: Decoder<TTo>, prefix: NumberDecoder): VariableSizeDecoder<TTo>;\nexport function addDecoderSizePrefix<TTo>(decoder: Decoder<TTo>, prefix: NumberDecoder): Decoder<TTo> {\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<TTo>['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<TFrom, TTo extends TFrom>(\n codec: FixedSizeCodec<TFrom, TTo>,\n prefix: FixedSizeNumberCodec,\n): FixedSizeCodec<TFrom, TTo>;\nexport function addCodecSizePrefix<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n prefix: NumberCodec,\n): VariableSizeCodec<TFrom, TTo>;\nexport function addCodecSizePrefix<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n prefix: NumberCodec,\n): Codec<TFrom, TTo> {\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<T>(decoder: Decoder<T>): Decoder<T> {\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<TFrom, TSize extends number>(\n encoder: Encoder<TFrom>,\n fixedBytes: TSize,\n): FixedSizeEncoder<TFrom, TSize> {\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<TTo, TSize extends number>(\n decoder: Decoder<TTo>,\n fixedBytes: TSize,\n): FixedSizeDecoder<TTo, TSize> {\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<TFrom, TTo extends TFrom, TSize extends number>(\n codec: Codec<TFrom, TTo>,\n fixedBytes: TSize,\n): FixedSizeCodec<TFrom, TTo, TSize> {\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<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec<any>;\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<TEncoder extends AnyEncoder>(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<TDecoder extends AnyDecoder>(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<TCodec extends AnyCodec>(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<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec<any>;\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<TFrom, TSize extends number, TNewSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n resize: (size: TSize) => TNewSize,\n): FixedSizeEncoder<TFrom, TNewSize>;\nexport function resizeEncoder<TEncoder extends AnyEncoder>(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder;\nexport function resizeEncoder<TEncoder extends AnyEncoder>(\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<TFrom, TSize extends number, TNewSize extends number>(\n decoder: FixedSizeDecoder<TFrom, TSize>,\n resize: (size: TSize) => TNewSize,\n): FixedSizeDecoder<TFrom, TNewSize>;\nexport function resizeDecoder<TDecoder extends AnyDecoder>(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder;\nexport function resizeDecoder<TDecoder extends AnyDecoder>(\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<TFrom, TTo extends TFrom, TSize extends number, TNewSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize>,\n resize: (size: TSize) => TNewSize,\n): FixedSizeCodec<TFrom, TTo, TNewSize>;\nexport function resizeCodec<TCodec extends AnyCodec>(codec: TCodec, resize: (size: number) => number): TCodec;\nexport function resizeCodec<TCodec extends AnyCodec>(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<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec<any>;\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<TEncoder extends AnyEncoder>(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<TEncoder extends AnyEncoder>(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<TDecoder extends AnyDecoder>(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<TDecoder extends AnyDecoder>(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<TCodec extends AnyCodec>(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<TCodec extends AnyCodec>(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<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n): FixedSizeEncoder<TFrom, TSize> {\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<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize>,\n): FixedSizeDecoder<TTo, TSize> {\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<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize>,\n): FixedSizeCodec<TFrom, TTo, TSize> {\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<A>` and returns an `Encoder<B>`, 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<TOldFrom, TNewFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TOldFrom, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder<TNewFrom, TSize>;\nexport function transformEncoder<TOldFrom, TNewFrom>(\n encoder: VariableSizeEncoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder<TNewFrom>;\nexport function transformEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom>;\nexport function transformEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom> {\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<A>` and returns a `Decoder<B>`, 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<TOldTo, TNewTo, TSize extends number>(\n decoder: FixedSizeDecoder<TOldTo, TSize>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder<TNewTo, TSize>;\nexport function transformDecoder<TOldTo, TNewTo>(\n decoder: VariableSizeDecoder<TOldTo>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder<TNewTo>;\nexport function transformDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo>;\nexport function transformDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo> {\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<A, B>` and returns a `Codec<C, D>`, 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<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeCodec<TNewFrom, TTo, TSize>;\nexport function transformCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: VariableSizeCodec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec<TNewFrom, TTo>;\nexport function transformCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: Codec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec<TNewFrom, TTo>;\nexport function transformCodec<\n TOldFrom,\n TNewFrom,\n TOldTo extends TOldFrom,\n TNewTo extends TNewFrom,\n TSize extends number,\n>(\n codec: FixedSizeCodec<TOldFrom, TOldTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec<TNewFrom, TNewTo, TSize>;\nexport function transformCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: VariableSizeCodec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec<TNewFrom, TNewTo>;\nexport function transformCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo>;\nexport function transformCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo> {\n return createCodec({\n ...transformEncoder(codec, unmap),\n read: map ? transformDecoder(codec, map).read : (codec.read as unknown as Decoder<TNewTo>['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<string>` 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<string> => {\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<string>` 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<string> => {\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<string>` 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<string> =>\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<string>` 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<string>` 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<string>` 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<string>` 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<string> =>\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<string>` 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<string> =>\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<string>` 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<string> => 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<string>` 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<string>` 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<string>` 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<string>` 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<string> =>\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<string>` 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<string> =>\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<string>` 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<string> =>\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<string>` 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<string> => {\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<string>` 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<string> => {\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<string>` 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<string> => 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<string>` 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<string> => {\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<string>` 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<string> => {\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<string>` 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<string> => combineCodec(getUtf8Encoder(), getUtf8Decoder());\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<TAddress extends string = string> = Brand<EncodedString<TAddress, 'base58'>, 'Address'>;\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\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<typeof putativeAddress> {\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<typeof putativeAddress> {\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<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address<TAddress>;\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<Address, 32> {\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<Address, 32> {\n return fixDecoderSize(getMemoizedBase58Decoder(), 32) as FixedSizeDecoder<Address, 32>;\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<Address, Address, 32> {\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<TAddress extends string = string> = AffinePoint<Address<TAddress>, '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<TAddress extends Address>(\n putativeOffCurveAddress: TAddress,\n): putativeOffCurveAddress is OffCurveAddress<TAddress> {\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<TAddress extends Address>(\n putativeOffCurveAddress: TAddress,\n): asserts putativeOffCurveAddress is OffCurveAddress<TAddress> {\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<TAddress extends Address>(\n putativeOffCurveAddress: TAddress,\n): OffCurveAddress<TAddress> {\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<TAddress extends string = string> = Readonly<\n [Address<TAddress>, 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<number, 'ProgramDerivedAddressBump'>;\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<TAddress extends string = string>(\n value: unknown,\n): value is ProgramDerivedAddress<TAddress> {\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<TAddress extends string = string>(\n value: unknown,\n): asserts value is ProgramDerivedAddress<TAddress> {\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<Address> {\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<ProgramDerivedAddress> {\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<Address> {\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<Address> {\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 type {\n WalletAddressResolution,\n WalletAddressSource,\n WalletIdentity,\n WalletIdentityAddress,\n WalletIdentityChainLike,\n} from \"../types\";\nimport { validateAddressForChain } from \"../validation/address\";\nimport { normalizeChainKey, normalizeChainType } from \"../utils/chains\";\n\nfunction normalizeIdentityChainId(\n chain?: WalletIdentityChainLike\n): string | undefined {\n if (!chain || typeof chain === \"string\") return undefined;\n const raw = chain.chainId ?? chain.id;\n if (raw === undefined || raw === null) return undefined;\n const normalized = String(raw).trim();\n return normalized || undefined;\n}\n\nfunction identityEntryMatchesChain(\n entry: WalletIdentityAddress,\n chainType?: string,\n chainKey?: string,\n chainId?: string\n) {\n if (chainKey && entry.chainKey && entry.chainKey === chainKey) return true;\n if (chainId && entry.chainId && entry.chainId === chainId) return true;\n if (chainType && entry.chainType === chainType) return true;\n return false;\n}\n\nexport function createWalletIdentity(\n addresses: WalletIdentityAddress[] = []\n): WalletIdentity {\n return { addresses };\n}\n\nexport function upsertWalletIdentityAddress(\n identity: WalletIdentity,\n next: WalletIdentityAddress\n): WalletIdentity {\n const normalizedAddress = next.address.trim();\n const normalizedChainKey = next.chainKey\n ? normalizeChainKey(next.chainKey)\n : undefined;\n const normalizedChainId = next.chainId?.trim() || undefined;\n\n const addresses = identity.addresses.filter((entry) => {\n if (entry.chainType !== next.chainType) return true;\n if (normalizedChainKey && entry.chainKey === normalizedChainKey)\n return false;\n if (normalizedChainId && entry.chainId === normalizedChainId) return false;\n if (!normalizedChainKey && !normalizedChainId) return false;\n return true;\n });\n\n if (!normalizedAddress) return createWalletIdentity(addresses);\n\n return createWalletIdentity([\n ...addresses,\n {\n ...next,\n address: normalizedAddress,\n chainKey: normalizedChainKey,\n chainId: normalizedChainId,\n },\n ]);\n}\n\nexport function resolveWalletAddressForChain(\n identity: WalletIdentity,\n chain?: WalletIdentityChainLike\n): WalletAddressResolution {\n const chainType = normalizeChainType(chain);\n const chainDef = typeof chain === \"object\" && chain ? chain : undefined;\n const chainKey = chainDef\n ? normalizeChainKey(\n chainDef.networkIdentifier ?? chainDef.chainId ?? chainDef.id\n )\n : typeof chain === \"string\"\n ? normalizeChainKey(chain)\n : undefined;\n const chainId = normalizeIdentityChainId(chain);\n\n if (!chainType) {\n return {\n status: \"missing\",\n reason: \"unknown_chain_type\",\n chainKey,\n chainId,\n };\n }\n\n const match = identity.addresses.find((entry) =>\n identityEntryMatchesChain(entry, chainType, chainKey, chainId)\n );\n\n if (!match) {\n return {\n status: \"missing\",\n reason: \"missing_chain_address\",\n chainType,\n chainKey,\n chainId,\n };\n }\n\n const validation = validateAddressForChain(\n match.address,\n chainDef ?? chainType\n );\n if (!validation.isValid) {\n return {\n status: \"invalid\",\n reason: validation.error ?? \"invalid_chain_address\",\n address: match.address,\n source: match.source,\n chainType,\n chainKey,\n chainId,\n };\n }\n\n return {\n status: \"resolved\",\n address: match.address.trim(),\n source: match.source,\n chainType,\n chainKey,\n chainId,\n };\n}\n\nexport function buildWalletIdentityAddress(params: {\n address: string;\n chain: WalletIdentityChainLike;\n source: WalletAddressSource;\n providerId?: string;\n}): WalletIdentityAddress | null {\n const chainType = normalizeChainType(params.chain);\n if (!chainType) return null;\n\n const address = params.address.trim();\n const chainId = normalizeIdentityChainId(params.chain);\n const chainDef =\n typeof params.chain === \"object\" && params.chain ? params.chain : undefined;\n const chainKey = chainDef\n ? normalizeChainKey(\n chainDef.networkIdentifier ?? chainDef.chainId ?? chainDef.id\n )\n : undefined;\n\n return {\n address,\n chainType,\n chainId,\n chainKey,\n providerId: params.providerId,\n source: params.source,\n };\n}\n\nexport class IdentityStore {\n private _identity = createWalletIdentity();\n\n get snapshot() {\n return this._identity;\n }\n\n reset() {\n this._identity = createWalletIdentity();\n }\n\n upsert(next: WalletIdentityAddress) {\n this._identity = upsertWalletIdentityAddress(this._identity, next);\n return this._identity;\n }\n\n resolve(chain?: WalletIdentityChainLike) {\n return resolveWalletAddressForChain(this._identity, chain);\n }\n}\n","import type {\n DetectedWallet,\n WalletInterFaceAPI,\n SimpleWalletInterface,\n WalletIdentityAddress,\n} from \"../types\";\nimport type { WagmiBridge } from \"./bridges\";\nimport { connectDetectedWallet } from \"./connect\";\nimport { useWalletDetection } from \"./detect\"; // you can also inline detect() if you want non-react\nimport { IdentityStore, buildWalletIdentityAddress } from \"../identity\";\nimport { bindSolanaProviderEvents } from \"./solana\";\n\ntype Status = \"idle\" | \"detecting\" | \"connecting\" | \"connected\" | \"error\";\ntype Listener = (s: Status) => void;\n\nclass WalletManager {\n private _status: Status = \"idle\";\n private _wallet: WalletInterFaceAPI | null = null;\n private _detected: DetectedWallet[] = [];\n private _listeners = new Set<Listener>();\n private _error: string | null = null;\n private _identity = new IdentityStore();\n private _providerCleanup: (() => void) | null = null;\n private _connectedWalletId: string | null = null;\n\n get status() {\n return this._status;\n }\n get error() {\n return this._error;\n }\n get detected(): DetectedWallet[] {\n return this._detected;\n }\n get wallet(): WalletInterFaceAPI | null {\n return this._wallet;\n }\n get simple(): SimpleWalletInterface | null {\n if (!this._wallet) return null;\n const { getAddress, disconnect } = this._wallet;\n return { getAddress, disconnect };\n }\n get identity() {\n return this._identity.snapshot;\n }\n get connectedWalletId() {\n return this._connectedWalletId;\n }\n\n onChange(fn: Listener) {\n this._listeners.add(fn);\n return () => this._listeners.delete(fn);\n }\n private emit() {\n for (const fn of this._listeners) fn(this._status);\n }\n\n /** Provide detection results (from your hook or custom function). */\n setDetected(list: DetectedWallet[]) {\n this._detected = list;\n }\n\n /** Optional: auto attach to the first/best detected wallet. */\n async autoAttach(opts?: {\n wagmi?: WagmiBridge;\n pick?: (list: DetectedWallet[]) => DetectedWallet | undefined;\n }) {\n if (!this._detected.length) return;\n const target = (opts?.pick ?? ((l) => l[0]))(this._detected);\n if (!target) return;\n await this.connectDetected(target, opts);\n }\n\n async connectDetected(\n target: DetectedWallet,\n opts?: { wagmi?: WagmiBridge }\n ) {\n if (\n this._status === \"connected\" &&\n this._connectedWalletId === target.meta.id &&\n this._wallet\n ) {\n this.emit();\n return;\n }\n\n this._status = \"connecting\";\n this.clearConnectedWalletState();\n this.emit();\n try {\n const { api, error } = await connectDetectedWallet(target, {\n wagmi: opts?.wagmi,\n });\n if (api && !error) {\n this._wallet = api;\n this._connectedWalletId = target.meta.id;\n this.bindProviderEvents(target);\n await this.syncIdentityFromWallet(target.meta.id);\n this._status = \"connected\";\n this._error = null;\n return { error: null, api };\n }\n\n if (error) {\n this._status = \"error\";\n this._error = error;\n return { error: error, api };\n }\n } catch (e) {\n this._error = e instanceof Error ? e.message : String(e);\n this._status = \"error\";\n this.clearConnectedWalletState();\n } finally {\n this.emit();\n }\n }\n\n async disconnect(wagmi?: WagmiBridge) {\n if (wagmi) await wagmi.disconnect().catch(() => {});\n if (this._wallet?.disconnect) {\n await this._wallet.disconnect().catch(() => {});\n }\n this.clearConnectedWalletState();\n this._status = \"idle\";\n this.emit();\n }\n\n /** Directly attach a pre-provided wallet interface (from old provider prop). */\n attachWallet(api: WalletInterFaceAPI) {\n this.clearConnectedWalletState();\n this._wallet = api;\n this._connectedWalletId = null;\n this._status = \"connected\";\n void this.syncIdentityFromWallet();\n this.emit();\n }\n\n /** Optional helper to set explicit status (e.g., \"initializing\" UX). */\n setStatus(s: Status) {\n this._status = s;\n this.emit();\n }\n\n addIdentityAddress(address: WalletIdentityAddress) {\n this._identity.upsert(address);\n }\n\n resolveAddressForChain(chain: Parameters<IdentityStore[\"resolve\"]>[0]) {\n return this._identity.resolve(chain);\n }\n\n private clearProviderCleanup() {\n this._providerCleanup?.();\n this._providerCleanup = null;\n }\n\n private clearConnectedWalletState() {\n this.clearProviderCleanup();\n this._wallet = null;\n this._connectedWalletId = null;\n }\n\n private bindProviderEvents(target: DetectedWallet) {\n if (!target.provider) return;\n\n if (target.via === \"solana-window\") {\n this._providerCleanup = bindSolanaProviderEvents(target.provider, {\n onConnect: () => {\n this._status = \"connected\";\n void this.syncIdentityFromWallet(target.meta.id);\n this.emit();\n },\n onAccountChanged: () => {\n void this.syncIdentityFromWallet(target.meta.id);\n this.emit();\n },\n onDisconnect: () => {\n this.clearConnectedWalletState();\n this._status = \"idle\";\n this.emit();\n },\n });\n return;\n }\n\n const provider = target.provider as {\n on?: (event: string, listener: (...args: unknown[]) => void) => void;\n off?: (event: string, listener: (...args: unknown[]) => void) => void;\n removeListener?: (\n event: string,\n listener: (...args: unknown[]) => void\n ) => void;\n };\n const onAccountsChanged = (accounts?: unknown) => {\n const nextAccounts = Array.isArray(accounts) ? accounts : [];\n if (nextAccounts.length === 0) {\n this.clearConnectedWalletState();\n this._status = \"idle\";\n this.emit();\n return;\n }\n this._status = \"connected\";\n void this.syncIdentityFromWallet(target.meta.id);\n this.emit();\n };\n const onDisconnect = () => {\n this.clearConnectedWalletState();\n this._status = \"idle\";\n this.emit();\n };\n\n provider.on?.(\"accountsChanged\", onAccountsChanged);\n provider.on?.(\"disconnect\", onDisconnect);\n this._providerCleanup = () => {\n provider.off?.(\"accountsChanged\", onAccountsChanged);\n provider.off?.(\"disconnect\", onDisconnect);\n provider.removeListener?.(\"accountsChanged\", onAccountsChanged);\n provider.removeListener?.(\"disconnect\", onDisconnect);\n };\n }\n\n private async syncIdentityFromWallet(providerId?: string) {\n if (!this._wallet) return;\n try {\n const address = await this._wallet.getAddress();\n const chain =\n this._wallet.ecosystem === \"evm\"\n ? { chainId: String(await this._wallet.getChainId()), type: \"evm\" }\n : {\n chainId: \"solana-mainnet-beta\",\n networkIdentifier: \"solana-mainnet-beta\",\n type: \"solana\",\n };\n const identityAddress = buildWalletIdentityAddress({\n address,\n chain,\n source: \"provider\",\n providerId,\n });\n if (identityAddress) {\n this._identity.upsert(identityAddress);\n }\n } catch {\n // identity sync is best-effort\n }\n }\n}\n\nexport const walletManager = new WalletManager();\n\n/* ---------- Optional tiny React hook to feed detection into the manager ---------- */\nimport { useEffect } from \"react\";\n\n/** If you’re in React, call this once near your widget to push detection results into the manager. */\nexport function useWireDetectionIntoManager() {\n const { detected } = useWalletDetection(); // your existing hook\n useEffect(() => {\n walletManager.setDetected(detected);\n }, [detected]);\n}\n","import { apiBase, jsonHeaders, assertOK, rateLimitedFetch } from \"./http\";\nimport type {\n BuildRouteResult,\n RouteParams,\n RoutePlan,\n Transaction,\n} from \"../types\";\nimport { TrustwareConfigStore } from \"src/config/store\";\nimport { validateRouteAddresses } from \"../validation/address\";\n\nexport type BuildRouteBody = {\n fromChain: string;\n toChain: string;\n fromToken: string;\n toToken: string;\n fromAmount: string;\n fromAddress: string;\n toAddress: string;\n fromAmountUsd?: string;\n fromAmountUSD?: string;\n refundAddress?: string;\n direction?: string;\n slippage?: number;\n slippageBps?: number;\n linkId?: string;\n memo?: string;\n};\n\nexport type TxRequest = {\n to?: string;\n target?: string;\n data: string;\n value?: string;\n gasLimit?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n chainId?: number | string;\n gasPrice?: string;\n};\n\nexport type BuildRouteResponse = {\n intentId?: string;\n route?: RoutePlan;\n data?: {\n intentId?: string;\n route?: RoutePlan;\n };\n error?: string;\n message?: string;\n};\n\ntype DepositAddress = {\n address?: string;\n memo?: string;\n expiresAt?: string;\n};\n\ntype BuildDepositAddressResponse = {\n depositAddress?: DepositAddress;\n intentId?: string;\n route?: RoutePlan;\n data?: {\n depositAddress?: DepositAddress;\n intentId?: string;\n route?: RoutePlan;\n };\n error?: string;\n message?: string;\n};\n\nexport function isEvmTxRequest(txReq?: TxRequest | null) {\n return Boolean(txReq?.data && (txReq.to || txReq.target));\n}\n\nexport function isSerializedSolanaTxRequest(txReq?: TxRequest | null) {\n return Boolean(txReq?.data && !txReq?.to && !txReq?.target);\n}\n\nexport async function buildRoute1(p: RouteParams): Promise<BuildRouteResult> {\n const r = await rateLimitedFetch(`${apiBase()}/squid/route`, {\n method: \"POST\",\n headers: jsonHeaders(),\n credentials: \"omit\",\n body: JSON.stringify(p),\n });\n await assertOK(r);\n const j = await r.json();\n return j.data as BuildRouteResult;\n}\n\nexport async function buildRoute(\n body: BuildRouteBody,\n signal?: AbortSignal\n): Promise<{\n intentId: string;\n txReq: TxRequest;\n actions: unknown[];\n finalExchangeRate: {\n fromAmountUSD?: string;\n toAmountMinUSD?: string;\n };\n route: RoutePlan | undefined;\n}> {\n const addressValidation = validateRouteAddresses({\n fromChain: body.fromChain,\n toChain: body.toChain,\n fromAddress: body.fromAddress,\n toAddress: body.toAddress,\n refundAddress: body.refundAddress,\n direction: body.direction,\n });\n if (!addressValidation.isValid) {\n throw new Error(addressValidation.error || \"Invalid route addresses.\");\n }\n\n const cfg = TrustwareConfigStore.get();\n const url = `${apiBase()}/v1/routes/route`;\n const payload = {\n ...body,\n slippageBps:\n body.slippageBps ??\n (body.slippage === undefined\n ? undefined\n : Math.round(body.slippage * 100)),\n fromAmountUSD: body.fromAmountUSD ?? body.fromAmountUsd,\n };\n const r = await rateLimitedFetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-API-Key\": cfg.apiKey },\n body: JSON.stringify(payload),\n signal,\n });\n\n let json: BuildRouteResponse = {};\n try {\n json = await r.json();\n } catch {\n // response body not JSON\n }\n\n if (!r.ok) {\n const msg = json?.error || json?.message || \"Failed to build route\";\n throw new Error(msg);\n }\n\n const intentId = json?.data?.intentId ?? json?.intentId ?? \"\";\n const route = json?.data?.route ?? json?.route;\n const txReq: TxRequest | undefined = route?.execution?.transaction;\n const actions = Array.isArray(route?.steps) ? route.steps : [];\n const estimate = route?.estimate ?? {};\n\n const finalExchangeRate = {\n fromAmountUSD: (estimate as { fromAmountUsd?: string }).fromAmountUsd,\n toAmountMinUSD: estimate?.toAmountMinUsd ?? estimate?.toAmountUsd,\n };\n\n if (!txReq?.data) {\n throw new Error(\"Invalid route: missing transaction data\");\n }\n\n return { intentId, txReq, actions, finalExchangeRate, route };\n}\n\nexport async function buildDepositAddress(\n body: BuildRouteBody,\n signal?: AbortSignal\n): Promise<{\n intentId: string;\n depositAddress: string;\n actions: unknown[];\n finalExchangeRate: {\n fromAmountUSD?: string;\n toAmountMinUSD?: string;\n };\n route: RoutePlan | undefined;\n}> {\n const cfg = TrustwareConfigStore.get();\n const url = `${apiBase()}/v1/routes/deposit-address`;\n const payload = {\n ...body,\n slippageBps:\n body.slippageBps ??\n (body.slippage === undefined\n ? undefined\n : Math.round(body.slippage * 100)),\n fromAmountUSD: body.fromAmountUSD ?? body.fromAmountUsd,\n };\n const r = await rateLimitedFetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-API-Key\": cfg.apiKey },\n body: JSON.stringify(payload),\n signal,\n });\n\n let json: BuildDepositAddressResponse = {};\n try {\n json = await r.json();\n } catch {\n // response body not JSON\n }\n\n if (!r.ok) {\n const msg =\n json?.error || json?.message || \"Failed to build deposit address\";\n throw new Error(msg);\n }\n\n const intentId = json?.data?.intentId ?? json?.intentId ?? \"\";\n const route = json?.data?.route ?? json?.route;\n const depositAddress =\n json?.data?.depositAddress?.address ?? json?.depositAddress?.address ?? \"\";\n const actions = Array.isArray(route?.steps) ? route.steps : [];\n const estimate = route?.estimate ?? {};\n if (!depositAddress) {\n throw new Error(\"Invalid route: missing deposit address\");\n }\n\n return {\n intentId,\n depositAddress,\n actions,\n finalExchangeRate: {\n fromAmountUSD: (estimate as { fromAmountUsd?: string }).fromAmountUsd,\n toAmountMinUSD: estimate?.toAmountMinUsd ?? estimate?.toAmountUsd,\n },\n route,\n };\n}\n\nexport async function submitReceipt(intentId: string, txHash: string) {\n const r = await rateLimitedFetch(\n `${apiBase()}/v1/route-intent/${intentId}/receipt`,\n {\n method: \"POST\",\n headers: jsonHeaders({ \"Idempotency-Key\": txHash }),\n body: JSON.stringify({ txHash }),\n }\n );\n await assertOK(r);\n const j = await r.json();\n return j.data;\n}\n\nexport async function getStatus(intentId: string): Promise<Transaction> {\n const r = await rateLimitedFetch(\n `${apiBase()}/v1/route-intent/${intentId}/status`,\n {\n headers: jsonHeaders(),\n }\n );\n await assertOK(r);\n const j = await r.json();\n return j.data as Transaction;\n}\n\nexport async function pollStatus(\n intentId: string,\n { intervalMs = 2000, timeoutMs = 5 * 60_000 } = {}\n): Promise<Transaction> {\n const t0 = Date.now();\n while (true) {\n const tx = await getStatus(intentId);\n if (tx.status === \"success\" || tx.status === \"failed\") return tx;\n if (Date.now() - t0 > timeoutMs) return tx;\n await new Promise((r) => setTimeout(r, intervalMs));\n }\n}\n","import type {\n BalanceRow,\n BalanceStreamOptions,\n WalletAddressBalanceWrapper,\n ChainDef,\n} from \"../types/\";\nimport { apiBase, jsonHeaders, rateLimitedFetch } from \"./http\";\nimport { Registry } from \"../registry\";\nimport { TrustwareConfigStore } from \"../config/store\";\nimport {\n getNativeTokenAddress,\n isZeroAddressLike,\n normalizeChainType,\n} from \"../utils/chains\";\nimport { validateAddressForChain } from \"../validation/address\";\n\nexport type { BalanceRow };\n\ntype RawBalanceRow = Record<string, unknown>;\ntype RawBalanceChunk =\n | WalletAddressBalanceWrapper\n | WalletAddressBalanceWrapper[];\n\nconst balanceCache = new Map<string, BalanceRow[]>();\n\nfunction toStringOrUndefined(value: unknown) {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n\nfunction toNumberOrUndefined(value: unknown) {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (typeof value === \"string\") {\n const parsed = Number(value.trim());\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n}\n\nfunction fallbackTokenSymbol(address: string, chainType?: string | null) {\n if (chainType?.toLowerCase() === \"solana\") {\n return \"SPL\";\n }\n return `TOKEN-${address.slice(0, 6)}`;\n}\n\nfunction emitBalanceStreamChunk(address: string, chunkSize: number) {\n TrustwareConfigStore.get().onEvent?.({\n type: \"balance_stream_chunk\",\n address,\n chunkSize,\n });\n}\n\nfunction emitBalanceStreamFallback(address: string, error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n TrustwareConfigStore.get().onEvent?.({\n type: \"balance_stream_fallback\",\n address,\n message,\n });\n}\n\nfunction normalizeRows(\n rows: RawBalanceRow[],\n chain: ChainDef,\n address: string,\n registry: Registry\n) {\n const chainKey = chain.networkIdentifier ?? String(chain.chainId ?? chain.id);\n const chainType = normalizeChainType(chain);\n const nativeAddress = getNativeTokenAddress(chainType);\n const map = new Map<string, BalanceRow>();\n\n for (const item of rows) {\n const category = toStringOrUndefined(item.category)?.toLowerCase();\n const addressRaw =\n item.contract ?? item.token_address ?? item.address ?? item.addr;\n const tokenAddress =\n typeof addressRaw === \"string\" ? addressRaw.trim() : undefined;\n const symbol = toStringOrUndefined(item.symbol ?? item.sym);\n const name =\n toStringOrUndefined(item.name ?? item.token_name ?? item.token) ?? symbol;\n const decimals = toNumberOrUndefined(item.decimals ?? item.dec);\n const balance = String(item.balance ?? item.bal ?? \"0\");\n const explicitNative = Boolean(item.native ?? item.is_native);\n const nativeFlag =\n explicitNative ||\n category === \"native\" ||\n isZeroAddressLike(tokenAddress, chainType);\n\n if (nativeFlag) {\n const nativeRow: BalanceRow = {\n chain_key: chainKey,\n category: \"native\",\n contract: nativeAddress,\n address: nativeAddress,\n symbol: symbol ?? chain.nativeCurrency?.symbol ?? \"NATIVE\",\n name: name ?? chain.nativeCurrency?.name ?? symbol,\n decimals: decimals ?? chain.nativeCurrency?.decimals ?? 18,\n balance,\n };\n map.set(`${chainKey}:${nativeAddress}`, nativeRow);\n continue;\n }\n\n if (!tokenAddress || decimals === undefined) continue;\n\n const metadata = registry.findToken(chain.chainId, tokenAddress);\n const displaySymbol =\n symbol ??\n metadata?.symbol ??\n fallbackTokenSymbol(tokenAddress, chainType);\n const displayName = name ?? metadata?.name ?? displaySymbol;\n const normalizedAddress = metadata?.address ?? tokenAddress;\n\n map.set(`${chainKey}:${normalizedAddress}`, {\n chain_key: chainKey,\n category:\n (category as BalanceRow[\"category\"] | undefined) ??\n (chainType === \"solana\" ? \"spl\" : \"erc20\"),\n contract: normalizedAddress,\n address: normalizedAddress,\n symbol: displaySymbol,\n name: displayName,\n decimals: metadata?.decimals ?? decimals,\n balance,\n logoURI: metadata?.logoURI,\n usdPrice: metadata?.usdPrice,\n });\n }\n\n if (!Array.from(map.values()).some((row) => row.category === \"native\")) {\n map.set(`${chainKey}:${nativeAddress}`, {\n chain_key: chainKey,\n category: \"native\",\n contract: nativeAddress,\n address: nativeAddress,\n symbol: chain.nativeCurrency?.symbol ?? \"NATIVE\",\n name: chain.nativeCurrency?.name ?? chain.nativeCurrency?.symbol,\n decimals: chain.nativeCurrency?.decimals ?? 18,\n balance: \"0\",\n });\n }\n\n return Array.from(map.values()).sort((a, b) => {\n try {\n return Number(BigInt(b.balance) - BigInt(a.balance));\n } catch {\n return 0;\n }\n });\n}\n\nfunction normalizeStreamChunk(\n chunk: RawBalanceChunk\n): WalletAddressBalanceWrapper[] {\n return Array.isArray(chunk) ? chunk : [chunk];\n}\n\nfunction mergeBalanceWrappers(\n current: WalletAddressBalanceWrapper[],\n incoming: WalletAddressBalanceWrapper[]\n): WalletAddressBalanceWrapper[] {\n const merged = new Map<string, WalletAddressBalanceWrapper>();\n\n for (const item of current) {\n merged.set(item.chain_id, item);\n }\n\n for (const item of incoming) {\n const existing = merged.get(item.chain_id);\n if (!existing) {\n merged.set(item.chain_id, item);\n continue;\n }\n\n const balancesByKey = new Map<string, BalanceRow>();\n for (const row of existing.balances ?? []) {\n balancesByKey.set(`${row.contract ?? row.address ?? row.symbol}`, row);\n }\n for (const row of item.balances ?? []) {\n balancesByKey.set(`${row.contract ?? row.address ?? row.symbol}`, row);\n }\n\n merged.set(item.chain_id, {\n ...existing,\n ...item,\n balances: Array.from(balancesByKey.values()),\n count: item.count ?? existing.count,\n });\n }\n\n return Array.from(merged.values());\n}\n\nasync function parseStreamingBalances(\n response: Response,\n address: string,\n options: BalanceStreamOptions = {}\n): Promise<AsyncGenerator<WalletAddressBalanceWrapper[], void, void>> {\n if (!response.body) {\n throw new Error(\"balances stream: empty response body\");\n }\n\n const decoder = new TextDecoder();\n const reader = response.body.getReader();\n\n async function* stream(): AsyncGenerator<\n WalletAddressBalanceWrapper[],\n void,\n void\n > {\n let buffer = \"\";\n\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const frames = buffer.split(/\\r?\\n/);\n buffer = frames.pop() ?? \"\";\n\n for (const frame of frames) {\n const trimmed = frame.trim();\n if (!trimmed) continue;\n\n try {\n const chunk = normalizeStreamChunk(\n JSON.parse(trimmed) as RawBalanceChunk\n );\n emitBalanceStreamChunk(address, chunk.length);\n yield chunk;\n } catch (error) {\n if (options.strict) {\n throw error;\n }\n }\n }\n }\n\n const tail = buffer.trim();\n if (tail) {\n const chunk = normalizeStreamChunk(JSON.parse(tail) as RawBalanceChunk);\n emitBalanceStreamChunk(address, chunk.length);\n yield chunk;\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n return stream();\n}\n\n/** Map chain reference -> backend chain_key and return enriched balances */\nexport async function getBalances(\n chainRef: string | number,\n address: string\n): Promise<BalanceRow[]> {\n const reg = await ensureRegistry();\n const chain = reg.chain(chainRef);\n if (!chain) return [];\n\n const trimmedAddress = address.trim();\n const validation = validateAddressForChain(trimmedAddress, chain);\n if (!validation.isValid) return [];\n\n const chainKey = chain.networkIdentifier ?? String(chain.chainId ?? chain.id);\n const cacheKey = [\n chainKey,\n trimmedAddress,\n chain.nativeCurrency?.symbol ?? \"\",\n chain.nativeCurrency?.decimals ?? \"\",\n normalizeChainType(chain) ?? \"\",\n ].join(\":\");\n const cached = balanceCache.get(cacheKey);\n if (cached) return cached;\n\n const url = `${apiBase()}/v1/data/wallets/${encodeURIComponent(chainKey)}/${trimmedAddress}/balances`;\n const response = await fetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n headers: jsonHeaders(),\n });\n if (!response.ok) throw new Error(`balances: HTTP ${response.status}`);\n const json = await response.json();\n const rows: RawBalanceRow[] = Array.isArray(json) ? json : (json.data ?? []);\n const normalized = normalizeRows(rows, chain, trimmedAddress, reg);\n balanceCache.set(cacheKey, normalized);\n return normalized;\n}\n\nexport async function getBalancesByAddress(\n address: string,\n opts?: BalanceStreamOptions\n): Promise<WalletAddressBalanceWrapper[]> {\n if (opts?.stream && TrustwareConfigStore.get().features.balanceStreaming) {\n const merged: WalletAddressBalanceWrapper[] = [];\n for await (const chunk of getBalancesByAddressStream(address, opts)) {\n const next = mergeBalanceWrappers(merged, chunk);\n merged.splice(0, merged.length, ...next);\n }\n return merged;\n }\n\n const url = `${apiBase()}/data/balances/${address}`;\n const r = await rateLimitedFetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n headers: jsonHeaders(),\n });\n if (!r.ok) throw new Error(`balances: HTTP ${r.status}`);\n const j = await r.json();\n return Array.isArray(j) ? j : (j.results ?? []);\n}\n\nexport async function* getBalancesByAddressStream(\n address: string,\n opts: BalanceStreamOptions = {}\n): AsyncGenerator<WalletAddressBalanceWrapper[], void, void> {\n if (!TrustwareConfigStore.get().features.balanceStreaming) {\n yield await getBalancesByAddress(address);\n return;\n }\n\n const url = `${apiBase()}/data/balances/${address}?stream=1`;\n\n try {\n const response = await rateLimitedFetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n headers: jsonHeaders({\n Accept: \"application/x-ndjson, application/json\",\n }),\n signal: opts.signal,\n });\n\n if (!response.ok) {\n throw new Error(`balances stream: HTTP ${response.status}`);\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n const payload = await response.json();\n yield Array.isArray(payload) ? payload : (payload.results ?? []);\n return;\n }\n\n const stream = await parseStreamingBalances(response, address, opts);\n for await (const chunk of stream) {\n yield chunk;\n }\n } catch (error) {\n emitBalanceStreamFallback(address, error);\n yield await getBalancesByAddress(address);\n }\n}\n\nlet _registry: Registry | undefined;\nasync function ensureRegistry(): Promise<Registry> {\n if (!_registry) {\n _registry = new Registry(apiBase());\n }\n await _registry.ensureLoaded();\n return _registry;\n}\n","import type { BuildRouteResult } from \"../types\";\nimport type { ChainDef } from \"../types\";\nimport { walletManager } from \"../wallets/\";\nimport {\n buildRoute,\n submitReceipt,\n pollStatus,\n isEvmTxRequest,\n isSerializedSolanaTxRequest,\n} from \"./routes\";\n\nfunction backendChainId(chain?: ChainDef, fallback?: number | string): string {\n const preferred = chain?.networkIdentifier ?? chain?.chainId ?? chain?.id;\n return String(preferred ?? fallback ?? \"\");\n}\n\nfunction isUserRejected(e: unknown): boolean {\n const code =\n (e as Record<string, unknown>)?.code ??\n ((e as Record<string, Record<string, unknown>>)?.data?.code as number);\n if (code === 4001) return true;\n const msg = String((e as Error)?.message || e)?.toLowerCase?.() || \"\";\n return msg.includes(\"user rejected\") || msg.includes(\"user denied\");\n}\n\nexport async function sendRouteTransaction(\n b: BuildRouteResult,\n fallbackChainId?: number | string\n): Promise<string> {\n const w = walletManager.wallet;\n if (!w) throw new Error(\"Trustware.wallet not configured\");\n\n const txReq = b.txReq;\n if (isEvmTxRequest(txReq)) {\n if (w.ecosystem !== \"evm\") {\n throw new Error(\"An EVM wallet is required for this route\");\n }\n\n const to = (txReq.to ?? txReq.target) as `0x${string}`;\n const data = txReq.data as `0x${string}`;\n const value = txReq.value ? BigInt(txReq.value) : 0n;\n const target = Number(txReq.chainId ?? fallbackChainId);\n\n if (Number.isFinite(target)) {\n const current = await w.getChainId();\n if (current !== target) {\n try {\n await w.switchChain(target);\n } catch {\n // switchChain failed/skipped — non-fatal\n }\n }\n }\n\n if (w.type === \"eip1193\") {\n const from = await w.getAddress();\n const hexValue = value ? `0x${value.toString(16)}` : \"0x0\";\n const params: Record<string, unknown> = {\n from,\n to,\n data,\n value: hexValue,\n };\n if (Number.isFinite(target)) {\n params.chainId = `0x${target.toString(16)}`;\n }\n\n const hash = await w.request({\n method: \"eth_sendTransaction\",\n params: [params],\n });\n return hash as string;\n }\n\n const response = await w.sendTransaction({\n to,\n data,\n value,\n chainId: Number.isFinite(target) ? target : undefined,\n });\n return response.hash as string;\n }\n\n if (isSerializedSolanaTxRequest(txReq)) {\n if (w.ecosystem !== \"solana\") {\n throw new Error(\"A Solana wallet is required for this route\");\n }\n\n const { Registry } = await import(\"../registry\");\n const { apiBase } = await import(\"./http\");\n const registry = new Registry(apiBase());\n await registry.ensureLoaded();\n\n const chain = registry.chain(\n String(fallbackChainId ?? txReq.chainId ?? \"\")\n );\n return w.sendSerializedTransaction(\n txReq.data,\n backendChainId(chain, fallbackChainId ?? txReq.chainId)\n );\n }\n\n throw new Error(\"Invalid route transaction payload\");\n}\n\nexport async function runTopUp(params: {\n fromChain?: string;\n toChain?: string;\n fromToken?: string;\n toToken?: string;\n toAddress?: string;\n fromAmount: string | number;\n}) {\n const w = walletManager.wallet;\n if (!w) throw new Error(\"Trustware.wallet not configured\");\n\n const { Registry } = await import(\"../registry\");\n const { apiBase } = await import(\"./http\");\n\n const reg = new Registry(apiBase());\n await reg.ensureLoaded();\n\n const fromAddress = await w.getAddress();\n const currentChainRef =\n w.ecosystem === \"evm\"\n ? String(await w.getChainId())\n : ((await w.getChainKey?.()) ?? \"solana-mainnet-beta\");\n const originalChain =\n w.ecosystem === \"evm\" ? await w.getChainId() : undefined;\n\n const fromChain = params.fromChain ?? currentChainRef;\n\n const { TrustwareConfigStore } = await import(\"../config/store\");\n const cfg = TrustwareConfigStore.get();\n const toChain = params.toChain ?? String(cfg.routes.toChain);\n\n const fromToken =\n reg.resolveToken(\n fromChain,\n params.fromToken ?? (cfg.routes.fromToken as string) ?? undefined\n ) ?? params.fromToken;\n const toToken =\n reg.resolveToken(\n toChain,\n params.toToken ?? (cfg.routes.toToken as string) ?? undefined\n ) ?? params.toToken;\n\n if (!fromToken || !toToken) {\n throw new Error(\"Unable to resolve route tokens\");\n }\n\n try {\n const build = await buildRoute({\n fromChain,\n toChain,\n fromToken,\n toToken,\n fromAmount: String(params.fromAmount),\n fromAddress,\n toAddress:\n params.toAddress ??\n cfg.routes.toAddress ??\n (cfg.routes.fromAddress as string | undefined) ??\n fromAddress,\n slippage: cfg.routes.defaultSlippage,\n });\n\n const hash = await sendRouteTransaction(build, fromChain);\n await submitReceipt(build.intentId, hash);\n return await pollStatus(build.intentId);\n } catch (e: unknown) {\n if (isUserRejected(e)) throw new Error(\"Transaction cancelled by user\");\n throw e;\n } finally {\n try {\n if (\n w.ecosystem === \"evm\" &&\n originalChain &&\n originalChain !== Number(fromChain)\n ) {\n await w.switchChain(originalChain);\n }\n } catch {\n // switch back skipped — non-fatal\n }\n }\n}\n","import { useState, useEffect, useMemo } from \"react\";\nimport { getSharedRegistry } from \"./registryClient\";\nimport type { ChainDef } from \"../types\";\nimport {\n canonicalChainKeyForLink,\n canonicalSeiChainKey,\n normalizeChainType,\n} from \"src/widget/helpers/chainHelpers\";\n\nexport interface UseChainsResult {\n /** All available chains */\n chains: ChainDef[];\n /** Popular/featured chains (Ethereum, Polygon, Base) */\n popularChains: ChainDef[];\n /** Other chains (not in popular list) */\n otherChains: ChainDef[];\n /** Whether chains are currently loading */\n isLoading: boolean;\n /** Error message if loading failed */\n error: string | null;\n\n chainMap: Map<string, ChainDef>;\n}\n\n/** Chain IDs for popular chains */\nconst POPULAR_CHAIN_IDS = new Set([\n 1, // Ethereum Mainnet\n 137, // Polygon\n 8453, // Base\n]);\n\nfunction filterSupportedChains(chains: ChainDef[]): ChainDef[] {\n const supportedChainTypes = new Set([\"evm\", \"solana\", \"cosmos\", \"bitcoin\"]);\n return chains.filter((chain) => {\n const chainType = normalizeChainType(chain);\n if (!chainType) return false;\n if (!supportedChainTypes.has(chainType)) {\n return false;\n }\n if (chainType === \"evm\") {\n // hide none working chains for now [Hedera]\n const evmKey = canonicalChainKeyForLink(chain);\n // console.log(\n // \"Checking EVM chain:\",\n // chain.chainId,\n // \"canonical key:\",\n // evmKey\n // );\n const disabledEvmChains = new Set([\"hedera\", \"295\"]);\n if (evmKey && disabledEvmChains.has(evmKey)) {\n return false;\n }\n }\n if (chainType === \"cosmos\") {\n const seiKey = canonicalSeiChainKey(chain.chainId ?? chain.id);\n if (seiKey !== \"sei\" && seiKey !== \"pacific-1\") {\n return false;\n }\n }\n // hide bitcoin for now until we have a better address resoultion for btc maybe wait for squid. or use lifi not sure yet\n if (chainType === \"bitcoin\") {\n return false;\n }\n return true;\n });\n}\n\n/**\n * Hook to load available chains from the registry.\n * Returns chains split into popular and other categories.\n */\nexport function useChains(): UseChainsResult {\n const [chains, setChains] = useState<ChainDef[]>([]);\n const [chainMap, setChainMap] = useState<Map<string, ChainDef>>(new Map());\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const registry = getSharedRegistry();\n\n useEffect(() => {\n if (chains.length > 0) return;\n\n let cancelled = false;\n\n const loadChains = async () => {\n try {\n setIsLoading(true);\n setError(null);\n\n await registry.ensureChainsLoaded();\n\n if (cancelled) return;\n\n // Filter and sort chains\n const loadedChains = registry.chains();\n // .filter((chain) => chain.visible !== false);\n // .filter((chain) => {\n // // Only include EVM chains\n // const type = (chain.type ?? chain.chainType)\n // ?.toString()\n // .toLowerCase();\n // return !type || type === \"evm\";\n // })\n // .sort((a, b) =>\n // resolveChainLabel(a).localeCompare(resolveChainLabel(b))\n // );\n const supportedChains = filterSupportedChains(loadedChains);\n const chainMap: Map<string, ChainDef> = new Map(\n supportedChains.map((chain) => [\n (chain.chainId ?? chain.id) as string,\n chain,\n ])\n );\n\n setChainMap(chainMap);\n\n setChains(supportedChains);\n } catch (err) {\n if (!cancelled) {\n const message =\n err instanceof Error ? err.message : \"Failed to load chains\";\n setError(message);\n setChains([]);\n }\n } finally {\n if (!cancelled) {\n setIsLoading(false);\n }\n }\n };\n\n void loadChains();\n\n return () => {\n cancelled = true;\n };\n }, [registry, chains.length]);\n\n // Split chains into popular and other\n const { popularChains, otherChains } = useMemo(() => {\n const popular: ChainDef[] = [];\n const other: ChainDef[] = [];\n\n for (const chain of chains) {\n const chainId = Number(chain.chainId ?? chain.id);\n if (POPULAR_CHAIN_IDS.has(chainId)) {\n popular.push(chain);\n } else {\n other.push(chain);\n }\n }\n\n // Sort popular chains by the order in POPULAR_CHAIN_IDS\n const popularOrder = [1, 137, 8453];\n popular.sort((a, b) => {\n const aId = Number(a.chainId ?? a.id);\n const bId = Number(b.chainId ?? b.id);\n return popularOrder.indexOf(aId) - popularOrder.indexOf(bId);\n });\n\n return { popularChains: popular, otherChains: other };\n }, [chains]);\n\n return {\n chains,\n chainMap,\n popularChains,\n otherChains,\n isLoading,\n error,\n };\n}\n","import { TrustwareConfigStore } from \"../config\";\nimport { Registry } from \"../registry\";\nimport { apiBase } from \"./http\";\n\nconst registryCache = new Map<string, Registry>();\n\nfunction registryCacheKey(): string {\n const base = apiBase();\n const apiKey = TrustwareConfigStore.peek()?.apiKey ?? \"__uninitialized__\";\n return `${base}::${apiKey}`;\n}\n\nexport function getSharedRegistry(): Registry {\n const key = registryCacheKey();\n const existing = registryCache.get(key);\n if (existing) {\n return existing;\n }\n\n const registry = new Registry(apiBase());\n registryCache.set(key, registry);\n return registry;\n}\n","import type { ChainDef } from \"../../types\";\n\nexport function normalizeChainKey(id: string | number | null): string {\n if (id === undefined || id === null) return \"\";\n return String(id).trim().toLowerCase();\n}\n\nexport const NATIVE_EVM = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\" as const;\nexport const NATIVE_SOLANA =\n \"So11111111111111111111111111111111111111111\" as const;\n\ntype TokenAddressLookupEntry = {\n address: string;\n symbol: string;\n chainId: string | number;\n};\n\nexport function getNativeTokenAddress(chainType?: ChainDef[\"type\"] | null) {\n const normalized = chainType?.toLowerCase?.();\n return normalized === \"solana\" ? NATIVE_SOLANA : NATIVE_EVM;\n}\n\nexport function isSolanaNativeTokenAlias(address?: string | null) {\n if (!address) return false;\n const trimmed = address.trim();\n if (!trimmed) return false;\n return trimmed === NATIVE_SOLANA || trimmed.toLowerCase() === NATIVE_EVM;\n}\n\nexport function parseDecimalToWei(\n input: string,\n decimals: number\n): bigint | null {\n // accepts strings like \"1\", \"1.\", \".5\", \"0.1234\"\n if (!input?.trim()) return null;\n const s = input.trim();\n if (!/^\\d*\\.?\\d*$/.test(s)) return null;\n const [intPartRaw, fracRaw = \"\"] = s.split(\".\");\n const intPart = intPartRaw.length ? BigInt(intPartRaw) : 0n;\n const frac = (fracRaw + \"0\".repeat(decimals)).slice(0, decimals); // pad/right-trim\n const fracPart = frac ? BigInt(frac) : 0n;\n const base = 10n ** BigInt(decimals);\n return intPart * base + fracPart;\n}\n\nconst CHAIN_TYPE_ALIASES: Record<string, SquidChainType> = {\n btc: \"bitcoin\",\n bitcoin: \"bitcoin\",\n sei: \"cosmos\",\n \"pacific-1\": \"cosmos\",\n};\n\nfunction inferChainTypeFromValue(\n normalized: string\n): SquidChainType | undefined {\n if (!normalized) return undefined;\n\n const aliased = CHAIN_TYPE_ALIASES[normalized];\n if (aliased) return aliased;\n\n if (\n normalized === \"evm\" ||\n normalized === \"solana\" ||\n normalized === \"cosmos\" ||\n normalized === \"bitcoin\"\n ) {\n return normalized;\n }\n\n if (/^eip155:\\d+$/.test(normalized) || /^\\d+$/.test(normalized)) {\n return \"evm\";\n }\n\n if (normalized.startsWith(\"solana:\") || normalized.includes(\"solana\")) {\n return \"solana\";\n }\n\n if (\n normalized.startsWith(\"cosmos:\") ||\n normalized.startsWith(\"sei:\") ||\n normalized === \"sei-evm\"\n ) {\n return \"cosmos\";\n }\n\n return undefined;\n}\n\nexport type SquidChainType = \"evm\" | \"cosmos\" | \"solana\" | \"btc\" | string;\n\nexport function normalizeChainType(\n chain?: ChainDef | SquidChainType | string | null\n): SquidChainType | undefined {\n if (!chain) return undefined;\n const raw =\n typeof chain === \"string\"\n ? chain\n : (chain.type ??\n chain.chainType ??\n chain.networkIdentifier ??\n chain.chainId ??\n chain.id ??\n chain.networkName ??\n chain.axelarChainName);\n if (!raw) return undefined;\n const normalized = String(raw).trim().toLowerCase();\n return inferChainTypeFromValue(normalized) ?? normalized;\n}\n\nexport function canonicalChainKeyForLink(chain: ChainDef): string {\n const seiKey = canonicalSeiChainKey(chain.chainId ?? chain.id);\n if (seiKey) return seiKey;\n return normalizeChainKey(\n chain.networkIdentifier ??\n chain.axelarChainName ??\n chain.id ??\n chain.chainId ??\n chain.networkName\n );\n}\n\nconst SEI_EVM_CHAIN_ID = \"1329\";\nconst SEI_COSMOS_CHAIN_ID = \"pacific-1\";\n\nexport function canonicalSeiChainKey(\n chainId: ChainDef[\"chainId\"] | ChainDef[\"id\"] | null\n): string | null {\n const normalized = normalizeChainKey(chainId as string | number | null);\n if (!normalized) return null;\n if (normalized === SEI_EVM_CHAIN_ID) return \"sei-evm\";\n if (normalized === SEI_COSMOS_CHAIN_ID) return \"sei\";\n return null;\n}\n\nexport function isZeroAddrLike(\n a?: string | null,\n chainType?: ChainDef[\"type\"] | null\n) {\n if (!a) return true;\n if (!chainType) return false;\n const s = normalizeAddress(a, chainType);\n return (\n s === normalizeAddress(getNativeTokenAddress(chainType), chainType) ||\n s === \"0x0000000000000000000000000000000000000000\"\n );\n}\n\nexport function normalizeAddress(\n address: string,\n chainType?: ChainDef[\"type\"]\n) {\n if (chainType?.toLowerCase?.() === \"solana\") {\n const trimmed = address.trim();\n if (isSolanaNativeTokenAlias(trimmed)) {\n return NATIVE_SOLANA;\n }\n return trimmed;\n }\n return address.toLowerCase();\n}\n\nexport function isNativeTokenAddress(\n address?: string | null,\n chainType?: ChainDef[\"type\"] | null\n) {\n if (!address) return false;\n if (!chainType) return false;\n return (\n normalizeAddress(address, chainType) ===\n normalizeAddress(getNativeTokenAddress(chainType), chainType)\n );\n}\n\n/**\n * Canonicalizes token identifiers across indexer and registry sources,\n * with cosmos native denom support (e.g. Sei \"usei\").\n */\nexport function canonicalTokenAddressForChain(\n chain: ChainDef,\n address?: string,\n chainTokens: TokenAddressLookupEntry[] = []\n): string {\n const chainType = normalizeChainType(chain);\n const rawAddress = (address ?? \"\").trim();\n\n // Preserve SPL mint addresses; only collapse native SOL aliases for identity.\n if (chainType === \"solana\") return normalizeAddress(rawAddress, \"solana\");\n\n if (chainType === \"cosmos\") {\n const chainIdKey = normalizeChainKey(chain.chainId ?? chain.id ?? \"\");\n const nativeSymbol = chain.nativeCurrency?.symbol?.toUpperCase?.();\n const nativeFromRegistry = chainTokens.find(\n (token) =>\n normalizeChainKey(token.chainId) === chainIdKey &&\n token.symbol?.toUpperCase?.() === nativeSymbol\n );\n const nativeDenom = (nativeFromRegistry?.address ?? \"usei\").toLowerCase();\n\n if (rawAddress.toLowerCase() === NATIVE_EVM) {\n return nativeDenom;\n }\n\n return rawAddress.toLowerCase();\n }\n\n const lowerAddress = rawAddress.toLowerCase();\n if (lowerAddress === \"0x0000000000000000000000000000000000000000\") {\n return NATIVE_EVM;\n }\n return lowerAddress;\n}\n","import { useState, useEffect, useMemo } from \"react\";\nimport { getSharedRegistry } from \"./registryClient\";\nimport type { TokenDef } from \"../types\";\nimport type { Token } from \"../widget/context/DepositContext\";\nimport { useChains } from \"./useChains\";\nimport { sortTokensByPopularity } from \"../widget/helpers/tokenPopularity\";\nimport { TrustwareConfigStore } from \"../config/store\";\n\nconst DEFAULT_PAGE_LIMIT = 100;\n\nexport interface UseTokensResult {\n /** All available tokens for the selected chain */\n tokens: Token[];\n /** Filtered tokens based on search query */\n filteredTokens: Token[];\n /** Whether tokens are currently loading */\n isLoading: boolean;\n /** Error message if loading failed */\n error: string | null;\n /** Current search query */\n searchQuery: string;\n /** Set the search query to filter tokens */\n setSearchQuery: (query: string) => void;\n /** Whether more tokens can be loaded for the active query */\n hasNextPage: boolean;\n /** Load the next token page when pagination is enabled */\n loadMore: () => Promise<void>;\n /** Whether an additional page request is in flight */\n isLoadingMore: boolean;\n}\n\nfunction mapTokenDefToToken(tokenDef: TokenDef): Token {\n return {\n address: tokenDef.address,\n chainId: tokenDef.chainId,\n symbol: tokenDef.symbol,\n name: tokenDef.name,\n decimals: tokenDef.decimals,\n iconUrl: tokenDef.logoURI,\n logoURI: tokenDef.logoURI,\n balance: undefined,\n usdPrice: tokenDef.usdPrice,\n };\n}\n\nfunction dedupeTokens(tokens: Token[]): Token[] {\n const byKey = new Map<string, Token>();\n for (const token of tokens) {\n byKey.set(`${token.chainId}:${token.address.toLowerCase()}`, token);\n }\n return Array.from(byKey.values());\n}\n\nexport function useTokens(\n chainId: string | number | null | undefined\n): UseTokensResult {\n const [tokens, setTokens] = useState<Token[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [searchQuery, setSearchQuery] = useState(\"\");\n const [nextCursor, setNextCursor] = useState<string | undefined>();\n const [hasNextPage, setHasNextPage] = useState(false);\n\n const registry = getSharedRegistry();\n const { chainMap } = useChains();\n const tokensPaginationEnabled =\n TrustwareConfigStore.peek()?.features.tokensPagination ?? false;\n const normalizedSearchQuery = searchQuery.trim();\n const queryDependency = tokensPaginationEnabled ? normalizedSearchQuery : \"\";\n\n useEffect(() => {\n setSearchQuery(\"\");\n setError(null);\n setTokens([]);\n setNextCursor(undefined);\n setHasNextPage(false);\n }, [chainId]);\n\n useEffect(() => {\n if (chainId === undefined || chainMap.size === 0) {\n setIsLoading(false);\n setIsLoadingMore(false);\n return;\n }\n\n let cancelled = false;\n\n const loadInitialTokens = async () => {\n try {\n setIsLoading(true);\n setError(null);\n setTokens([]);\n setNextCursor(undefined);\n setHasNextPage(false);\n\n if (chainId === null || !tokensPaginationEnabled) {\n await registry.ensureLoaded();\n\n if (cancelled) return;\n\n const tokenDefs =\n chainId === null ? registry.allTokens() : registry.tokens(chainId);\n const filtered = tokenDefs.filter((item) =>\n chainMap.has(item.chainId.toString())\n );\n setTokens(filtered.map(mapTokenDefToToken));\n return;\n }\n\n const page = await registry.tokensPage(chainId, {\n q: queryDependency || undefined,\n limit: DEFAULT_PAGE_LIMIT,\n });\n\n if (cancelled) return;\n\n const filtered = page.data.filter((item) =>\n chainMap.has(item.chainId.toString())\n );\n setTokens(filtered.map(mapTokenDefToToken));\n setNextCursor(page.pageInfo.nextCursor);\n setHasNextPage(page.pageInfo.hasNextPage);\n } catch (err) {\n if (!cancelled) {\n const message =\n err instanceof Error ? err.message : \"Failed to load tokens\";\n setError(message);\n setTokens([]);\n setNextCursor(undefined);\n setHasNextPage(false);\n }\n } finally {\n if (!cancelled) {\n setIsLoading(false);\n }\n }\n };\n\n void loadInitialTokens();\n\n return () => {\n cancelled = true;\n };\n }, [chainId, registry, chainMap, queryDependency, tokensPaginationEnabled]);\n\n const loadMore = async () => {\n if (\n chainId == null ||\n !tokensPaginationEnabled ||\n !hasNextPage ||\n !nextCursor ||\n isLoadingMore\n ) {\n return;\n }\n\n try {\n setIsLoadingMore(true);\n const page = await registry.tokensPage(chainId, {\n cursor: nextCursor,\n q: queryDependency || undefined,\n limit: DEFAULT_PAGE_LIMIT,\n });\n const filtered = page.data.filter((item) =>\n chainMap.has(item.chainId.toString())\n );\n setTokens((current) =>\n dedupeTokens([...current, ...filtered.map(mapTokenDefToToken)])\n );\n setNextCursor(page.pageInfo.nextCursor);\n setHasNextPage(page.pageInfo.hasNextPage);\n } catch (err) {\n const message =\n err instanceof Error ? err.message : \"Failed to load more tokens\";\n setError(message);\n } finally {\n setIsLoadingMore(false);\n }\n };\n\n const filteredTokens = useMemo(() => {\n const query = searchQuery.toLowerCase().trim();\n const source =\n query.length === 0 || tokensPaginationEnabled\n ? tokens\n : tokens.filter(\n (token: Token) =>\n token.symbol.toLowerCase().includes(query) ||\n token.name.toLowerCase().includes(query) ||\n token.address.toLowerCase().includes(query)\n );\n\n return sortTokensByPopularity(source);\n }, [tokens, searchQuery, tokensPaginationEnabled]);\n\n return {\n tokens,\n filteredTokens,\n isLoading,\n error,\n searchQuery,\n setSearchQuery,\n hasNextPage,\n loadMore,\n isLoadingMore,\n };\n}\n","{\n \"ethereum\": 1,\n \"1\": 1,\n \"arbitrum\": 2,\n \"arbitrum-one\": 2,\n \"42161\": 2,\n \"base\": 3,\n \"8453\": 3,\n \"bsc\": 4,\n \"binance\": 4,\n \"binance-smart-chain\": 4,\n \"56\": 4,\n \"solana\": 5,\n \"solana-mainnet-beta\": 5,\n \"avalanche\": 6,\n \"avalanche-c-chain\": 6,\n \"43114\": 6,\n \"tron\": 7,\n \"728126428\": 7,\n \"sui\": 8,\n \"137\": 9,\n \"polygon\": 9,\n \"polygon-pos\": 9,\n \"optimism\": 10,\n \"10\": 10,\n \"bitcoin\": 11,\n \"cosmoshub\": 12,\n \"cosmos\": 12,\n \"osmosis\": 13,\n \"sei\": 14,\n \"sei-evm\": 14,\n \"pacific-1\": 14,\n \"1329\": 14,\n \"mantle\": 15,\n \"5000\": 15,\n \"linea\": 16,\n \"59144\": 16,\n \"zksync\": 17,\n \"zksync-era\": 17,\n \"324\": 17,\n \"blast\": 18,\n \"81457\": 18,\n \"scroll\": 19,\n \"534352\": 19,\n \"sonic\": 20,\n \"146\": 20\n}\n","import chainPopularityMap from \"../data/chainPopularity.json\";\nimport { normalizeChainKey } from \"./chainHelpers\";\n\ntype ChainPopularityLookup = Record<string, number>;\n\nconst popularityByKey = chainPopularityMap as ChainPopularityLookup;\n\nexport type ChainPopularityInput = {\n chainId?: string | number | null;\n networkIdentifier?: string | number | null;\n networkName?: string | number | null;\n axelarChainName?: string | number | null;\n};\n\nexport function getChainPopularityRank(\n chain: ChainPopularityInput | null | undefined\n): number | null {\n if (!chain) return null;\n\n const aliases = [\n chain.chainId,\n chain.networkIdentifier,\n chain.networkName,\n chain.axelarChainName,\n ];\n\n for (const alias of aliases) {\n const key = normalizeChainKey(alias ?? null);\n if (!key) continue;\n\n const rank = popularityByKey[key];\n if (typeof rank === \"number\") {\n return rank;\n }\n }\n\n return null;\n}\n","import { getChainPopularityRank } from \"./chainPopularity\";\n\nexport interface TokenPopularitySortable {\n symbol?: string;\n name?: string;\n address?: string;\n balance?: string;\n chainId?: string | number;\n}\n\n/**\n * Mirrors frontend popularity ranking by symbol and well-known contracts.\n */\nconst POPULAR_TOKEN_SYMBOLS = new Set(\n [\n \"USDC\",\n \"USDC.E\",\n \"USDBC\",\n \"USDT\",\n \"DAI\",\n \"ETH\",\n \"WETH\",\n \"WBTC\",\n \"BTC\",\n \"SOL\",\n \"MATIC\",\n ].map((symbol) => symbol.toUpperCase())\n);\n\nconst POPULAR_TOKEN_CONTRACTS = new Set([\n \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\", // USDC (Ethereum)\n \"0xdac17f958d2ee523a2206206994597c13d831ec7\", // USDT (Ethereum)\n \"0x6b175474e89094c44da98b954eedeac495271d0f\", // DAI (Ethereum)\n \"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913\", // USDC (Base)\n \"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359\", // USDC (Polygon)\n \"0x2791bca1f2de4661ed88a30c99a7a9449aa84174\", // USDC.e (Polygon)\n \"0xc2132d05d31c914a87c6611c10748aeb04b58e8f\", // USDT (Polygon)\n \"0xaf88d065e77c8cc2239327c5edb3a432268e5831\", // USDC (Arbitrum)\n \"0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9\", // USDT (Arbitrum)\n \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\", // EVM native token marker\n \"so11111111111111111111111111111111111111112\", // Wrapped SOL\n]);\n\nfunction normalizeSymbol(symbol?: string): string {\n return (symbol ?? \"\").trim().toUpperCase();\n}\n\nfunction normalizeAddress(address?: string): string {\n return (address ?? \"\").trim().toLowerCase();\n}\n\nfunction hasPositiveBalance(balance?: string): boolean {\n if (!balance) return false;\n const trimmed = balance.trim();\n if (!trimmed) return false;\n\n if (/^[+-]?\\d+$/.test(trimmed)) {\n try {\n return BigInt(trimmed) > 0n;\n } catch {\n return false;\n }\n }\n\n if (/^[+-]?\\d*\\.\\d+$/.test(trimmed)) {\n const isNegative = trimmed.startsWith(\"-\");\n if (isNegative) return false;\n\n const normalized = trimmed.startsWith(\"+\") ? trimmed.slice(1) : trimmed;\n const [whole, fraction = \"\"] = normalized.split(\".\");\n const wholeInt = whole ? BigInt(whole) : 0n;\n if (wholeInt > 0n) return true;\n return /[1-9]/.test(fraction);\n }\n\n const asNumber = Number(trimmed);\n return Number.isFinite(asNumber) && asNumber > 0;\n}\n\nexport function isPopularToken(token: TokenPopularitySortable): boolean {\n const normalizedSymbol = normalizeSymbol(token.symbol);\n const normalizedAddress = normalizeAddress(token.address);\n\n return (\n POPULAR_TOKEN_SYMBOLS.has(normalizedSymbol) ||\n POPULAR_TOKEN_CONTRACTS.has(normalizedAddress)\n );\n}\n\nfunction compareText(a?: string, b?: string): number {\n return (a ?? \"\").localeCompare(b ?? \"\", undefined, {\n sensitivity: \"base\",\n });\n}\n\nfunction getGroupRank(token: TokenPopularitySortable): number {\n const popular = isPopularToken(token);\n const positiveBalance = hasPositiveBalance(token.balance);\n\n if (popular && positiveBalance) return 0; // Group A\n if (popular && !positiveBalance) return 1; // Group B\n if (!popular && positiveBalance) return 2; // Group C\n return 3; // Group D\n}\n\nfunction compareChainPopularity(\n a: TokenPopularitySortable,\n b: TokenPopularitySortable\n): number {\n const rankA = getChainPopularityRank({ chainId: a.chainId });\n const rankB = getChainPopularityRank({ chainId: b.chainId });\n\n if (rankA !== null && rankB !== null && rankA !== rankB) {\n return rankA - rankB;\n }\n\n if (rankA !== null && rankB === null) return -1;\n if (rankA === null && rankB !== null) return 1;\n\n return 0;\n}\n\nexport function sortTokensByPopularity<T extends TokenPopularitySortable>(\n tokens: T[]\n): T[] {\n return tokens\n .map((token, index) => ({ token, index }))\n .sort((a, b) => {\n const rankDiff = getGroupRank(a.token) - getGroupRank(b.token);\n if (rankDiff !== 0) return rankDiff;\n\n const chainPopularityDiff = compareChainPopularity(a.token, b.token);\n if (chainPopularityDiff !== 0) return chainPopularityDiff;\n\n const symbolDiff = compareText(a.token.symbol, b.token.symbol);\n if (symbolDiff !== 0) return symbolDiff;\n\n const nameDiff = compareText(a.token.name, b.token.name);\n if (nameDiff !== 0) return nameDiff;\n\n const addressDiff = compareText(a.token.address, b.token.address);\n if (addressDiff !== 0) return addressDiff;\n\n // Stable deterministic tiebreaker for complete duplicates.\n return a.index - b.index;\n })\n .map(({ token }) => token);\n}\n","import { TrustwareErrorCode } from \"./errorCodes\";\n\nexport class TrustwareError extends Error {\n code: TrustwareErrorCode;\n userMessage?: string;\n cause?: unknown;\n\n constructor(params: {\n code: TrustwareErrorCode;\n message: string;\n userMessage?: string;\n cause?: unknown;\n }) {\n super(params.message);\n\n this.name = \"TrustwareError\";\n this.code = params.code;\n this.userMessage = params.userMessage;\n this.cause = params.cause;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n userMessage: this.userMessage,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAEa,kBACA,8BAEA,eASA;AAdb;AAAA;AAAA;AAEO,IAAM,mBAAmB;AACzB,IAAM,+BAA+B;AAErC,IAAM,gBAAsC;AAAA,MACjD,cAAc;AAAA,MACd,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,WAAW;AAAA,MACX,aAAa;AAAA,MACb,QAAQ;AAAA,IACV;AAEO,IAAM,mBAA4C;AAAA,MACvD,OAAO;AAAA,MACP,aAAa;AAAA,IACf;AAAA;AAAA;;;ACjBA,IA0Ja,sBAOA;AAjKb;AAAA;AAAA;AA0JO,IAAM,uBAA4C;AAAA,MACvD,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,aAAa;AAAA,MACb,sBAAsB;AAAA,IACxB;AAEO,IAAM,wBAA8C;AAAA,MACzD,kBAAkB;AAAA,MAClB,kBAAkB;AAAA,MAClB,gBAAgB;AAAA,IAClB;AAAA;AAAA;;;ACrKA,IAKa,UACA,aACA,UAEA,YAOA;AAhBb;AAAA;AAAA;AAKO,IAAM,WAAW;AACjB,IAAM,cAAsB;AAC5B,IAAM,WAAmB;AAEzB,IAAM,aAAa;AAOnB,IAAM,2BAA2B;AAAA;AAAA;;;ACIxC,SAAS,2BACP,OACyC;AAEzC,MAAI,OAAO,SAAU,QAAO;AAG5B,QAAM,YAAY,OAAO,aAAa;AAEtC,SAAO;AAAA,IACL;AAAA,IACA,QAAQ,OAAO,UAAU,CAAC,CAAC;AAAA;AAAA,IAC3B,gBAAgB,OAAO,kBAAkB;AAAA,MACvC;AAAA,MAAG;AAAA,MAAI;AAAA,MAAI;AAAA,MAAK;AAAA,MAAM;AAAA,MAAO;AAAA,IAC/B;AAAA;AAAA,IACA,UAAU;AAAA,MACR,MAAM,OAAO,UAAU,QAAQ;AAAA,MAC/B,a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;AACD,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,YAAuC;AACrC,WAAO,cAAc;AAAA,EACvB;AAAA,EAEA,cAAc;AACZ,WAAO,cAAc;AAAA,EACvB;AAAA,EAEA,uBACE,OACA;AACA,WAAO,cAAc,uBAAuB,KAAK;AAAA,EACnD;AAAA,EAEA,mBACE,SACA;AACA,kBAAc,mBAAmB,OAAO;AACxC,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,MAAM,aAA8B;AAClC,UAAM,IAAI,cAAc;AACxB,QAAI,CAAC,EAAG,OAAM,IAAI,MAAM,iCAAiC;AACzD,WAAO,EAAE,WAAW;AAAA,EACtB;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AACF;","names":["init_config","init_config","e","alphabet","alphabet","alphabet","TextDecoder","TextEncoder","isEvmAddress","fromResult","toResult","e","e","Registry","apiBase","TrustwareConfigStore","import_react","init_config","normalizeChainKey","CHAIN_TYPE_ALIASES","inferChainTypeFromValue","normalizeChainType","normalizeChainKey","normalizeChainType","chainMap","import_react","normalizeChainKey","normalizeAddress","filtered"]}
1
+ {"version":3,"sources":["../src/config/defaults.ts","../src/types/config.ts","../src/config/merge.ts","../src/config/store.ts","../src/constants.ts","../src/config/index.ts","../src/core/http.ts","../src/utils/chains.ts","../src/registry.ts","../src/core.ts","../src/core/index.ts","../src/wallets/eipWallets.ts","../src/wallets/solana.ts","../src/core/sdkRpc.ts","../src/wallets/adapters.ts","../src/wallets/connect.ts","../src/validation/address.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/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","../src/identity/index.ts","../src/wallets/manager.ts","../src/core/routes.ts","../src/core/balances.ts","../src/core/tx.ts","../src/core/useChains.ts","../src/core/registryClient.ts","../src/widget/helpers/chainHelpers.ts","../src/core/useTokens.ts","../src/widget/data/chainPopularity.json","../src/widget/helpers/chainPopularity.ts","../src/widget/helpers/tokenPopularity.ts","../src/errors/TrustwareError.ts"],"sourcesContent":["import { TrustwareWidgetTheme, TrustwareWidgetMessages } from \"../types/\";\n\nexport const DEFAULT_SLIPPAGE = 1;\nexport const DEFAULT_AUTO_DETECT_PROVIDER = false;\n\nexport const DEFAULT_THEME: TrustwareWidgetTheme = {\n primaryColor: \"#4F46E5\",\n secondaryColor: \"#6366F1\",\n backgroundColor: \"#FFFFFF\",\n textColor: \"#111827\",\n borderColor: \"#E5E7EB\",\n radius: 8,\n};\n\nexport const DEFAULT_MESSAGES: TrustwareWidgetMessages = {\n title: \"Trustware SDK\",\n description: \"Seamlessly bridge assets across chains with Trustware.\",\n};\n","import { TrustwareError } from \"src/errors/TrustwareError\";\nimport { TrustwareWidgetTheme, TrustwareWidgetMessages } from \"./theme\";\nimport { TrustwareEvent } from \"src/events/events\";\nimport { Transaction } from \"./routes\";\n\n/** WalletConnect configuration options (all optional - SDK has built-in defaults) */\nexport type WalletConnectConfig = {\n /** Override the built-in WalletConnect project ID (optional - SDK includes one) */\n projectId?: string;\n /** Chain IDs to support (defaults to [1] for Ethereum mainnet) */\n chains?: number[];\n /** Optional chain IDs (chains that can be switched to) */\n optionalChains?: number[];\n /** dApp metadata shown in wallet */\n metadata?: {\n name: string;\n description?: string;\n url: string;\n icons?: string[];\n };\n /** Custom relay URL (defaults to WalletConnect's relay) */\n relayUrl?: string;\n /** Whether to show our custom QR modal (default: true) */\n showQrModal?: boolean;\n /** Disable WalletConnect entirely (default: false) */\n disabled?: boolean;\n};\n\n/** Resolved WalletConnect config with defaults applied */\nexport type ResolvedWalletConnectConfig = {\n projectId: string;\n chains: number[];\n optionalChains: number[];\n metadata: {\n name: string;\n description: string;\n url: string;\n icons: string[];\n };\n relayUrl?: string;\n showQrModal: boolean;\n};\n\nexport type TrustwareConfigOptions = {\n apiKey: string; // Required API key for authentication\n routes: {\n toChain: string; // Default destination chain\n toToken: string; // Default destination token\n fromToken?: string; // Default source token (optional)\n fromAddress?: string; // Default source address (optional)\n toAddress?: string; // Default destination address (optional; can be updated later via Trustware.setDestinationAddress)\n defaultSlippage?: number; // Default slippage percentage (optional) defautts to 1\n routeType?: string; // Route type: \"swap\" | \"deposit\" | \"withdraw\" | \"cross\" (default: \"swap\")\n options?: {\n routeRefreshMs?: number; // Route refresh interval in milliseconds (optional)\n fixedFromAmount?: string | number;\n minAmountOut?: string | number;\n maxAmountOut?: string | number;\n };\n };\n autoDetectProvider?: boolean; // Whether to auto-detect wallet provider (optional, default: false.)\n theme?: TrustwareWidgetTheme; // Optional theme customization\n messages?: Partial<TrustwareWidgetMessages>; // Optional message customization\n retry?: RetryConfig; // Optional retry configuration for rate-limited requests\n walletConnect?: WalletConnectConfig; // Optional WalletConnect configuration\n features?: FeatureFlags; // Optional feature rollout controls\n\n onError?: (error: TrustwareError) => void;\n onSuccess?: (transaction: Transaction) => void;\n onEvent?: (event: TrustwareEvent) => void;\n};\n\nexport type ResolvedTrustwareConfig = {\n apiKey: string;\n routes: {\n toChain: string;\n toToken: string;\n fromToken?: string;\n fromAddress?: string;\n toAddress?: string;\n defaultSlippage: number; // resolved\n routeType: string; // resolved\n options: {\n routeRefreshMs?: number;\n fixedFromAmount?: string | number;\n minAmountOut?: string | number;\n maxAmountOut?: string | number;\n };\n };\n autoDetectProvider: boolean;\n theme: TrustwareWidgetTheme;\n messages: TrustwareWidgetMessages;\n retry: ResolvedRetryConfig;\n walletConnect?: ResolvedWalletConnectConfig | WalletConnectConfig | undefined;\n features: ResolvedFeatureFlags;\n onError?: (error: TrustwareError) => void;\n onSuccess?: (transaction: Transaction) => void;\n onEvent?: (event: TrustwareEvent) => void;\n};\n\nexport type FeatureFlags = {\n tokensPagination?: boolean;\n balanceStreaming?: boolean;\n shouldAllowGA4?: boolean;\n};\n\nexport type ResolvedFeatureFlags = {\n tokensPagination: boolean;\n balanceStreaming: boolean;\n shouldAllowGA4: boolean;\n};\n\nexport const DEFAULT_SLIPPAGE = 1; // Default slippage percentage\nexport const DEFAULT_AUTO_DETECT_PROVIDER = false; // Default auto-detect provider setting\n\n// Rate limit types for SDK rate limit handling\nexport type RateLimitInfo = {\n /** Maximum requests allowed in the current window */\n limit: number;\n /** Requests remaining in the current window */\n remaining: number;\n /** Unix timestamp when the rate limit window resets */\n reset: number;\n /** Seconds until rate limit resets (only present on 429 responses) */\n retryAfter?: number;\n};\n\nexport type RetryConfig = {\n /** Enable automatic retry on 429 responses (default: true). Note: This does NOT disable backend rate limits, only client-side retry behavior. */\n autoRetry?: boolean;\n /** Maximum number of retries on 429 (default: 3) */\n maxRetries?: number;\n /** Base delay in ms for exponential backoff (default: 1000) */\n baseDelayMs?: number;\n /** Callback when rate limit info is received from server */\n onRateLimitInfo?: (info: RateLimitInfo) => void;\n /** Callback when rate limit is hit (429 received) */\n onRateLimited?: (info: RateLimitInfo, retryCount: number) => void;\n /** Callback when remaining requests fall below threshold */\n onRateLimitApproaching?: (info: RateLimitInfo, threshold: number) => void;\n /** Threshold for onRateLimitApproaching callback (default: 5) */\n approachingThreshold?: number;\n};\n\nexport type ResolvedRetryConfig = {\n autoRetry: boolean;\n maxRetries: number;\n baseDelayMs: number;\n approachingThreshold: number;\n onRateLimitInfo?: (info: RateLimitInfo) => void;\n onRateLimited?: (info: RateLimitInfo, retryCount: number) => void;\n onRateLimitApproaching?: (info: RateLimitInfo, threshold: number) => void;\n};\n\nexport const DEFAULT_RETRY_CONFIG: ResolvedRetryConfig = {\n autoRetry: true,\n maxRetries: 3,\n baseDelayMs: 1000,\n approachingThreshold: 5,\n};\n\nexport const DEFAULT_FEATURE_FLAGS: ResolvedFeatureFlags = {\n tokensPagination: false,\n balanceStreaming: false,\n shouldAllowGA4: true,\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n TrustwareConfigOptions,\n ResolvedTrustwareConfig,\n} from \"../types/\";\nimport {\n DEFAULT_AUTO_DETECT_PROVIDER,\n DEFAULT_SLIPPAGE,\n DEFAULT_THEME,\n DEFAULT_MESSAGES,\n} from \"./defaults\";\nimport { DEFAULT_FEATURE_FLAGS, DEFAULT_RETRY_CONFIG } from \"../types/config\";\n// import { getUniversalConnector } from \"./walletconnect\";\n\n/**\n * Resolve WalletConnect config with built-in defaults.\n * WalletConnect is ENABLED by default - no user configuration required.\n */\n// function resolveWalletConnectConfig(\n// input?: WalletConnectConfig\n// ): ResolvedWalletConnectConfig | undefined {\n// // Allow users to explicitly disable WalletConnect\n// if (input?.disabled) return undefined;\n\n// // Use built-in project ID by default, allow override\n// const projectId = input?.projectId ?? WALLETCONNECT_PROJECT_ID;\n\n// return {\n// projectId,\n// chains: input?.chains ?? [1], // Default to Ethereum mainnet\n// optionalChains: input?.optionalChains ?? [\n// 1, 10, 56, 137, 8453, 42161, 43114,\n// ], // ETH, OP, BSC, Polygon, Base, Arbitrum, Avalanche\n// metadata: {\n// name: input?.metadata?.name ?? \"Trustware\",\n// description:\n// input?.metadata?.description ?? \"Cross-chain bridge & top-up\",\n// url: input?.metadata?.url ?? \"https://trustware.io\",\n// icons: input?.metadata?.icons ?? [\"https://app.trustware.io/icon.png\"],\n// },\n// relayUrl: input?.relayUrl,\n// showQrModal: input?.showQrModal ?? true,\n// };\n// }\n\n// tiny deep merge for plain objects\nfunction deepMerge<T extends Record<string, any>>(\n base: T,\n patch?: Partial<T>\n): T {\n if (!patch) return { ...base };\n const out: any = Array.isArray(base) ? [...(base as any)] : { ...base };\n for (const [k, v] of Object.entries(patch)) {\n if (v && typeof v === \"object\" && !Array.isArray(v)) {\n (out as any)[k] = deepMerge((base as any)[k] ?? {}, v as any);\n } else {\n (out as any)[k] = v;\n }\n }\n return out;\n}\n\nfunction normalizeSlippage(v: unknown): number {\n const n = Number(v);\n if (!Number.isFinite(n)) return DEFAULT_SLIPPAGE;\n // clamp sane range 0.01%..5% (0.0001..0.05)\n if (n <= 0) return DEFAULT_SLIPPAGE;\n if (n > 5) return 5;\n return n;\n}\n\nexport function resolveConfig(\n input: TrustwareConfigOptions\n): ResolvedTrustwareConfig {\n if (!input?.apiKey) {\n throw new Error(\"TrustwareConfig: 'apiKey' is required.\");\n }\n if (!input.routes?.toChain || !input.routes?.toToken) {\n throw new Error(\n \"TrustwareConfig: 'routes.toChain' and 'routes.toToken' are required.\"\n );\n }\n\n const autoDetectProvider =\n typeof input.autoDetectProvider === \"boolean\"\n ? input.autoDetectProvider\n : DEFAULT_AUTO_DETECT_PROVIDER;\n\n const routes = {\n toChain: input.routes.toChain,\n toToken: input.routes.toToken,\n fromToken: input.routes.fromToken,\n fromAddress: input.routes.fromAddress,\n toAddress: input.routes.toAddress,\n defaultSlippage: normalizeSlippage(\n input.routes.defaultSlippage ?? DEFAULT_SLIPPAGE\n ),\n routeType: input.routes.routeType ?? \"swap\",\n options: {\n ...input.routes.options,\n },\n };\n\n const theme = deepMerge(DEFAULT_THEME, input.theme);\n const messages = deepMerge(DEFAULT_MESSAGES, input.messages);\n\n // Merge retry config with defaults\n const retry = {\n autoRetry: input.retry?.autoRetry ?? DEFAULT_RETRY_CONFIG.autoRetry,\n maxRetries: input.retry?.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries,\n baseDelayMs: input.retry?.baseDelayMs ?? DEFAULT_RETRY_CONFIG.baseDelayMs,\n approachingThreshold:\n input.retry?.approachingThreshold ??\n DEFAULT_RETRY_CONFIG.approachingThreshold,\n onRateLimitInfo: input.retry?.onRateLimitInfo,\n onRateLimited: input.retry?.onRateLimited,\n onRateLimitApproaching: input.retry?.onRateLimitApproaching,\n };\n\n // Resolve WalletConnect config (optional)\n // const walletConnect = resolveWalletConnectConfig(input.walletConnect);\n const walletConnect = input.walletConnect;\n const features = {\n tokensPagination:\n input.features?.tokensPagination ??\n DEFAULT_FEATURE_FLAGS.tokensPagination,\n balanceStreaming:\n input.features?.balanceStreaming ??\n DEFAULT_FEATURE_FLAGS.balanceStreaming,\n shouldAllowGA4:\n input.features?.shouldAllowGA4 ?? DEFAULT_FEATURE_FLAGS.shouldAllowGA4,\n };\n\n return {\n apiKey: input.apiKey,\n routes,\n autoDetectProvider,\n theme,\n messages,\n retry,\n walletConnect,\n features,\n onError: input.onError,\n onSuccess: input.onSuccess,\n onEvent: input.onEvent,\n };\n}\n","import type {\n ResolvedTrustwareConfig,\n TrustwareConfigOptions,\n} from \"../types/\";\nimport { resolveConfig } from \"./merge\";\n\ntype Listener = (cfg: ResolvedTrustwareConfig) => void;\n\nclass ConfigStore {\n private _cfg: ResolvedTrustwareConfig | null = null;\n private _listeners = new Set<Listener>();\n\n isInitialized(): boolean {\n return this._cfg != null;\n }\n\n peek(): ResolvedTrustwareConfig | null {\n return this._cfg;\n }\n\n /** Initialize or replace the config */\n init(opts: TrustwareConfigOptions) {\n this._cfg = resolveConfig(opts);\n this.emit();\n }\n\n /** Partially update by re-resolving from last + patch */\n update(patch: Partial<TrustwareConfigOptions>) {\n if (!this._cfg) throw new Error(\"TrustwareConfig: call init() first.\");\n const next = resolveConfig({\n ...this._cfg,\n ...patch,\n routes: { ...this._cfg.routes, ...(patch.routes ?? {}) },\n theme: {\n ...this._cfg.theme,\n ...(patch.theme ?? {}),\n } as ResolvedTrustwareConfig[\"theme\"],\n messages: {\n ...this._cfg.messages,\n ...(patch.messages ?? {}),\n } as ResolvedTrustwareConfig[\"messages\"],\n retry: { ...this._cfg.retry, ...(patch.retry ?? {}) },\n features: { ...this._cfg.features, ...(patch.features ?? {}) },\n walletConnect: patch.walletConnect\n ? { ...this._cfg.walletConnect, ...patch.walletConnect }\n : this._cfg.walletConnect,\n } as TrustwareConfigOptions);\n this._cfg = next;\n this.emit();\n }\n\n get(): ResolvedTrustwareConfig {\n if (!this._cfg) throw new Error(\"TrustwareConfig: not initialized.\");\n return this._cfg;\n }\n\n getTheme() {\n return this.get().theme;\n }\n\n getMessages() {\n return this.get().messages;\n }\n\n subscribe(fn: (cfg: ResolvedTrustwareConfig) => void) {\n this._listeners.add(fn);\n if (this._cfg) fn(this._cfg);\n return () => {\n this._listeners.delete(fn);\n };\n }\n\n private emit() {\n if (!this._cfg) return;\n for (const fn of this._listeners) fn(this._cfg);\n }\n}\nexport const TrustwareConfigStore = new ConfigStore();\n\n/** Convenience for non-React environments */\nexport const TrustwareConfig = {\n init: (opts: TrustwareConfigOptions) => TrustwareConfigStore.init(opts),\n update: (patch: Partial<TrustwareConfigOptions>) =>\n TrustwareConfigStore.update(patch),\n get: () => TrustwareConfigStore.get(),\n getTheme: () => TrustwareConfigStore.get().theme,\n getMessages: () => TrustwareConfigStore.get().messages,\n subscribe: (fn: (cfg: ResolvedTrustwareConfig) => void) =>\n TrustwareConfigStore.subscribe(fn),\n};\n","// constants.ts\ndeclare const __SDK_VERSION__: string;\ndeclare const __API_ROOT__: string;\ndeclare const __GTM_ID__: string;\ndeclare const __WALLETCONNECT_PROJECT_ID__: string;\n\nexport const SDK_NAME = \"@trustware/sdk\";\nexport const SDK_VERSION: string = __SDK_VERSION__;\nexport const API_ROOT: string = __API_ROOT__;\nexport const GTM_ID: string = __GTM_ID__;\nexport const API_PREFIX = \"/api\";\nexport const WALLETCONNECT_PROJECT_ID = __WALLETCONNECT_PROJECT_ID__;\n\n// Assets base URL for wallet logos and other static assets\nexport const ASSETS_BASE_URL = \"https://app.trustware.io\";\n\n// WalletConnect Cloud project ID - built into the SDK for seamless wallet connections\n// This is a public identifier (not a secret) registered with WalletConnect Cloud\n// export const WALLETCONNECT_PROJECT_ID = \"4ead125c-63be-4b1a-a835-cef2dce67b84\";\n","export * from \"./defaults\";\nexport * from \"./merge\";\nexport * from \"./store\";\n// walletconnect.ts is excluded: depends on @reown/appkit-universal-connector (not installed)\n","/* core/http.ts */\nimport { SDK_NAME, SDK_VERSION, API_ROOT, API_PREFIX } from \"../constants\";\nimport { TrustwareConfigStore } from \"../config/\";\nimport type { RateLimitInfo } from \"../types/config\";\n\nexport function apiBase() {\n return `${API_ROOT}${API_PREFIX}`;\n}\n\nexport function jsonHeaders(extra?: Record<string, string>): HeadersInit {\n const cfg = TrustwareConfigStore.get();\n const h: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"X-API-Key\": cfg.apiKey,\n \"X-SDK-Name\": SDK_NAME,\n \"X-SDK-Version\": SDK_VERSION,\n \"X-API-Version\": \"2025-10-01\",\n };\n return { ...h, ...(extra || {}) };\n}\n\nexport async function assertOK(r: Response) {\n if (r.ok) return;\n let msg = r.statusText;\n try {\n const j = await r.json();\n if (j?.error) msg = j.error;\n } catch {\n // response body not JSON, use statusText\n }\n throw new Error(`HTTP ${r.status}: ${msg}`);\n}\n\n///sdk/validate\nexport async function validateSdkAccess() {\n const r = await fetch(`${apiBase()}/sdk/validate`, {\n method: \"GET\",\n headers: jsonHeaders(),\n });\n await assertOK(r);\n const j = await r.json();\n return j.data;\n}\n\n/** Parse rate limit headers from a response */\nexport function parseRateLimitHeaders(r: Response): RateLimitInfo | null {\n const limit = r.headers.get(\"X-RateLimit-Limit\");\n const remaining = r.headers.get(\"X-RateLimit-Remaining\");\n const reset = r.headers.get(\"X-RateLimit-Reset\");\n\n if (!limit || !remaining || !reset) {\n return null;\n }\n\n const info: RateLimitInfo = {\n limit: parseInt(limit, 10),\n remaining: parseInt(remaining, 10),\n reset: parseInt(reset, 10),\n };\n\n // Add retryAfter if present (only on 429 responses)\n const retryAfter = r.headers.get(\"Retry-After\");\n if (retryAfter) {\n info.retryAfter = parseInt(retryAfter, 10);\n }\n\n return info;\n}\n\n/** Notify rate limit callbacks based on response */\nfunction notifyRateLimitCallbacks(\n info: RateLimitInfo,\n isRateLimited: boolean,\n retryCount: number\n) {\n const cfg = TrustwareConfigStore.get();\n const { retry } = cfg;\n\n // Always notify onRateLimitInfo if configured\n if (retry.onRateLimitInfo) {\n retry.onRateLimitInfo(info);\n }\n\n // Notify when rate limited\n if (isRateLimited && retry.onRateLimited) {\n retry.onRateLimited(info, retryCount);\n }\n\n // Notify when approaching limit\n if (\n !isRateLimited &&\n retry.onRateLimitApproaching &&\n info.remaining <= retry.approachingThreshold\n ) {\n retry.onRateLimitApproaching(info, retry.approachingThreshold);\n }\n}\n\n/** Calculate delay for exponential backoff */\nfunction calculateBackoffDelay(\n baseDelayMs: number,\n retryCount: number,\n retryAfter?: number\n): number {\n // If server specified retry-after, use that (in seconds, convert to ms)\n if (retryAfter && retryAfter > 0) {\n return retryAfter * 1000;\n }\n // Otherwise use exponential backoff: base * 2^retryCount\n return baseDelayMs * Math.pow(2, retryCount);\n}\n\n/** Sleep for specified milliseconds */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport class RateLimitError extends Error {\n public readonly rateLimitInfo: RateLimitInfo;\n public readonly retriesExhausted: boolean;\n\n constructor(info: RateLimitInfo, retriesExhausted: boolean) {\n const message = retriesExhausted\n ? `Rate limit exceeded after max retries. Try again in ${info.retryAfter ?? Math.ceil((info.reset * 1000 - Date.now()) / 1000)} seconds.`\n : `Rate limit exceeded. Try again in ${info.retryAfter} seconds.`;\n super(message);\n this.name = \"RateLimitError\";\n this.rateLimitInfo = info;\n this.retriesExhausted = retriesExhausted;\n }\n}\n\ntype FetchOptions = RequestInit & {\n /** Skip rate limit handling for this request */\n skipRateLimit?: boolean;\n};\n\n/**\n * Rate-limit-aware fetch wrapper.\n * Automatically handles 429 responses with exponential backoff retry.\n * Notifies callbacks on rate limit events.\n */\nexport async function rateLimitedFetch(\n url: string,\n options: FetchOptions = {}\n): Promise<Response> {\n const { skipRateLimit, ...fetchOptions } = options;\n\n // If auto-retry is disabled or skipped, just do a normal fetch\n const cfg = TrustwareConfigStore.get();\n if (!cfg.retry.autoRetry || skipRateLimit) {\n return fetch(url, fetchOptions);\n }\n\n const { maxRetries, baseDelayMs } = cfg.retry;\n let retryCount = 0;\n\n while (true) {\n const response = await fetch(url, fetchOptions);\n\n // Parse rate limit headers\n const rateLimitInfo = parseRateLimitHeaders(response);\n\n if (response.status === 429) {\n // Rate limited\n if (rateLimitInfo) {\n notifyRateLimitCallbacks(rateLimitInfo, true, retryCount);\n }\n\n // Check if we should retry\n if (retryCount >= maxRetries) {\n // Max retries exhausted\n throw new RateLimitError(\n rateLimitInfo || { limit: 0, remaining: 0, reset: 0 },\n true\n );\n }\n\n // Calculate delay and retry\n const delay = calculateBackoffDelay(\n baseDelayMs,\n retryCount,\n rateLimitInfo?.retryAfter\n );\n await sleep(delay);\n retryCount++;\n continue;\n }\n\n // Not rate limited - notify callbacks if we have info\n if (rateLimitInfo) {\n notifyRateLimitCallbacks(rateLimitInfo, false, 0);\n }\n\n return response;\n }\n}\n","import type { ChainDef, ChainType } from \"../types\";\n\nexport const NATIVE_EVM = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\";\nexport const NATIVE_SOLANA = \"So11111111111111111111111111111111111111111\";\n\nconst CHAIN_TYPE_ALIASES: Record<string, ChainType> = {\n btc: \"bitcoin\",\n bitcoin: \"bitcoin\",\n sei: \"cosmos\",\n \"pacific-1\": \"cosmos\",\n};\n\nfunction inferChainTypeFromValue(normalized: string): ChainType | undefined {\n if (!normalized) return undefined;\n\n const aliased = CHAIN_TYPE_ALIASES[normalized];\n if (aliased) return aliased;\n\n if (\n normalized === \"evm\" ||\n normalized === \"solana\" ||\n normalized === \"cosmos\" ||\n normalized === \"bitcoin\"\n ) {\n return normalized;\n }\n\n if (/^eip155:\\d+$/.test(normalized) || /^\\d+$/.test(normalized)) {\n return \"evm\";\n }\n\n if (normalized.startsWith(\"solana:\") || normalized.includes(\"solana\")) {\n return \"solana\";\n }\n\n if (\n normalized.startsWith(\"cosmos:\") ||\n normalized.startsWith(\"sei:\") ||\n normalized === \"sei-evm\"\n ) {\n return \"cosmos\";\n }\n\n return undefined;\n}\n\nexport function normalizeChainKey(\n value: string | number | null | undefined\n): string {\n if (value === undefined || value === null) return \"\";\n return String(value).trim().toLowerCase();\n}\n\nexport function normalizeChainType(\n chain?: ChainDef | ChainType | string | null\n): ChainType | undefined {\n if (!chain) return undefined;\n const raw =\n typeof chain === \"string\"\n ? chain\n : (chain.type ??\n chain.chainType ??\n chain.networkIdentifier ??\n chain.chainId ??\n chain.id ??\n chain.networkName ??\n chain.axelarChainName);\n if (!raw) return undefined;\n const normalized = String(raw).trim().toLowerCase();\n return inferChainTypeFromValue(normalized) ?? normalized;\n}\n\nexport function getNativeTokenAddress(chainType?: ChainType | null) {\n return normalizeChainType(chainType) === \"solana\"\n ? NATIVE_SOLANA\n : NATIVE_EVM;\n}\n\nexport function isSolanaNativeTokenAlias(address?: string | null) {\n if (!address) return false;\n const trimmed = address.trim();\n if (!trimmed) return false;\n return trimmed === NATIVE_SOLANA || trimmed.toLowerCase() === NATIVE_EVM;\n}\n\nexport function normalizeAddress(\n address: string,\n chainType?: ChainType | null\n) {\n const trimmed = address.trim();\n if (normalizeChainType(chainType) === \"solana\") {\n if (isSolanaNativeTokenAlias(trimmed)) {\n return NATIVE_SOLANA;\n }\n return trimmed;\n }\n return trimmed.toLowerCase();\n}\n\nexport function isZeroAddressLike(\n address?: string | null,\n chainType?: ChainType | null\n) {\n if (!address) return true;\n const normalized = normalizeAddress(address, chainType);\n return (\n normalized ===\n normalizeAddress(getNativeTokenAddress(chainType), chainType) ||\n normalized === \"0x0000000000000000000000000000000000000000\"\n );\n}\n","import { TrustwareConfigStore } from \"./config/store\";\nimport type {\n ChainDef,\n TokenDef,\n TokenPageOptions,\n TokenPageResult,\n} from \"./types/\";\nimport {\n getNativeTokenAddress,\n normalizeAddress,\n normalizeChainKey,\n normalizeChainType,\n} from \"./utils/chains\";\n\nexport const NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\n\nconst PAGE_CACHE_TTL_MS = 5 * 60 * 1000;\nconst PAGE_CACHE_LIMIT = 100;\n\ntype CachedTokenPage = TokenPageResult & { storedAt: number };\n\nfunction getChainAliases(chain: ChainDef): string[] {\n const values = [\n chain.chainId,\n chain.id,\n chain.networkIdentifier,\n chain.axelarChainName,\n chain.networkName,\n ];\n return values.map((value) => normalizeChainKey(value)).filter(Boolean);\n}\n\nfunction tokenKey(token: TokenDef): string {\n return `${normalizeChainKey(token.chainId)}:${token.address.toLowerCase()}`;\n}\n\nfunction parseTokenPage(payload: unknown): TokenPageResult {\n if (Array.isArray(payload)) {\n return {\n data: payload as TokenDef[],\n pageInfo: { hasNextPage: false },\n };\n }\n\n const parsed = (payload ?? {}) as {\n data?: TokenDef[];\n results?: TokenDef[];\n tokens?: TokenDef[];\n pageInfo?: { hasNextPage?: boolean; nextCursor?: string };\n pagination?: { hasNextPage?: boolean; nextCursor?: string };\n nextCursor?: string;\n hasNextPage?: boolean;\n };\n\n const data = parsed.data ?? parsed.results ?? parsed.tokens ?? [];\n const info = parsed.pageInfo ?? parsed.pagination;\n return {\n data: Array.isArray(data) ? data : [],\n pageInfo: {\n hasNextPage:\n info?.hasNextPage ?? parsed.hasNextPage ?? Boolean(info?.nextCursor),\n nextCursor: info?.nextCursor ?? parsed.nextCursor,\n },\n };\n}\n\nfunction normalizeToken(token: TokenDef): TokenDef {\n return {\n ...token,\n chainId: token.chainId,\n };\n}\n\nexport class Registry {\n private _chainsById = new Map<string, ChainDef>();\n private _chainAliases = new Map<string, string>();\n private _tokensByChain = new Map<string, TokenDef[]>();\n private _tokensByChainKey = new Map<string, Map<string, TokenDef>>();\n private _pageCache = new Map<string, CachedTokenPage>();\n private _loaded = false;\n private _chainsLoaded = false;\n private _loadingPromise: Promise<void> | null = null;\n private _chainsLoadingPromise: Promise<void> | null = null;\n\n constructor(private baseURL: string) {}\n\n async ensureLoaded() {\n if (this._loaded) return;\n if (this._loadingPromise) {\n await this._loadingPromise;\n return;\n }\n\n this._loadingPromise = this.loadAllTokens();\n try {\n await this._loadingPromise;\n } finally {\n this._loadingPromise = null;\n }\n }\n\n async ensureChainsLoaded() {\n if (this._chainsLoaded) return;\n if (this._chainsLoadingPromise) {\n await this._chainsLoadingPromise;\n return;\n }\n\n this._chainsLoadingPromise = this.loadChains();\n try {\n await this._chainsLoadingPromise;\n } finally {\n this._chainsLoadingPromise = null;\n }\n }\n\n private get config() {\n return TrustwareConfigStore.get();\n }\n\n private emitPageLoaded(\n chainRef: string | number,\n query: string | undefined,\n result: TokenPageResult,\n cursor?: string\n ) {\n this.config.onEvent?.({\n type: \"token_page_loaded\",\n chainRef: String(chainRef),\n query,\n count: result.data.length,\n hasNextPage: result.pageInfo.hasNextPage,\n cursor,\n });\n }\n\n private emitPageError(\n chainRef: string | number,\n query: string | undefined,\n cursor: string | undefined,\n error: unknown\n ) {\n const message = error instanceof Error ? error.message : String(error);\n this.config.onEvent?.({\n type: \"token_page_error\",\n chainRef: String(chainRef),\n query,\n cursor,\n message,\n });\n }\n\n private storeChain(chain: ChainDef) {\n const canonical = chain?.chainId ?? chain?.id;\n if (canonical == null) return;\n const normalized: ChainDef = {\n ...chain,\n id: chain.id ?? canonical,\n chainId: chain.chainId ?? canonical,\n };\n const canonicalKey = normalizeChainKey(canonical);\n this._chainsById.set(canonicalKey, normalized);\n for (const alias of getChainAliases(normalized)) {\n this._chainAliases.set(alias, canonicalKey);\n }\n }\n\n private storeTokenForAlias(chainKey: string, token: TokenDef) {\n const key = tokenKey(token);\n const existingByKey = this._tokensByChainKey.get(chainKey) ?? new Map();\n existingByKey.set(key, token);\n this._tokensByChainKey.set(chainKey, existingByKey);\n this._tokensByChain.set(chainKey, Array.from(existingByKey.values()));\n }\n\n private storeToken(token: TokenDef) {\n const chainRef = token?.chainId;\n if (chainRef == null) return;\n const normalized = normalizeToken(token);\n const resolvedChain = this.chain(chainRef);\n const aliases = resolvedChain\n ? getChainAliases(resolvedChain)\n : [normalizeChainKey(chainRef)];\n for (const alias of aliases) {\n this.storeTokenForAlias(alias, normalized);\n }\n }\n\n private async loadChains() {\n const chainsRes = await fetch(`${this.baseURL}/v1/routes/chains`, {\n headers: { Accept: \"application/json\", \"X-API-Key\": this.config.apiKey },\n });\n if (!chainsRes.ok) throw new Error(`chains: HTTP ${chainsRes.status}`);\n\n const chains = await chainsRes.json();\n const chainsArr: ChainDef[] = Array.isArray(chains)\n ? chains\n : (chains.data ?? []);\n\n for (const chain of chainsArr) {\n this.storeChain(chain);\n }\n\n this._chainsLoaded = true;\n }\n\n private async loadAllTokens() {\n await this.ensureChainsLoaded();\n\n const tokensRes = await fetch(`${this.baseURL}/v1/routes/tokens`, {\n headers: { Accept: \"application/json\", \"X-API-Key\": this.config.apiKey },\n });\n if (!tokensRes.ok) throw new Error(`tokens: HTTP ${tokensRes.status}`);\n\n const tokens = await tokensRes.json();\n const tokensArr: TokenDef[] = Array.isArray(tokens)\n ? tokens\n : (tokens.data ?? []);\n for (const token of tokensArr) {\n this.storeToken(token);\n }\n\n this._loaded = true;\n }\n\n private prunePageCache() {\n const now = Date.now();\n for (const [key, value] of this._pageCache.entries()) {\n if (now - value.storedAt > PAGE_CACHE_TTL_MS) {\n this._pageCache.delete(key);\n }\n }\n\n while (this._pageCache.size > PAGE_CACHE_LIMIT) {\n const oldestKey = this._pageCache.keys().next().value;\n if (!oldestKey) {\n break;\n }\n this._pageCache.delete(oldestKey);\n }\n }\n\n private pageCacheKey(\n chainRef: string | number,\n opts: TokenPageOptions = {}\n ): string {\n const chain = this.chain(chainRef);\n const canonical = normalizeChainKey(chain?.chainId ?? chainRef);\n return `${canonical}::${opts.q ?? \"\"}::${opts.limit ?? \"\"}::${opts.cursor ?? \"\"}`;\n }\n\n private filterTokens(\n tokens: TokenDef[],\n chainRef: string | number,\n query?: string\n ): TokenDef[] {\n const normalizedChain = normalizeChainKey(chainRef);\n const normalizedQuery = query?.trim().toLowerCase();\n return tokens.filter((token) => {\n if (normalizeChainKey(token.chainId) !== normalizedChain) {\n return false;\n }\n if (!normalizedQuery) {\n return true;\n }\n return (\n token.symbol?.toLowerCase().includes(normalizedQuery) ||\n token.name?.toLowerCase().includes(normalizedQuery) ||\n token.address?.toLowerCase().includes(normalizedQuery)\n );\n });\n }\n\n chains(): ChainDef[] {\n return Array.from(this._chainsById.values());\n }\n\n chain(chainRef: string | number): ChainDef | undefined {\n const normalized = normalizeChainKey(chainRef);\n const canonicalKey = this._chainAliases.get(normalized) ?? normalized;\n return this._chainsById.get(canonicalKey);\n }\n\n allTokens(): TokenDef[] {\n const unique = new Map<string, TokenDef>();\n for (const list of this._tokensByChain.values()) {\n for (const token of list) {\n unique.set(tokenKey(token), token);\n }\n }\n return Array.from(unique.values());\n }\n\n tokens(chainRef: string | number): TokenDef[] {\n return this._tokensByChain.get(normalizeChainKey(chainRef)) ?? [];\n }\n\n async tokensPage(\n chainRef: string | number,\n opts: TokenPageOptions = {}\n ): Promise<TokenPageResult> {\n await this.ensureChainsLoaded();\n\n if (!this.config.features.tokensPagination) {\n await this.ensureLoaded();\n const all = this.filterTokens(this.allTokens(), chainRef, opts.q);\n const start = opts.cursor ? Number(opts.cursor) || 0 : 0;\n const limit = opts.limit ?? all.length;\n const data = all.slice(start, start + limit);\n return {\n data,\n pageInfo: {\n hasNextPage: start + limit < all.length,\n nextCursor:\n start + limit < all.length ? String(start + limit) : undefined,\n },\n };\n }\n\n const cacheKey = this.pageCacheKey(chainRef, opts);\n const cached = this._pageCache.get(cacheKey);\n if (cached && Date.now() - cached.storedAt <= PAGE_CACHE_TTL_MS) {\n return { data: cached.data, pageInfo: cached.pageInfo };\n }\n\n const chain = this.chain(chainRef);\n const chainKey = normalizeChainKey(chain?.chainId ?? chainRef);\n const url = new URL(`${this.baseURL}/v1/routes/tokens`);\n url.searchParams.set(\"chainId\", chainKey);\n if (opts.cursor) url.searchParams.set(\"cursor\", opts.cursor);\n if (opts.limit != null) url.searchParams.set(\"limit\", String(opts.limit));\n if (opts.q) url.searchParams.set(\"q\", opts.q);\n\n try {\n const res = await fetch(url.toString(), {\n headers: {\n Accept: \"application/json\",\n \"X-API-Key\": this.config.apiKey,\n },\n });\n\n if (!res.ok) {\n throw new Error(`tokens page: HTTP ${res.status}`);\n }\n\n const parsed = parseTokenPage(await res.json());\n const deduped = new Map<string, TokenDef>();\n for (const token of parsed.data) {\n const normalized = normalizeToken(token);\n this.storeToken(normalized);\n deduped.set(tokenKey(normalized), normalized);\n }\n\n const result = {\n data: Array.from(deduped.values()),\n pageInfo: parsed.pageInfo,\n };\n\n this._pageCache.set(cacheKey, { ...result, storedAt: Date.now() });\n this.prunePageCache();\n this.emitPageLoaded(chainRef, opts.q, result, opts.cursor);\n return result;\n } catch (error) {\n this.emitPageError(chainRef, opts.q, opts.cursor, error);\n await this.ensureLoaded();\n const fallback = this.filterTokens(this.allTokens(), chainRef, opts.q);\n return {\n data: fallback,\n pageInfo: { hasNextPage: false },\n };\n }\n }\n\n async *iterateTokens(\n chainRef: string | number,\n opts: Omit<TokenPageOptions, \"cursor\"> = {}\n ): AsyncGenerator<TokenPageResult, void, void> {\n let cursor: string | undefined;\n do {\n const page = await this.tokensPage(chainRef, { ...opts, cursor });\n yield page;\n cursor = page.pageInfo.nextCursor;\n if (!page.pageInfo.hasNextPage) {\n break;\n }\n } while (cursor);\n }\n\n findToken(chainRef: string | number, address: string): TokenDef | undefined {\n const chain = this.chain(chainRef);\n const chainType = normalizeChainType(chain);\n const normalizedAddress = normalizeAddress(address, chainType);\n return this.tokens(chainRef).find((token) => {\n return normalizeAddress(token.address, chainType) === normalizedAddress;\n });\n }\n\n resolveToken(\n chainRef: string | number,\n input?: string | null\n ): string | undefined {\n if (!input) return undefined;\n const s = String(input).trim();\n const chain = this.chain(chainRef);\n const chainType = normalizeChainType(chain);\n\n if (/^0x[0-9a-fA-F]{40}$/.test(s)) return s;\n if (chainType === \"solana\" && s.length > 20) return s;\n\n const nativeAddress = getNativeTokenAddress(chainType);\n const nativeSymbol = chain?.nativeCurrency?.symbol?.toUpperCase?.();\n if (\n (nativeSymbol && s.toUpperCase() === nativeSymbol) ||\n [\"ETH\", \"MATIC\", \"AVAX\", \"BNB\", \"SOL\", \"NATIVE\"].includes(s.toUpperCase())\n ) {\n return chainType === \"solana\" ? nativeAddress : NATIVE;\n }\n\n const hit = this.tokens(chainRef).find((token) => {\n if (!token.symbol) return false;\n return token.symbol.toUpperCase() === s.toUpperCase();\n });\n if (hit) return hit.address;\n\n return s;\n }\n}\n","export * from \"./core/index\";\n","/* core/index.ts */\nimport type {\n TrustwareConfigOptions,\n ResolvedTrustwareConfig,\n WalletInterFaceAPI,\n} from \"../types\";\nimport { TrustwareConfigStore } from \"../config/store\";\nimport { walletManager } from \"../wallets/manager\";\nimport {\n buildRoute,\n buildDepositAddress,\n submitReceipt,\n getStatus,\n pollStatus,\n} from \"./routes\";\nimport {\n getBalances,\n getBalancesByAddress,\n getBalancesByAddressStream,\n} from \"./balances\";\nimport { sendRouteTransaction, runTopUp } from \"./tx\";\nimport { validateSdkAccess } from \"./http\";\nimport { useChains } from \"./useChains\";\nimport { useTokens } from \"./useTokens\";\nimport { TrustwareError } from \"../errors/TrustwareError\";\nimport { TrustwareErrorCode } from \"../errors/errorCodes\";\nimport {\n validateAddressForChain,\n validateRouteAddresses,\n} from \"../validation/address\";\n\n// simple memo to avoid re-validating same key repeatedly\nlet _lastValidatedKey: string | null = null;\n\nexport const Trustware = {\n /** Initialize config */\n async init(cfg: TrustwareConfigOptions) {\n TrustwareConfigStore.init(cfg);\n const key = TrustwareConfigStore.get().apiKey;\n\n if (_lastValidatedKey !== key) {\n try {\n await validateSdkAccess();\n _lastValidatedKey = key;\n } catch (err: unknown) {\n const reason =\n err instanceof Error && err.message ? `: ${err.message}` : \"\";\n const error = new TrustwareError({\n code: TrustwareErrorCode.INVALID_API_KEY,\n message: `Trustware.init: API key validation failed${reason}`,\n userMessage:\n \"API key validation failed. Please verify your Trustware API key.\",\n cause: err,\n });\n const config = TrustwareConfigStore.get();\n config.onError?.(error);\n config.onEvent?.({ type: \"error\", error });\n throw error;\n }\n }\n return Trustware;\n },\n\n /** Attach a wallet interface directly (skips detection) */\n useWallet(w: WalletInterFaceAPI) {\n walletManager.attachWallet(w);\n return Trustware;\n },\n\n /** Best-effort background attach to detected wallet(s) (detection hook should be running in the app) */\n async autoDetect(_timeoutMs?: number) {\n await walletManager.autoAttach();\n return walletManager.wallet != null;\n },\n\n /** Read resolved config */\n getConfig(): ResolvedTrustwareConfig {\n return TrustwareConfigStore.get();\n },\n\n setDestinationAddress(address?: string | null) {\n const prev = TrustwareConfigStore.get();\n TrustwareConfigStore.update({\n routes: {\n ...prev.routes,\n toAddress: address ?? undefined,\n },\n });\n return Trustware;\n },\n\n setDestinationChain(chain: string) {\n const prev = TrustwareConfigStore.get();\n TrustwareConfigStore.update({\n routes: {\n ...prev.routes,\n toChain: chain,\n },\n });\n return Trustware;\n },\n\n setDestinationToken(token: string) {\n const prev = TrustwareConfigStore.get();\n TrustwareConfigStore.update({\n routes: {\n ...prev.routes,\n toToken: token,\n },\n });\n return Trustware;\n },\n\n /** Read active wallet */\n getWallet(): WalletInterFaceAPI | null {\n return walletManager.wallet;\n },\n\n getIdentity() {\n return walletManager.identity;\n },\n\n resolveAddressForChain(\n chain: Parameters<typeof walletManager.resolveAddressForChain>[0]\n ) {\n return walletManager.resolveAddressForChain(chain);\n },\n\n addIdentityAddress(\n address: Parameters<typeof walletManager.addIdentityAddress>[0]\n ) {\n walletManager.addIdentityAddress(address);\n return Trustware;\n },\n\n /** Simple helpers */\n async getAddress(): Promise<string> {\n const w = walletManager.wallet;\n if (!w) throw new Error(\"Trustware.wallet not configured\");\n return w.getAddress();\n },\n\n // ---- REST methods (re-export) ----\n buildRoute,\n buildDepositAddress,\n submitReceipt,\n getStatus,\n pollStatus,\n getBalances,\n getBalancesByAddress,\n getBalancesByAddressStream,\n useChains,\n useTokens,\n validateAddressForChain,\n validateRouteAddresses,\n\n // ---- Tx helpers ----\n sendRouteTransaction,\n runTopUp,\n};\n\nexport type TrustwareCore = typeof Trustware;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n// src/wallet.ts\nimport type { WalletInterFaceAPI, EIP1193 } from \"../types/\";\n\n/* ---------------- chain params for addChain fallback ---------------- */\nconst CHAIN_PARAMS: Record<\n number,\n {\n chainIdHex: `0x${string}`;\n chainName: string;\n rpcUrls: string[];\n nativeCurrency: { name: string; symbol: string; decimals: number };\n blockExplorerUrls?: string[];\n }\n> = {\n 8453: {\n chainIdHex: \"0x2105\",\n chainName: \"Base\",\n rpcUrls: [\"https://mainnet.base.org\"],\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n blockExplorerUrls: [\"https://basescan.org\"],\n },\n 42161: {\n chainIdHex: \"0xa4b1\",\n chainName: \"Arbitrum One\",\n rpcUrls: [\"https://arb1.arbitrum.io/rpc\"],\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n blockExplorerUrls: [\"https://arbiscan.io\"],\n },\n 43114: {\n chainIdHex: \"0xa86a\",\n chainName: \"Avalanche C-Chain\",\n rpcUrls: [\"https://api.avax.network/ext/bc/C/rpc\"],\n nativeCurrency: { name: \"Avalanche\", symbol: \"AVAX\", decimals: 18 },\n blockExplorerUrls: [\"https://snowtrace.io\"],\n },\n};\n\nasync function addThenSwitch(eth: EIP1193, chainId: number) {\n const p = CHAIN_PARAMS[chainId];\n if (!p) throw new Error(`Unknown chain ${chainId} (no params to add)`);\n await eth.request({ method: \"wallet_addEthereumChain\", params: [p] as any });\n await eth.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: p.chainIdHex }] as any,\n });\n}\n\n/* ---------------- EIP-1193 adapter (safe switching) ---------------- */\nexport function useEIP1193(eth: EIP1193): WalletInterFaceAPI {\n if (!eth?.request) throw new Error(\"useEIP1193: invalid provider\");\n let switching = false;\n\n return {\n ecosystem: \"evm\",\n type: \"eip1193\",\n async getAddress() {\n const [a] = (await eth.request({\n method: \"eth_requestAccounts\",\n })) as string[];\n if (!a) throw new Error(\"No connected address\");\n return a;\n },\n async getChainId() {\n const hex = await eth.request({ method: \"eth_chainId\" });\n return parseInt(String(hex), 16);\n },\n async switchChain(chainId: number) {\n if (switching) return; // prevent 4001: already in progress\n switching = true;\n const hex =\n CHAIN_PARAMS[chainId]?.chainIdHex ?? `0x${chainId.toString(16)}`;\n try {\n await eth.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: hex }],\n });\n } catch (e: any) {\n if (e?.code === 4902) {\n await addThenSwitch(eth, chainId);\n } else if (e?.code === 4001) {\n // user rejected or wallet busy; don’t crash the flow\n } else {\n throw e;\n }\n } finally {\n switching = false;\n }\n },\n request: (args) => eth.request(args),\n };\n}\n\n/* ---------------- Wagmi/Viem client adapter (version-agnostic) ---------------- */\nexport function useWagmi(client: any): WalletInterFaceAPI {\n if (!client) throw new Error(\"useWagmi: missing client\");\n let switching = false;\n\n async function getAddress(): Promise<`0x${string}`> {\n const addr = client.account?.address as `0x${string}` | undefined;\n if (addr) return addr;\n if (typeof client.getAddresses === \"function\") {\n const arr = await client.getAddresses();\n if (arr?.[0]) return arr[0];\n }\n throw new Error(\"No connected address\");\n }\n\n async function getChainId(): Promise<number> {\n const id = client.chain?.id ?? (await client.getChainId?.());\n return typeof id === \"number\" ? id : 0;\n }\n\n async function switchChain(target: number) {\n if (switching) return;\n switching = true;\n try {\n if (typeof client.switchChain === \"function\") {\n try {\n await client.switchChain({ id: target });\n } catch {\n await client.switchChain({ chainId: target });\n }\n return;\n }\n const eth = (globalThis as any).ethereum as EIP1193 | undefined;\n if (!eth?.request) throw new Error(\"switchChain not available\");\n try {\n const hex =\n CHAIN_PARAMS[target]?.chainIdHex ?? `0x${target.toString(16)}`;\n await eth.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: hex }],\n });\n } catch (e: any) {\n if (e?.code === 4902) await addThenSwitch(eth, target);\n else if (e?.code === 4001)\n void 0; // switchChain rejected/in-progress — non-fatal\n else throw e;\n }\n } finally {\n switching = false;\n }\n }\n\n async function sendTransaction(tx: {\n to: `0x${string}`;\n data: `0x${string}`;\n value?: bigint;\n chainId?: number;\n }) {\n if (typeof client.sendTransaction !== \"function\")\n throw new Error(\"sendTransaction not available\");\n const account = await getAddress();\n const chainId = tx.chainId ?? (await getChainId());\n try {\n const res = await client.sendTransaction({\n account,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n chain: { id: chainId },\n });\n return { hash: res.hash as `0x${string}` };\n } catch {\n const res = await client.sendTransaction({\n account,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n chainId,\n });\n return { hash: res.hash as `0x${string}` };\n }\n }\n\n return {\n ecosystem: \"evm\",\n type: \"wagmi\",\n getAddress,\n getChainId,\n switchChain,\n sendTransaction,\n };\n}\n\n/* ---------------- Provider discovery (prefer Rabby) ---------------- */\n\ntype Detected = { id: string; name: string; provider: EIP1193 };\n\nfunction nameOf(p: any): string {\n return (\n p?.providerInfo?.name ||\n p?.info?.name ||\n (p?.isRabby && \"Rabby\") ||\n (p?.isMetaMask && \"MetaMask\") ||\n (p?.isBraveWallet && \"Brave Wallet\") ||\n (p?.isCoinbaseWallet && \"Coinbase Wallet\") ||\n \"Injected Wallet\"\n );\n}\nfunction idOf(p: any): string {\n return nameOf(p).toLowerCase().replace(/\\s+/g, \"-\") || \"injected\";\n}\n\nfunction rank(list: Detected[]): Detected[] {\n const score = (n: string) => {\n const s = n.toLowerCase();\n if (s.includes(\"rabby\")) return 0;\n if (s.includes(\"metamask\")) return 1;\n if (s.includes(\"coinbase\")) return 2;\n if (s.includes(\"okx\")) return 3;\n if (s.includes(\"brave\")) return 99; // de-prioritize Brave\n return 50;\n };\n return [...list].sort((a, b) => score(a.name) - score(b.name));\n}\n\n/** Prefer Rabby automatically; fallback to others (no browser setting needed) */\nexport async function autoDetectWallet(\n timeoutMs = 400\n): Promise<{ kind: \"eip1193\"; wallet: WalletInterFaceAPI } | null> {\n if (typeof window === \"undefined\") return null;\n const w = window as any;\n\n const announced: any[] = [];\n const handler = (e: any) => {\n if (e?.detail?.provider?.request) announced.push(e.detail.provider);\n };\n w.addEventListener?.(\"eip6963:announceProvider\", handler);\n w.dispatchEvent?.(new Event(\"eip6963:requestProvider\"));\n await new Promise((res) => setTimeout(res, timeoutMs));\n w.removeEventListener?.(\"eip6963:announceProvider\", handler);\n\n const candidates: any[] = [];\n if (w.ethereum?.request) {\n const multi = Array.isArray(w.ethereum.providers)\n ? w.ethereum.providers\n : [w.ethereum];\n for (const p of multi) if (p?.request) candidates.push(p);\n }\n for (const p of announced)\n if (p?.request && !candidates.includes(p)) candidates.push(p);\n\n if (candidates.length === 0) return null;\n\n const dedup = new Map<string, Detected>();\n for (const p of candidates) {\n const det = { id: idOf(p), name: nameOf(p), provider: p as EIP1193 };\n dedup.set(det.id, det);\n }\n\n const best = rank(Array.from(dedup.values()))[0];\n return { kind: \"eip1193\", wallet: useEIP1193(best.provider) };\n}\n","import { Transaction, VersionedTransaction } from \"@solana/web3.js\";\nimport { getSolanaTxStatus, sendSolanaSerialized } from \"../core/sdkRpc\";\n\nimport type {\n DetectedWallet,\n SolanaProviderLike,\n SolanaWalletInterface,\n WalletId,\n WalletMeta,\n} from \"../types\";\n\ntype SolanaEventHandlers = {\n onConnect?: () => void;\n onAccountChanged?: () => void;\n onDisconnect?: () => void;\n};\n\nconst SOLANA_WALLET_IDS: WalletId[] = [\n \"phantom-solana\",\n \"solflare\",\n \"backpack\",\n];\n\nfunction getPublicKeyString(provider?: SolanaProviderLike | null) {\n const publicKey = provider?.publicKey;\n if (!publicKey) return null;\n const text = publicKey.toString().trim();\n return text || null;\n}\n\nfunction decodeBase64(serializedTransaction: string) {\n const trimmed = serializedTransaction.trim();\n if (typeof Buffer !== \"undefined\") {\n return Uint8Array.from(Buffer.from(trimmed, \"base64\"));\n }\n const binary = globalThis.atob(trimmed);\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n}\n\nfunction decodeBase64Transaction(serializedTransaction: string) {\n const bytes = decodeBase64(serializedTransaction);\n try {\n return VersionedTransaction.deserialize(bytes);\n } catch {\n return Transaction.from(bytes);\n }\n}\n\nfunction encodeBase64(bytes: Uint8Array) {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(bytes).toString(\"base64\");\n }\n\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return globalThis.btoa(binary);\n}\n\nasync function waitForSolanaConfirmation(chainId: string, signature: string) {\n const started = Date.now();\n const timeoutMs = 120000;\n const intervalMs = 2000;\n\n while (Date.now() - started < timeoutMs) {\n const status = await getSolanaTxStatus({ chainId, signature });\n if (status.status === \"success\") return signature;\n if (status.status === \"failed\") {\n throw new Error(\"Solana transaction failed\");\n }\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n\n throw new Error(\"Timed out waiting for Solana transaction confirmation\");\n}\n\nexport function getSolanaProviders(): Partial<\n Record<WalletId, SolanaProviderLike>\n> {\n if (typeof window === \"undefined\") return {};\n\n const win = window as typeof window & {\n solana?: SolanaProviderLike;\n phantom?: { solana?: SolanaProviderLike };\n solflare?: SolanaProviderLike;\n backpack?: { solana?: SolanaProviderLike };\n };\n\n const providers: Partial<Record<WalletId, SolanaProviderLike>> = {};\n const phantom =\n win.phantom?.solana ?? (win.solana?.isPhantom ? win.solana : undefined);\n const solflare =\n win.solflare ?? (win.solana?.isSolflare ? win.solana : undefined);\n const backpack =\n win.backpack?.solana ?? (win.solana?.isBackpack ? win.solana : undefined);\n\n if (phantom) providers[\"phantom-solana\"] = phantom;\n if (solflare) providers.solflare = solflare;\n if (backpack) providers.backpack = backpack;\n\n return providers;\n}\n\nexport function detectSolanaWallets(wallets: WalletMeta[]): DetectedWallet[] {\n const providers = getSolanaProviders();\n return SOLANA_WALLET_IDS.flatMap((walletId) => {\n const provider = providers[walletId];\n const meta = wallets.find((item) => item.id === walletId);\n if (!provider || !meta) return [];\n return [{ meta, provider, via: \"solana-window\" as const }];\n });\n}\n\nexport function bindSolanaProviderEvents(\n provider: SolanaProviderLike,\n handlers: SolanaEventHandlers\n) {\n const onConnect = () => handlers.onConnect?.();\n const onAccountChanged = () => handlers.onAccountChanged?.();\n const onDisconnect = () => handlers.onDisconnect?.();\n\n provider.on?.(\"connect\", onConnect);\n provider.on?.(\"accountChanged\", onAccountChanged);\n provider.on?.(\"disconnect\", onDisconnect);\n\n return () => {\n provider.off?.(\"connect\", onConnect);\n provider.off?.(\"accountChanged\", onAccountChanged);\n provider.off?.(\"disconnect\", onDisconnect);\n provider.removeListener?.(\"connect\", onConnect);\n provider.removeListener?.(\"accountChanged\", onAccountChanged);\n provider.removeListener?.(\"disconnect\", onDisconnect);\n };\n}\n\nexport function toSolanaWalletInterface(\n provider: SolanaProviderLike\n): SolanaWalletInterface {\n return {\n ecosystem: \"solana\",\n type: \"solana\",\n async getAddress() {\n const current = getPublicKeyString(provider);\n if (current) return current;\n if (!provider.connect) {\n throw new Error(\"Selected Solana wallet cannot connect\");\n }\n await provider.connect();\n const next = getPublicKeyString(provider);\n if (!next) throw new Error(\"No connected Solana address\");\n return next;\n },\n async disconnect() {\n await provider.disconnect?.();\n },\n async getChainKey() {\n return \"solana-mainnet-beta\";\n },\n async sendSerializedTransaction(\n serializedTransactionBase64: string,\n chainId?: string\n ) {\n const transaction = decodeBase64Transaction(serializedTransactionBase64);\n\n if (provider.signAndSendTransaction) {\n const result = await provider.signAndSendTransaction(transaction, {\n preflightCommitment: \"confirmed\",\n });\n\n if (typeof result === \"string\") return result;\n if (result?.signature) return result.signature;\n }\n\n if (!provider.signTransaction) {\n throw new Error(\"Connected Solana wallet cannot sign transactions\");\n }\n\n const signed = await provider.signTransaction(transaction);\n const resolvedChainId = chainId?.trim() || \"solana-mainnet\";\n const serializedSigned = encodeBase64(signed.serialize());\n const { signature } = await sendSolanaSerialized({\n chainId: resolvedChainId,\n serializedTransaction: serializedSigned,\n });\n await waitForSolanaConfirmation(resolvedChainId, signature);\n return signature;\n },\n };\n}\n","import { apiBase, jsonHeaders, rateLimitedFetch } from \"./http\";\n\ntype SDKRPCErrorPayload = {\n code?: string;\n message?: string;\n context?: Record<string, unknown>;\n};\n\ntype SDKRPCEnvelope<T> = {\n success?: boolean;\n data?: T;\n error?: SDKRPCErrorPayload;\n};\n\nexport class SDKRPCError extends Error {\n code?: string;\n context?: Record<string, unknown>;\n status?: number;\n\n constructor(\n message: string,\n options?: {\n code?: string;\n context?: Record<string, unknown>;\n status?: number;\n }\n ) {\n super(message);\n this.name = \"SDKRPCError\";\n this.code = options?.code;\n this.context = options?.context;\n this.status = options?.status;\n }\n}\n\nasync function requestSDKRPC<T>(\n path: string,\n init: RequestInit = {}\n): Promise<T> {\n const response = await rateLimitedFetch(`${apiBase()}/v1/sdk/rpc${path}`, {\n ...init,\n headers: jsonHeaders(),\n });\n\n let payload: SDKRPCEnvelope<T> | null = null;\n try {\n payload = (await response.json()) as SDKRPCEnvelope<T>;\n } catch {\n payload = null;\n }\n\n if (response.ok && payload?.success && payload.data !== undefined) {\n return payload.data;\n }\n\n throw new SDKRPCError(\n payload?.error?.message ||\n `HTTP ${response.status}: ${response.statusText || \"SDK RPC request failed\"}`,\n {\n code: payload?.error?.code,\n context: payload?.error?.context,\n status: response.status,\n }\n );\n}\n\nexport type EVMAllowanceResponse = {\n chainId: string;\n tokenAddress: string;\n ownerAddress: string;\n spenderAddress: string;\n allowance: string;\n rpcHost?: string;\n};\n\nexport type EVMTxStatusResponse = {\n chainId: string;\n txHash: string;\n found: boolean;\n confirmed: boolean;\n status: \"pending\" | \"success\" | \"reverted\" | \"not_found\";\n blockNumber?: string;\n gasUsed?: string;\n effectiveGasPrice?: string;\n confirmations?: string;\n rpcHost?: string;\n};\n\nexport type EVMFeeDataResponse = {\n chainId: string;\n gasPrice?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n supportsEip1559?: boolean;\n rpcHost?: string;\n};\n\nexport type EVMEstimateGasResponse = {\n chainId: string;\n gasLimit: string;\n rpcHost?: string;\n};\n\nexport type SolanaSendSerializedResponse = {\n chainId: string;\n signature: string;\n rpcHost?: string;\n};\n\nexport type SolanaTxStatusResponse = {\n chainId: string;\n signature: string;\n found: boolean;\n confirmed: boolean;\n status: \"pending\" | \"success\" | \"failed\" | \"not_found\";\n slot?: number;\n err?: unknown;\n rpcHost?: string;\n};\n\nexport async function getEVMAllowance(params: {\n chainId: string;\n tokenAddress: string;\n ownerAddress: string;\n spenderAddress: string;\n}) {\n const search = new URLSearchParams(params);\n return requestSDKRPC<EVMAllowanceResponse>(\n `/evm/allowance?${search.toString()}`,\n { method: \"GET\" }\n );\n}\n\nexport async function getEVMTxStatus(params: {\n chainId: string;\n txHash: string;\n}) {\n const search = new URLSearchParams(params);\n return requestSDKRPC<EVMTxStatusResponse>(\n `/evm/tx-status?${search.toString()}`,\n { method: \"GET\" }\n );\n}\n\nexport async function getEVMFeeData(params: { chainId: string }) {\n const search = new URLSearchParams(params);\n return requestSDKRPC<EVMFeeDataResponse>(\n `/evm/fee-data?${search.toString()}`,\n { method: \"GET\" }\n );\n}\n\nexport async function estimateEVMGas(body: {\n chainId: string;\n fromAddress: string;\n to: string;\n data: string;\n value: string;\n}) {\n return requestSDKRPC<EVMEstimateGasResponse>(\"/evm/estimate-gas\", {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n}\n\nexport async function sendSolanaSerialized(body: {\n chainId: string;\n serializedTransaction: string;\n}) {\n return requestSDKRPC<SolanaSendSerializedResponse>(\n \"/solana/send-serialized\",\n {\n method: \"POST\",\n body: JSON.stringify(body),\n }\n );\n}\n\nexport async function getSolanaTxStatus(params: {\n chainId: string;\n signature: string;\n}) {\n const search = new URLSearchParams(params);\n return requestSDKRPC<SolanaTxStatusResponse>(\n `/solana/tx-status?${search.toString()}`,\n { method: \"GET\" }\n );\n}\n","import type { WalletInterFaceAPI, DetectedWallet, EIP1193 } from \"../types/\";\nimport { useEIP1193, useWagmi } from \"./eipWallets\";\nimport { toSolanaWalletInterface } from \"./solana\";\n\nexport { useEIP1193, useWagmi };\n\nexport function toWalletInterfaceFromDetected(\n dw: DetectedWallet\n): WalletInterFaceAPI {\n if (!dw?.provider) throw new Error(\"No provider on detected wallet\");\n if (dw.via === \"solana-window\" || dw.meta.ecosystem === \"solana\") {\n return toSolanaWalletInterface(dw.provider);\n }\n const eth = dw.provider as EIP1193;\n return useEIP1193(eth);\n}\n","import type { DetectedWallet, WalletInterFaceAPI } from \"../types\";\nimport type { WagmiBridge } from \"./bridges\";\nimport { toWalletInterfaceFromDetected } from \"./adapters\";\n// import { connectWalletConnect } from \"./walletconnect\";\n\nfunction pickWagmiConnector(\n wagmi: WagmiBridge,\n metaName: string,\n metaId: string,\n metaCategory: string\n) {\n const lower = metaName.toLowerCase();\n const cons = wagmi.connectors();\n return (\n cons.find((c) => c.name.toLowerCase().includes(lower)) ||\n (metaId === \"coinbase\" &&\n cons.find((c) => c.name.toLowerCase().includes(\"coinbase\"))) ||\n (metaId === \"walletconnect\" &&\n cons.find((c) => (c.type ?? \"\").toLowerCase() === \"walletconnect\")) ||\n (metaCategory === \"injected\" &&\n cons.find((c) => (c.type ?? \"\").toLowerCase() === \"injected\")) ||\n null\n );\n}\n\n/** Try wagmi bridge first (if provided), otherwise return EIP-1193 adapter. */\nexport async function connectDetectedWallet(\n dw: DetectedWallet,\n opts?: { wagmi?: WagmiBridge; touchAddress?: boolean }\n): Promise<{\n via: \"wagmi\" | \"eip1193\" | \"walletconnect\";\n api: WalletInterFaceAPI | null;\n error?: string | null;\n}> {\n const { wagmi, touchAddress = true } = opts ?? {};\n\n // Handle WalletConnect specially\n if (dw.meta.id === \"walletconnect\" || dw.via === \"walletconnect\") {\n // First try wagmi if available (host may have WC configured in wagmi)\n if (wagmi) {\n const conn = pickWagmiConnector(\n wagmi,\n dw.meta.name,\n dw.meta.id,\n dw.meta.category\n );\n if (conn) {\n await wagmi.connect(conn);\n return { via: \"wagmi\", api: null };\n }\n }\n\n // Use our native WalletConnect integration (built-in, always available)\n // const api = await connectWalletConnect();\n // if (api) {\n // if (touchAddress) await api.getAddress();\n // return { via: \"walletconnect\", api };\n // }\n\n throw new Error(\"WalletConnect connection failed. Please try again.\");\n }\n\n if (dw.via === \"solana-window\" || dw.meta.ecosystem === \"solana\") {\n try {\n const provider = dw.provider;\n await provider.connect();\n return {\n via: \"eip1193\",\n api: toWalletInterfaceFromDetected(dw),\n error: null,\n };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n return { via: \"eip1193\", api: null, error: errorMsg };\n }\n }\n\n if (wagmi) {\n const conn = pickWagmiConnector(\n wagmi,\n dw.meta.name,\n dw.meta.id,\n dw.meta.category\n );\n if (conn) {\n await wagmi.connect(conn);\n // when the host uses wagmi, you can later wrap the host client using your old useWagmi adapter\n return { via: \"wagmi\", api: null, error: null };\n }\n }\n\n // fallback: raw EIP-1193\n const api = toWalletInterfaceFromDetected(dw);\n if (touchAddress) await api.getAddress(); // triggers permission prompt\n return { via: \"eip1193\", api, error: null };\n}\n","import { isAddress as isEvmAddress } from \"viem\";\nimport { isAddress as isSolanaAddress } from \"@solana/addresses\";\n\nimport type { ChainDef, ChainType } from \"../types\";\nimport { normalizeChainType } from \"../utils/chains\";\n\ntype AddressValidationResult = { isValid: boolean; error?: string };\n\nconst BECH32_CHARSET = /^[023456789acdefghjklmnpqrstuvwxyz]+$/i;\n\nfunction hasMixedCase(value: string) {\n return value !== value.toLowerCase() && value !== value.toUpperCase();\n}\n\nfunction validateBech32LikeAddress(\n address: string,\n prefix: string\n): AddressValidationResult {\n const trimmed = address.trim();\n if (!trimmed) {\n return { isValid: false, error: \"Address is required.\" };\n }\n if (hasMixedCase(trimmed)) {\n return { isValid: false, error: \"Bech32 addresses cannot mix case.\" };\n }\n\n const lower = trimmed.toLowerCase();\n const expectedPrefix = `${prefix.toLowerCase()}1`;\n if (!lower.startsWith(expectedPrefix)) {\n return {\n isValid: false,\n error: `Address must start with ${expectedPrefix}.`,\n };\n }\n\n const dataPart = lower.slice(expectedPrefix.length);\n if (dataPart.length < 6 || !BECH32_CHARSET.test(dataPart)) {\n return {\n isValid: false,\n error: \"Bech32 address format is invalid.\",\n };\n }\n\n return { isValid: true };\n}\n\nexport function validateEvmAddress(address: string): AddressValidationResult {\n if (!isEvmAddress(address.trim())) {\n return {\n isValid: false,\n error: \"EVM addresses must be 0x-prefixed 20-byte hex strings.\",\n };\n }\n return { isValid: true };\n}\n\nexport function validateSeiAddress(address: string): AddressValidationResult {\n const trimmed = address.trim();\n if (isEvmAddress(trimmed)) {\n return { isValid: true };\n }\n const result = validateBech32LikeAddress(trimmed, \"sei\");\n if (result.isValid) return result;\n return {\n isValid: false,\n error: \"SEI addresses must be 0x-prefixed EVM or sei1 bech32 strings.\",\n };\n}\n\nexport function validateSolanaAddress(\n address: string\n): AddressValidationResult {\n const trimmed = address.trim();\n if (trimmed.startsWith(\"0x\") || isEvmAddress(trimmed)) {\n return {\n isValid: false,\n error: \"Solana addresses must be base58-encoded strings.\",\n };\n }\n if (\n trimmed.toLowerCase().startsWith(\"bc1\") ||\n trimmed.toLowerCase().startsWith(\"sei1\")\n ) {\n return {\n isValid: false,\n error: \"Solana addresses cannot be bech32 strings.\",\n };\n }\n if (!isSolanaAddress(trimmed)) {\n return {\n isValid: false,\n error: \"Solana addresses must be base58-encoded strings.\",\n };\n }\n return { isValid: true };\n}\n\nexport function validateBtcAddress(address: string): AddressValidationResult {\n const trimmed = address.trim();\n if (hasMixedCase(trimmed)) {\n return { isValid: false, error: \"Bitcoin addresses cannot mix case.\" };\n }\n const result = validateBech32LikeAddress(trimmed, \"bc\");\n if (result.isValid) return result;\n return {\n isValid: false,\n error: \"Bitcoin addresses must use native SegWit (bc1...) format.\",\n };\n}\n\nexport function validateAddressForChain(\n address: string,\n chain?: ChainDef | ChainType | string | null\n): AddressValidationResult {\n const trimmed = address.trim();\n if (!trimmed) return { isValid: true };\n const chainType = normalizeChainType(chain);\n const chainDef = typeof chain === \"object\" && chain ? chain : undefined;\n\n switch (chainType) {\n case \"evm\":\n return validateEvmAddress(trimmed);\n case \"solana\":\n return validateSolanaAddress(trimmed);\n case \"bitcoin\":\n return validateBtcAddress(trimmed);\n case \"cosmos\":\n if (chainDef?.networkIdentifier?.toLowerCase() === \"sei\") {\n return validateSeiAddress(trimmed);\n }\n return validateBech32LikeAddress(trimmed, \"sei\");\n default:\n return { isValid: false, error: \"Unsupported or unknown chain type.\" };\n }\n}\n\nfunction validateAddressForRouteChain(address: string, chainType: ChainType) {\n switch (normalizeChainType(chainType)) {\n case \"evm\":\n return validateEvmAddress(address);\n case \"solana\":\n return validateSolanaAddress(address);\n case \"bitcoin\":\n return validateBtcAddress(address);\n case \"cosmos\":\n return validateSeiAddress(address);\n default:\n return { isValid: false, error: \"Unsupported chain type.\" };\n }\n}\n\nexport function validateRouteAddresses(params: {\n fromChain?: ChainDef | ChainType | string | null;\n toChain?: ChainDef | ChainType | string | null;\n fromAddress: string;\n toAddress: string;\n refundAddress?: string;\n direction?: string;\n}): AddressValidationResult {\n const fromType = normalizeChainType(params.fromChain);\n const toType = normalizeChainType(params.toChain);\n\n if (!fromType || !toType) {\n return {\n isValid: false,\n error: \"Missing chain types for route validation.\",\n };\n }\n\n const fromAddress = params.fromAddress.trim();\n const toAddress = params.toAddress.trim();\n if (!fromAddress || !toAddress) {\n return { isValid: false, error: \"Route addresses are required.\" };\n }\n\n const normalizedDirection = params.direction?.trim().toLowerCase();\n const isDepositFlow =\n normalizedDirection === \"deposit\" ||\n ((toType === \"evm\" || toType === \"cosmos\") &&\n (fromType === \"bitcoin\" || fromType === \"solana\"));\n\n if (isDepositFlow) {\n const fromResult = validateAddressForRouteChain(fromAddress, fromType);\n if (!fromResult.isValid) {\n return {\n isValid: false,\n error: `From address: ${fromResult.error ?? \"Invalid address.\"}`,\n };\n }\n const toResult =\n toType === \"cosmos\"\n ? validateSeiAddress(toAddress)\n : validateEvmAddress(toAddress);\n if (!toResult.isValid) {\n return {\n isValid: false,\n error: `To address: ${toResult.error ?? \"Invalid address.\"}`,\n };\n }\n if (fromType === \"bitcoin\") {\n const refundAddress = params.refundAddress?.trim();\n if (!refundAddress) {\n return {\n isValid: false,\n error: \"Refund address is required for BTC deposit routes.\",\n };\n }\n const refundResult = validateBtcAddress(refundAddress);\n if (!refundResult.isValid) {\n return {\n isValid: false,\n error: `Refund address: ${refundResult.error ?? \"Invalid address.\"}`,\n };\n }\n }\n return { isValid: true };\n }\n\n const fromResult = validateAddressForRouteChain(fromAddress, fromType);\n if (!fromResult.isValid) {\n return {\n isValid: false,\n error: `From address: ${fromResult.error ?? \"Invalid address.\"}`,\n };\n }\n\n const toResult = validateAddressForRouteChain(toAddress, toType);\n if (!toResult.isValid) {\n return {\n isValid: false,\n error: `To address: ${toResult.error ?? \"Invalid address.\"}`,\n };\n }\n\n return { isValid: true };\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<T extends SolanaErrorCode> = { [P in T]: { index: number } };\n\ntype DefaultUnspecifiedErrorContextToUndefined<T> = {\n [P in SolanaErrorCode]: P extends keyof T ? T[P] : undefined;\n};\n\ntype ReadonlyContextValue<T> = {\n [P in keyof T]: Readonly<T[P]>;\n};\n\ntype TypedArrayMutableProperties = 'copyWithin' | 'fill' | 'reverse' | 'set' | 'sort';\ninterface ReadonlyUint8Array extends Omit<Uint8Array, TypedArrayMutableProperties> {\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<TErrorCode extends SolanaErrorCode>(\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<TErrorCode extends SolanaErrorCode>(\n code: TErrorCode,\n context: Record<string, unknown> = {},\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<SolanaError<TErrorCode>, '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<TErrorCode extends SolanaErrorCodeWithDeprecatedCause>(\n e: unknown,\n code: TErrorCode,\n): e is SolanaErrorWithDeprecatedCause<TErrorCode>;\nexport function isSolanaError<TErrorCode extends SolanaErrorCode>(\n e: unknown,\n code?: TErrorCode,\n): e is SolanaError<TErrorCode>;\nexport function isSolanaError<TErrorCode extends SolanaErrorCode>(\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<TErrorCode> {\n const isSolanaError = e instanceof Error && e.name === 'SolanaError';\n if (isSolanaError) {\n if (code !== undefined) {\n return (e as SolanaError<TErrorCode>).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<TErrorCode extends SolanaErrorCode = SolanaErrorCode> 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<typeof Error.captureStackTrace>): 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<typeof getSolanaErrorFromInstructionError>),\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<TFrom> = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => ReadonlyUint8Array<ArrayBuffer>;\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<number, 4>;\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<TFrom, TSize extends number = number> = BaseEncoder<TFrom> & {\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<string>;\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<TFrom> = BaseEncoder<TFrom> & {\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<string>;\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<string>;\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<Person> =>\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<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>;\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<TTo> = {\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<number, 4>;\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<TTo, TSize extends number = number> = BaseDecoder<TTo> & {\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<number>;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type VariableSizeDecoder<TTo> = BaseDecoder<TTo> & {\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<string>;\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<string>;\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<Person> =>\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<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>;\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<number | bigint, bigint, 8>;\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<TFrom, TTo extends TFrom = TFrom, TSize extends number = number> = FixedSizeDecoder<\n TTo,\n TSize\n> &\n FixedSizeEncoder<TFrom, TSize>;\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<number | bigint, bigint>;\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<TFrom, TTo extends TFrom = TFrom> = VariableSizeDecoder<TTo> & VariableSizeEncoder<TFrom>;\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<string>;\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<bigint | number, bigint>` can encode both\n * `bigint` and `number` values, but will always decode to a `bigint`.\n *\n * ```ts\n * const codec: Codec<bigint | number, bigint>;\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<TFrom, TTo>` can be combined from an `Encoder<TFrom>`\n * and a `Decoder<TTo>` 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<bigint | number>;\n * const decoder: Decoder<bigint>;\n * const codec: Codec<bigint | number, bigint> = 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<Person> =>\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<TFrom, TTo extends TFrom = TFrom> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>;\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<TFrom>(\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<Person> = 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<TFrom, TSize extends number>(\n encoder: Omit<FixedSizeEncoder<TFrom, TSize>, 'encode'>,\n): FixedSizeEncoder<TFrom, TSize>;\nexport function createEncoder<TFrom>(encoder: Omit<VariableSizeEncoder<TFrom>, 'encode'>): VariableSizeEncoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom> {\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<Person> = 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<TTo, TSize extends number>(\n decoder: Omit<FixedSizeDecoder<TTo, TSize>, 'decode'>,\n): FixedSizeDecoder<TTo, TSize>;\nexport function createDecoder<TTo>(decoder: Omit<VariableSizeDecoder<TTo>, 'decode'>): VariableSizeDecoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo> {\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<PersonInput, Person> = 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<TFrom, TTo extends TFrom = TFrom, TSize extends number = number>(\n codec: Omit<FixedSizeCodec<TFrom, TTo, TSize>, 'decode' | 'encode'>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec: Omit<VariableSizeCodec<TFrom, TTo>, 'decode' | 'encode'>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'decode' | 'encode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'decode' | 'encode'>,\n): Codec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'decode' | 'encode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'decode' | 'encode'>,\n): Codec<TFrom, TTo> {\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<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function isFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n): decoder is FixedSizeDecoder<TTo, TSize>;\nexport function isFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n): codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function isFixedSize<TSize extends number>(\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<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): asserts encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function assertIsFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n): asserts decoder is FixedSizeDecoder<TTo, TSize>;\nexport function assertIsFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n): asserts codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function assertIsFixedSize<TSize extends number>(\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<TFrom>(encoder: Encoder<TFrom>): encoder is VariableSizeEncoder<TFrom>;\nexport function isVariableSize<TTo>(decoder: Decoder<TTo>): decoder is VariableSizeDecoder<TTo>;\nexport function isVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): codec is VariableSizeCodec<TFrom, TTo>;\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<TFrom>(encoder: Encoder<TFrom>): asserts encoder is VariableSizeEncoder<TFrom>;\nexport function assertIsVariableSize<TTo>(decoder: Decoder<TTo>): asserts decoder is VariableSizeDecoder<TTo>;\nexport function assertIsVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): asserts codec is VariableSizeCodec<TFrom, TTo>;\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<TFrom>` and a `Decoder<TTo>`, this function returns a `Codec<TFrom, TTo>`.\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<MyType> => { \\/* ... *\\/ };\n * const getMyTypeDecoder = (): Decoder<MyType> => { \\/* ... *\\/ };\n * const getMyTypeCodec = (): Codec<MyType> =>\n * combineCodec(getMyTypeEncoder(), getMyTypeDecoder());\n * ```\n *\n * @see {@link Codec}\n * @see {@link Encoder}\n * @see {@link Decoder}\n */\nexport function combineCodec<TFrom, TTo extends TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n decoder: FixedSizeDecoder<TTo, TSize>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: VariableSizeEncoder<TFrom>,\n decoder: VariableSizeDecoder<TTo>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>,\n): Codec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>,\n): Codec<TFrom, TTo> {\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<TFrom>(\n encoder: FixedSizeEncoder<TFrom>,\n sentinel: ReadonlyUint8Array,\n): FixedSizeEncoder<TFrom>;\nexport function addEncoderSentinel<TFrom>(\n encoder: Encoder<TFrom>,\n sentinel: ReadonlyUint8Array,\n): VariableSizeEncoder<TFrom>;\nexport function addEncoderSentinel<TFrom>(encoder: Encoder<TFrom>, sentinel: ReadonlyUint8Array): Encoder<TFrom> {\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<TFrom>['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<TTo>(\n decoder: FixedSizeDecoder<TTo>,\n sentinel: ReadonlyUint8Array,\n): FixedSizeDecoder<TTo>;\nexport function addDecoderSentinel<TTo>(decoder: Decoder<TTo>, sentinel: ReadonlyUint8Array): VariableSizeDecoder<TTo>;\nexport function addDecoderSentinel<TTo>(decoder: Decoder<TTo>, sentinel: ReadonlyUint8Array): Decoder<TTo> {\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<TTo>['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<TFrom, TTo extends TFrom>(\n codec: FixedSizeCodec<TFrom, TTo>,\n sentinel: ReadonlyUint8Array,\n): FixedSizeCodec<TFrom, TTo>;\nexport function addCodecSentinel<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n sentinel: ReadonlyUint8Array,\n): VariableSizeCodec<TFrom, TTo>;\nexport function addCodecSentinel<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n sentinel: ReadonlyUint8Array,\n): Codec<TFrom, TTo> {\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<bigint | number> | Encoder<number>;\ntype FixedSizeNumberEncoder<TSize extends number = number> =\n | FixedSizeEncoder<bigint | number, TSize>\n | FixedSizeEncoder<number, TSize>;\ntype NumberDecoder = Decoder<bigint> | Decoder<number>;\ntype FixedSizeNumberDecoder<TSize extends number = number> =\n | FixedSizeDecoder<bigint, TSize>\n | FixedSizeDecoder<number, TSize>;\ntype NumberCodec = Codec<bigint | number, bigint> | Codec<number>;\ntype FixedSizeNumberCodec<TSize extends number = number> =\n | FixedSizeCodec<bigint | number, bigint, TSize>\n | FixedSizeCodec<number, number, TSize>;\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<TFrom>(\n encoder: FixedSizeEncoder<TFrom>,\n prefix: FixedSizeNumberEncoder,\n): FixedSizeEncoder<TFrom>;\nexport function addEncoderSizePrefix<TFrom>(encoder: Encoder<TFrom>, prefix: NumberEncoder): VariableSizeEncoder<TFrom>;\nexport function addEncoderSizePrefix<TFrom>(encoder: Encoder<TFrom>, prefix: NumberEncoder): Encoder<TFrom> {\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<TFrom>['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<TTo>(\n decoder: FixedSizeDecoder<TTo>,\n prefix: FixedSizeNumberDecoder,\n): FixedSizeDecoder<TTo>;\nexport function addDecoderSizePrefix<TTo>(decoder: Decoder<TTo>, prefix: NumberDecoder): VariableSizeDecoder<TTo>;\nexport function addDecoderSizePrefix<TTo>(decoder: Decoder<TTo>, prefix: NumberDecoder): Decoder<TTo> {\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<TTo>['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<TFrom, TTo extends TFrom>(\n codec: FixedSizeCodec<TFrom, TTo>,\n prefix: FixedSizeNumberCodec,\n): FixedSizeCodec<TFrom, TTo>;\nexport function addCodecSizePrefix<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n prefix: NumberCodec,\n): VariableSizeCodec<TFrom, TTo>;\nexport function addCodecSizePrefix<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n prefix: NumberCodec,\n): Codec<TFrom, TTo> {\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<T>(decoder: Decoder<T>): Decoder<T> {\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<TFrom, TSize extends number>(\n encoder: Encoder<TFrom>,\n fixedBytes: TSize,\n): FixedSizeEncoder<TFrom, TSize> {\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<TTo, TSize extends number>(\n decoder: Decoder<TTo>,\n fixedBytes: TSize,\n): FixedSizeDecoder<TTo, TSize> {\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<TFrom, TTo extends TFrom, TSize extends number>(\n codec: Codec<TFrom, TTo>,\n fixedBytes: TSize,\n): FixedSizeCodec<TFrom, TTo, TSize> {\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<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec<any>;\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<TEncoder extends AnyEncoder>(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<TDecoder extends AnyDecoder>(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<TCodec extends AnyCodec>(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<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec<any>;\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<TFrom, TSize extends number, TNewSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n resize: (size: TSize) => TNewSize,\n): FixedSizeEncoder<TFrom, TNewSize>;\nexport function resizeEncoder<TEncoder extends AnyEncoder>(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder;\nexport function resizeEncoder<TEncoder extends AnyEncoder>(\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<TFrom, TSize extends number, TNewSize extends number>(\n decoder: FixedSizeDecoder<TFrom, TSize>,\n resize: (size: TSize) => TNewSize,\n): FixedSizeDecoder<TFrom, TNewSize>;\nexport function resizeDecoder<TDecoder extends AnyDecoder>(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder;\nexport function resizeDecoder<TDecoder extends AnyDecoder>(\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<TFrom, TTo extends TFrom, TSize extends number, TNewSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize>,\n resize: (size: TSize) => TNewSize,\n): FixedSizeCodec<TFrom, TTo, TNewSize>;\nexport function resizeCodec<TCodec extends AnyCodec>(codec: TCodec, resize: (size: number) => number): TCodec;\nexport function resizeCodec<TCodec extends AnyCodec>(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<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder<any>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec<any>;\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<TEncoder extends AnyEncoder>(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<TEncoder extends AnyEncoder>(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<TDecoder extends AnyDecoder>(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<TDecoder extends AnyDecoder>(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<TCodec extends AnyCodec>(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<TCodec extends AnyCodec>(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<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n): FixedSizeEncoder<TFrom, TSize> {\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<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize>,\n): FixedSizeDecoder<TTo, TSize> {\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<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize>,\n): FixedSizeCodec<TFrom, TTo, TSize> {\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<A>` and returns an `Encoder<B>`, 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<TOldFrom, TNewFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TOldFrom, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder<TNewFrom, TSize>;\nexport function transformEncoder<TOldFrom, TNewFrom>(\n encoder: VariableSizeEncoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder<TNewFrom>;\nexport function transformEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom>;\nexport function transformEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom> {\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<A>` and returns a `Decoder<B>`, 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<TOldTo, TNewTo, TSize extends number>(\n decoder: FixedSizeDecoder<TOldTo, TSize>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder<TNewTo, TSize>;\nexport function transformDecoder<TOldTo, TNewTo>(\n decoder: VariableSizeDecoder<TOldTo>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder<TNewTo>;\nexport function transformDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo>;\nexport function transformDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo> {\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<A, B>` and returns a `Codec<C, D>`, 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<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeCodec<TNewFrom, TTo, TSize>;\nexport function transformCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: VariableSizeCodec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec<TNewFrom, TTo>;\nexport function transformCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: Codec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec<TNewFrom, TTo>;\nexport function transformCodec<\n TOldFrom,\n TNewFrom,\n TOldTo extends TOldFrom,\n TNewTo extends TNewFrom,\n TSize extends number,\n>(\n codec: FixedSizeCodec<TOldFrom, TOldTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec<TNewFrom, TNewTo, TSize>;\nexport function transformCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: VariableSizeCodec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec<TNewFrom, TNewTo>;\nexport function transformCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo>;\nexport function transformCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo> {\n return createCodec({\n ...transformEncoder(codec, unmap),\n read: map ? transformDecoder(codec, map).read : (codec.read as unknown as Decoder<TNewTo>['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<string>` 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<string> => {\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<string>` 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<string> => {\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<string>` 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<string> =>\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<string>` 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<string>` 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<string>` 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<string>` 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<string> =>\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<string>` 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<string> =>\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<string>` 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<string> => 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<string>` 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<string>` 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<string>` 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<string>` 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<string> =>\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<string>` 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<string> =>\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<string>` 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<string> =>\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<string>` 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<string> => {\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<string>` 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<string> => {\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<string>` 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<string> => 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<string>` 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<string> => {\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<string>` 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<string> => {\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<string>` 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<string> => combineCodec(getUtf8Encoder(), getUtf8Decoder());\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<TAddress extends string = string> = Brand<EncodedString<TAddress, 'base58'>, 'Address'>;\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\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<typeof putativeAddress> {\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<typeof putativeAddress> {\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<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address<TAddress>;\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<Address, 32> {\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<Address, 32> {\n return fixDecoderSize(getMemoizedBase58Decoder(), 32) as FixedSizeDecoder<Address, 32>;\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<Address, Address, 32> {\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<TAddress extends string = string> = AffinePoint<Address<TAddress>, '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<TAddress extends Address>(\n putativeOffCurveAddress: TAddress,\n): putativeOffCurveAddress is OffCurveAddress<TAddress> {\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<TAddress extends Address>(\n putativeOffCurveAddress: TAddress,\n): asserts putativeOffCurveAddress is OffCurveAddress<TAddress> {\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<TAddress extends Address>(\n putativeOffCurveAddress: TAddress,\n): OffCurveAddress<TAddress> {\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<TAddress extends string = string> = Readonly<\n [Address<TAddress>, 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<number, 'ProgramDerivedAddressBump'>;\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<TAddress extends string = string>(\n value: unknown,\n): value is ProgramDerivedAddress<TAddress> {\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<TAddress extends string = string>(\n value: unknown,\n): asserts value is ProgramDerivedAddress<TAddress> {\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<Address> {\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<ProgramDerivedAddress> {\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<Address> {\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<Address> {\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 type {\n WalletAddressResolution,\n WalletAddressSource,\n WalletIdentity,\n WalletIdentityAddress,\n WalletIdentityChainLike,\n} from \"../types\";\nimport { validateAddressForChain } from \"../validation/address\";\nimport { normalizeChainKey, normalizeChainType } from \"../utils/chains\";\n\nfunction normalizeIdentityChainId(\n chain?: WalletIdentityChainLike\n): string | undefined {\n if (!chain || typeof chain === \"string\") return undefined;\n const raw = chain.chainId ?? chain.id;\n if (raw === undefined || raw === null) return undefined;\n const normalized = String(raw).trim();\n return normalized || undefined;\n}\n\nfunction identityEntryMatchesChain(\n entry: WalletIdentityAddress,\n chainType?: string,\n chainKey?: string,\n chainId?: string\n) {\n if (chainKey && entry.chainKey && entry.chainKey === chainKey) return true;\n if (chainId && entry.chainId && entry.chainId === chainId) return true;\n if (chainType && entry.chainType === chainType) return true;\n return false;\n}\n\nexport function createWalletIdentity(\n addresses: WalletIdentityAddress[] = []\n): WalletIdentity {\n return { addresses };\n}\n\nexport function upsertWalletIdentityAddress(\n identity: WalletIdentity,\n next: WalletIdentityAddress\n): WalletIdentity {\n const normalizedAddress = next.address.trim();\n const normalizedChainKey = next.chainKey\n ? normalizeChainKey(next.chainKey)\n : undefined;\n const normalizedChainId = next.chainId?.trim() || undefined;\n\n const addresses = identity.addresses.filter((entry) => {\n if (entry.chainType !== next.chainType) return true;\n if (normalizedChainKey && entry.chainKey === normalizedChainKey)\n return false;\n if (normalizedChainId && entry.chainId === normalizedChainId) return false;\n if (!normalizedChainKey && !normalizedChainId) return false;\n return true;\n });\n\n if (!normalizedAddress) return createWalletIdentity(addresses);\n\n return createWalletIdentity([\n ...addresses,\n {\n ...next,\n address: normalizedAddress,\n chainKey: normalizedChainKey,\n chainId: normalizedChainId,\n },\n ]);\n}\n\nexport function resolveWalletAddressForChain(\n identity: WalletIdentity,\n chain?: WalletIdentityChainLike\n): WalletAddressResolution {\n const chainType = normalizeChainType(chain);\n const chainDef = typeof chain === \"object\" && chain ? chain : undefined;\n const chainKey = chainDef\n ? normalizeChainKey(\n chainDef.networkIdentifier ?? chainDef.chainId ?? chainDef.id\n )\n : typeof chain === \"string\"\n ? normalizeChainKey(chain)\n : undefined;\n const chainId = normalizeIdentityChainId(chain);\n\n if (!chainType) {\n return {\n status: \"missing\",\n reason: \"unknown_chain_type\",\n chainKey,\n chainId,\n };\n }\n\n const match = identity.addresses.find((entry) =>\n identityEntryMatchesChain(entry, chainType, chainKey, chainId)\n );\n\n if (!match) {\n return {\n status: \"missing\",\n reason: \"missing_chain_address\",\n chainType,\n chainKey,\n chainId,\n };\n }\n\n const validation = validateAddressForChain(\n match.address,\n chainDef ?? chainType\n );\n if (!validation.isValid) {\n return {\n status: \"invalid\",\n reason: validation.error ?? \"invalid_chain_address\",\n address: match.address,\n source: match.source,\n chainType,\n chainKey,\n chainId,\n };\n }\n\n return {\n status: \"resolved\",\n address: match.address.trim(),\n source: match.source,\n chainType,\n chainKey,\n chainId,\n };\n}\n\nexport function buildWalletIdentityAddress(params: {\n address: string;\n chain: WalletIdentityChainLike;\n source: WalletAddressSource;\n providerId?: string;\n}): WalletIdentityAddress | null {\n const chainType = normalizeChainType(params.chain);\n if (!chainType) return null;\n\n const address = params.address.trim();\n const chainId = normalizeIdentityChainId(params.chain);\n const chainDef =\n typeof params.chain === \"object\" && params.chain ? params.chain : undefined;\n const chainKey = chainDef\n ? normalizeChainKey(\n chainDef.networkIdentifier ?? chainDef.chainId ?? chainDef.id\n )\n : undefined;\n\n return {\n address,\n chainType,\n chainId,\n chainKey,\n providerId: params.providerId,\n source: params.source,\n };\n}\n\nexport class IdentityStore {\n private _identity = createWalletIdentity();\n\n get snapshot() {\n return this._identity;\n }\n\n reset() {\n this._identity = createWalletIdentity();\n }\n\n upsert(next: WalletIdentityAddress) {\n this._identity = upsertWalletIdentityAddress(this._identity, next);\n return this._identity;\n }\n\n resolve(chain?: WalletIdentityChainLike) {\n return resolveWalletAddressForChain(this._identity, chain);\n }\n}\n","import type {\n DetectedWallet,\n WalletInterFaceAPI,\n SimpleWalletInterface,\n WalletIdentityAddress,\n} from \"../types\";\nimport type { WagmiBridge } from \"./bridges\";\nimport { connectDetectedWallet } from \"./connect\";\nimport { useWalletDetection } from \"./detect\"; // you can also inline detect() if you want non-react\nimport { IdentityStore, buildWalletIdentityAddress } from \"../identity\";\nimport { bindSolanaProviderEvents } from \"./solana\";\n\ntype Status = \"idle\" | \"detecting\" | \"connecting\" | \"connected\" | \"error\";\ntype Listener = (s: Status) => void;\n\nclass WalletManager {\n private _status: Status = \"idle\";\n private _wallet: WalletInterFaceAPI | null = null;\n private _detected: DetectedWallet[] = [];\n private _listeners = new Set<Listener>();\n private _error: string | null = null;\n private _identity = new IdentityStore();\n private _providerCleanup: (() => void) | null = null;\n private _connectedWalletId: string | null = null;\n\n get status() {\n return this._status;\n }\n get error() {\n return this._error;\n }\n get detected(): DetectedWallet[] {\n return this._detected;\n }\n get wallet(): WalletInterFaceAPI | null {\n return this._wallet;\n }\n get simple(): SimpleWalletInterface | null {\n if (!this._wallet) return null;\n const { getAddress, disconnect } = this._wallet;\n return { getAddress, disconnect };\n }\n get identity() {\n return this._identity.snapshot;\n }\n get connectedWalletId() {\n return this._connectedWalletId;\n }\n\n onChange(fn: Listener) {\n this._listeners.add(fn);\n return () => this._listeners.delete(fn);\n }\n private emit() {\n for (const fn of this._listeners) fn(this._status);\n }\n\n /** Provide detection results (from your hook or custom function). */\n setDetected(list: DetectedWallet[]) {\n this._detected = list;\n }\n\n /** Optional: auto attach to the first/best detected wallet. */\n async autoAttach(opts?: {\n wagmi?: WagmiBridge;\n pick?: (list: DetectedWallet[]) => DetectedWallet | undefined;\n }) {\n if (!this._detected.length) return;\n const target = (opts?.pick ?? ((l) => l[0]))(this._detected);\n if (!target) return;\n await this.connectDetected(target, opts);\n }\n\n async connectDetected(\n target: DetectedWallet,\n opts?: { wagmi?: WagmiBridge }\n ) {\n if (\n this._status === \"connected\" &&\n this._connectedWalletId === target.meta.id &&\n this._wallet\n ) {\n this.emit();\n return;\n }\n\n this._status = \"connecting\";\n this.clearConnectedWalletState();\n this.emit();\n try {\n const { api, error } = await connectDetectedWallet(target, {\n wagmi: opts?.wagmi,\n });\n if (api && !error) {\n this._wallet = api;\n this._connectedWalletId = target.meta.id;\n this.bindProviderEvents(target);\n await this.syncIdentityFromWallet(target.meta.id);\n this._status = \"connected\";\n this._error = null;\n return { error: null, api };\n }\n\n if (error) {\n this._status = \"error\";\n this._error = error;\n return { error: error, api };\n }\n } catch (e) {\n this._error = e instanceof Error ? e.message : String(e);\n this._status = \"error\";\n this.clearConnectedWalletState();\n } finally {\n this.emit();\n }\n }\n\n async disconnect(wagmi?: WagmiBridge) {\n if (wagmi) await wagmi.disconnect().catch(() => {});\n if (this._wallet?.disconnect) {\n await this._wallet.disconnect().catch(() => {});\n }\n this.clearConnectedWalletState();\n this._status = \"idle\";\n this.emit();\n }\n\n /** Directly attach a pre-provided wallet interface (from old provider prop). */\n attachWallet(api: WalletInterFaceAPI) {\n this.clearConnectedWalletState();\n this._wallet = api;\n this._connectedWalletId = null;\n this._status = \"connected\";\n void this.syncIdentityFromWallet();\n this.emit();\n }\n\n /** Optional helper to set explicit status (e.g., \"initializing\" UX). */\n setStatus(s: Status) {\n this._status = s;\n this.emit();\n }\n\n addIdentityAddress(address: WalletIdentityAddress) {\n this._identity.upsert(address);\n }\n\n resolveAddressForChain(chain: Parameters<IdentityStore[\"resolve\"]>[0]) {\n return this._identity.resolve(chain);\n }\n\n private clearProviderCleanup() {\n this._providerCleanup?.();\n this._providerCleanup = null;\n }\n\n private clearConnectedWalletState() {\n this.clearProviderCleanup();\n this._wallet = null;\n this._connectedWalletId = null;\n }\n\n private bindProviderEvents(target: DetectedWallet) {\n if (!target.provider) return;\n\n if (target.via === \"solana-window\") {\n this._providerCleanup = bindSolanaProviderEvents(target.provider, {\n onConnect: () => {\n this._status = \"connected\";\n void this.syncIdentityFromWallet(target.meta.id);\n this.emit();\n },\n onAccountChanged: () => {\n void this.syncIdentityFromWallet(target.meta.id);\n this.emit();\n },\n onDisconnect: () => {\n this.clearConnectedWalletState();\n this._status = \"idle\";\n this.emit();\n },\n });\n return;\n }\n\n const provider = target.provider as {\n on?: (event: string, listener: (...args: unknown[]) => void) => void;\n off?: (event: string, listener: (...args: unknown[]) => void) => void;\n removeListener?: (\n event: string,\n listener: (...args: unknown[]) => void\n ) => void;\n };\n const onAccountsChanged = (accounts?: unknown) => {\n const nextAccounts = Array.isArray(accounts) ? accounts : [];\n if (nextAccounts.length === 0) {\n this.clearConnectedWalletState();\n this._status = \"idle\";\n this.emit();\n return;\n }\n this._status = \"connected\";\n void this.syncIdentityFromWallet(target.meta.id);\n this.emit();\n };\n const onDisconnect = () => {\n this.clearConnectedWalletState();\n this._status = \"idle\";\n this.emit();\n };\n\n provider.on?.(\"accountsChanged\", onAccountsChanged);\n provider.on?.(\"disconnect\", onDisconnect);\n this._providerCleanup = () => {\n provider.off?.(\"accountsChanged\", onAccountsChanged);\n provider.off?.(\"disconnect\", onDisconnect);\n provider.removeListener?.(\"accountsChanged\", onAccountsChanged);\n provider.removeListener?.(\"disconnect\", onDisconnect);\n };\n }\n\n private async syncIdentityFromWallet(providerId?: string) {\n if (!this._wallet) return;\n try {\n const address = await this._wallet.getAddress();\n const chain =\n this._wallet.ecosystem === \"evm\"\n ? { chainId: String(await this._wallet.getChainId()), type: \"evm\" }\n : {\n chainId: \"solana-mainnet-beta\",\n networkIdentifier: \"solana-mainnet-beta\",\n type: \"solana\",\n };\n const identityAddress = buildWalletIdentityAddress({\n address,\n chain,\n source: \"provider\",\n providerId,\n });\n if (identityAddress) {\n this._identity.upsert(identityAddress);\n }\n } catch {\n // identity sync is best-effort\n }\n }\n}\n\nexport const walletManager = new WalletManager();\n\n/* ---------- Optional tiny React hook to feed detection into the manager ---------- */\nimport { useEffect } from \"react\";\n\n/** If you’re in React, call this once near your widget to push detection results into the manager. */\nexport function useWireDetectionIntoManager() {\n const { detected } = useWalletDetection(); // your existing hook\n useEffect(() => {\n walletManager.setDetected(detected);\n }, [detected]);\n}\n","import { apiBase, jsonHeaders, assertOK, rateLimitedFetch } from \"./http\";\nimport type {\n BuildRouteResult,\n RouteParams,\n RoutePlan,\n Transaction,\n} from \"../types\";\nimport { TrustwareConfigStore } from \"src/config/store\";\nimport { validateRouteAddresses } from \"../validation/address\";\n\nexport type BuildRouteBody = {\n fromChain: string;\n toChain: string;\n fromToken: string;\n toToken: string;\n fromAmount: string;\n fromAddress: string;\n toAddress: string;\n fromAmountUsd?: string;\n fromAmountUSD?: string;\n refundAddress?: string;\n direction?: string;\n slippage?: number;\n slippageBps?: number;\n linkId?: string;\n memo?: string;\n};\n\nexport type TxRequest = {\n to?: string;\n target?: string;\n data: string;\n value?: string;\n gasLimit?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n chainId?: number | string;\n gasPrice?: string;\n};\n\nexport type BuildRouteResponse = {\n intentId?: string;\n route?: RoutePlan;\n data?: {\n intentId?: string;\n route?: RoutePlan;\n };\n error?: string;\n message?: string;\n};\n\ntype DepositAddress = {\n address?: string;\n memo?: string;\n expiresAt?: string;\n};\n\ntype BuildDepositAddressResponse = {\n depositAddress?: DepositAddress;\n intentId?: string;\n route?: RoutePlan;\n data?: {\n depositAddress?: DepositAddress;\n intentId?: string;\n route?: RoutePlan;\n };\n error?: string;\n message?: string;\n};\n\nexport function isEvmTxRequest(txReq?: TxRequest | null) {\n return Boolean(txReq?.data && (txReq.to || txReq.target));\n}\n\nexport function isSerializedSolanaTxRequest(txReq?: TxRequest | null) {\n return Boolean(txReq?.data && !txReq?.to && !txReq?.target);\n}\n\nexport async function buildRoute1(p: RouteParams): Promise<BuildRouteResult> {\n const r = await rateLimitedFetch(`${apiBase()}/squid/route`, {\n method: \"POST\",\n headers: jsonHeaders(),\n credentials: \"omit\",\n body: JSON.stringify(p),\n });\n await assertOK(r);\n const j = await r.json();\n return j.data as BuildRouteResult;\n}\n\nexport async function buildRoute(\n body: BuildRouteBody,\n signal?: AbortSignal\n): Promise<{\n intentId: string;\n txReq: TxRequest;\n actions: unknown[];\n finalExchangeRate: {\n fromAmountUSD?: string;\n toAmountMinUSD?: string;\n };\n route: RoutePlan | undefined;\n}> {\n const addressValidation = validateRouteAddresses({\n fromChain: body.fromChain,\n toChain: body.toChain,\n fromAddress: body.fromAddress,\n toAddress: body.toAddress,\n refundAddress: body.refundAddress,\n direction: body.direction,\n });\n if (!addressValidation.isValid) {\n throw new Error(addressValidation.error || \"Invalid route addresses.\");\n }\n\n const cfg = TrustwareConfigStore.get();\n const url = `${apiBase()}/v1/routes/route`;\n const payload = {\n ...body,\n slippageBps:\n body.slippageBps ??\n (body.slippage === undefined\n ? undefined\n : Math.round(body.slippage * 100)),\n fromAmountUSD: body.fromAmountUSD ?? body.fromAmountUsd,\n };\n const r = await rateLimitedFetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-API-Key\": cfg.apiKey },\n body: JSON.stringify(payload),\n signal,\n });\n\n let json: BuildRouteResponse = {};\n try {\n json = await r.json();\n } catch {\n // response body not JSON\n }\n\n if (!r.ok) {\n const msg = json?.error || json?.message || \"Failed to build route\";\n throw new Error(msg);\n }\n\n const intentId = json?.data?.intentId ?? json?.intentId ?? \"\";\n const route = json?.data?.route ?? json?.route;\n const txReq: TxRequest | undefined = route?.execution?.transaction;\n const actions = Array.isArray(route?.steps) ? route.steps : [];\n const estimate = route?.estimate ?? {};\n\n const finalExchangeRate = {\n fromAmountUSD: (estimate as { fromAmountUsd?: string }).fromAmountUsd,\n toAmountMinUSD: estimate?.toAmountMinUsd ?? estimate?.toAmountUsd,\n };\n\n if (!txReq?.data) {\n throw new Error(\"Invalid route: missing transaction data\");\n }\n\n return { intentId, txReq, actions, finalExchangeRate, route };\n}\n\nexport async function buildDepositAddress(\n body: BuildRouteBody,\n signal?: AbortSignal\n): Promise<{\n intentId: string;\n depositAddress: string;\n actions: unknown[];\n finalExchangeRate: {\n fromAmountUSD?: string;\n toAmountMinUSD?: string;\n };\n route: RoutePlan | undefined;\n}> {\n const cfg = TrustwareConfigStore.get();\n const url = `${apiBase()}/v1/routes/deposit-address`;\n const payload = {\n ...body,\n slippageBps:\n body.slippageBps ??\n (body.slippage === undefined\n ? undefined\n : Math.round(body.slippage * 100)),\n fromAmountUSD: body.fromAmountUSD ?? body.fromAmountUsd,\n };\n const r = await rateLimitedFetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-API-Key\": cfg.apiKey },\n body: JSON.stringify(payload),\n signal,\n });\n\n let json: BuildDepositAddressResponse = {};\n try {\n json = await r.json();\n } catch {\n // response body not JSON\n }\n\n if (!r.ok) {\n const msg =\n json?.error || json?.message || \"Failed to build deposit address\";\n throw new Error(msg);\n }\n\n const intentId = json?.data?.intentId ?? json?.intentId ?? \"\";\n const route = json?.data?.route ?? json?.route;\n const depositAddress =\n json?.data?.depositAddress?.address ?? json?.depositAddress?.address ?? \"\";\n const actions = Array.isArray(route?.steps) ? route.steps : [];\n const estimate = route?.estimate ?? {};\n if (!depositAddress) {\n throw new Error(\"Invalid route: missing deposit address\");\n }\n\n return {\n intentId,\n depositAddress,\n actions,\n finalExchangeRate: {\n fromAmountUSD: (estimate as { fromAmountUsd?: string }).fromAmountUsd,\n toAmountMinUSD: estimate?.toAmountMinUsd ?? estimate?.toAmountUsd,\n },\n route,\n };\n}\n\nexport async function submitReceipt(intentId: string, txHash: string) {\n const r = await rateLimitedFetch(\n `${apiBase()}/v1/route-intent/${intentId}/receipt`,\n {\n method: \"POST\",\n headers: jsonHeaders({ \"Idempotency-Key\": txHash }),\n body: JSON.stringify({ txHash }),\n }\n );\n await assertOK(r);\n const j = await r.json();\n return j.data;\n}\n\nexport async function getStatus(intentId: string): Promise<Transaction> {\n const r = await rateLimitedFetch(\n `${apiBase()}/v1/route-intent/${intentId}/status`,\n {\n headers: jsonHeaders(),\n }\n );\n await assertOK(r);\n const j = await r.json();\n return j.data as Transaction;\n}\n\nexport async function pollStatus(\n intentId: string,\n { intervalMs = 2000, timeoutMs = 5 * 60_000 } = {}\n): Promise<Transaction> {\n const t0 = Date.now();\n while (true) {\n const tx = await getStatus(intentId);\n if (tx.status === \"success\" || tx.status === \"failed\") return tx;\n if (Date.now() - t0 > timeoutMs) return tx;\n await new Promise((r) => setTimeout(r, intervalMs));\n }\n}\n","import type {\n BalanceRow,\n BalanceStreamOptions,\n WalletAddressBalanceWrapper,\n ChainDef,\n} from \"../types/\";\nimport { apiBase, jsonHeaders, rateLimitedFetch } from \"./http\";\nimport { Registry } from \"../registry\";\nimport { TrustwareConfigStore } from \"../config/store\";\nimport {\n getNativeTokenAddress,\n isZeroAddressLike,\n normalizeChainType,\n} from \"../utils/chains\";\nimport { validateAddressForChain } from \"../validation/address\";\n\nexport type { BalanceRow };\n\ntype RawBalanceRow = Record<string, unknown>;\ntype RawBalanceChunk =\n | WalletAddressBalanceWrapper\n | WalletAddressBalanceWrapper[];\n\nconst balanceCache = new Map<string, BalanceRow[]>();\n\nfunction toStringOrUndefined(value: unknown) {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n\nfunction toNumberOrUndefined(value: unknown) {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (typeof value === \"string\") {\n const parsed = Number(value.trim());\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n}\n\nfunction fallbackTokenSymbol(address: string, chainType?: string | null) {\n if (chainType?.toLowerCase() === \"solana\") {\n return \"SPL\";\n }\n return `TOKEN-${address.slice(0, 6)}`;\n}\n\nfunction emitBalanceStreamChunk(address: string, chunkSize: number) {\n TrustwareConfigStore.get().onEvent?.({\n type: \"balance_stream_chunk\",\n address,\n chunkSize,\n });\n}\n\nfunction emitBalanceStreamFallback(address: string, error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n TrustwareConfigStore.get().onEvent?.({\n type: \"balance_stream_fallback\",\n address,\n message,\n });\n}\n\nfunction normalizeRows(\n rows: RawBalanceRow[],\n chain: ChainDef,\n address: string,\n registry: Registry\n) {\n const chainKey = chain.networkIdentifier ?? String(chain.chainId ?? chain.id);\n const chainType = normalizeChainType(chain);\n const nativeAddress = getNativeTokenAddress(chainType);\n const map = new Map<string, BalanceRow>();\n\n for (const item of rows) {\n const category = toStringOrUndefined(item.category)?.toLowerCase();\n const addressRaw =\n item.contract ?? item.token_address ?? item.address ?? item.addr;\n const tokenAddress =\n typeof addressRaw === \"string\" ? addressRaw.trim() : undefined;\n const symbol = toStringOrUndefined(item.symbol ?? item.sym);\n const name =\n toStringOrUndefined(item.name ?? item.token_name ?? item.token) ?? symbol;\n const decimals = toNumberOrUndefined(item.decimals ?? item.dec);\n const balance = String(item.balance ?? item.bal ?? \"0\");\n const explicitNative = Boolean(item.native ?? item.is_native);\n const nativeFlag =\n explicitNative ||\n category === \"native\" ||\n isZeroAddressLike(tokenAddress, chainType);\n\n if (nativeFlag) {\n const nativeRow: BalanceRow = {\n chain_key: chainKey,\n category: \"native\",\n contract: nativeAddress,\n address: nativeAddress,\n symbol: symbol ?? chain.nativeCurrency?.symbol ?? \"NATIVE\",\n name: name ?? chain.nativeCurrency?.name ?? symbol,\n decimals: decimals ?? chain.nativeCurrency?.decimals ?? 18,\n balance,\n };\n map.set(`${chainKey}:${nativeAddress}`, nativeRow);\n continue;\n }\n\n if (!tokenAddress || decimals === undefined) continue;\n\n const metadata = registry.findToken(chain.chainId, tokenAddress);\n const displaySymbol =\n symbol ??\n metadata?.symbol ??\n fallbackTokenSymbol(tokenAddress, chainType);\n const displayName = name ?? metadata?.name ?? displaySymbol;\n const normalizedAddress = metadata?.address ?? tokenAddress;\n\n map.set(`${chainKey}:${normalizedAddress}`, {\n chain_key: chainKey,\n category:\n (category as BalanceRow[\"category\"] | undefined) ??\n (chainType === \"solana\" ? \"spl\" : \"erc20\"),\n contract: normalizedAddress,\n address: normalizedAddress,\n symbol: displaySymbol,\n name: displayName,\n decimals: metadata?.decimals ?? decimals,\n balance,\n logoURI: metadata?.logoURI,\n usdPrice: metadata?.usdPrice,\n });\n }\n\n if (!Array.from(map.values()).some((row) => row.category === \"native\")) {\n map.set(`${chainKey}:${nativeAddress}`, {\n chain_key: chainKey,\n category: \"native\",\n contract: nativeAddress,\n address: nativeAddress,\n symbol: chain.nativeCurrency?.symbol ?? \"NATIVE\",\n name: chain.nativeCurrency?.name ?? chain.nativeCurrency?.symbol,\n decimals: chain.nativeCurrency?.decimals ?? 18,\n balance: \"0\",\n });\n }\n\n return Array.from(map.values()).sort((a, b) => {\n try {\n return Number(BigInt(b.balance) - BigInt(a.balance));\n } catch {\n return 0;\n }\n });\n}\n\nfunction normalizeStreamChunk(\n chunk: RawBalanceChunk\n): WalletAddressBalanceWrapper[] {\n return Array.isArray(chunk) ? chunk : [chunk];\n}\n\nfunction mergeBalanceWrappers(\n current: WalletAddressBalanceWrapper[],\n incoming: WalletAddressBalanceWrapper[]\n): WalletAddressBalanceWrapper[] {\n const merged = new Map<string, WalletAddressBalanceWrapper>();\n\n for (const item of current) {\n merged.set(item.chain_id, item);\n }\n\n for (const item of incoming) {\n const existing = merged.get(item.chain_id);\n if (!existing) {\n merged.set(item.chain_id, item);\n continue;\n }\n\n const balancesByKey = new Map<string, BalanceRow>();\n for (const row of existing.balances ?? []) {\n balancesByKey.set(`${row.contract ?? row.address ?? row.symbol}`, row);\n }\n for (const row of item.balances ?? []) {\n balancesByKey.set(`${row.contract ?? row.address ?? row.symbol}`, row);\n }\n\n merged.set(item.chain_id, {\n ...existing,\n ...item,\n balances: Array.from(balancesByKey.values()),\n count: item.count ?? existing.count,\n });\n }\n\n return Array.from(merged.values());\n}\n\nasync function parseStreamingBalances(\n response: Response,\n address: string,\n options: BalanceStreamOptions = {}\n): Promise<AsyncGenerator<WalletAddressBalanceWrapper[], void, void>> {\n if (!response.body) {\n throw new Error(\"balances stream: empty response body\");\n }\n\n const decoder = new TextDecoder();\n const reader = response.body.getReader();\n\n async function* stream(): AsyncGenerator<\n WalletAddressBalanceWrapper[],\n void,\n void\n > {\n let buffer = \"\";\n\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const frames = buffer.split(/\\r?\\n/);\n buffer = frames.pop() ?? \"\";\n\n for (const frame of frames) {\n const trimmed = frame.trim();\n if (!trimmed) continue;\n\n try {\n const chunk = normalizeStreamChunk(\n JSON.parse(trimmed) as RawBalanceChunk\n );\n emitBalanceStreamChunk(address, chunk.length);\n yield chunk;\n } catch (error) {\n if (options.strict) {\n throw error;\n }\n }\n }\n }\n\n const tail = buffer.trim();\n if (tail) {\n const chunk = normalizeStreamChunk(JSON.parse(tail) as RawBalanceChunk);\n emitBalanceStreamChunk(address, chunk.length);\n yield chunk;\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n return stream();\n}\n\n/** Map chain reference -> backend chain_key and return enriched balances */\nexport async function getBalances(\n chainRef: string | number,\n address: string\n): Promise<BalanceRow[]> {\n const reg = await ensureRegistry();\n const chain = reg.chain(chainRef);\n if (!chain) return [];\n\n const trimmedAddress = address.trim();\n const validation = validateAddressForChain(trimmedAddress, chain);\n if (!validation.isValid) return [];\n\n const chainKey = chain.networkIdentifier ?? String(chain.chainId ?? chain.id);\n const cacheKey = [\n chainKey,\n trimmedAddress,\n chain.nativeCurrency?.symbol ?? \"\",\n chain.nativeCurrency?.decimals ?? \"\",\n normalizeChainType(chain) ?? \"\",\n ].join(\":\");\n const cached = balanceCache.get(cacheKey);\n if (cached) return cached;\n\n const url = `${apiBase()}/v1/data/wallets/${encodeURIComponent(chainKey)}/${trimmedAddress}/balances`;\n const response = await fetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n headers: jsonHeaders(),\n });\n if (!response.ok) throw new Error(`balances: HTTP ${response.status}`);\n const json = await response.json();\n const rows: RawBalanceRow[] = Array.isArray(json) ? json : (json.data ?? []);\n const normalized = normalizeRows(rows, chain, trimmedAddress, reg);\n balanceCache.set(cacheKey, normalized);\n return normalized;\n}\n\nexport async function getBalancesByAddress(\n address: string,\n opts?: BalanceStreamOptions\n): Promise<WalletAddressBalanceWrapper[]> {\n if (opts?.stream && TrustwareConfigStore.get().features.balanceStreaming) {\n const merged: WalletAddressBalanceWrapper[] = [];\n for await (const chunk of getBalancesByAddressStream(address, opts)) {\n const next = mergeBalanceWrappers(merged, chunk);\n merged.splice(0, merged.length, ...next);\n }\n return merged;\n }\n\n const url = `${apiBase()}/data/balances/${address}`;\n const r = await rateLimitedFetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n headers: jsonHeaders(),\n });\n if (!r.ok) throw new Error(`balances: HTTP ${r.status}`);\n const j = await r.json();\n return Array.isArray(j) ? j : (j.results ?? []);\n}\n\nexport async function* getBalancesByAddressStream(\n address: string,\n opts: BalanceStreamOptions = {}\n): AsyncGenerator<WalletAddressBalanceWrapper[], void, void> {\n if (!TrustwareConfigStore.get().features.balanceStreaming) {\n yield await getBalancesByAddress(address);\n return;\n }\n\n const url = `${apiBase()}/data/balances/${address}?stream=1`;\n\n try {\n const response = await rateLimitedFetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n headers: jsonHeaders({\n Accept: \"application/x-ndjson, application/json\",\n }),\n signal: opts.signal,\n });\n\n if (!response.ok) {\n throw new Error(`balances stream: HTTP ${response.status}`);\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n const payload = await response.json();\n yield Array.isArray(payload) ? payload : (payload.results ?? []);\n return;\n }\n\n const stream = await parseStreamingBalances(response, address, opts);\n for await (const chunk of stream) {\n yield chunk;\n }\n } catch (error) {\n emitBalanceStreamFallback(address, error);\n yield await getBalancesByAddress(address);\n }\n}\n\nlet _registry: Registry | undefined;\nasync function ensureRegistry(): Promise<Registry> {\n if (!_registry) {\n _registry = new Registry(apiBase());\n }\n await _registry.ensureLoaded();\n return _registry;\n}\n","import type { BuildRouteResult } from \"../types\";\nimport type { ChainDef } from \"../types\";\nimport { walletManager } from \"../wallets/\";\nimport {\n buildRoute,\n submitReceipt,\n pollStatus,\n isEvmTxRequest,\n isSerializedSolanaTxRequest,\n} from \"./routes\";\n\nfunction backendChainId(chain?: ChainDef, fallback?: number | string): string {\n const preferred = chain?.networkIdentifier ?? chain?.chainId ?? chain?.id;\n return String(preferred ?? fallback ?? \"\");\n}\n\nfunction isUserRejected(e: unknown): boolean {\n const code =\n (e as Record<string, unknown>)?.code ??\n ((e as Record<string, Record<string, unknown>>)?.data?.code as number);\n if (code === 4001) return true;\n const msg = String((e as Error)?.message || e)?.toLowerCase?.() || \"\";\n return msg.includes(\"user rejected\") || msg.includes(\"user denied\");\n}\n\nexport async function sendRouteTransaction(\n b: BuildRouteResult,\n fallbackChainId?: number | string\n): Promise<string> {\n const w = walletManager.wallet;\n if (!w) throw new Error(\"Trustware.wallet not configured\");\n\n const txReq = b.txReq;\n if (isEvmTxRequest(txReq)) {\n if (w.ecosystem !== \"evm\") {\n throw new Error(\"An EVM wallet is required for this route\");\n }\n\n const to = (txReq.to ?? txReq.target) as `0x${string}`;\n const data = txReq.data as `0x${string}`;\n const value = txReq.value ? BigInt(txReq.value) : 0n;\n const target = Number(txReq.chainId ?? fallbackChainId);\n\n if (Number.isFinite(target)) {\n const current = await w.getChainId();\n if (current !== target) {\n try {\n await w.switchChain(target);\n } catch {\n // switchChain failed/skipped — non-fatal\n }\n }\n }\n\n if (w.type === \"eip1193\") {\n const from = await w.getAddress();\n const hexValue = value ? `0x${value.toString(16)}` : \"0x0\";\n const params: Record<string, unknown> = {\n from,\n to,\n data,\n value: hexValue,\n };\n if (Number.isFinite(target)) {\n params.chainId = `0x${target.toString(16)}`;\n }\n\n const hash = await w.request({\n method: \"eth_sendTransaction\",\n params: [params],\n });\n return hash as string;\n }\n\n const response = await w.sendTransaction({\n to,\n data,\n value,\n chainId: Number.isFinite(target) ? target : undefined,\n });\n return response.hash as string;\n }\n\n if (isSerializedSolanaTxRequest(txReq)) {\n if (w.ecosystem !== \"solana\") {\n throw new Error(\"A Solana wallet is required for this route\");\n }\n\n const { Registry } = await import(\"../registry\");\n const { apiBase } = await import(\"./http\");\n const registry = new Registry(apiBase());\n await registry.ensureLoaded();\n\n const chain = registry.chain(\n String(fallbackChainId ?? txReq.chainId ?? \"\")\n );\n return w.sendSerializedTransaction(\n txReq.data,\n backendChainId(chain, fallbackChainId ?? txReq.chainId)\n );\n }\n\n throw new Error(\"Invalid route transaction payload\");\n}\n\nexport async function runTopUp(params: {\n fromChain?: string;\n toChain?: string;\n fromToken?: string;\n toToken?: string;\n toAddress?: string;\n fromAmount: string | number;\n}) {\n const w = walletManager.wallet;\n if (!w) throw new Error(\"Trustware.wallet not configured\");\n\n const { Registry } = await import(\"../registry\");\n const { apiBase } = await import(\"./http\");\n\n const reg = new Registry(apiBase());\n await reg.ensureLoaded();\n\n const fromAddress = await w.getAddress();\n const currentChainRef =\n w.ecosystem === \"evm\"\n ? String(await w.getChainId())\n : ((await w.getChainKey?.()) ?? \"solana-mainnet-beta\");\n const originalChain =\n w.ecosystem === \"evm\" ? await w.getChainId() : undefined;\n\n const fromChain = params.fromChain ?? currentChainRef;\n\n const { TrustwareConfigStore } = await import(\"../config/store\");\n const cfg = TrustwareConfigStore.get();\n const toChain = params.toChain ?? String(cfg.routes.toChain);\n\n const fromToken =\n reg.resolveToken(\n fromChain,\n params.fromToken ?? (cfg.routes.fromToken as string) ?? undefined\n ) ?? params.fromToken;\n const toToken =\n reg.resolveToken(\n toChain,\n params.toToken ?? (cfg.routes.toToken as string) ?? undefined\n ) ?? params.toToken;\n\n if (!fromToken || !toToken) {\n throw new Error(\"Unable to resolve route tokens\");\n }\n\n try {\n const build = await buildRoute({\n fromChain,\n toChain,\n fromToken,\n toToken,\n fromAmount: String(params.fromAmount),\n fromAddress,\n toAddress:\n params.toAddress ??\n cfg.routes.toAddress ??\n (cfg.routes.fromAddress as string | undefined) ??\n fromAddress,\n slippage: cfg.routes.defaultSlippage,\n });\n\n const hash = await sendRouteTransaction(build, fromChain);\n await submitReceipt(build.intentId, hash);\n return await pollStatus(build.intentId);\n } catch (e: unknown) {\n if (isUserRejected(e)) throw new Error(\"Transaction cancelled by user\");\n throw e;\n } finally {\n try {\n if (\n w.ecosystem === \"evm\" &&\n originalChain &&\n originalChain !== Number(fromChain)\n ) {\n await w.switchChain(originalChain);\n }\n } catch {\n // switch back skipped — non-fatal\n }\n }\n}\n","import { useState, useEffect, useMemo } from \"react\";\nimport { getSharedRegistry } from \"./registryClient\";\nimport type { ChainDef } from \"../types\";\nimport {\n canonicalChainKeyForLink,\n canonicalSeiChainKey,\n normalizeChainType,\n} from \"src/widget/helpers/chainHelpers\";\n\nexport interface UseChainsResult {\n /** All available chains */\n chains: ChainDef[];\n /** Popular/featured chains (Ethereum, Polygon, Base) */\n popularChains: ChainDef[];\n /** Other chains (not in popular list) */\n otherChains: ChainDef[];\n /** Whether chains are currently loading */\n isLoading: boolean;\n /** Error message if loading failed */\n error: string | null;\n\n chainMap: Map<string, ChainDef>;\n}\n\n/** Chain IDs for popular chains */\nconst POPULAR_CHAIN_IDS = new Set([\n 1, // Ethereum Mainnet\n 137, // Polygon\n 8453, // Base\n]);\n\nfunction filterSupportedChains(chains: ChainDef[]): ChainDef[] {\n const supportedChainTypes = new Set([\"evm\", \"solana\", \"cosmos\", \"bitcoin\"]);\n return chains.filter((chain) => {\n const chainType = normalizeChainType(chain);\n if (!chainType) return false;\n if (!supportedChainTypes.has(chainType)) {\n return false;\n }\n if (chainType === \"evm\") {\n // hide none working chains for now [Hedera]\n const evmKey = canonicalChainKeyForLink(chain);\n // console.log(\n // \"Checking EVM chain:\",\n // chain.chainId,\n // \"canonical key:\",\n // evmKey\n // );\n const disabledEvmChains = new Set([\"hedera\", \"295\"]);\n if (evmKey && disabledEvmChains.has(evmKey)) {\n return false;\n }\n }\n if (chainType === \"cosmos\") {\n const seiKey = canonicalSeiChainKey(chain.chainId ?? chain.id);\n if (seiKey !== \"sei\" && seiKey !== \"pacific-1\") {\n return false;\n }\n }\n // hide bitcoin for now until we have a better address resoultion for btc maybe wait for squid. or use lifi not sure yet\n if (chainType === \"bitcoin\") {\n return false;\n }\n return true;\n });\n}\n\n/**\n * Hook to load available chains from the registry.\n * Returns chains split into popular and other categories.\n */\nexport function useChains(): UseChainsResult {\n const [chains, setChains] = useState<ChainDef[]>([]);\n const [chainMap, setChainMap] = useState<Map<string, ChainDef>>(new Map());\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const registry = getSharedRegistry();\n\n useEffect(() => {\n if (chains.length > 0) return;\n\n let cancelled = false;\n\n const loadChains = async () => {\n try {\n setIsLoading(true);\n setError(null);\n\n await registry.ensureChainsLoaded();\n\n if (cancelled) return;\n\n // Filter and sort chains\n const loadedChains = registry.chains();\n // .filter((chain) => chain.visible !== false);\n // .filter((chain) => {\n // // Only include EVM chains\n // const type = (chain.type ?? chain.chainType)\n // ?.toString()\n // .toLowerCase();\n // return !type || type === \"evm\";\n // })\n // .sort((a, b) =>\n // resolveChainLabel(a).localeCompare(resolveChainLabel(b))\n // );\n const supportedChains = filterSupportedChains(loadedChains);\n const chainMap: Map<string, ChainDef> = new Map(\n supportedChains.map((chain) => [\n (chain.chainId ?? chain.id) as string,\n chain,\n ])\n );\n\n setChainMap(chainMap);\n\n setChains(supportedChains);\n } catch (err) {\n if (!cancelled) {\n const message =\n err instanceof Error ? err.message : \"Failed to load chains\";\n setError(message);\n setChains([]);\n }\n } finally {\n if (!cancelled) {\n setIsLoading(false);\n }\n }\n };\n\n void loadChains();\n\n return () => {\n cancelled = true;\n };\n }, [registry, chains.length]);\n\n // Split chains into popular and other\n const { popularChains, otherChains } = useMemo(() => {\n const popular: ChainDef[] = [];\n const other: ChainDef[] = [];\n\n for (const chain of chains) {\n const chainId = Number(chain.chainId ?? chain.id);\n if (POPULAR_CHAIN_IDS.has(chainId)) {\n popular.push(chain);\n } else {\n other.push(chain);\n }\n }\n\n // Sort popular chains by the order in POPULAR_CHAIN_IDS\n const popularOrder = [1, 137, 8453];\n popular.sort((a, b) => {\n const aId = Number(a.chainId ?? a.id);\n const bId = Number(b.chainId ?? b.id);\n return popularOrder.indexOf(aId) - popularOrder.indexOf(bId);\n });\n\n return { popularChains: popular, otherChains: other };\n }, [chains]);\n\n return {\n chains,\n chainMap,\n popularChains,\n otherChains,\n isLoading,\n error,\n };\n}\n","import { TrustwareConfigStore } from \"../config\";\nimport { Registry } from \"../registry\";\nimport { apiBase } from \"./http\";\n\nconst registryCache = new Map<string, Registry>();\n\nfunction registryCacheKey(): string {\n const base = apiBase();\n const apiKey = TrustwareConfigStore.peek()?.apiKey ?? \"__uninitialized__\";\n return `${base}::${apiKey}`;\n}\n\nexport function getSharedRegistry(): Registry {\n const key = registryCacheKey();\n const existing = registryCache.get(key);\n if (existing) {\n return existing;\n }\n\n const registry = new Registry(apiBase());\n registryCache.set(key, registry);\n return registry;\n}\n","import type { ChainDef } from \"../../types\";\n\nexport function normalizeChainKey(id: string | number | null): string {\n if (id === undefined || id === null) return \"\";\n return String(id).trim().toLowerCase();\n}\n\nexport const NATIVE_EVM = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\" as const;\nexport const NATIVE_SOLANA =\n \"So11111111111111111111111111111111111111111\" as const;\n\ntype TokenAddressLookupEntry = {\n address: string;\n symbol: string;\n chainId: string | number;\n};\n\nexport function getNativeTokenAddress(chainType?: ChainDef[\"type\"] | null) {\n const normalized = chainType?.toLowerCase?.();\n return normalized === \"solana\" ? NATIVE_SOLANA : NATIVE_EVM;\n}\n\nexport function isSolanaNativeTokenAlias(address?: string | null) {\n if (!address) return false;\n const trimmed = address.trim();\n if (!trimmed) return false;\n return trimmed === NATIVE_SOLANA || trimmed.toLowerCase() === NATIVE_EVM;\n}\n\nexport function parseDecimalToWei(\n input: string,\n decimals: number\n): bigint | null {\n // accepts strings like \"1\", \"1.\", \".5\", \"0.1234\"\n if (!input?.trim()) return null;\n const s = input.trim();\n if (!/^\\d*\\.?\\d*$/.test(s)) return null;\n const [intPartRaw, fracRaw = \"\"] = s.split(\".\");\n const intPart = intPartRaw.length ? BigInt(intPartRaw) : 0n;\n const frac = (fracRaw + \"0\".repeat(decimals)).slice(0, decimals); // pad/right-trim\n const fracPart = frac ? BigInt(frac) : 0n;\n const base = 10n ** BigInt(decimals);\n return intPart * base + fracPart;\n}\n\nconst CHAIN_TYPE_ALIASES: Record<string, SquidChainType> = {\n btc: \"bitcoin\",\n bitcoin: \"bitcoin\",\n sei: \"cosmos\",\n \"pacific-1\": \"cosmos\",\n};\n\nfunction inferChainTypeFromValue(\n normalized: string\n): SquidChainType | undefined {\n if (!normalized) return undefined;\n\n const aliased = CHAIN_TYPE_ALIASES[normalized];\n if (aliased) return aliased;\n\n if (\n normalized === \"evm\" ||\n normalized === \"solana\" ||\n normalized === \"cosmos\" ||\n normalized === \"bitcoin\"\n ) {\n return normalized;\n }\n\n if (/^eip155:\\d+$/.test(normalized) || /^\\d+$/.test(normalized)) {\n return \"evm\";\n }\n\n if (normalized.startsWith(\"solana:\") || normalized.includes(\"solana\")) {\n return \"solana\";\n }\n\n if (\n normalized.startsWith(\"cosmos:\") ||\n normalized.startsWith(\"sei:\") ||\n normalized === \"sei-evm\"\n ) {\n return \"cosmos\";\n }\n\n return undefined;\n}\n\nexport type SquidChainType = \"evm\" | \"cosmos\" | \"solana\" | \"btc\" | string;\n\nexport function normalizeChainType(\n chain?: ChainDef | SquidChainType | string | null\n): SquidChainType | undefined {\n if (!chain) return undefined;\n const raw =\n typeof chain === \"string\"\n ? chain\n : (chain.type ??\n chain.chainType ??\n chain.networkIdentifier ??\n chain.chainId ??\n chain.id ??\n chain.networkName ??\n chain.axelarChainName);\n if (!raw) return undefined;\n const normalized = String(raw).trim().toLowerCase();\n return inferChainTypeFromValue(normalized) ?? normalized;\n}\n\nexport function canonicalChainKeyForLink(chain: ChainDef): string {\n const seiKey = canonicalSeiChainKey(chain.chainId ?? chain.id);\n if (seiKey) return seiKey;\n return normalizeChainKey(\n chain.networkIdentifier ??\n chain.axelarChainName ??\n chain.id ??\n chain.chainId ??\n chain.networkName\n );\n}\n\nconst SEI_EVM_CHAIN_ID = \"1329\";\nconst SEI_COSMOS_CHAIN_ID = \"pacific-1\";\n\nexport function canonicalSeiChainKey(\n chainId: ChainDef[\"chainId\"] | ChainDef[\"id\"] | null\n): string | null {\n const normalized = normalizeChainKey(chainId as string | number | null);\n if (!normalized) return null;\n if (normalized === SEI_EVM_CHAIN_ID) return \"sei-evm\";\n if (normalized === SEI_COSMOS_CHAIN_ID) return \"sei\";\n return null;\n}\n\nexport function isZeroAddrLike(\n a?: string | null,\n chainType?: ChainDef[\"type\"] | null\n) {\n if (!a) return true;\n if (!chainType) return false;\n const s = normalizeAddress(a, chainType);\n return (\n s === normalizeAddress(getNativeTokenAddress(chainType), chainType) ||\n s === \"0x0000000000000000000000000000000000000000\"\n );\n}\n\nexport function normalizeAddress(\n address: string,\n chainType?: ChainDef[\"type\"]\n) {\n if (chainType?.toLowerCase?.() === \"solana\") {\n const trimmed = address.trim();\n if (isSolanaNativeTokenAlias(trimmed)) {\n return NATIVE_SOLANA;\n }\n return trimmed;\n }\n return address.toLowerCase();\n}\n\nexport function isNativeTokenAddress(\n address?: string | null,\n chainType?: ChainDef[\"type\"] | null\n) {\n if (!address) return false;\n if (!chainType) return false;\n return (\n normalizeAddress(address, chainType) ===\n normalizeAddress(getNativeTokenAddress(chainType), chainType)\n );\n}\n\n/**\n * Canonicalizes token identifiers across indexer and registry sources,\n * with cosmos native denom support (e.g. Sei \"usei\").\n */\nexport function canonicalTokenAddressForChain(\n chain: ChainDef,\n address?: string,\n chainTokens: TokenAddressLookupEntry[] = []\n): string {\n const chainType = normalizeChainType(chain);\n const rawAddress = (address ?? \"\").trim();\n\n // Preserve SPL mint addresses; only collapse native SOL aliases for identity.\n if (chainType === \"solana\") return normalizeAddress(rawAddress, \"solana\");\n\n if (chainType === \"cosmos\") {\n const chainIdKey = normalizeChainKey(chain.chainId ?? chain.id ?? \"\");\n const nativeSymbol = chain.nativeCurrency?.symbol?.toUpperCase?.();\n const nativeFromRegistry = chainTokens.find(\n (token) =>\n normalizeChainKey(token.chainId) === chainIdKey &&\n token.symbol?.toUpperCase?.() === nativeSymbol\n );\n const nativeDenom = (nativeFromRegistry?.address ?? \"usei\").toLowerCase();\n\n if (rawAddress.toLowerCase() === NATIVE_EVM) {\n return nativeDenom;\n }\n\n return rawAddress.toLowerCase();\n }\n\n const lowerAddress = rawAddress.toLowerCase();\n if (lowerAddress === \"0x0000000000000000000000000000000000000000\") {\n return NATIVE_EVM;\n }\n return lowerAddress;\n}\n","import { useState, useEffect, useMemo } from \"react\";\nimport { getSharedRegistry } from \"./registryClient\";\nimport type { TokenDef } from \"../types\";\nimport type { Token } from \"../widget/context/DepositContext\";\nimport { useChains } from \"./useChains\";\nimport { sortTokensByPopularity } from \"../widget/helpers/tokenPopularity\";\nimport { TrustwareConfigStore } from \"../config/store\";\n\nconst DEFAULT_PAGE_LIMIT = 100;\n\nexport interface UseTokensResult {\n /** All available tokens for the selected chain */\n tokens: Token[];\n /** Filtered tokens based on search query */\n filteredTokens: Token[];\n /** Whether tokens are currently loading */\n isLoading: boolean;\n /** Error message if loading failed */\n error: string | null;\n /** Current search query */\n searchQuery: string;\n /** Set the search query to filter tokens */\n setSearchQuery: (query: string) => void;\n /** Whether more tokens can be loaded for the active query */\n hasNextPage: boolean;\n /** Load the next token page when pagination is enabled */\n loadMore: () => Promise<void>;\n /** Whether an additional page request is in flight */\n isLoadingMore: boolean;\n}\n\nfunction mapTokenDefToToken(tokenDef: TokenDef): Token {\n return {\n address: tokenDef.address,\n chainId: tokenDef.chainId,\n symbol: tokenDef.symbol,\n name: tokenDef.name,\n decimals: tokenDef.decimals,\n iconUrl: tokenDef.logoURI,\n logoURI: tokenDef.logoURI,\n balance: undefined,\n usdPrice: tokenDef.usdPrice,\n };\n}\n\nfunction dedupeTokens(tokens: Token[]): Token[] {\n const byKey = new Map<string, Token>();\n for (const token of tokens) {\n byKey.set(`${token.chainId}:${token.address.toLowerCase()}`, token);\n }\n return Array.from(byKey.values());\n}\n\nexport function useTokens(\n chainId: string | number | null | undefined\n): UseTokensResult {\n const [tokens, setTokens] = useState<Token[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [searchQuery, setSearchQuery] = useState(\"\");\n const [nextCursor, setNextCursor] = useState<string | undefined>();\n const [hasNextPage, setHasNextPage] = useState(false);\n\n const registry = getSharedRegistry();\n const { chainMap } = useChains();\n const tokensPaginationEnabled =\n TrustwareConfigStore.peek()?.features.tokensPagination ?? false;\n const normalizedSearchQuery = searchQuery.trim();\n const queryDependency = tokensPaginationEnabled ? normalizedSearchQuery : \"\";\n\n useEffect(() => {\n setSearchQuery(\"\");\n setError(null);\n setTokens([]);\n setNextCursor(undefined);\n setHasNextPage(false);\n }, [chainId]);\n\n useEffect(() => {\n if (chainId === undefined || chainMap.size === 0) {\n setIsLoading(false);\n setIsLoadingMore(false);\n return;\n }\n\n let cancelled = false;\n\n const loadInitialTokens = async () => {\n try {\n setIsLoading(true);\n setError(null);\n setTokens([]);\n setNextCursor(undefined);\n setHasNextPage(false);\n\n if (chainId === null || !tokensPaginationEnabled) {\n await registry.ensureLoaded();\n\n if (cancelled) return;\n\n const tokenDefs =\n chainId === null ? registry.allTokens() : registry.tokens(chainId);\n const filtered = tokenDefs.filter((item) =>\n chainMap.has(item.chainId.toString())\n );\n setTokens(filtered.map(mapTokenDefToToken));\n return;\n }\n\n const page = await registry.tokensPage(chainId, {\n q: queryDependency || undefined,\n limit: DEFAULT_PAGE_LIMIT,\n });\n\n if (cancelled) return;\n\n const filtered = page.data.filter((item) =>\n chainMap.has(item.chainId.toString())\n );\n setTokens(filtered.map(mapTokenDefToToken));\n setNextCursor(page.pageInfo.nextCursor);\n setHasNextPage(page.pageInfo.hasNextPage);\n } catch (err) {\n if (!cancelled) {\n const message =\n err instanceof Error ? err.message : \"Failed to load tokens\";\n setError(message);\n setTokens([]);\n setNextCursor(undefined);\n setHasNextPage(false);\n }\n } finally {\n if (!cancelled) {\n setIsLoading(false);\n }\n }\n };\n\n void loadInitialTokens();\n\n return () => {\n cancelled = true;\n };\n }, [chainId, registry, chainMap, queryDependency, tokensPaginationEnabled]);\n\n const loadMore = async () => {\n if (\n chainId == null ||\n !tokensPaginationEnabled ||\n !hasNextPage ||\n !nextCursor ||\n isLoadingMore\n ) {\n return;\n }\n\n try {\n setIsLoadingMore(true);\n const page = await registry.tokensPage(chainId, {\n cursor: nextCursor,\n q: queryDependency || undefined,\n limit: DEFAULT_PAGE_LIMIT,\n });\n const filtered = page.data.filter((item) =>\n chainMap.has(item.chainId.toString())\n );\n setTokens((current) =>\n dedupeTokens([...current, ...filtered.map(mapTokenDefToToken)])\n );\n setNextCursor(page.pageInfo.nextCursor);\n setHasNextPage(page.pageInfo.hasNextPage);\n } catch (err) {\n const message =\n err instanceof Error ? err.message : \"Failed to load more tokens\";\n setError(message);\n } finally {\n setIsLoadingMore(false);\n }\n };\n\n const filteredTokens = useMemo(() => {\n const query = searchQuery.toLowerCase().trim();\n const source =\n query.length === 0 || tokensPaginationEnabled\n ? tokens\n : tokens.filter(\n (token: Token) =>\n token.symbol.toLowerCase().includes(query) ||\n token.name.toLowerCase().includes(query) ||\n token.address.toLowerCase().includes(query)\n );\n\n return sortTokensByPopularity(source);\n }, [tokens, searchQuery, tokensPaginationEnabled]);\n\n return {\n tokens,\n filteredTokens,\n isLoading,\n error,\n searchQuery,\n setSearchQuery,\n hasNextPage,\n loadMore,\n isLoadingMore,\n };\n}\n","{\n \"ethereum\": 1,\n \"1\": 1,\n \"arbitrum\": 2,\n \"arbitrum-one\": 2,\n \"42161\": 2,\n \"base\": 3,\n \"8453\": 3,\n \"bsc\": 4,\n \"binance\": 4,\n \"binance-smart-chain\": 4,\n \"56\": 4,\n \"solana\": 5,\n \"solana-mainnet-beta\": 5,\n \"avalanche\": 6,\n \"avalanche-c-chain\": 6,\n \"43114\": 6,\n \"tron\": 7,\n \"728126428\": 7,\n \"sui\": 8,\n \"137\": 9,\n \"polygon\": 9,\n \"polygon-pos\": 9,\n \"optimism\": 10,\n \"10\": 10,\n \"bitcoin\": 11,\n \"cosmoshub\": 12,\n \"cosmos\": 12,\n \"osmosis\": 13,\n \"sei\": 14,\n \"sei-evm\": 14,\n \"pacific-1\": 14,\n \"1329\": 14,\n \"mantle\": 15,\n \"5000\": 15,\n \"linea\": 16,\n \"59144\": 16,\n \"zksync\": 17,\n \"zksync-era\": 17,\n \"324\": 17,\n \"blast\": 18,\n \"81457\": 18,\n \"scroll\": 19,\n \"534352\": 19,\n \"sonic\": 20,\n \"146\": 20\n}\n","import chainPopularityMap from \"../data/chainPopularity.json\";\nimport { normalizeChainKey } from \"./chainHelpers\";\n\ntype ChainPopularityLookup = Record<string, number>;\n\nconst popularityByKey = chainPopularityMap as ChainPopularityLookup;\n\nexport type ChainPopularityInput = {\n chainId?: string | number | null;\n networkIdentifier?: string | number | null;\n networkName?: string | number | null;\n axelarChainName?: string | number | null;\n};\n\nexport function getChainPopularityRank(\n chain: ChainPopularityInput | null | undefined\n): number | null {\n if (!chain) return null;\n\n const aliases = [\n chain.chainId,\n chain.networkIdentifier,\n chain.networkName,\n chain.axelarChainName,\n ];\n\n for (const alias of aliases) {\n const key = normalizeChainKey(alias ?? null);\n if (!key) continue;\n\n const rank = popularityByKey[key];\n if (typeof rank === \"number\") {\n return rank;\n }\n }\n\n return null;\n}\n","import { getChainPopularityRank } from \"./chainPopularity\";\n\nexport interface TokenPopularitySortable {\n symbol?: string;\n name?: string;\n address?: string;\n balance?: string;\n chainId?: string | number;\n}\n\n/**\n * Mirrors frontend popularity ranking by symbol and well-known contracts.\n */\nconst POPULAR_TOKEN_SYMBOLS = new Set(\n [\n \"USDC\",\n \"USDC.E\",\n \"USDBC\",\n \"USDT\",\n \"DAI\",\n \"ETH\",\n \"WETH\",\n \"WBTC\",\n \"BTC\",\n \"SOL\",\n \"MATIC\",\n ].map((symbol) => symbol.toUpperCase())\n);\n\nconst POPULAR_TOKEN_CONTRACTS = new Set([\n \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\", // USDC (Ethereum)\n \"0xdac17f958d2ee523a2206206994597c13d831ec7\", // USDT (Ethereum)\n \"0x6b175474e89094c44da98b954eedeac495271d0f\", // DAI (Ethereum)\n \"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913\", // USDC (Base)\n \"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359\", // USDC (Polygon)\n \"0x2791bca1f2de4661ed88a30c99a7a9449aa84174\", // USDC.e (Polygon)\n \"0xc2132d05d31c914a87c6611c10748aeb04b58e8f\", // USDT (Polygon)\n \"0xaf88d065e77c8cc2239327c5edb3a432268e5831\", // USDC (Arbitrum)\n \"0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9\", // USDT (Arbitrum)\n \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\", // EVM native token marker\n \"so11111111111111111111111111111111111111112\", // Wrapped SOL\n]);\n\nfunction normalizeSymbol(symbol?: string): string {\n return (symbol ?? \"\").trim().toUpperCase();\n}\n\nfunction normalizeAddress(address?: string): string {\n return (address ?? \"\").trim().toLowerCase();\n}\n\nfunction hasPositiveBalance(balance?: string): boolean {\n if (!balance) return false;\n const trimmed = balance.trim();\n if (!trimmed) return false;\n\n if (/^[+-]?\\d+$/.test(trimmed)) {\n try {\n return BigInt(trimmed) > 0n;\n } catch {\n return false;\n }\n }\n\n if (/^[+-]?\\d*\\.\\d+$/.test(trimmed)) {\n const isNegative = trimmed.startsWith(\"-\");\n if (isNegative) return false;\n\n const normalized = trimmed.startsWith(\"+\") ? trimmed.slice(1) : trimmed;\n const [whole, fraction = \"\"] = normalized.split(\".\");\n const wholeInt = whole ? BigInt(whole) : 0n;\n if (wholeInt > 0n) return true;\n return /[1-9]/.test(fraction);\n }\n\n const asNumber = Number(trimmed);\n return Number.isFinite(asNumber) && asNumber > 0;\n}\n\nexport function isPopularToken(token: TokenPopularitySortable): boolean {\n const normalizedSymbol = normalizeSymbol(token.symbol);\n const normalizedAddress = normalizeAddress(token.address);\n\n return (\n POPULAR_TOKEN_SYMBOLS.has(normalizedSymbol) ||\n POPULAR_TOKEN_CONTRACTS.has(normalizedAddress)\n );\n}\n\nfunction compareText(a?: string, b?: string): number {\n return (a ?? \"\").localeCompare(b ?? \"\", undefined, {\n sensitivity: \"base\",\n });\n}\n\nfunction getGroupRank(token: TokenPopularitySortable): number {\n const popular = isPopularToken(token);\n const positiveBalance = hasPositiveBalance(token.balance);\n\n if (popular && positiveBalance) return 0; // Group A\n if (popular && !positiveBalance) return 1; // Group B\n if (!popular && positiveBalance) return 2; // Group C\n return 3; // Group D\n}\n\nfunction compareChainPopularity(\n a: TokenPopularitySortable,\n b: TokenPopularitySortable\n): number {\n const rankA = getChainPopularityRank({ chainId: a.chainId });\n const rankB = getChainPopularityRank({ chainId: b.chainId });\n\n if (rankA !== null && rankB !== null && rankA !== rankB) {\n return rankA - rankB;\n }\n\n if (rankA !== null && rankB === null) return -1;\n if (rankA === null && rankB !== null) return 1;\n\n return 0;\n}\n\nexport function sortTokensByPopularity<T extends TokenPopularitySortable>(\n tokens: T[]\n): T[] {\n return tokens\n .map((token, index) => ({ token, index }))\n .sort((a, b) => {\n const rankDiff = getGroupRank(a.token) - getGroupRank(b.token);\n if (rankDiff !== 0) return rankDiff;\n\n const chainPopularityDiff = compareChainPopularity(a.token, b.token);\n if (chainPopularityDiff !== 0) return chainPopularityDiff;\n\n const symbolDiff = compareText(a.token.symbol, b.token.symbol);\n if (symbolDiff !== 0) return symbolDiff;\n\n const nameDiff = compareText(a.token.name, b.token.name);\n if (nameDiff !== 0) return nameDiff;\n\n const addressDiff = compareText(a.token.address, b.token.address);\n if (addressDiff !== 0) return addressDiff;\n\n // Stable deterministic tiebreaker for complete duplicates.\n return a.index - b.index;\n })\n .map(({ token }) => token);\n}\n","import { TrustwareErrorCode } from \"./errorCodes\";\n\nexport class TrustwareError extends Error {\n code: TrustwareErrorCode;\n userMessage?: string;\n cause?: unknown;\n\n constructor(params: {\n code: TrustwareErrorCode;\n message: string;\n userMessage?: string;\n cause?: unknown;\n }) {\n super(params.message);\n\n this.name = \"TrustwareError\";\n this.code = params.code;\n this.userMessage = params.userMessage;\n this.cause = params.cause;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n userMessage: this.userMessage,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAEa,kBACA,8BAEA,eASA;AAdb;AAAA;AAAA;AAEO,IAAM,mBAAmB;AACzB,IAAM,+BAA+B;AAErC,IAAM,gBAAsC;AAAA,MACjD,cAAc;AAAA,MACd,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,WAAW;AAAA,MACX,aAAa;AAAA,MACb,QAAQ;AAAA,IACV;AAEO,IAAM,mBAA4C;AAAA,MACvD,OAAO;AAAA,MACP,aAAa;AAAA,IACf;AAAA;AAAA;;;ACjBA,IA0Ja,sBAOA;AAjKb;AAAA;AAAA;AA0JO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ACjC,UAAM,OAAO,qBAAqB,IAAI;AACtC,yBAAqB,OAAO;AAAA,MAC1B,QAAQ;AAAA,QACN,GAAG,KAAK;AAAA,QACR,SAAS;AAAA,MACX;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,YAAuC;AACrC,WAAO,cAAc;AAAA,EACvB;AAAA,EAEA,cAAc;AACZ,WAAO,cAAc;AAAA,EACvB;AAAA,EAEA,uBACE,OACA;AACA,WAAO,cAAc,uBAAuB,KAAK;AAAA,EACnD;AAAA,EAEA,mBACE,SACA;AACA,kBAAc,mBAAmB,OAAO;AACxC,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,MAAM,aAA8B;AAClC,UAAM,IAAI,cAAc;AACxB,QAAI,CAAC,EAAG,OAAM,IAAI,MAAM,iCAAiC;AACzD,WAAO,EAAE,WAAW;AAAA,EACtB;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AACF;","names":["init_config","init_config","e","alphabet","alphabet","alphabet","TextDecoder","TextEncoder","isEvmAddress","fromResult","toResult","e","e","Registry","apiBase","TrustwareConfigStore","import_react","init_config","normalizeChainKey","CHAIN_TYPE_ALIASES","inferChainTypeFromValue","normalizeChainType","normalizeChainKey","normalizeChainType","chainMap","import_react","normalizeChainKey","normalizeAddress","filtered"]}