@qntx/wallet-chains 0.11.0 → 0.13.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"solana.mjs","names":["decoder","u64","isRecord"],"sources":["../src/solana/ids.ts","../src/solana/message.ts","../src/solana/assets.ts","../src/solana/tokens.ts","../src/solana/decode.ts","../src/solana/token2022.ts","../src/solana/verify.ts","../src/solana/index.ts"],"sourcesContent":["import { getAddressDecoder } from \"@solana/addresses\";\n\nimport { ChainError } from \"../index.ts\";\n\n/** Well-known Solana program ids (base58, 32 bytes) — frozen constants. */\nexport const PROGRAM_IDS: Readonly<{\n system: string;\n computeBudget: string;\n associatedToken: string;\n token: string;\n token2022: string;\n stake: string;\n}> = Object.freeze({\n system: \"11111111111111111111111111111111\",\n computeBudget: \"ComputeBudget111111111111111111111111111111\",\n associatedToken: \"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL\",\n token: \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\",\n token2022: \"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb\",\n stake: \"Stake11111111111111111111111111111111111111\",\n});\n\n/**\n * CAIP-2 ids the wallet knows. The wire message itself carries no network marker — `network` is the\n * only declaration and cannot be proven from the bytes.\n */\nexport const SOLANA_NETWORKS: ReadonlyArray<string> = Object.freeze([\n \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\",\n \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\",\n] as const);\n\nconst BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\nexport const isSolanaAddress = (value: string): boolean => BASE58.test(value);\n\nconst decoder = getAddressDecoder();\n\n/** Base58-encoded address for a 32-byte ed25519 public key. */\nexport function solanaAddressFromPublicKey(pubkey: Uint8Array): string {\n if (pubkey.length !== 32) {\n throw new ChainError(\"invalid-address\", \"expected a 32-byte ed25519 public key\");\n }\n return decoder.decode(pubkey);\n}\n","import { getCompiledTransactionMessageDecoder } from \"@solana/transaction-messages\";\n\nimport { ChainError } from \"../index.ts\";\nimport { isSolanaAddress } from \"./ids.ts\";\n\nexport const SOLANA_TRANSACTION_MAX_BYTES = 1232;\n\nexport type CompiledIx = {\n readonly programAddressIndex: number;\n readonly accountIndices: ReadonlyArray<number>;\n readonly data: Uint8Array;\n};\n\nexport type ParsedSolanaMessage = {\n readonly version: \"legacy\" | 0;\n readonly numRequiredSignatures: number;\n readonly staticAccounts: ReadonlyArray<string>;\n readonly instructions: ReadonlyArray<CompiledIx>;\n readonly lookups: ReadonlyArray<LookupReference>;\n};\n\n/** One address-table lookup: the table and which of its entries the message references. */\nexport type LookupReference = {\n readonly address: string;\n readonly writableIndexes: ReadonlyArray<number>;\n readonly readonlyIndexes: ReadonlyArray<number>;\n};\n\nconst decoder = getCompiledTransactionMessageDecoder();\n\n/**\n * Decodes a compiled wire message; rejects trailing bytes and the 1232-byte transaction limit. The\n * fee payer is `staticAccounts[0]` — every valid transaction signs it.\n */\nexport const parseCompiledMessage = (bytes: Uint8Array): ParsedSolanaMessage => {\n if (bytes.length > SOLANA_TRANSACTION_MAX_BYTES) {\n throw new ChainError(\"invalid-request\", \"compiled message exceeds the 1232-byte limit\");\n }\n if (bytes.length === 0) {\n throw new ChainError(\"invalid-request\", \"compiled message is empty\");\n }\n let decoded: unknown;\n try {\n decoded = decoder.decode(bytes);\n } catch {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n const message = asCompiledMessage(decoded);\n const staticAccounts = [...message.staticAccounts];\n const lookups = message.addressTableLookups;\n return {\n version: message.version,\n numRequiredSignatures: message.numSignerAccounts,\n staticAccounts,\n instructions: message.instructions,\n lookups: lookups.map((l) => ({\n address: l.lookupTableAddress,\n writableIndexes: l.writableIndexes,\n readonlyIndexes: l.readonlyIndexes,\n })),\n };\n};\n\ntype CompiledMessage = {\n readonly version: \"legacy\" | 0;\n readonly numSignerAccounts: number;\n readonly staticAccounts: ReadonlyArray<string>;\n readonly instructions: ReadonlyArray<CompiledIx>;\n readonly addressTableLookups: ReadonlyArray<{\n readonly lookupTableAddress: string;\n readonly readonlyIndexes: ReadonlyArray<number>;\n readonly writableIndexes: ReadonlyArray<number>;\n }>;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isStringArray = (value: unknown): value is ReadonlyArray<string> =>\n Array.isArray(value) && value.every((v) => typeof v === \"string\");\n\nconst isNumberArray = (value: unknown): value is ReadonlyArray<number> =>\n Array.isArray(value) && value.every((v) => typeof v === \"number\");\n\nconst isArrayLike = (value: unknown): value is { readonly length: number } =>\n isRecord(value) && typeof value[\"length\"] === \"number\";\n\nconst isIx = (value: unknown): value is CompiledIx =>\n isRecord(value) &&\n typeof value[\"programAddressIndex\"] === \"number\" &&\n (value[\"accountIndices\"] === undefined ||\n isNumberArray(value[\"accountIndices\"]) ||\n isArrayLike(value[\"accountIndices\"])) &&\n value[\"data\"] instanceof Uint8Array;\n\nconst isLookup = (\n value: unknown,\n): value is {\n lookupTableAddress: string;\n readonlyIndexes: ReadonlyArray<number> | Uint8Array;\n writableIndexes: ReadonlyArray<number> | Uint8Array;\n} =>\n isRecord(value) &&\n typeof value[\"lookupTableAddress\"] === \"string\" &&\n (isNumberArray(value[\"readonlyIndexes\"]) || value[\"readonlyIndexes\"] instanceof Uint8Array) &&\n (isNumberArray(value[\"writableIndexes\"]) || value[\"writableIndexes\"] instanceof Uint8Array);\n\nconst asCompiledMessage = (value: unknown): CompiledMessage => {\n if (!isRecord(value) || !isRecord(value[\"header\"])) {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n const { header } = value;\n const { staticAccounts } = value;\n const { instructions } = value;\n const lookups = value[\"addressTableLookups\"];\n if (\n typeof header[\"numSignerAccounts\"] !== \"number\" ||\n !isStringArray(staticAccounts) ||\n !Array.isArray(instructions) ||\n !instructions.every(isIx) ||\n (lookups !== undefined && (!Array.isArray(lookups) || !lookups.every(isLookup)))\n ) {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n const version = value[\"version\"] === 0 ? 0 : \"legacy\";\n const ixs = instructions.map((ix) => {\n if (!isIx(ix)) {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n const indices = ix.accountIndices;\n return {\n programAddressIndex: ix.programAddressIndex,\n accountIndices: indices === undefined ? [] : [...indices],\n data: ix.data,\n };\n });\n const tables = (lookups ?? []).map((t) => {\n if (!isLookup(t)) {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n return {\n lookupTableAddress: t.lookupTableAddress,\n readonlyIndexes: [...t.readonlyIndexes],\n writableIndexes: [...t.writableIndexes],\n };\n });\n return {\n version,\n numSignerAccounts: header[\"numSignerAccounts\"],\n staticAccounts,\n instructions: ixs,\n addressTableLookups: tables,\n };\n};\n\n/**\n * Resolves an account index across static accounts and (request-declared) lookup tables in the\n * compiled lookup order: writable entries then readable.\n */\nexport const resolveAccountIndex = (\n parsed: ParsedSolanaMessage,\n index: number,\n lookups: ReadonlyArray<{ address: string; addresses: ReadonlyArray<string> }> | undefined,\n): string | undefined => {\n if (index < parsed.staticAccounts.length) {\n return parsed.staticAccounts[index];\n }\n if (lookups === undefined) {\n return undefined;\n }\n let offset = index - parsed.staticAccounts.length;\n for (const table of lookups) {\n if (offset < table.addresses.length) {\n return table.addresses[offset];\n }\n offset -= table.addresses.length;\n }\n return undefined;\n};\n\n/** All declared lookup-table entries must be valid base58 32-byte addresses. */\nexport const validateLookupTables = (\n tables: ReadonlyArray<{ address: string; addresses: ReadonlyArray<string> }> | undefined,\n): void => {\n if (tables === undefined) {\n return;\n }\n for (const table of tables) {\n if (!isSolanaAddress(table.address) || !table.addresses.every(isSolanaAddress)) {\n throw new ChainError(\n \"invalid-address\",\n \"lookup table entries must be base58 32-byte addresses\",\n );\n }\n }\n};\n","/** The native asset id in `AssetFlow` and simulated asset changes. */\nexport const SOLANA_NATIVE_ASSET = \"lamports\";\n","/**\n * Built-in SPL token table, keyed by `network` then mint address. An entry makes a\n * `transferChecked` `full`-verifiable (WD-065), so every entry must come from the issuer's own\n * published list; the source is recorded per issuer below.\n */\n\nexport type SolanaToken = {\n readonly symbol: string;\n readonly decimals: number;\n readonly name?: string;\n};\n\nexport type SolanaTokenTable = Readonly<Record<string, Readonly<Record<string, SolanaToken>>>>;\n\n// Circle USDC on Solana mainnet (SPL Token program mint, 6 decimals), from\n// https://developers.circle.com/stablecoins/usdc-contract-addresses (reviewed 2026-10-30).\nconst USDC: SolanaToken = Object.freeze({ symbol: \"USDC\", decimals: 6, name: \"USD Coin\" });\n\n// Tether USDT on Solana mainnet (SPL Token program mint, 6 decimals), from\n// https://tether.to/en/supported-protocols/ (reviewed 2026-10-31).\nconst USDT: SolanaToken = Object.freeze({ symbol: \"USDT\", decimals: 6, name: \"Tether USD\" });\n\nexport const solanaTokenTable: SolanaTokenTable = Object.freeze({\n \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\": Object.freeze({\n EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: USDC,\n Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: USDT,\n }),\n});\n\nexport const lookupSolanaToken = (\n table: SolanaTokenTable,\n network: string,\n mint: string,\n): SolanaToken | undefined => table[network]?.[mint];\n","import { getU32Decoder, getU64Decoder } from \"@solana/codecs\";\n\nimport type {\n ApprovalChange,\n AssetFlow,\n DisplayIntent,\n SignRequest,\n Verifiability,\n} from \"../index.ts\";\nimport { SOLANA_NATIVE_ASSET } from \"./assets.ts\";\nimport { PROGRAM_IDS } from \"./ids.ts\";\nimport { parseCompiledMessage, resolveAccountIndex } from \"./message.ts\";\nimport type { ParsedSolanaMessage } from \"./message.ts\";\nimport { lookupSolanaToken, solanaTokenTable } from \"./tokens.ts\";\nimport type { SolanaTokenTable } from \"./tokens.ts\";\n\nconst u32 = getU32Decoder();\nconst u64 = getU64Decoder();\nconst u32le = (data: Uint8Array, offset: number): number => u32.decode(data, offset);\nconst u64le = (data: Uint8Array, offset: number): bigint => u64.decode(data, offset);\n\ntype IxCall = {\n readonly kind:\n | \"system-transfer\"\n | \"cu-limit\"\n | \"cu-price\"\n | \"ata-create\"\n | \"ata-create-idempotent\"\n | \"token-transfer-checked\"\n | \"token-approve\"\n | \"stake\"\n | \"other\";\n readonly to?: string | undefined;\n readonly amount?: bigint | undefined;\n readonly decimals?: number | undefined;\n readonly mint?: string | undefined;\n readonly units?: number | undefined;\n readonly microLamports?: bigint | undefined;\n};\n\n/**\n * Classifies one instruction by program + discriminator/layout. Exact-length checks keep\n * non-canonical encodings out of the `full` class.\n */\nconst classifyIx = (\n parsed: ParsedSolanaMessage,\n ix: { programAddressIndex: number; accountIndices: ReadonlyArray<number>; data: Uint8Array },\n lookups: ReadonlyArray<{ address: string; addresses: ReadonlyArray<string> }> | undefined,\n): IxCall => {\n const program = resolveAccountIndex(parsed, ix.programAddressIndex, lookups);\n const { data } = ix;\n if (program === PROGRAM_IDS.system) {\n if (data.length === 12 && u32le(data, 0) === 2) {\n return {\n kind: \"system-transfer\",\n to: resolveAccountIndex(parsed, ix.accountIndices[1] ?? 0, lookups),\n amount: u64le(data, 4),\n };\n }\n return { kind: \"other\" };\n }\n if (program === PROGRAM_IDS.computeBudget) {\n if (data.length === 5 && data[0] === 2) {\n return { kind: \"cu-limit\", units: u32le(data, 1) };\n }\n if (data.length === 9 && data[0] === 3) {\n return { kind: \"cu-price\", microLamports: u64le(data, 1) };\n }\n return { kind: \"other\" };\n }\n if (program === PROGRAM_IDS.associatedToken) {\n if (data.length === 1 && data[0] === 0) {\n return { kind: \"ata-create\" };\n }\n if (data.length === 1 && data[0] === 1) {\n return { kind: \"ata-create-idempotent\" };\n }\n return { kind: \"other\" };\n }\n if (program === PROGRAM_IDS.token || program === PROGRAM_IDS.token2022) {\n if (data.length === 10 && data[0] === 12) {\n return {\n kind: \"token-transfer-checked\",\n amount: u64le(data, 1),\n decimals: data[9],\n to: resolveAccountIndex(parsed, ix.accountIndices[2] ?? 0, lookups),\n mint: resolveAccountIndex(parsed, ix.accountIndices[1] ?? 0, lookups),\n };\n }\n if (data.length === 9 && data[0] === 4) {\n return {\n kind: \"token-approve\",\n amount: u64le(data, 1),\n to: resolveAccountIndex(parsed, ix.accountIndices[1] ?? 0, lookups),\n };\n }\n return { kind: \"other\" };\n }\n if (program === PROGRAM_IDS.stake) {\n return { kind: \"stake\" };\n }\n return { kind: \"other\" };\n};\n\nconst FULL_KINDS = new Set([\n \"system-transfer\",\n \"cu-limit\",\n \"cu-price\",\n \"ata-create\",\n \"ata-create-idempotent\",\n]);\n\nconst classify = (\n parsed: ParsedSolanaMessage,\n calls: ReadonlyArray<IxCall>,\n network: string,\n table: SolanaTokenTable,\n): Verifiability => {\n if (parsed.lookups.length > 0) {\n return \"partial\";\n }\n let allFull = true;\n for (const call of calls) {\n if (call.kind === \"other\") {\n return \"opaque\";\n }\n if (call.kind === \"token-approve\" || call.kind === \"stake\") {\n allFull = false;\n }\n if (\n call.kind === \"token-transfer-checked\" &&\n lookupSolanaToken(table, network, call.mint ?? \"\") === undefined\n ) {\n allFull = false;\n }\n if (\n !FULL_KINDS.has(call.kind) &&\n call.kind !== \"token-transfer-checked\" &&\n call.kind !== \"token-approve\" &&\n call.kind !== \"stake\"\n ) {\n return \"opaque\";\n }\n }\n return allFull ? \"full\" : \"partial\";\n};\n\nconst feeLamports = (\n parsed: ParsedSolanaMessage,\n calls: ReadonlyArray<IxCall>,\n): bigint | undefined => {\n const limit = calls.find((c) => c.kind === \"cu-limit\")?.units;\n const price = calls.find((c) => c.kind === \"cu-price\")?.microLamports;\n if (limit === undefined || price === undefined) {\n return undefined;\n }\n const signatures = BigInt(parsed.numRequiredSignatures);\n return 5000n * signatures + (price * BigInt(limit) + 999_999n) / 1_000_000n;\n};\n\nconst decodeTransaction = (\n request: Extract<SignRequest, { kind: \"solana.transaction\" }>,\n signer: string,\n table: SolanaTokenTable,\n): DisplayIntent => {\n const parsed = parseCompiledMessage(request.message);\n const lookups = request.lookupTables?.map((t) => ({\n address: t.address,\n addresses: t.addresses,\n }));\n const calls = parsed.instructions.map((ix) => classifyIx(parsed, ix, lookups));\n const verifiability = classify(parsed, calls, request.network, table);\n const outflows: AssetFlow[] = [];\n const approvals: ApprovalChange[] = [];\n for (const call of calls) {\n if (call.kind === \"system-transfer\" && call.to !== undefined) {\n const [source] = parsed.staticAccounts;\n if (source === signer) {\n outflows.push({\n to: call.to,\n amount: { asset: SOLANA_NATIVE_ASSET, amount: (call.amount ?? 0n).toString(10) },\n verified: true,\n });\n }\n }\n if (call.kind === \"token-transfer-checked\") {\n const token = lookupSolanaToken(table, request.network, call.mint ?? \"\");\n outflows.push({\n to: call.to ?? \"\",\n amount: {\n asset: call.mint ?? \"\",\n amount: (call.amount ?? 0n).toString(10),\n ...(token === undefined ? {} : { symbol: token.symbol, decimals: token.decimals }),\n },\n verified: token !== undefined,\n });\n }\n if (call.kind === \"token-approve\") {\n const token = lookupSolanaToken(table, request.network, call.mint ?? \"\");\n approvals.push({\n kind: \"allowance\",\n spender: call.to ?? \"\",\n amount: {\n asset: call.mint ?? \"\",\n amount: (call.amount ?? 0n).toString(10),\n ...(token === undefined ? {} : { symbol: token.symbol, decimals: token.decimals }),\n },\n change: \"set\",\n unlimited: false,\n verified: token !== undefined,\n });\n }\n }\n const fee = feeLamports(parsed, calls);\n return {\n family: \"solana\",\n network: request.network,\n summary: outflows.length > 0 ? \"transfer\" : \"contract-call\",\n outflows,\n approvals,\n fee:\n fee === undefined\n ? undefined\n : { max: { asset: SOLANA_NATIVE_ASSET, amount: fee.toString(10) } },\n warnings: [],\n verifiability,\n };\n};\n\n/** What the signer can guarantee about this request (WD-065). */\nexport const verifiabilitySolana = (\n request: Extract<SignRequest, { kind: \"solana.transaction\" }>,\n signer: string,\n table: SolanaTokenTable = solanaTokenTable,\n): Verifiability => decodeSolana(request, signer, table).verifiability;\n\nexport const decodeSolana = (\n request: Extract<SignRequest, { kind: \"solana.transaction\" }>,\n signer: string,\n table: SolanaTokenTable = solanaTokenTable,\n): DisplayIntent => decodeTransaction(request, signer, table);\n","import { ChainError } from \"../index.ts\";\n\n/** SPL Token-2022 mint-account TLV extension type numbers (spl-token-2022 `ExtensionType`). */\nexport const EXT = {\n transferFeeConfig: 1,\n confidentialTransferMint: 4,\n defaultAccountState: 6,\n nonTransferable: 9,\n cpiGuard: 11,\n permanentDelegate: 12,\n transferHook: 14,\n confidentialTransferFee: 16,\n confidentialTransferFeeAmount: 17,\n} as const;\n\nexport type MintExtensionSummary = {\n /** The current-epoch fee from TransferFeeConfig (basis points and the maximum fee), if set. */\n readonly transferFee?: { readonly basisPoints: number; readonly maximumFee: bigint };\n readonly transferHook?: { readonly programId: Uint8Array };\n readonly permanentDelegate?: { readonly delegate: Uint8Array };\n readonly nonTransferable?: boolean;\n /** True when a ConfidentialTransfer extension is present — confidential amounts are not supported. */\n readonly confidential?: boolean;\n /** Extension type numbers we do not parse (informational). */\n readonly unknown?: ReadonlyArray<number>;\n};\n\nconst u64 = (v: Uint8Array): bigint =>\n new DataView(v.buffer, v.byteOffset, 8).getBigUint64(0, true);\nconst u16 = (v: Uint8Array): number => new DataView(v.buffer, v.byteOffset, 2).getUint16(0, true);\n\nconst ACCOUNT_TYPE_MINT = 1;\nconst TYPE_OFFSET = 165;\n\n/**\n * Parse the extension region of a full Token-2022 mint account. The account is the 82-byte mint\n * base, zero padding up to byte 165, the account-type byte (`1` = Mint) at 165, then the TLV region\n * at 166 — each entry `u16 type, u16 len, len bytes`. Returns a typed summary; extensions this\n * layer does not read are reported by type number in `unknown` rather than parsed.\n */\nexport const parseMintExtensions = (data: Uint8Array, epoch: bigint): MintExtensionSummary => {\n if (data.length <= TYPE_OFFSET + 1 || data[TYPE_OFFSET] !== ACCOUNT_TYPE_MINT) {\n return {};\n }\n const tlv = data.subarray(TYPE_OFFSET + 1);\n const out: {\n transferFee?: { basisPoints: number; maximumFee: bigint };\n transferHook?: { programId: Uint8Array };\n permanentDelegate?: { delegate: Uint8Array };\n nonTransferable?: boolean;\n confidential?: boolean;\n unknown: number[];\n } = { unknown: [] };\n let offset = 0;\n while (offset + 2 <= tlv.length) {\n const type = u16(tlv.subarray(offset, offset + 2));\n // Uninitialized entries are a u16 marker only — the program stops scanning there and\n // treats the rest as unused space.\n if (type === 0) {\n break;\n }\n if (offset + 4 > tlv.length) {\n throw new ChainError(\"invalid-request\", `mint extension ${type} truncated`);\n }\n const len = u16(tlv.subarray(offset + 2, offset + 4));\n offset += 4;\n if (offset + len > tlv.length) {\n throw new ChainError(\"invalid-request\", `mint extension ${type} truncated`);\n }\n const body = tlv.subarray(offset, offset + len);\n offset += len;\n if (type === EXT.transferFeeConfig && len >= 108) {\n // OptionalNonZeroPubkey×2 (32 B each, zero = none) + u64 withheld + TransferFee×2\n // (18 B each: u64 epoch + u64 maximumFee + u16 basisPoints). The current-epoch fee is\n // the \"newer\" record once its activation epoch is reached, else the \"older\" one.\n const olderMax = u64(body.subarray(80));\n const olderBps = u16(body.subarray(88));\n const newerEpoch = u64(body.subarray(90));\n const newerMax = u64(body.subarray(98));\n const newerBps = u16(body.subarray(106));\n const active =\n newerEpoch <= epoch ? { bps: newerBps, max: newerMax } : { bps: olderBps, max: olderMax };\n if (active.bps !== 0 || active.max !== 0n) {\n out.transferFee = { basisPoints: active.bps, maximumFee: active.max };\n }\n } else if (type === EXT.transferHook && len >= 64) {\n // OptionalNonZeroPubkey authority (32) + program id (32).\n const programId = body.subarray(32, 64);\n out.transferHook = { programId };\n } else if (type === EXT.permanentDelegate && len >= 32) {\n // OptionalNonZeroPubkey delegate (32) — all-zero means none.\n const delegate = body.subarray(0, 32);\n if (delegate.some((b) => b !== 0)) {\n out.permanentDelegate = { delegate };\n }\n } else if (type === EXT.nonTransferable) {\n out.nonTransferable = true;\n } else if (\n type === EXT.confidentialTransferMint ||\n type === EXT.confidentialTransferFee ||\n type === EXT.confidentialTransferFeeAmount\n ) {\n out.confidential = true;\n } else {\n out.unknown.push(type);\n }\n }\n return out.unknown.length === 0 ? out : { ...out, unknown: out.unknown };\n};\n\n/**\n * Net amount a recipient gets after the current-epoch transfer fee, `amt − min(amt*bps/10000,\n * max)`.\n */\nexport const netAfterTransferFee = (amount: bigint, bps: number, max: bigint): bigint => {\n const fee = (amount * BigInt(bps)) / 10_000n;\n return amount - (fee > max ? max : fee);\n};\n","/**\n * Ed25519 signature verification for `chain.sign` results: the host checks the kernel's 64-byte\n * signature against the message and the account address returned by `wallet.accounts` — a wrong\n * signer fails closed.\n */\nimport { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { address, getAddressEncoder } from \"@solana/addresses\";\n\n/** Whether `signature` is a valid ed25519 signature of `message` by the key behind `address`. */\nexport const verifySolanaSignature = (\n message: Uint8Array,\n signature: Uint8Array,\n accountAddress: string,\n): boolean => {\n if (signature.length !== 64) {\n return false;\n }\n try {\n return ed25519.verify(\n signature,\n message,\n new Uint8Array(getAddressEncoder().encode(address(accountAddress))),\n );\n } catch {\n return false;\n }\n};\n","import { isRecord, requestBase } from \"../account-ref.ts\";\nimport { ChainError } from \"../index.ts\";\nimport type { SignRequest } from \"../index.ts\";\nimport { SOLANA_NETWORKS, isSolanaAddress } from \"./ids.ts\";\nimport { parseCompiledMessage, validateLookupTables } from \"./message.ts\";\n\nexport {\n PROGRAM_IDS,\n SOLANA_NETWORKS,\n isSolanaAddress,\n solanaAddressFromPublicKey,\n} from \"./ids.ts\";\nexport { decodeSolana, verifiabilitySolana } from \"./decode.ts\";\nexport { EXT, parseMintExtensions, netAfterTransferFee } from \"./token2022.ts\";\nexport type { MintExtensionSummary } from \"./token2022.ts\";\nexport { SOLANA_NATIVE_ASSET } from \"./assets.ts\";\nexport { parseCompiledMessage } from \"./message.ts\";\nexport type { LookupReference, ParsedSolanaMessage } from \"./message.ts\";\nexport { verifySolanaSignature } from \"./verify.ts\";\nexport type { SolanaTokenTable } from \"./tokens.ts\";\nexport { solanaTokenTable } from \"./tokens.ts\";\n\nconst solanaNetwork = (network: string): void => {\n if (!SOLANA_NETWORKS.includes(network)) {\n throw new ChainError(\"unsupported\", `unknown Solana network: ${network}`);\n }\n};\n\ntype LookupTable = {\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n};\n\nconst validateLookupTablesRaw = (tables: unknown): ReadonlyArray<LookupTable> | undefined => {\n if (tables === undefined) {\n return undefined;\n }\n if (!Array.isArray(tables)) {\n throw new ChainError(\"unknown-field\", \"lookupTables must be an array\");\n }\n const parsed = tables.map((t): LookupTable => {\n if (!isRecord(t) || typeof t[\"address\"] !== \"string\" || !Array.isArray(t[\"addresses\"])) {\n throw new ChainError(\"unknown-field\", \"lookupTables entries must be { address, addresses }\");\n }\n const addresses = t[\"addresses\"].map((a): string => {\n if (typeof a !== \"string\") {\n throw new ChainError(\"invalid-address\", \"lookup table addresses must be strings\");\n }\n return a;\n });\n return { address: t[\"address\"], addresses };\n });\n validateLookupTables(parsed);\n return parsed;\n};\n\n/**\n * Normalizes a Solana sign request. `signer` is the fee payer the wallet is about to sign for — the\n * message must declare it as the first static account. A raw `solana.message` must not decode as a\n * transaction message (chains.mdx rule — a bytes-to-sign path that produces a transaction signature\n * is a wallet-drainer). Idempotent.\n */\nexport const normalizeSolana = (request: unknown, signer: string): SignRequest => {\n if (!isRecord(request) || typeof request[\"kind\"] !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request must be an object with a kind\");\n }\n const { network, account } = requestBase(request);\n solanaNetwork(network);\n if (!isSolanaAddress(signer)) {\n throw new ChainError(\"invalid-address\", \"signer is not a base58 address\");\n }\n const { message } = request;\n if (!(message instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"message must be bytes\");\n }\n if (request[\"kind\"] === \"solana.transaction\") {\n const lookupTables = validateLookupTablesRaw(request[\"lookupTables\"]);\n const parsed = parseCompiledMessage(message);\n const [feePayer] = parsed.staticAccounts;\n if (feePayer === undefined || feePayer !== signer) {\n throw new ChainError(\"fee-payer-mismatch\", \"signer is not the transaction fee payer\");\n }\n return {\n kind: \"solana.transaction\",\n network,\n account,\n message,\n ...(lookupTables === undefined\n ? {}\n : {\n lookupTables: (\n lookupTables as ReadonlyArray<{\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n }>\n ).map((t) => ({ address: t.address, addresses: [...t.addresses] })),\n }),\n };\n }\n if (request[\"kind\"] === \"solana.message\") {\n const { format } = request;\n if (format !== \"raw\") {\n throw new ChainError(\n \"unsupported\",\n `solana.message format ${String(format)} is not supported`,\n );\n }\n let decodesAsTransaction = true;\n try {\n parseCompiledMessage(message);\n } catch {\n decodesAsTransaction = false;\n }\n if (decodesAsTransaction) {\n throw new ChainError(\n \"invalid-request\",\n \"solana.message payload decodes as a transaction message — use solana.transaction\",\n );\n }\n return { kind: \"solana.message\", network, account, message, format };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n"],"mappings":";;;;;;;;AAKA,MAAa,cAOR,OAAO,OAAO;CACjB,QAAQ;CACR,eAAe;CACf,iBAAiB;CACjB,OAAO;CACP,WAAW;CACX,OAAO;AACT,CAAC;;;;;AAMD,MAAa,kBAAyC,OAAO,OAAO,CAClE,2CACA,yCACF,CAAU;AAEV,MAAM,SAAS;AAEf,MAAa,mBAAmB,UAA2B,OAAO,KAAK,KAAK;AAE5E,MAAMA,YAAU,kBAAkB;;AAGlC,SAAgB,2BAA2B,QAA4B;CACrE,IAAI,OAAO,WAAW,IACpB,MAAM,IAAI,WAAW,mBAAmB,uCAAuC;CAEjF,OAAOA,UAAQ,OAAO,MAAM;AAC9B;ACdA,MAAM,UAAU,qCAAqC;;;;;AAMrD,MAAa,wBAAwB,UAA2C;CAC9E,IAAI,MAAM,SAAA,MACR,MAAM,IAAI,WAAW,mBAAmB,8CAA8C;CAExF,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,WAAW,mBAAmB,2BAA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W,OACb,MAAM,IAAI,WACR,eACA,yBAAyB,OAAO,MAAM,EAAE,kBAC1C;EAEF,IAAI,uBAAuB;EAC3B,IAAI;GACF,qBAAqB,OAAO;EAC9B,QAAQ;GACN,uBAAuB;EACzB;EACA,IAAI,sBACF,MAAM,IAAI,WACR,mBACA,kFACF;EAEF,OAAO;GAAE,MAAM;GAAkB;GAAS;GAAS;GAAS;EAAO;CACrE;CACA,MAAM,IAAI,WAAW,eAAe,kCAAkC,QAAQ,SAAS;AACzF"}
1
+ {"version":3,"file":"solana.mjs","names":["decoder","decoder","u16","u32","u64","u32","u64","u32le","u64le","u64","isRecord"],"sources":["../src/solana/ids.ts","../src/solana/message.ts","../src/solana/assets.ts","../src/solana/ata.ts","../src/solana/core.ts","../src/solana/jupiter.ts","../src/solana/stake.ts","../src/solana/tokens.ts","../src/solana/decode.ts","../src/solana/token2022.ts","../src/solana/verify.ts","../src/solana/index.ts"],"sourcesContent":["import { getAddressDecoder } from \"@solana/addresses\";\n\nimport { ChainError } from \"../index.ts\";\n\n/** Well-known Solana program ids (base58, 32 bytes) — frozen constants. */\nexport const PROGRAM_IDS: Readonly<{\n system: string;\n computeBudget: string;\n associatedToken: string;\n token: string;\n token2022: string;\n stake: string;\n}> = Object.freeze({\n system: \"11111111111111111111111111111111\",\n computeBudget: \"ComputeBudget111111111111111111111111111111\",\n associatedToken: \"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL\",\n token: \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\",\n token2022: \"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb\",\n stake: \"Stake11111111111111111111111111111111111111\",\n});\n\n/**\n * CAIP-2 ids the wallet knows. The wire message itself carries no network marker — `network` is the\n * only declaration and cannot be proven from the bytes.\n */\nexport const SOLANA_NETWORKS: ReadonlyArray<string> = Object.freeze([\n \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\",\n \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\",\n] as const);\n\nconst BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\nexport const isSolanaAddress = (value: string): boolean => BASE58.test(value);\n\nconst decoder = getAddressDecoder();\n\n/** Base58-encoded address for a 32-byte ed25519 public key. */\nexport function solanaAddressFromPublicKey(pubkey: Uint8Array): string {\n if (pubkey.length !== 32) {\n throw new ChainError(\"invalid-address\", \"expected a 32-byte ed25519 public key\");\n }\n return decoder.decode(pubkey);\n}\n","import { getCompiledTransactionMessageDecoder } from \"@solana/transaction-messages\";\n\nimport { ChainError } from \"../index.ts\";\nimport { isSolanaAddress } from \"./ids.ts\";\n\nexport const SOLANA_TRANSACTION_MAX_BYTES = 1232;\n\nexport type CompiledIx = {\n readonly programAddressIndex: number;\n readonly accountIndices: ReadonlyArray<number>;\n readonly data: Uint8Array;\n};\n\nexport type ParsedSolanaMessage = {\n readonly version: \"legacy\" | 0;\n readonly numRequiredSignatures: number;\n readonly staticAccounts: ReadonlyArray<string>;\n readonly instructions: ReadonlyArray<CompiledIx>;\n readonly lookups: ReadonlyArray<LookupReference>;\n};\n\n/** One address-table lookup: the table and which of its entries the message references. */\nexport type LookupReference = {\n readonly address: string;\n readonly writableIndexes: ReadonlyArray<number>;\n readonly readonlyIndexes: ReadonlyArray<number>;\n};\n\nconst decoder = getCompiledTransactionMessageDecoder();\n\n/**\n * Decodes a compiled wire message; rejects trailing bytes and the 1232-byte transaction limit. The\n * fee payer is `staticAccounts[0]` — every valid transaction signs it.\n */\nexport const parseCompiledMessage = (bytes: Uint8Array): ParsedSolanaMessage => {\n if (bytes.length > SOLANA_TRANSACTION_MAX_BYTES) {\n throw new ChainError(\"invalid-request\", \"compiled message exceeds the 1232-byte limit\");\n }\n if (bytes.length === 0) {\n throw new ChainError(\"invalid-request\", \"compiled message is empty\");\n }\n let decoded: unknown;\n try {\n decoded = decoder.decode(bytes);\n } catch {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n const message = asCompiledMessage(decoded);\n const staticAccounts = [...message.staticAccounts];\n const lookups = message.addressTableLookups;\n return {\n version: message.version,\n numRequiredSignatures: message.numSignerAccounts,\n staticAccounts,\n instructions: message.instructions,\n lookups: lookups.map((l) => ({\n address: l.lookupTableAddress,\n writableIndexes: l.writableIndexes,\n readonlyIndexes: l.readonlyIndexes,\n })),\n };\n};\n\ntype CompiledMessage = {\n readonly version: \"legacy\" | 0;\n readonly numSignerAccounts: number;\n readonly staticAccounts: ReadonlyArray<string>;\n readonly instructions: ReadonlyArray<CompiledIx>;\n readonly addressTableLookups: ReadonlyArray<{\n readonly lookupTableAddress: string;\n readonly readonlyIndexes: ReadonlyArray<number>;\n readonly writableIndexes: ReadonlyArray<number>;\n }>;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isStringArray = (value: unknown): value is ReadonlyArray<string> =>\n Array.isArray(value) && value.every((v) => typeof v === \"string\");\n\nconst isNumberArray = (value: unknown): value is ReadonlyArray<number> =>\n Array.isArray(value) && value.every((v) => typeof v === \"number\");\n\nconst isArrayLike = (value: unknown): value is { readonly length: number } =>\n isRecord(value) && typeof value[\"length\"] === \"number\";\n\nconst isIx = (value: unknown): value is CompiledIx =>\n isRecord(value) &&\n typeof value[\"programAddressIndex\"] === \"number\" &&\n (value[\"accountIndices\"] === undefined ||\n isNumberArray(value[\"accountIndices\"]) ||\n isArrayLike(value[\"accountIndices\"])) &&\n value[\"data\"] instanceof Uint8Array;\n\nconst isLookup = (\n value: unknown,\n): value is {\n lookupTableAddress: string;\n readonlyIndexes: ReadonlyArray<number> | Uint8Array;\n writableIndexes: ReadonlyArray<number> | Uint8Array;\n} =>\n isRecord(value) &&\n typeof value[\"lookupTableAddress\"] === \"string\" &&\n (isNumberArray(value[\"readonlyIndexes\"]) || value[\"readonlyIndexes\"] instanceof Uint8Array) &&\n (isNumberArray(value[\"writableIndexes\"]) || value[\"writableIndexes\"] instanceof Uint8Array);\n\nconst asCompiledMessage = (value: unknown): CompiledMessage => {\n if (!isRecord(value) || !isRecord(value[\"header\"])) {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n const { header } = value;\n const { staticAccounts } = value;\n const { instructions } = value;\n const lookups = value[\"addressTableLookups\"];\n if (\n typeof header[\"numSignerAccounts\"] !== \"number\" ||\n !isStringArray(staticAccounts) ||\n !Array.isArray(instructions) ||\n !instructions.every(isIx) ||\n (lookups !== undefined && (!Array.isArray(lookups) || !lookups.every(isLookup)))\n ) {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n const version = value[\"version\"] === 0 ? 0 : \"legacy\";\n const ixs = instructions.map((ix) => {\n if (!isIx(ix)) {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n const indices = ix.accountIndices;\n return {\n programAddressIndex: ix.programAddressIndex,\n accountIndices: indices === undefined ? [] : [...indices],\n data: ix.data,\n };\n });\n const tables = (lookups ?? []).map((t) => {\n if (!isLookup(t)) {\n throw new ChainError(\"invalid-request\", \"compiled message failed to decode\");\n }\n return {\n lookupTableAddress: t.lookupTableAddress,\n readonlyIndexes: [...t.readonlyIndexes],\n writableIndexes: [...t.writableIndexes],\n };\n });\n return {\n version,\n numSignerAccounts: header[\"numSignerAccounts\"],\n staticAccounts,\n instructions: ixs,\n addressTableLookups: tables,\n };\n};\n\n/**\n * Resolves an account index across static accounts and (request-declared) lookup tables in the\n * compiled lookup order: writable entries then readable.\n */\nexport const resolveAccountIndex = (\n parsed: ParsedSolanaMessage,\n index: number,\n lookups: ReadonlyArray<{ address: string; addresses: ReadonlyArray<string> }> | undefined,\n): string | undefined => {\n if (index < parsed.staticAccounts.length) {\n return parsed.staticAccounts[index];\n }\n if (lookups === undefined) {\n return undefined;\n }\n /* v0 orders loaded addresses as every table's writable entries (table order), then every\n table's readonly entries (table order); each reference is itself an index into that table's\n declared addresses. */\n const declared = new Map(lookups.map((t) => [t.address, t.addresses]));\n const loaded = [\n ...parsed.lookups.flatMap((t) => t.writableIndexes.map((i) => declared.get(t.address)?.[i])),\n ...parsed.lookups.flatMap((t) => t.readonlyIndexes.map((i) => declared.get(t.address)?.[i])),\n ];\n return loaded[index - parsed.staticAccounts.length];\n};\n\n/** All declared lookup-table entries must be valid base58 32-byte addresses. */\nexport const validateLookupTables = (\n tables: ReadonlyArray<{ address: string; addresses: ReadonlyArray<string> }> | undefined,\n): void => {\n if (tables === undefined) {\n return;\n }\n for (const table of tables) {\n if (!isSolanaAddress(table.address) || !table.addresses.every(isSolanaAddress)) {\n throw new ChainError(\n \"invalid-address\",\n \"lookup table entries must be base58 32-byte addresses\",\n );\n }\n }\n};\n","/** The native asset id in `AssetFlow` and simulated asset changes. */\nexport const SOLANA_NATIVE_ASSET = \"lamports\";\n","import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { address, getAddressDecoder, getAddressEncoder } from \"@solana/addresses\";\n\nimport { ChainError } from \"../index.ts\";\nimport { PROGRAM_IDS } from \"./ids.ts\";\n\nconst PDA_SEED = new TextEncoder().encode(\"ProgramDerivedAddress\");\nconst encoder = getAddressEncoder();\nconst decoder = getAddressDecoder();\n\nconst onCurve = (candidate: Uint8Array): boolean => {\n try {\n ed25519.Point.fromBytes(candidate);\n return true;\n } catch {\n return false;\n }\n};\n\n/**\n * Sync Associated Token Account derivation for the kernel: `findAssociatedTokenPda` is async, so\n * the decoder derives `sha256(owner ‖ tokenProgram ‖ mint ‖ bump ‖ ata ‖ \"ProgramDerivedAddress\")`\n * over bump 255→0 and takes the first hash off the ed25519 curve — matching the on-chain rule.\n */\nexport const associatedTokenAddress = (\n owner: string,\n mint: string,\n tokenProgram: string,\n): string => {\n const ownerBytes = encoder.encode(address(owner));\n const programBytes = encoder.encode(address(tokenProgram));\n const mintBytes = encoder.encode(address(mint));\n const ataBytes = encoder.encode(address(PROGRAM_IDS.associatedToken));\n const input = new Uint8Array(\n ownerBytes.length +\n programBytes.length +\n mintBytes.length +\n 1 +\n ataBytes.length +\n PDA_SEED.length,\n );\n let o = 0;\n const put = (bytes: ArrayLike<number>) => {\n input.set(bytes, o);\n o += bytes.length;\n };\n put(ownerBytes);\n put(programBytes);\n put(mintBytes);\n const bumpAt = o;\n o += 1;\n put(ataBytes);\n put(PDA_SEED);\n for (let bump = 255; bump >= 0; bump -= 1) {\n input[bumpAt] = bump;\n const candidate = sha256(input);\n if (!onCurve(candidate)) {\n return decoder.decode(candidate);\n }\n }\n throw new ChainError(\"invalid-request\", \"no PDA bump for the associated token account\");\n};\n","import type { ParsedSolanaMessage } from \"./message.ts\";\nimport { resolveAccountIndex } from \"./message.ts\";\n\n/** Metaplex Core — recognised by program id; the transfer authority is verified on-chain. */\nexport const MPL_CORE_PROGRAM = \"CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d\";\n\n/**\n * `MplAssetInstruction::TransferV1` = 14; `TransferV1Args` is `{ compressionProof: Option }` — a\n * bare transfer carries `[14, 0]` (no compression proof). mpl-core IDL at c8732ac.\n */\nconst TRANSFER_V1 = Uint8Array.from([14, 0]);\n\nexport type CoreTransfer = {\n readonly authority: string;\n readonly asset: string;\n readonly newOwner: string;\n};\n\n/**\n * `TransferV1` with the accounts `[asset, collection, payer, authority, newOwner, systemProgram,\n * logWrapper]` — omitted optionals carry the program id itself (the Shank convention). The\n * authority slot resolves to the payer when it is the placeholder; it must be the signer for the\n * call to count as a transfer the wallet is doing.\n */\nexport const decodeCoreIx = (\n parsed: ParsedSolanaMessage,\n ix: { readonly accountIndices: ReadonlyArray<number>; readonly data: Uint8Array },\n lookups: ReadonlyArray<{ address: string; addresses: ReadonlyArray<string> }> | undefined,\n): CoreTransfer | undefined => {\n const { data } = ix;\n const account = (i: number): string | undefined => {\n const index = ix.accountIndices[i];\n return index === undefined ? undefined : resolveAccountIndex(parsed, index, lookups);\n };\n /* Data must be exactly [14, 0] — a compression-proof transfer carries a proof blob. */\n if (data.length !== 2 || data[0] !== TRANSFER_V1[0] || data[1] !== TRANSFER_V1[1]) {\n return undefined;\n }\n const asset = account(0);\n const payer = account(2);\n const authoritySlot = account(3);\n const newOwner = account(4);\n if (\n asset === undefined ||\n payer === undefined ||\n authoritySlot === undefined ||\n newOwner === undefined\n ) {\n return undefined;\n }\n const authority = authoritySlot === MPL_CORE_PROGRAM ? payer : authoritySlot;\n return { authority, asset, newOwner };\n};\n","import { getU16Decoder, getU32Decoder, getU64Decoder } from \"@solana/codecs\";\n\nimport type { ParsedSolanaMessage } from \"./message.ts\";\nimport { resolveAccountIndex } from \"./message.ts\";\n\n/** Jupiter's swap program — recognised by program id like Lido's upgradeable proxies. */\nexport const JUPITER_PROGRAM = \"JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4\";\nexport const WSOL_MINT = \"So11111111111111111111111111111111111111112\";\n\nconst ROUTE_V2 = Uint8Array.from([0xbb, 0x64, 0xfa, 0xcc, 0x31, 0xc4, 0xaf, 0x14]);\nconst SHARED_ROUTE_V2 = Uint8Array.from([0xd1, 0x98, 0x53, 0x93, 0x7c, 0xfe, 0xd8, 0xe9]);\n\nconst u16 = getU16Decoder();\nconst u32 = getU32Decoder();\nconst u64 = getU64Decoder();\n\nconst startsWith = (data: Uint8Array, prefix: Uint8Array): boolean =>\n data.length >= prefix.length && prefix.every((b, i) => data[i] === b);\n\nexport type JupiterSwap = {\n readonly authority: string;\n readonly sourceMint: string;\n readonly destinationMint: string;\n readonly destinationTokenProgram: string;\n /**\n * The token account the user receives into — `user_destination_token_account` when the optional\n * destination account field carries the program id (None).\n */\n readonly destinationAccount: string;\n readonly inAmount: bigint;\n readonly quotedOut: bigint;\n readonly slippageBps: number;\n readonly platformFeeBps: number;\n};\n\n/**\n * `route_v2` / `shared_accounts_route_v2`: the fixed scalar prefix must be exact and the trailing\n * `route_plan` vector must declare enough remaining bytes (each step is ≥ 5 bytes on the wire). The\n * route steps themselves stay opaque — the intent only shows the inputs and the floor.\n */\nexport const decodeJupiterIx = (\n parsed: ParsedSolanaMessage,\n ix: { readonly accountIndices: ReadonlyArray<number>; readonly data: Uint8Array },\n lookups: ReadonlyArray<{ address: string; addresses: ReadonlyArray<string> }> | undefined,\n): JupiterSwap | undefined => {\n const { data } = ix;\n const account = (i: number): string | undefined => {\n const index = ix.accountIndices[i];\n return index === undefined ? undefined : resolveAccountIndex(parsed, index, lookups);\n };\n const require = (i: number): string => account(i) ?? \"\";\n const planWellFormed = (offset: number): boolean => {\n if (data.length < offset + 4) {\n return false;\n }\n const count = u32.decode(data, offset);\n return data.length >= offset + 4 + count * 5;\n };\n const scalars = (\n o: number,\n ): Omit<\n JupiterSwap,\n | \"authority\"\n | \"sourceMint\"\n | \"destinationMint\"\n | \"destinationTokenProgram\"\n | \"destinationAccount\"\n > => ({\n inAmount: u64.decode(data, o),\n quotedOut: u64.decode(data, o + 8),\n slippageBps: u16.decode(data, o + 16),\n platformFeeBps: u16.decode(data, o + 18),\n });\n if (startsWith(data, ROUTE_V2)) {\n /* scalars: u64 + u64 + u16 + u16 + u16 = 22 bytes after the 8-byte discriminator. */\n if (ix.accountIndices.length < 10 || !planWellFormed(30)) {\n return undefined;\n }\n const optionalDest = require(7);\n return {\n authority: require(0),\n sourceMint: require(3),\n destinationMint: require(4),\n destinationTokenProgram: require(6),\n destinationAccount: optionalDest === JUPITER_PROGRAM ? require(2) : optionalDest,\n ...scalars(8),\n };\n }\n if (startsWith(data, SHARED_ROUTE_V2)) {\n /* u8 id precedes the same scalars — prefix is 8 + 1 + 22 = 31 bytes. */\n if (ix.accountIndices.length < 12 || !planWellFormed(31)) {\n return undefined;\n }\n return {\n authority: require(1),\n sourceMint: require(6),\n destinationMint: require(7),\n destinationTokenProgram: require(9),\n destinationAccount: require(5),\n ...scalars(9),\n };\n }\n return undefined;\n};\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { address, getAddressEncoder } from \"@solana/addresses\";\nimport { getU32Decoder, getU64Decoder, getI64Decoder } from \"@solana/codecs\";\n\nimport { PROGRAM_IDS, solanaAddressFromPublicKey } from \"./ids.ts\";\nimport { resolveAccountIndex } from \"./message.ts\";\nimport type { ParsedSolanaMessage } from \"./message.ts\";\n\n/** Sysvars the legacy stake account lists carry; post-SIMD-0490 forms omit them. */\nexport const SYSVAR_IDS: Readonly<{\n clock: string;\n rent: string;\n stakeHistory: string;\n stakeConfig: string;\n}> = Object.freeze({\n clock: \"SysvarC1ock11111111111111111111111111111111\",\n rent: \"SysvarRent111111111111111111111111111111111\",\n stakeHistory: \"SysvarStakeHistory1111111111111111111111111\",\n stakeConfig: \"StakeConfig11111111111111111111111111111111\",\n});\n\nconst ZERO_ADDRESS = \"11111111111111111111111111111111\";\n\nconst u32 = getU32Decoder();\nconst u64 = getU64Decoder();\nconst i64 = getI64Decoder();\nconst addr = getAddressEncoder();\n\nconst u32le = (data: Uint8Array, offset: number): number => u32.decode(data, offset);\nconst u64le = (data: Uint8Array, offset: number): bigint => u64.decode(data, offset);\nconst i64le = (data: Uint8Array, offset: number): bigint => i64.decode(data, offset);\nconst key = (data: Uint8Array, offset: number): string =>\n solanaAddressFromPublicKey(data.subarray(offset, offset + 32));\n\n/** One recognized stake-program instruction (bincode data + both account-list forms). */\nexport type StakeIx =\n | {\n readonly kind: \"initialize\";\n readonly account: string;\n readonly staker: string;\n readonly withdrawer: string;\n readonly lockup: boolean;\n }\n | {\n readonly kind: \"initialize-checked\";\n readonly account: string;\n readonly staker: string;\n readonly withdrawer: string;\n }\n | { readonly kind: \"delegate\"; readonly account: string; readonly validator: string }\n | { readonly kind: \"deactivate\"; readonly account: string }\n | {\n readonly kind: \"withdraw\";\n readonly account: string;\n readonly to: string;\n readonly lamports: bigint;\n }\n | {\n readonly kind: \"authorize\";\n readonly account: string;\n readonly role: \"staker\" | \"withdrawer\";\n readonly authority: string;\n };\n\n/** A system-program account creation whose owner is the Stake program. */\nexport type StakeCreate = {\n readonly kind: \"create\";\n readonly account: string;\n readonly from: string;\n readonly lamports: bigint;\n};\n\nconst account = (\n parsed: ParsedSolanaMessage,\n ix: { readonly accountIndices: ReadonlyArray<number> },\n index: number,\n lookups: Parameters<typeof resolveAccountIndex>[2],\n): string | undefined =>\n index < ix.accountIndices.length\n ? resolveAccountIndex(parsed, ix.accountIndices[index] ?? 0, lookups)\n : undefined;\n\nconst role = (data: Uint8Array, offset: number): \"staker\" | \"withdrawer\" | \"other\" => {\n const r = u32le(data, offset);\n return r === 0 ? \"staker\" : r === 1 ? \"withdrawer\" : \"other\";\n};\n\n/**\n * Decodes one Stake-program instruction — exact data length and an account list matching either the\n * current form or the legacy one (recognised by the sysvar it inserts at a fixed position).\n * Anything else is `undefined` → the whole transaction decodes `opaque`.\n */\nexport const decodeStakeIx = (\n parsed: ParsedSolanaMessage,\n ix: { readonly accountIndices: ReadonlyArray<number>; readonly data: Uint8Array },\n lookups: Parameters<typeof resolveAccountIndex>[2],\n): StakeIx | undefined => {\n const { data } = ix;\n const acc = (i: number): string | undefined => account(parsed, ix, i, lookups);\n const n = ix.accountIndices.length;\n if (data.length < 4) {\n return undefined;\n }\n switch (u32le(data, 0)) {\n case 0: {\n /* Initialize: [stake] or [stake, Rent]; staker/withdrawer/lockup in the data. */\n if (data.length !== 116 || !(n === 1 || (n === 2 && acc(1) === SYSVAR_IDS.rent))) {\n return undefined;\n }\n const stake = acc(0);\n if (stake === undefined) {\n return undefined;\n }\n const lockup =\n i64le(data, 68) !== 0n || u64le(data, 76) !== 0n || key(data, 84) !== ZERO_ADDRESS;\n return {\n kind: \"initialize\",\n account: stake,\n staker: key(data, 4),\n withdrawer: key(data, 36),\n lockup,\n };\n }\n case 1: {\n /* Authorize: newAuthority in the data; [stake, auth, (cust)] or [stake, Clock, auth, (cust)]. */\n if (data.length !== 40) {\n return undefined;\n }\n const r = role(data, 36);\n const legacy = acc(1) === SYSVAR_IDS.clock;\n const stake = acc(0);\n const count = legacy ? n === 3 || n === 4 : n === 2 || n === 3;\n if (r === \"other\" || stake === undefined || !count) {\n return undefined;\n }\n return { kind: \"authorize\", account: stake, role: r, authority: key(data, 4) };\n }\n case 2: {\n /* DelegateStake: [stake, vote, staker] or [stake, vote, Clock, StakeHistory, StakeConfig, staker]. */\n const legacy = acc(2) === SYSVAR_IDS.clock;\n const stake = acc(0);\n const vote = acc(1);\n if (\n data.length !== 4 ||\n stake === undefined ||\n vote === undefined ||\n !(\n n === 3 ||\n (n === 6 &&\n legacy &&\n acc(3) === SYSVAR_IDS.stakeHistory &&\n acc(4) === SYSVAR_IDS.stakeConfig)\n )\n ) {\n return undefined;\n }\n return { kind: \"delegate\", account: stake, validator: vote };\n }\n case 4: {\n /* Withdraw: [stake, to, withdrawer, (cust)] or [stake, to, Clock, StakeHistory, withdrawer, (cust)]. */\n const legacy = acc(2) === SYSVAR_IDS.clock && acc(3) === SYSVAR_IDS.stakeHistory;\n const stake = acc(0);\n const to = acc(1);\n if (\n data.length !== 12 ||\n stake === undefined ||\n to === undefined ||\n !(n === 3 || n === 4 || ((n === 5 || n === 6) && legacy))\n ) {\n return undefined;\n }\n return { kind: \"withdraw\", account: stake, to, lamports: u64le(data, 4) };\n }\n case 5: {\n /* Deactivate: [stake, staker] or [stake, Clock, staker]. */\n const stake = acc(0);\n if (\n data.length !== 4 ||\n stake === undefined ||\n !(n === 2 || (n === 3 && acc(1) === SYSVAR_IDS.clock))\n ) {\n return undefined;\n }\n return { kind: \"deactivate\", account: stake };\n }\n case 9: {\n /* InitializeChecked: authorities are accounts — [stake, staker, withdrawer] or [stake, Rent, staker, withdrawer]. */\n const legacy = acc(1) === SYSVAR_IDS.rent;\n const stake = acc(0);\n const staker = acc(legacy ? 2 : 1);\n const withdrawer = acc(legacy ? 3 : 2);\n if (\n data.length !== 4 ||\n stake === undefined ||\n staker === undefined ||\n withdrawer === undefined ||\n !(n === 3 || (n === 4 && legacy))\n ) {\n return undefined;\n }\n return { kind: \"initialize-checked\", account: stake, staker, withdrawer };\n }\n case 10: {\n /* AuthorizeChecked: role in the data; [stake, auth, newAuth, (cust)] or [stake, Clock, auth, newAuth, (cust)]. */\n if (data.length !== 8) {\n return undefined;\n }\n const r = role(data, 4);\n const legacy = acc(1) === SYSVAR_IDS.clock;\n const stake = acc(0);\n const authority = acc(legacy ? 3 : 2);\n const count = legacy ? n === 4 || n === 5 : n === 3 || n === 4;\n if (r === \"other\" || stake === undefined || authority === undefined || !count) {\n return undefined;\n }\n return { kind: \"authorize\", account: stake, role: r, authority };\n }\n default:\n return undefined;\n }\n};\n\n/**\n * A system-program `CreateAccount` (u32 0) or `CreateAccountWithSeed` (u32 3) whose owner is the\n * Stake program — `undefined` for other owners or any layout deviation. A with-seed creation is\n * only recognised when `to` is the sha256(base ‖ seed ‖ owner) derived address.\n */\nexport const decodeStakeCreate = (\n parsed: ParsedSolanaMessage,\n ix: { readonly accountIndices: ReadonlyArray<number>; readonly data: Uint8Array },\n lookups: Parameters<typeof resolveAccountIndex>[2],\n): StakeCreate | \"other\" | undefined => {\n const { data } = ix;\n const acc = (i: number): string | undefined => account(parsed, ix, i, lookups);\n if (data.length < 4) {\n return \"other\";\n }\n if (u32le(data, 0) === 0) {\n if (data.length !== 52 || ix.accountIndices.length !== 2) {\n return \"other\";\n }\n const from = acc(0);\n const to = acc(1);\n if (from === undefined || to === undefined) {\n return \"other\";\n }\n if (key(data, 20) !== PROGRAM_IDS.stake) {\n return \"other\";\n }\n return { kind: \"create\", account: to, from, lamports: u64le(data, 4) };\n }\n if (u32le(data, 0) === 3) {\n /* base(32) + seed(len u64 + bytes) + lamports(8) + space(8) + owner(32). */\n const seedLen = data.length >= 44 ? Number(u64le(data, 36)) : -1;\n const end = 92 + seedLen;\n if (seedLen < 0 || seedLen > 32 || data.length !== end) {\n return \"other\";\n }\n const from = acc(0);\n const to = acc(1);\n if (\n from === undefined ||\n to === undefined ||\n !(ix.accountIndices.length === 2 || ix.accountIndices.length === 3)\n ) {\n return \"other\";\n }\n const base = key(data, 4);\n const owner = key(data, end - 32);\n if (owner !== PROGRAM_IDS.stake) {\n return \"other\";\n }\n if (ix.accountIndices.length === 3 && acc(2) !== base) {\n return \"other\";\n }\n if (ix.accountIndices.length === 2 && base !== from) {\n return \"other\";\n }\n const seed = data.subarray(44, 44 + seedLen);\n const derived = solanaAddressFromPublicKey(\n sha256(\n new Uint8Array([\n ...addr.encode(address(base)),\n ...seed,\n ...addr.encode(address(PROGRAM_IDS.stake)),\n ]),\n ),\n );\n return to === derived\n ? { kind: \"create\", account: to, from, lamports: u64le(data, 44 + seedLen) }\n : \"other\";\n }\n return undefined;\n};\n","/**\n * Built-in SPL token table, keyed by `network` then mint address. An entry makes a\n * `transferChecked` `full`-verifiable (WD-065), so every entry must come from the issuer's own\n * published list; the source is recorded per issuer below.\n */\n\nexport type SolanaToken = {\n readonly symbol: string;\n readonly decimals: number;\n readonly name?: string;\n};\n\nexport type SolanaTokenTable = Readonly<Record<string, Readonly<Record<string, SolanaToken>>>>;\n\n// Circle USDC on Solana mainnet (SPL Token program mint, 6 decimals), from\n// https://developers.circle.com/stablecoins/usdc-contract-addresses (reviewed 2026-10-30).\nconst USDC: SolanaToken = Object.freeze({ symbol: \"USDC\", decimals: 6, name: \"USD Coin\" });\n\n// Tether USDT on Solana mainnet (SPL Token program mint, 6 decimals), from\n// https://tether.to/en/supported-protocols/ (reviewed 2026-10-31).\nconst USDT: SolanaToken = Object.freeze({ symbol: \"USDT\", decimals: 6, name: \"Tether USD\" });\n\nexport const solanaTokenTable: SolanaTokenTable = Object.freeze({\n \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\": Object.freeze({\n EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: USDC,\n Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: USDT,\n }),\n});\n\nexport const lookupSolanaToken = (\n table: SolanaTokenTable,\n network: string,\n mint: string,\n): SolanaToken | undefined => table[network]?.[mint];\n","import { getU32Decoder, getU64Decoder } from \"@solana/codecs\";\n\nimport type {\n ApprovalChange,\n AssetFlow,\n DisplayIntent,\n IntentWarning,\n SignRequest,\n StakeAction,\n Verifiability,\n} from \"../index.ts\";\nimport { SOLANA_NATIVE_ASSET } from \"./assets.ts\";\nimport { associatedTokenAddress } from \"./ata.ts\";\nimport { MPL_CORE_PROGRAM, decodeCoreIx } from \"./core.ts\";\nimport { PROGRAM_IDS } from \"./ids.ts\";\nimport { JUPITER_PROGRAM, WSOL_MINT, decodeJupiterIx } from \"./jupiter.ts\";\nimport type { JupiterSwap } from \"./jupiter.ts\";\nimport { parseCompiledMessage, resolveAccountIndex } from \"./message.ts\";\nimport type { ParsedSolanaMessage } from \"./message.ts\";\nimport { decodeStakeCreate, decodeStakeIx } from \"./stake.ts\";\nimport type { StakeCreate, StakeIx } from \"./stake.ts\";\nimport { lookupSolanaToken, solanaTokenTable } from \"./tokens.ts\";\nimport type { SolanaTokenTable } from \"./tokens.ts\";\n\nconst u32 = getU32Decoder();\nconst u64 = getU64Decoder();\nconst u32le = (data: Uint8Array, offset: number): number => u32.decode(data, offset);\nconst u64le = (data: Uint8Array, offset: number): bigint => u64.decode(data, offset);\n\ntype IxCall = {\n readonly kind:\n | \"system-transfer\"\n | \"system-create\"\n | \"cu-limit\"\n | \"cu-price\"\n | \"ata-create\"\n | \"ata-create-idempotent\"\n | \"token-transfer-checked\"\n | \"token-approve\"\n | \"stake\"\n | \"token-sync-native\"\n | \"token-close-account\"\n | \"jupiter\"\n | \"core-transfer\"\n | \"other\";\n readonly to?: string | undefined;\n readonly amount?: bigint | undefined;\n readonly decimals?: number | undefined;\n readonly mint?: string | undefined;\n readonly units?: number | undefined;\n readonly microLamports?: bigint | undefined;\n /** The instruction's source account — the transfer/create funder, not the fee payer. */\n readonly from?: string | undefined;\n /** A recognized staking instruction: a system create-account or a stake-program op. */\n readonly stake?: StakeIx | StakeCreate | undefined;\n /** A recognised Jupiter swap instruction. */\n readonly jupiter?: JupiterSwap | undefined;\n /** A recognised Metaplex Core transfer: the asset leaves for `newOwner`. */\n readonly core?: { readonly asset: string; readonly newOwner: string } | undefined;\n};\n\n/**\n * Classifies one instruction by program + discriminator/layout. Exact-length checks keep\n * non-canonical encodings out of the `full` class.\n */\nconst classifyIx = (\n parsed: ParsedSolanaMessage,\n ix: { programAddressIndex: number; accountIndices: ReadonlyArray<number>; data: Uint8Array },\n lookups: ReadonlyArray<{ address: string; addresses: ReadonlyArray<string> }> | undefined,\n signer: string,\n): IxCall => {\n const program = resolveAccountIndex(parsed, ix.programAddressIndex, lookups);\n const { data } = ix;\n if (program === PROGRAM_IDS.system) {\n if (data.length === 12 && u32le(data, 0) === 2) {\n return {\n kind: \"system-transfer\",\n from: resolveAccountIndex(parsed, ix.accountIndices[0] ?? 0, lookups),\n to: resolveAccountIndex(parsed, ix.accountIndices[1] ?? 0, lookups),\n amount: u64le(data, 4),\n };\n }\n const create = decodeStakeCreate(parsed, ix, lookups);\n if (create !== undefined && create !== \"other\") {\n return { kind: \"system-create\", stake: create };\n }\n return { kind: \"other\" };\n }\n if (program === PROGRAM_IDS.computeBudget) {\n if (data.length === 5 && data[0] === 2) {\n return { kind: \"cu-limit\", units: u32le(data, 1) };\n }\n if (data.length === 9 && data[0] === 3) {\n return { kind: \"cu-price\", microLamports: u64le(data, 1) };\n }\n return { kind: \"other\" };\n }\n if (program === PROGRAM_IDS.associatedToken) {\n if (data.length === 1 && data[0] === 0) {\n return { kind: \"ata-create\" };\n }\n if (data.length === 1 && data[0] === 1) {\n return { kind: \"ata-create-idempotent\" };\n }\n return { kind: \"other\" };\n }\n if (program === PROGRAM_IDS.token || program === PROGRAM_IDS.token2022) {\n if (data.length === 10 && data[0] === 12) {\n return {\n kind: \"token-transfer-checked\",\n amount: u64le(data, 1),\n decimals: data[9],\n to: resolveAccountIndex(parsed, ix.accountIndices[2] ?? 0, lookups),\n mint: resolveAccountIndex(parsed, ix.accountIndices[1] ?? 0, lookups),\n };\n }\n if (data.length === 9 && data[0] === 4) {\n return {\n kind: \"token-approve\",\n amount: u64le(data, 1),\n to: resolveAccountIndex(parsed, ix.accountIndices[1] ?? 0, lookups),\n };\n }\n if (data.length === 1 && data[0] === 17) {\n /* SyncNative refreshes a wrapped-SOL balance — the wrap itself is the transfer. */\n return { kind: \"token-sync-native\" };\n }\n if (data.length === 1 && data[0] === 9) {\n /* CloseAccount [account, destination, owner] — rent to a foreign address is an outflow the\n amount cannot be read from; a close back to the signer is plumbing. */\n const destination = resolveAccountIndex(parsed, ix.accountIndices[1] ?? 0, lookups);\n return destination === signer ? { kind: \"token-close-account\" } : { kind: \"other\" };\n }\n return { kind: \"other\" };\n }\n if (program === JUPITER_PROGRAM) {\n const jupiter = decodeJupiterIx(parsed, ix, lookups);\n return jupiter !== undefined && jupiter.authority === signer\n ? { kind: \"jupiter\", jupiter }\n : { kind: \"other\" };\n }\n if (program === MPL_CORE_PROGRAM) {\n const core = decodeCoreIx(parsed, ix, lookups);\n return core !== undefined && core.authority === signer\n ? { kind: \"core-transfer\", core }\n : { kind: \"other\" };\n }\n if (program === PROGRAM_IDS.stake) {\n const stake = decodeStakeIx(parsed, ix, lookups);\n return stake === undefined ? { kind: \"other\" } : { kind: \"stake\", stake };\n }\n return { kind: \"other\" };\n};\n\nconst FULL_KINDS = new Set([\n \"system-transfer\",\n \"system-create\",\n \"cu-limit\",\n \"cu-price\",\n \"ata-create\",\n \"ata-create-idempotent\",\n \"stake\",\n \"token-sync-native\",\n \"token-close-account\",\n]);\n\nconst classify = (\n parsed: ParsedSolanaMessage,\n calls: ReadonlyArray<IxCall>,\n network: string,\n table: SolanaTokenTable,\n): Verifiability => {\n let allFull = true;\n for (const call of calls) {\n if (call.kind === \"other\") {\n return \"opaque\";\n }\n if (call.kind === \"token-approve\" || call.kind === \"jupiter\" || call.kind === \"core-transfer\") {\n allFull = false;\n }\n if (\n call.kind === \"token-transfer-checked\" &&\n lookupSolanaToken(table, network, call.mint ?? \"\") === undefined\n ) {\n allFull = false;\n }\n if (\n !FULL_KINDS.has(call.kind) &&\n call.kind !== \"token-transfer-checked\" &&\n call.kind !== \"token-approve\" &&\n call.kind !== \"jupiter\" &&\n call.kind !== \"core-transfer\"\n ) {\n return \"opaque\";\n }\n }\n if (parsed.lookups.length > 0) {\n return \"partial\";\n }\n return allFull ? \"full\" : \"partial\";\n};\n\nconst feeLamports = (\n parsed: ParsedSolanaMessage,\n calls: ReadonlyArray<IxCall>,\n): bigint | undefined => {\n const limit = calls.find((c) => c.kind === \"cu-limit\")?.units;\n const price = calls.find((c) => c.kind === \"cu-price\")?.microLamports;\n if (limit === undefined || price === undefined) {\n return undefined;\n }\n const signatures = BigInt(parsed.numRequiredSignatures);\n return 5000n * signatures + (price * BigInt(limit) + 999_999n) / 1_000_000n;\n};\n\nconst decodeTransaction = (\n request: Extract<SignRequest, { kind: \"solana.transaction\" }>,\n signer: string,\n table: SolanaTokenTable,\n): DisplayIntent => {\n const parsed = parseCompiledMessage(request.message);\n const lookups = request.lookupTables?.map((t) => ({\n address: t.address,\n addresses: t.addresses,\n }));\n const calls = parsed.instructions.map((ix) => classifyIx(parsed, ix, lookups, signer));\n const verifiability = classify(parsed, calls, request.network, table);\n const outflows: AssetFlow[] = [];\n const approvals: ApprovalChange[] = [];\n const staking: StakeAction[] = [];\n const warnings: IntentWarning[] = [];\n const minimumReceived: Array<{ to: string; amount: AssetFlow[\"amount\"] }> = [];\n const wsolAtas = new Set([\n associatedTokenAddress(signer, WSOL_MINT, PROGRAM_IDS.token),\n associatedTokenAddress(signer, WSOL_MINT, PROGRAM_IDS.token2022),\n ]);\n let otherTransfer = false;\n let hasJupiter = false;\n for (const call of calls) {\n if (call.kind === \"system-transfer\" && call.to !== undefined && call.from === signer) {\n /* The source is the instruction's first account — a second signer funds its own transfer. */\n if (wsolAtas.has(call.to)) {\n /* Funding the signer's own wSOL ATA is wrapping, not an outflow — the swap shows the SOL. */\n continue;\n }\n otherTransfer = true;\n outflows.push({\n to: call.to,\n amount: { asset: SOLANA_NATIVE_ASSET, amount: (call.amount ?? 0n).toString(10) },\n verified: true,\n });\n }\n if (call.kind === \"jupiter\" && call.jupiter !== undefined) {\n const swap = call.jupiter;\n hasJupiter = true;\n otherTransfer = true;\n const sell = lookupSolanaToken(table, request.network, swap.sourceMint);\n outflows.push({\n to: JUPITER_PROGRAM,\n amount:\n swap.sourceMint === WSOL_MINT\n ? { asset: SOLANA_NATIVE_ASSET, amount: swap.inAmount.toString(10) }\n : {\n asset: swap.sourceMint,\n amount: swap.inAmount.toString(10),\n ...(sell === undefined ? {} : { symbol: sell.symbol, decimals: sell.decimals }),\n },\n verified: swap.sourceMint === WSOL_MINT || sell !== undefined,\n });\n const minimum = (swap.quotedOut * BigInt(10_000 - swap.slippageBps) + 9999n) / 10_000n;\n const buy = lookupSolanaToken(table, request.network, swap.destinationMint);\n const destAta = associatedTokenAddress(\n signer,\n swap.destinationMint,\n swap.destinationTokenProgram,\n );\n minimumReceived.push({\n to: swap.destinationAccount === destAta ? signer : swap.destinationAccount,\n amount:\n swap.destinationMint === WSOL_MINT\n ? { asset: SOLANA_NATIVE_ASSET, amount: minimum.toString(10) }\n : {\n asset: swap.destinationMint,\n amount: minimum.toString(10),\n ...(buy === undefined ? {} : { symbol: buy.symbol, decimals: buy.decimals }),\n },\n });\n if (swap.platformFeeBps > 0) {\n warnings.push({ kind: \"platform-fee\", message: `${swap.platformFeeBps} bps` });\n }\n }\n if (call.kind === \"core-transfer\" && call.core !== undefined) {\n otherTransfer = true;\n outflows.push({\n to: call.core.newOwner,\n amount: { asset: call.core.asset, amount: \"1\" },\n verified: false,\n });\n }\n if (call.kind === \"token-transfer-checked\") {\n otherTransfer = true;\n const token = lookupSolanaToken(table, request.network, call.mint ?? \"\");\n outflows.push({\n to: call.to ?? \"\",\n amount: {\n asset: call.mint ?? \"\",\n amount: (call.amount ?? 0n).toString(10),\n ...(token === undefined ? {} : { symbol: token.symbol, decimals: token.decimals }),\n },\n verified: token !== undefined,\n });\n }\n if (call.kind === \"token-approve\") {\n const token = lookupSolanaToken(table, request.network, call.mint ?? \"\");\n approvals.push({\n kind: \"allowance\",\n spender: call.to ?? \"\",\n amount: {\n asset: call.mint ?? \"\",\n amount: (call.amount ?? 0n).toString(10),\n ...(token === undefined ? {} : { symbol: token.symbol, decimals: token.decimals }),\n },\n change: \"set\",\n unlimited: false,\n verified: token !== undefined,\n });\n }\n const { stake } = call;\n if (stake !== undefined) {\n switch (stake.kind) {\n case \"create\":\n staking.push({\n kind: \"create\",\n account: stake.account,\n lamports: stake.lamports.toString(10),\n });\n if (stake.from === signer) {\n outflows.push({\n to: stake.account,\n amount: { asset: SOLANA_NATIVE_ASSET, amount: stake.lamports.toString(10) },\n verified: true,\n });\n }\n break;\n case \"initialize\":\n case \"initialize-checked\":\n if (stake.staker !== signer) {\n approvals.push({\n kind: \"stake-authority\",\n account: stake.account,\n role: \"staker\",\n authority: stake.staker,\n verified: false,\n });\n }\n if (stake.withdrawer !== signer) {\n approvals.push({\n kind: \"stake-authority\",\n account: stake.account,\n role: \"withdrawer\",\n authority: stake.withdrawer,\n verified: false,\n });\n }\n if (stake.kind === \"initialize\" && stake.lockup) {\n warnings.push({\n kind: \"stake-lockup\",\n message: \"the stake account is locked — funds cannot move until the lockup expires\",\n });\n }\n break;\n case \"delegate\":\n staking.push({ kind: \"delegate\", account: stake.account, validator: stake.validator });\n break;\n case \"deactivate\":\n staking.push({ kind: \"deactivate\", account: stake.account });\n break;\n case \"withdraw\":\n staking.push({\n kind: \"withdraw\",\n account: stake.account,\n to: stake.to,\n lamports: stake.lamports.toString(10),\n });\n if (stake.to !== signer) {\n outflows.push({\n to: stake.to,\n amount: {\n asset: SOLANA_NATIVE_ASSET,\n amount: stake.lamports.toString(10),\n },\n verified: true,\n });\n }\n break;\n case \"authorize\":\n if (stake.authority !== signer) {\n approvals.push({\n kind: \"stake-authority\",\n account: stake.account,\n role: stake.role,\n authority: stake.authority,\n verified: false,\n });\n }\n break;\n }\n }\n }\n const fee = feeLamports(parsed, calls);\n const summary = hasJupiter\n ? \"swap\"\n : otherTransfer\n ? \"transfer\"\n : staking.length > 0\n ? \"stake\"\n : outflows.length > 0\n ? \"transfer\"\n : \"contract-call\";\n return {\n family: \"solana\",\n network: request.network,\n summary,\n outflows,\n approvals,\n fee:\n fee === undefined\n ? undefined\n : { max: { asset: SOLANA_NATIVE_ASSET, amount: fee.toString(10) } },\n ...(staking.length === 0 ? {} : { staking }),\n ...(minimumReceived.length === 0 ? {} : { minimumReceived }),\n warnings,\n verifiability,\n };\n};\n\n/** What the signer can guarantee about this request (WD-065). */\nexport const verifiabilitySolana = (\n request: Extract<SignRequest, { kind: \"solana.transaction\" }>,\n signer: string,\n table: SolanaTokenTable = solanaTokenTable,\n): Verifiability => decodeSolana(request, signer, table).verifiability;\n\nexport const decodeSolana = (\n request: Extract<SignRequest, { kind: \"solana.transaction\" }>,\n signer: string,\n table: SolanaTokenTable = solanaTokenTable,\n): DisplayIntent => decodeTransaction(request, signer, table);\n","import { ChainError } from \"../index.ts\";\n\n/** SPL Token-2022 mint-account TLV extension type numbers (spl-token-2022 `ExtensionType`). */\nexport const EXT = {\n transferFeeConfig: 1,\n confidentialTransferMint: 4,\n defaultAccountState: 6,\n nonTransferable: 9,\n cpiGuard: 11,\n permanentDelegate: 12,\n transferHook: 14,\n confidentialTransferFee: 16,\n confidentialTransferFeeAmount: 17,\n} as const;\n\nexport type MintExtensionSummary = {\n /** The current-epoch fee from TransferFeeConfig (basis points and the maximum fee), if set. */\n readonly transferFee?: { readonly basisPoints: number; readonly maximumFee: bigint };\n readonly transferHook?: { readonly programId: Uint8Array };\n readonly permanentDelegate?: { readonly delegate: Uint8Array };\n readonly nonTransferable?: boolean;\n /** True when a ConfidentialTransfer extension is present — confidential amounts are not supported. */\n readonly confidential?: boolean;\n /** Extension type numbers we do not parse (informational). */\n readonly unknown?: ReadonlyArray<number>;\n};\n\nconst u64 = (v: Uint8Array): bigint =>\n new DataView(v.buffer, v.byteOffset, 8).getBigUint64(0, true);\nconst u16 = (v: Uint8Array): number => new DataView(v.buffer, v.byteOffset, 2).getUint16(0, true);\n\nconst ACCOUNT_TYPE_MINT = 1;\nconst TYPE_OFFSET = 165;\n\n/**\n * Parse the extension region of a full Token-2022 mint account. The account is the 82-byte mint\n * base, zero padding up to byte 165, the account-type byte (`1` = Mint) at 165, then the TLV region\n * at 166 — each entry `u16 type, u16 len, len bytes`. Returns a typed summary; extensions this\n * layer does not read are reported by type number in `unknown` rather than parsed.\n */\nexport const parseMintExtensions = (data: Uint8Array, epoch: bigint): MintExtensionSummary => {\n if (data.length <= TYPE_OFFSET + 1 || data[TYPE_OFFSET] !== ACCOUNT_TYPE_MINT) {\n return {};\n }\n const tlv = data.subarray(TYPE_OFFSET + 1);\n const out: {\n transferFee?: { basisPoints: number; maximumFee: bigint };\n transferHook?: { programId: Uint8Array };\n permanentDelegate?: { delegate: Uint8Array };\n nonTransferable?: boolean;\n confidential?: boolean;\n unknown: number[];\n } = { unknown: [] };\n let offset = 0;\n while (offset + 2 <= tlv.length) {\n const type = u16(tlv.subarray(offset, offset + 2));\n // Uninitialized entries are a u16 marker only — the program stops scanning there and\n // treats the rest as unused space.\n if (type === 0) {\n break;\n }\n if (offset + 4 > tlv.length) {\n throw new ChainError(\"invalid-request\", `mint extension ${type} truncated`);\n }\n const len = u16(tlv.subarray(offset + 2, offset + 4));\n offset += 4;\n if (offset + len > tlv.length) {\n throw new ChainError(\"invalid-request\", `mint extension ${type} truncated`);\n }\n const body = tlv.subarray(offset, offset + len);\n offset += len;\n if (type === EXT.transferFeeConfig && len >= 108) {\n // OptionalNonZeroPubkey×2 (32 B each, zero = none) + u64 withheld + TransferFee×2\n // (18 B each: u64 epoch + u64 maximumFee + u16 basisPoints). The current-epoch fee is\n // the \"newer\" record once its activation epoch is reached, else the \"older\" one.\n const olderMax = u64(body.subarray(80));\n const olderBps = u16(body.subarray(88));\n const newerEpoch = u64(body.subarray(90));\n const newerMax = u64(body.subarray(98));\n const newerBps = u16(body.subarray(106));\n const active =\n newerEpoch <= epoch ? { bps: newerBps, max: newerMax } : { bps: olderBps, max: olderMax };\n if (active.bps !== 0 || active.max !== 0n) {\n out.transferFee = { basisPoints: active.bps, maximumFee: active.max };\n }\n } else if (type === EXT.transferHook && len >= 64) {\n // OptionalNonZeroPubkey authority (32) + program id (32).\n const programId = body.subarray(32, 64);\n out.transferHook = { programId };\n } else if (type === EXT.permanentDelegate && len >= 32) {\n // OptionalNonZeroPubkey delegate (32) — all-zero means none.\n const delegate = body.subarray(0, 32);\n if (delegate.some((b) => b !== 0)) {\n out.permanentDelegate = { delegate };\n }\n } else if (type === EXT.nonTransferable) {\n out.nonTransferable = true;\n } else if (\n type === EXT.confidentialTransferMint ||\n type === EXT.confidentialTransferFee ||\n type === EXT.confidentialTransferFeeAmount\n ) {\n out.confidential = true;\n } else {\n out.unknown.push(type);\n }\n }\n return out.unknown.length === 0 ? out : { ...out, unknown: out.unknown };\n};\n\n/**\n * Net amount a recipient gets after the current-epoch transfer fee, `amt − min(amt*bps/10000,\n * max)`.\n */\nexport const netAfterTransferFee = (amount: bigint, bps: number, max: bigint): bigint => {\n const fee = (amount * BigInt(bps)) / 10_000n;\n return amount - (fee > max ? max : fee);\n};\n","/**\n * Ed25519 signature verification for `chain.sign` results: the host checks the kernel's 64-byte\n * signature against the message and the account address returned by `wallet.accounts` — a wrong\n * signer fails closed.\n */\nimport { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { address, getAddressEncoder } from \"@solana/addresses\";\n\n/** Whether `signature` is a valid ed25519 signature of `message` by the key behind `address`. */\nexport const verifySolanaSignature = (\n message: Uint8Array,\n signature: Uint8Array,\n accountAddress: string,\n): boolean => {\n if (signature.length !== 64) {\n return false;\n }\n try {\n return ed25519.verify(\n signature,\n message,\n new Uint8Array(getAddressEncoder().encode(address(accountAddress))),\n );\n } catch {\n return false;\n }\n};\n","import { isRecord, requestBase } from \"../account-ref.ts\";\nimport { ChainError } from \"../index.ts\";\nimport type { SignRequest } from \"../index.ts\";\nimport { SOLANA_NETWORKS, isSolanaAddress } from \"./ids.ts\";\nimport { parseCompiledMessage, validateLookupTables } from \"./message.ts\";\n\nexport {\n PROGRAM_IDS,\n SOLANA_NETWORKS,\n isSolanaAddress,\n solanaAddressFromPublicKey,\n} from \"./ids.ts\";\nexport { decodeSolana, verifiabilitySolana } from \"./decode.ts\";\nexport { EXT, parseMintExtensions, netAfterTransferFee } from \"./token2022.ts\";\nexport type { MintExtensionSummary } from \"./token2022.ts\";\nexport { SOLANA_NATIVE_ASSET } from \"./assets.ts\";\nexport { associatedTokenAddress } from \"./ata.ts\";\nexport { MPL_CORE_PROGRAM, decodeCoreIx } from \"./core.ts\";\nexport { JUPITER_PROGRAM, WSOL_MINT } from \"./jupiter.ts\";\nexport { parseCompiledMessage } from \"./message.ts\";\nexport type { LookupReference, ParsedSolanaMessage } from \"./message.ts\";\nexport { verifySolanaSignature } from \"./verify.ts\";\nexport type { SolanaTokenTable } from \"./tokens.ts\";\nexport { solanaTokenTable } from \"./tokens.ts\";\n\nconst solanaNetwork = (network: string): void => {\n if (!SOLANA_NETWORKS.includes(network)) {\n throw new ChainError(\"unsupported\", `unknown Solana network: ${network}`);\n }\n};\n\ntype LookupTable = {\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n};\n\nconst validateLookupTablesRaw = (tables: unknown): ReadonlyArray<LookupTable> | undefined => {\n if (tables === undefined) {\n return undefined;\n }\n if (!Array.isArray(tables)) {\n throw new ChainError(\"unknown-field\", \"lookupTables must be an array\");\n }\n const parsed = tables.map((t): LookupTable => {\n if (!isRecord(t) || typeof t[\"address\"] !== \"string\" || !Array.isArray(t[\"addresses\"])) {\n throw new ChainError(\"unknown-field\", \"lookupTables entries must be { address, addresses }\");\n }\n const addresses = t[\"addresses\"].map((a): string => {\n if (typeof a !== \"string\") {\n throw new ChainError(\"invalid-address\", \"lookup table addresses must be strings\");\n }\n return a;\n });\n return { address: t[\"address\"], addresses };\n });\n validateLookupTables(parsed);\n return parsed;\n};\n\n/**\n * Normalizes a Solana sign request. `signer` is the fee payer the wallet is about to sign for — the\n * message must declare it as the first static account. A raw `solana.message` must not decode as a\n * transaction message (chains.mdx rule — a bytes-to-sign path that produces a transaction signature\n * is a wallet-drainer). Idempotent.\n */\nexport const normalizeSolana = (request: unknown, signer: string): SignRequest => {\n if (!isRecord(request) || typeof request[\"kind\"] !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request must be an object with a kind\");\n }\n const { network, account } = requestBase(request);\n solanaNetwork(network);\n if (!isSolanaAddress(signer)) {\n throw new ChainError(\"invalid-address\", \"signer is not a base58 address\");\n }\n const { message } = request;\n if (!(message instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"message must be bytes\");\n }\n if (request[\"kind\"] === \"solana.transaction\") {\n const lookupTables = validateLookupTablesRaw(request[\"lookupTables\"]);\n const parsed = parseCompiledMessage(message);\n const [feePayer] = parsed.staticAccounts;\n if (feePayer === undefined || feePayer !== signer) {\n throw new ChainError(\"fee-payer-mismatch\", \"signer is not the transaction fee payer\");\n }\n return {\n kind: \"solana.transaction\",\n network,\n account,\n message,\n ...(lookupTables === undefined\n ? {}\n : {\n lookupTables: (\n lookupTables as ReadonlyArray<{\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n }>\n ).map((t) => ({ address: t.address, addresses: [...t.addresses] })),\n }),\n };\n }\n if (request[\"kind\"] === \"solana.message\") {\n const { format } = request;\n if (format !== \"raw\") {\n throw new ChainError(\n \"unsupported\",\n `solana.message format ${String(format)} is not supported`,\n );\n }\n let decodesAsTransaction = true;\n try {\n parseCompiledMessage(message);\n } catch {\n decodesAsTransaction = false;\n }\n if (decodesAsTransaction) {\n throw new ChainError(\n \"invalid-request\",\n \"solana.message payload decodes as a transaction message — use solana.transaction\",\n );\n }\n return { kind: \"solana.message\", network, account, message, format };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n"],"mappings":";;;;;;;;;AAKA,MAAa,cAOR,OAAO,OAAO;CACjB,QAAQ;CACR,e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AAe;EAEpE,MAAM,CAAC,YADQ,qBAAqB,OACZ,CAAC,CAAC;EAC1B,IAAI,aAAa,KAAA,KAAa,aAAa,QACzC,MAAM,IAAI,WAAW,sBAAsB,yCAAyC;EAEtF,OAAO;GACL,MAAM;GACN;GACA;GACA;GACA,GAAI,iBAAiB,KAAA,IACjB,CAAC,IACD,EACE,cACE,aAIA,KAAK,OAAO;IAAE,SAAS,EAAE;IAAS,WAAW,CAAC,GAAG,EAAE,SAAS;GAAE,EAAE,EACpE;EACN;CACF;CACA,IAAI,QAAQ,YAAY,kBAAkB;EACxC,MAAM,EAAE,WAAW;EACnB,IAAI,WAAW,OACb,MAAM,IAAI,WACR,eACA,yBAAyB,OAAO,MAAM,EAAE,kBAC1C;EAEF,IAAI,uBAAuB;EAC3B,IAAI;GACF,qBAAqB,OAAO;EAC9B,QAAQ;GACN,uBAAuB;EACzB;EACA,IAAI,sBACF,MAAM,IAAI,WACR,mBACA,kFACF;EAEF,OAAO;GAAE,MAAM;GAAkB;GAAS;GAAS;GAAS;EAAO;CACrE;CACA,MAAM,IAAI,WAAW,eAAe,kCAAkC,QAAQ,SAAS;AACzF"}
@@ -1 +1 @@
1
- {"version":3,"file":"src-8NZeEnrW.mjs","names":[],"sources":["../src/sign-in.ts","../src/index.ts"],"sourcesContent":["/** Recognition of Sign-In with Ethereum (ERC-4361) and Sign-In with Solana text in signed messages. */\nimport type { Message, MessageFields } from \"@qntx/siwx\";\nimport { evm } from \"@qntx/siwx/evm\";\nimport { siws, validateAddress as validateSolanaAddress } from \"@qntx/siwx/svm\";\n\n/** A Sign-In with X message found in signed text (ERC-4361 / SIWS). */\nexport type SignInParse =\n | { readonly status: \"valid\"; readonly fields: MessageFields }\n /** The text contains the sign-in preamble but is not a conforming message for this chain family. */\n | { readonly status: \"malformed\" };\n\nconst PREAMBLE = \" wants you to sign in with your \";\n\nconst OPTIONAL_KEYS = [\"scheme\", \"statement\", \"expirationTime\", \"notBefore\", \"requestId\"] as const;\n\nconst plainFields = (message: Message): MessageFields => {\n const { domain, address, uri, version, chainId, nonce, issuedAt, resources } = message;\n const fields: { -readonly [K in keyof MessageFields]: MessageFields[K] } = {\n domain,\n address,\n uri,\n version,\n chainId,\n nonce,\n issuedAt,\n };\n for (const key of OPTIONAL_KEYS) {\n const value = message[key];\n if (value !== undefined) {\n fields[key] = value;\n }\n }\n if (resources !== undefined) {\n fields.resources = [...resources];\n }\n return fields;\n};\n\nconst parseValid = (text: string, family: \"evm\" | \"solana\"): MessageFields => {\n if (family === \"evm\") {\n const ns = evm();\n const message = ns.parse(new TextEncoder().encode(text));\n ns.account(message);\n return plainFields(message);\n }\n const message = siws.parse(text);\n validateSolanaAddress(message.address);\n return plainFields(message);\n};\n\n/**\n * Finds a Sign-In with X message in `text` for the chain `family`. `undefined` when the text has no\n * sign-in preamble; `malformed` when it has one but is not a conforming message for the family\n * (ERC-4361: wallets should warn about that shape).\n */\nexport function parseSignIn(text: string, family: \"evm\" | \"solana\"): SignInParse | undefined {\n try {\n return { status: \"valid\", fields: parseValid(text, family) };\n } catch {\n return text.includes(PREAMBLE) ? { status: \"malformed\" } : undefined;\n }\n}\n","/**\n * @qntx/wallet-chains — shared chain semantics for the wallet.\n * Types here are wire-safe: values crossing the main↔kernel protocol are\n * Uint8Array, safe integers, strings, booleans, arrays and plain objects.\n * Quantities are canonical `0x` hex (lowercase, no leading zeros, `0x0` for\n * zero), token amounts are decimal strings of the smallest unit.\n */\n\nimport type { SignInParse } from \"./sign-in.ts\";\n\nexport { parseSignIn } from \"./sign-in.ts\";\nexport type { SignInParse } from \"./sign-in.ts\";\n\nexport type ChainFamily = \"evm\" | \"solana\" | \"bitcoin\";\n\nexport type AccountRef =\n | {\n readonly kind: \"hd\";\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: string;\n }\n | { readonly kind: \"imported\"; readonly keyId: string; readonly family: ChainFamily };\n\nexport type SignRequest =\n | {\n readonly kind: \"bitcoin.psbt\";\n readonly network: string;\n readonly account: AccountRef;\n readonly psbt: Uint8Array;\n /** Input indices to sign — non-empty, unique, ascending, in range. */\n readonly sign: ReadonlyArray<number>;\n }\n | {\n readonly kind: \"bitcoin.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly address: string;\n readonly message: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n /** Account change chain and index the address is derived at (0 = receive, 1 = change). */\n readonly change: 0 | 1;\n readonly index: number;\n }\n | {\n readonly kind: \"solana.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n /** Compiled wire message (legacy or v0). */\n readonly message: Uint8Array;\n readonly lookupTables?: ReadonlyArray<{\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n }>;\n }\n | {\n readonly kind: \"solana.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n /** Only \"raw\" exists in this layer; offchain formats land with C7. */\n readonly format: \"raw\";\n }\n | {\n readonly kind: \"evm.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n readonly tx: EvmTransaction;\n }\n | {\n readonly kind: \"evm.personal-message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n }\n | {\n readonly kind: \"evm.typed-data\";\n readonly network: string;\n readonly account: AccountRef;\n readonly typedData: string;\n };\n\nexport type EvmAccessListEntry = {\n readonly address: string;\n readonly storageKeys: ReadonlyArray<string>;\n};\n\ntype EvmTransactionBase = {\n readonly chainId: number;\n readonly nonce: number;\n readonly gas: string;\n readonly value: string;\n readonly data: string;\n readonly to?: string;\n};\n\n/**\n * A complete transaction — every field the signer needs is present; `to` absent means contract\n * creation.\n */\nexport type EvmTransaction =\n | (EvmTransactionBase & { readonly type: \"legacy\"; readonly gasPrice: string })\n | (EvmTransactionBase & {\n readonly type: \"eip2930\";\n readonly gasPrice: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n })\n | (EvmTransactionBase & {\n readonly type: \"eip1559\";\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n });\n\nexport type Verifiability = \"full\" | \"partial\" | \"opaque\";\n\nexport type IntentSummary =\n | \"transfer\"\n | \"approve\"\n | \"contract-call\"\n | \"swap\"\n | \"message\"\n | \"authorization\"\n | \"batch\";\n\nexport type AssetAmount = {\n readonly asset: string;\n readonly amount: string;\n readonly decimals?: number;\n readonly symbol?: string;\n};\n\nexport type AssetFlow = {\n readonly to: string;\n readonly amount: AssetAmount;\n readonly verified: boolean;\n /** The ENS name the recipient was resolved from; attached by the engine, never decoded. */\n readonly name?: string;\n};\n\nexport type ApprovalChange =\n | {\n /** A fungible-token allowance: on the token itself, or on Permit2 when `via` is \"permit2\". */\n readonly kind: \"allowance\";\n readonly spender: string;\n /** The token and amount (base units); symbol/decimals when the token is in the built-in table. */\n readonly amount: AssetAmount;\n /**\n * `set`: the allowance becomes `amount`; `increase`/`decrease`: it changes by `amount`;\n * `transfer`: a one-time right to take up to `amount` before `expiration` (Permit2\n * SignatureTransfer).\n */\n readonly change: \"set\" | \"increase\" | \"decrease\" | \"transfer\";\n /** `amount` is the type's maximum (uint256; uint160 for Permit2). */\n readonly unlimited: boolean;\n /** Unix seconds after which the allowance lapses (Permit2), when it has one. */\n readonly expiration?: number;\n readonly via?: \"permit2\";\n /** The token is in the built-in table. */\n readonly verified: boolean;\n }\n | {\n /** ERC-721/1155 `setApprovalForAll`: `spender` may move every token of `asset`. */\n readonly kind: \"operator\";\n readonly asset: string;\n readonly spender: string;\n /** `false` revokes. */\n readonly approved: boolean;\n readonly verified: false;\n };\n\nexport type IntentWarning = {\n readonly kind: string;\n readonly message: string;\n};\n\n/** One item a Seaport order offers or requests; recognized from EIP-712 `itemType` 0–5. */\nexport type SeaportItem = {\n readonly kind: \"native\" | \"erc20\" | \"erc721\" | \"erc1155\" | \"erc721-criteria\" | \"erc1155-criteria\";\n /** The item's contract (EIP-55 checksummed; the zero address for `native`). */\n readonly token: string;\n /** `identifierOrCriteria` as a decimal string; a criteria root for the criteria kinds. */\n readonly identifier: string;\n readonly startAmount: AssetAmount;\n readonly endAmount: AssetAmount;\n};\n\n/** A recognized Seaport `OrderComponents` message. */\nexport type SeaportOrder = {\n readonly offerer: string;\n readonly zone: string;\n readonly startTime: number | undefined;\n readonly endTime: number | undefined;\n readonly offer: ReadonlyArray<SeaportItem>;\n readonly consideration: ReadonlyArray<SeaportItem & { readonly recipient: string }>;\n};\n\n/** A recognized Safe `SafeTx` message. */\nexport type SafeTransaction = {\n readonly safe: string;\n /** The Safe nonce as a decimal string. */\n readonly nonce: string;\n readonly operation: \"call\" | \"delegatecall\";\n readonly to: string;\n /** Wei, decimal. */\n readonly value: string;\n readonly data: string;\n /** The inner call(s) decoded with the transaction rules (no fee); one per MultiSend entry. */\n readonly calls: ReadonlyArray<DisplayIntent>;\n /** The gas-refund terms, present when `gasPrice` is not zero. */\n readonly refund?: {\n readonly gasPrice: string;\n readonly gasToken: string;\n readonly refundReceiver: string;\n };\n};\n\n/** The EIP-712 domain fields a wallet shows. */\nexport type TypedDataDomain = {\n readonly name?: string;\n readonly version?: string;\n readonly chainId?: number;\n /** EIP-55 checksummed. */\n readonly verifyingContract?: string;\n readonly salt?: string;\n};\n\n/** What a message request signs. */\nexport type MessageContent =\n | { readonly kind: \"text\"; readonly text: string; readonly signIn?: SignInParse }\n | { readonly kind: \"bytes\"; readonly hex: string }\n | {\n readonly kind: \"typed-data\";\n readonly primaryType: string;\n readonly domain: TypedDataDomain;\n readonly data: Readonly<Record<string, unknown>>;\n /** A recognized Seaport order; only the exact `OrderComponents` shape populates it. */\n readonly seaport?: SeaportOrder;\n /** A recognized Safe transaction; only the exact `SafeTx` shape populates it. */\n readonly safe?: SafeTransaction;\n };\n\nexport type DisplayIntent = {\n readonly family: ChainFamily;\n readonly network: string;\n readonly summary: IntentSummary;\n readonly outflows: ReadonlyArray<AssetFlow>;\n readonly approvals: ReadonlyArray<ApprovalChange>;\n /**\n * `l1Data`: OP Stack L1 data fee plus operator fee, estimated by the engine and charged on top of\n * `max`; not decodable from the transaction, so the kernel's own decode never sets it.\n */\n readonly fee: { readonly max: AssetAmount; readonly l1Data?: AssetAmount } | undefined;\n readonly warnings: ReadonlyArray<IntentWarning>;\n /** What a message request signs; absent for transactions. */\n readonly message?: MessageContent;\n readonly verifiability: Verifiability;\n};\n\nexport type ChainErrorCode =\n | \"unknown-field\"\n | \"chain-id-mismatch\"\n | \"fee-payer-mismatch\"\n | \"invalid-quantity\"\n | \"invalid-address\"\n | \"invalid-typed-data\"\n | \"invalid-request\"\n | \"unsupported\";\n\nexport class ChainError extends Error {\n readonly code: ChainErrorCode;\n constructor(code: ChainErrorCode, message: string) {\n super(message);\n this.name = \"ChainError\";\n this.code = code;\n }\n}\n"],"mappings":";;;AAWA,MAAM,WAAW;AAEjB,MAAM,gBAAgB;CAAC;CAAU;CAAa;CAAkB;CAAa;AAAW;AAExF,MAAM,eAAe,YAAoC;CACvD,MAAM,EAAE,QAAQ,SAAS,KAAK,SAAS,SAAS,OAAO,UAAU,cAAc;CAC/E,MAAM,SAAqE;EACzE;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CACA,KAAK,MAAM,OAAO,eAAe;EAC/B,MAAM,QAAQ,QAAQ;EACtB,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO;CAElB;CACA,IAAI,cAAc,KAAA,GAChB,OAAO,YAAY,CAAC,GAAG,SAAS;CAElC,OAAO;AACT;AAEA,MAAM,cAAc,MAAc,WAA4C;CAC5E,IAAI,WAAW,OAAO;EACpB,MAAM,KAAK,IAAI;EACf,MAAM,UAAU,GAAG,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;EACvD,GAAG,QAAQ,OAAO;EAClB,OAAO,YAAY,OAAO;CAC5B;CACA,MAAM,UAAU,KAAK,MAAM,IAAI;CAC/B,gBAAsB,QAAQ,OAAO;CACrC,OAAO,YAAY,OAAO;AAC5B;;;;;;AAOA,SAAgB,YAAY,MAAc,QAAmD;CAC3F,IAAI;EACF,OAAO;GAAE,QAAQ;GAAS,QAAQ,WAAW,MAAM,MAAM;EAAE;CAC7D,QAAQ;EACN,OAAO,KAAK,SAAS,QAAQ,IAAI,EAAE,QAAQ,YAAY,IAAI,KAAA;CAC7D;AACF;;ACgNA,IAAa,aAAb,cAAgC,MAAM;CACpC;CACA,YAAY,MAAsB,SAAiB;EACjD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"src-8NZeEnrW.mjs","names":[],"sources":["../src/sign-in.ts","../src/index.ts"],"sourcesContent":["/** Recognition of Sign-In with Ethereum (ERC-4361) and Sign-In with Solana text in signed messages. */\nimport type { Message, MessageFields } from \"@qntx/siwx\";\nimport { evm } from \"@qntx/siwx/evm\";\nimport { siws, validateAddress as validateSolanaAddress } from \"@qntx/siwx/svm\";\n\n/** A Sign-In with X message found in signed text (ERC-4361 / SIWS). */\nexport type SignInParse =\n | { readonly status: \"valid\"; readonly fields: MessageFields }\n /** The text contains the sign-in preamble but is not a conforming message for this chain family. */\n | { readonly status: \"malformed\" };\n\nconst PREAMBLE = \" wants you to sign in with your \";\n\nconst OPTIONAL_KEYS = [\"scheme\", \"statement\", \"expirationTime\", \"notBefore\", \"requestId\"] as const;\n\nconst plainFields = (message: Message): MessageFields => {\n const { domain, address, uri, version, chainId, nonce, issuedAt, resources } = message;\n const fields: { -readonly [K in keyof MessageFields]: MessageFields[K] } = {\n domain,\n address,\n uri,\n version,\n chainId,\n nonce,\n issuedAt,\n };\n for (const key of OPTIONAL_KEYS) {\n const value = message[key];\n if (value !== undefined) {\n fields[key] = value;\n }\n }\n if (resources !== undefined) {\n fields.resources = [...resources];\n }\n return fields;\n};\n\nconst parseValid = (text: string, family: \"evm\" | \"solana\"): MessageFields => {\n if (family === \"evm\") {\n const ns = evm();\n const message = ns.parse(new TextEncoder().encode(text));\n ns.account(message);\n return plainFields(message);\n }\n const message = siws.parse(text);\n validateSolanaAddress(message.address);\n return plainFields(message);\n};\n\n/**\n * Finds a Sign-In with X message in `text` for the chain `family`. `undefined` when the text has no\n * sign-in preamble; `malformed` when it has one but is not a conforming message for the family\n * (ERC-4361: wallets should warn about that shape).\n */\nexport function parseSignIn(text: string, family: \"evm\" | \"solana\"): SignInParse | undefined {\n try {\n return { status: \"valid\", fields: parseValid(text, family) };\n } catch {\n return text.includes(PREAMBLE) ? { status: \"malformed\" } : undefined;\n }\n}\n","/**\n * @qntx/wallet-chains — shared chain semantics for the wallet.\n * Types here are wire-safe: values crossing the main↔kernel protocol are\n * Uint8Array, safe integers, strings, booleans, arrays and plain objects.\n * Quantities are canonical `0x` hex (lowercase, no leading zeros, `0x0` for\n * zero), token amounts are decimal strings of the smallest unit.\n */\n\nimport type { SignInParse } from \"./sign-in.ts\";\n\nexport { parseSignIn } from \"./sign-in.ts\";\nexport type { SignInParse } from \"./sign-in.ts\";\n\nexport type ChainFamily = \"evm\" | \"solana\" | \"bitcoin\";\n\nexport type AccountRef =\n | {\n readonly kind: \"hd\";\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: string;\n }\n | { readonly kind: \"imported\"; readonly keyId: string; readonly family: ChainFamily };\n\n/** The BIP-44/49/84/86 account-level templates a bitcoin.psbt input may sign under. */\nexport type BitcoinTemplate = \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n\nexport type SignRequest =\n | {\n readonly kind: \"bitcoin.psbt\";\n readonly network: string;\n /** The wallet group whose keys sign; each signed input names its template. */\n readonly account: {\n readonly kind: \"hd\";\n readonly walletId: string;\n readonly groupIndex: number;\n };\n readonly psbt: Uint8Array;\n /** Inputs to sign — non-empty, unique, ascending by index, in range; each with its template. */\n readonly sign: ReadonlyArray<{ readonly index: number; readonly template: BitcoinTemplate }>;\n }\n | {\n readonly kind: \"bitcoin.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly address: string;\n readonly message: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n /** Account change chain and index the address is derived at (0 = receive, 1 = change). */\n readonly change: 0 | 1;\n readonly index: number;\n }\n | {\n readonly kind: \"solana.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n /** Compiled wire message (legacy or v0). */\n readonly message: Uint8Array;\n readonly lookupTables?: ReadonlyArray<{\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n }>;\n }\n | {\n readonly kind: \"solana.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n /** Only \"raw\" exists in this layer; offchain formats land with C7. */\n readonly format: \"raw\";\n }\n | {\n readonly kind: \"evm.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n readonly tx: EvmTransaction;\n }\n | {\n readonly kind: \"evm.personal-message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n }\n | {\n readonly kind: \"evm.typed-data\";\n readonly network: string;\n readonly account: AccountRef;\n readonly typedData: string;\n };\n\nexport type EvmAccessListEntry = {\n readonly address: string;\n readonly storageKeys: ReadonlyArray<string>;\n};\n\ntype EvmTransactionBase = {\n readonly chainId: number;\n readonly nonce: number;\n readonly gas: string;\n readonly value: string;\n readonly data: string;\n readonly to?: string;\n};\n\n/**\n * A complete transaction — every field the signer needs is present; `to` absent means contract\n * creation.\n */\nexport type EvmTransaction =\n | (EvmTransactionBase & { readonly type: \"legacy\"; readonly gasPrice: string })\n | (EvmTransactionBase & {\n readonly type: \"eip2930\";\n readonly gasPrice: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n })\n | (EvmTransactionBase & {\n readonly type: \"eip1559\";\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n })\n | (Omit<EvmTransactionBase, \"to\"> & {\n readonly type: \"eip7702\";\n readonly to: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n /**\n * One self-sponsored authorization: its chain id is the transaction's chain id and its nonce\n * is `tx.nonce + 1`, so multi-tuple or nonce-mismatched authorizations are unrepresentable.\n * The zero address revokes an existing delegation.\n */\n readonly authorization: { readonly address: string };\n });\n\nexport type Verifiability = \"full\" | \"partial\" | \"opaque\";\n\nexport type IntentSummary =\n | \"transfer\"\n | \"approve\"\n | \"contract-call\"\n | \"swap\"\n | \"message\"\n | \"authorization\"\n | \"batch\"\n | \"stake\"\n | \"bridge\";\n\nexport type AssetAmount = {\n readonly asset: string;\n readonly amount: string;\n readonly decimals?: number;\n readonly symbol?: string;\n /** NFT flows only: the decimal token id; `amount` is then the unit count. */\n readonly tokenId?: string;\n};\n\nexport type AssetFlow = {\n readonly to: string;\n readonly amount: AssetAmount;\n readonly verified: boolean;\n /** The ENS name the recipient was resolved from; attached by the engine, never decoded. */\n readonly name?: string;\n};\n\nexport type ApprovalChange =\n | {\n /** A fungible-token allowance: on the token itself, or on Permit2 when `via` is \"permit2\". */\n readonly kind: \"allowance\";\n readonly spender: string;\n /** The token and amount (base units); symbol/decimals when the token is in the built-in table. */\n readonly amount: AssetAmount;\n /**\n * `set`: the allowance becomes `amount`; `increase`/`decrease`: it changes by `amount`;\n * `transfer`: a one-time right to take up to `amount` before `expiration` (Permit2\n * SignatureTransfer).\n */\n readonly change: \"set\" | \"increase\" | \"decrease\" | \"transfer\";\n /** `amount` is the type's maximum (uint256; uint160 for Permit2). */\n readonly unlimited: boolean;\n /** Unix seconds after which the allowance lapses (Permit2), when it has one. */\n readonly expiration?: number;\n readonly via?: \"permit2\" | \"allowance-holder\";\n /** The token is in the built-in table. */\n readonly verified: boolean;\n }\n | {\n /** ERC-721/1155 `setApprovalForAll`: `spender` may move every token of `asset`. */\n readonly kind: \"operator\";\n readonly asset: string;\n readonly spender: string;\n /** `false` revokes. */\n readonly approved: boolean;\n readonly verified: false;\n }\n | {\n /**\n * A Solana stake account's staker or withdrawer role handed to a key other than the signer —\n * by an `Authorize`/`AuthorizeChecked` instruction, or by `Initialize` naming a non-signer.\n */\n readonly kind: \"stake-authority\";\n /** The stake account the role applies to. */\n readonly account: string;\n readonly role: \"staker\" | \"withdrawer\";\n /** The key receiving the role. */\n readonly authority: string;\n readonly verified: false;\n };\n\n/** One staking operation shown on the signing surface. */\nexport type StakeAction =\n | { readonly kind: \"create\"; readonly account: string; readonly lamports: string }\n | { readonly kind: \"delegate\"; readonly account: string; readonly validator: string }\n | { readonly kind: \"deactivate\"; readonly account: string }\n | {\n readonly kind: \"withdraw\";\n readonly account: string;\n readonly to: string;\n readonly lamports: string;\n }\n /** Lido `submit` on Ethereum mainnet: ETH in, approximately `receive` stETH back. */\n | { readonly kind: \"lido-submit\"; readonly amount: AssetAmount; readonly receive: AssetAmount }\n /** Lido withdrawal request on Ethereum mainnet; `owner` gets the claim NFT. */\n | {\n readonly kind: \"lido-request\";\n readonly token: string;\n readonly amount: AssetAmount;\n readonly owner: string;\n }\n /** Lido claim of finalised withdrawal requests on Ethereum mainnet (ETH to the caller). */\n | { readonly kind: \"lido-claim\"; readonly requestIds: ReadonlyArray<string> };\n\nexport type IntentWarning = {\n readonly kind: string;\n readonly message: string;\n};\n\n/** One item a Seaport order offers or requests; recognized from EIP-712 `itemType` 0–5. */\nexport type SeaportItem = {\n readonly kind: \"native\" | \"erc20\" | \"erc721\" | \"erc1155\" | \"erc721-criteria\" | \"erc1155-criteria\";\n /** The item's contract (EIP-55 checksummed; the zero address for `native`). */\n readonly token: string;\n /** `identifierOrCriteria` as a decimal string; a criteria root for the criteria kinds. */\n readonly identifier: string;\n readonly startAmount: AssetAmount;\n readonly endAmount: AssetAmount;\n};\n\n/** A recognized Seaport `OrderComponents` message. */\nexport type SeaportOrder = {\n readonly offerer: string;\n readonly zone: string;\n readonly startTime: number | undefined;\n readonly endTime: number | undefined;\n readonly offer: ReadonlyArray<SeaportItem>;\n readonly consideration: ReadonlyArray<SeaportItem & { readonly recipient: string }>;\n};\n\n/** A recognized Safe `SafeTx` message. */\nexport type SafeTransaction = {\n readonly safe: string;\n /** The Safe nonce as a decimal string. */\n readonly nonce: string;\n readonly operation: \"call\" | \"delegatecall\";\n readonly to: string;\n /** Wei, decimal. */\n readonly value: string;\n readonly data: string;\n /** The inner call(s) decoded with the transaction rules (no fee); one per MultiSend entry. */\n readonly calls: ReadonlyArray<DisplayIntent>;\n /** The gas-refund terms, present when `gasPrice` is not zero. */\n readonly refund?: {\n readonly gasPrice: string;\n readonly gasToken: string;\n readonly refundReceiver: string;\n };\n};\n\n/** The EIP-712 domain fields a wallet shows. */\nexport type TypedDataDomain = {\n readonly name?: string;\n readonly version?: string;\n readonly chainId?: number;\n /** EIP-55 checksummed. */\n readonly verifyingContract?: string;\n readonly salt?: string;\n};\n\n/** What a message request signs. */\nexport type MessageContent =\n | { readonly kind: \"text\"; readonly text: string; readonly signIn?: SignInParse }\n | { readonly kind: \"bytes\"; readonly hex: string }\n | {\n readonly kind: \"typed-data\";\n readonly primaryType: string;\n readonly domain: TypedDataDomain;\n readonly data: Readonly<Record<string, unknown>>;\n /** A recognized Seaport order; only the exact `OrderComponents` shape populates it. */\n readonly seaport?: SeaportOrder;\n /** A recognized Safe transaction; only the exact `SafeTx` shape populates it. */\n readonly safe?: SafeTransaction;\n };\n\nexport type DisplayIntent = {\n readonly family: ChainFamily;\n readonly network: string;\n readonly summary: IntentSummary;\n readonly outflows: ReadonlyArray<AssetFlow>;\n readonly approvals: ReadonlyArray<ApprovalChange>;\n /**\n * The minimums the settlement contracts enforce on-chain for recognised swaps — each\n * `minAmountOut` a Settler requires its own balance to reach before paying the recipient, not an\n * estimate. Present only when non-empty; a batch concatenates its calls' lists like the others.\n */\n readonly minimumReceived?: ReadonlyArray<{\n readonly to: string;\n readonly amount: AssetAmount;\n }>;\n /**\n * `l1Data`: OP Stack L1 data fee plus operator fee, estimated by the engine and charged on top of\n * `max`; not decodable from the transaction, so the kernel's own decode never sets it.\n */\n readonly fee: { readonly max: AssetAmount; readonly l1Data?: AssetAmount } | undefined;\n /**\n * Recognized Solana stake operations — create, delegate, deactivate, withdraw — one per\n * instruction, in order. Present only when non-empty.\n */\n readonly staking?: ReadonlyArray<StakeAction>;\n /**\n * A recognized Across SpokePool deposit: the calldata-stated destination chain, the fill deadline\n * after which an unfilled deposit refunds `refundTo` on this chain.\n */\n readonly bridge?: {\n readonly destinationNetwork: string;\n readonly fillDeadline: number;\n readonly refundTo: string;\n };\n readonly warnings: ReadonlyArray<IntentWarning>;\n /** What a message request signs; absent for transactions. */\n readonly message?: MessageContent;\n readonly verifiability: Verifiability;\n /** Present iff the transaction carries an EIP-7702 authorization. */\n readonly delegation?:\n | {\n readonly kind: \"set\";\n readonly delegator: string;\n readonly name: string;\n readonly version: string;\n }\n | { readonly kind: \"revoke\" };\n /** The decoded inner calls of a recognized ERC-7821 batch execute. */\n readonly calls?: ReadonlyArray<DisplayIntent>;\n};\n\nexport type ChainErrorCode =\n | \"unknown-field\"\n | \"chain-id-mismatch\"\n | \"fee-payer-mismatch\"\n | \"invalid-quantity\"\n | \"invalid-address\"\n | \"invalid-typed-data\"\n | \"invalid-request\"\n | \"unsupported\";\n\nexport class ChainError extends Error {\n readonly code: ChainErrorCode;\n constructor(code: ChainErrorCode, message: string) {\n super(message);\n this.name = \"ChainError\";\n this.code = code;\n }\n}\n"],"mappings":";;;AAWA,MAAM,WAAW;AAEjB,MAAM,gBAAgB;CAAC;CAAU;CAAa;CAAkB;CAAa;AAAW;AAExF,MAAM,eAAe,YAAoC;CACvD,MAAM,EAAE,QAAQ,SAAS,KAAK,SAAS,SAAS,OAAO,UAAU,cAAc;CAC/E,MAAM,SAAqE;EACzE;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CACA,KAAK,MAAM,OAAO,eAAe;EAC/B,MAAM,QAAQ,QAAQ;EACtB,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO;CAElB;CACA,IAAI,cAAc,KAAA,GAChB,OAAO,YAAY,CAAC,GAAG,SAAS;CAElC,OAAO;AACT;AAEA,MAAM,cAAc,MAAc,WAA4C;CAC5E,IAAI,WAAW,OAAO;EACpB,MAAM,KAAK,IAAI;EACf,MAAM,UAAU,GAAG,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;EACvD,GAAG,QAAQ,OAAO;EAClB,OAAO,YAAY,OAAO;CAC5B;CACA,MAAM,UAAU,KAAK,MAAM,IAAI;CAC/B,gBAAsB,QAAQ,OAAO;CACrC,OAAO,YAAY,OAAO;AAC5B;;;;;;AAOA,SAAgB,YAAY,MAAc,QAAmD;CAC3F,IAAI;EACF,OAAO;GAAE,QAAQ;GAAS,QAAQ,WAAW,MAAM,MAAM;EAAE;CAC7D,QAAQ;EACN,OAAO,KAAK,SAAS,QAAQ,IAAI,EAAE,QAAQ,YAAY,IAAI,KAAA;CAC7D;AACF;;AC+SA,IAAa,aAAb,cAAgC,MAAM;CACpC;CACA,YAAY,MAAsB,SAAiB;EACjD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF"}
@@ -3,6 +3,9 @@ import { secp256k1 } from "@noble/curves/secp256k1.js";
3
3
  import { keccak_256 } from "@noble/hashes/sha3.js";
4
4
  import { bytesToHex } from "@noble/hashes/utils.js";
5
5
  import * as Address from "ox/Address";
6
+ import * as AbiFunction from "ox/AbiFunction";
7
+ import * as AbiParameters from "ox/AbiParameters";
8
+ import * as Hex from "ox/Hex";
6
9
  import * as TypedData from "ox/TypedData";
7
10
  // src/evm/address.ts
8
11
  /** EIP-55 checksummed address, e.g. `0x52908400098527886E0F7030069857D2E4169EE7`. */
@@ -19,6 +22,71 @@ function evmAddressFromPublicKey(pubkey) {
19
22
  if (uncompressed === void 0 || uncompressed[0] !== 4) throw new ChainError("invalid-address", "expected a compressed or uncompressed secp256k1 key");
20
23
  return checksumEvmAddress(`0x${bytesToHex(keccak_256(uncompressed.subarray(1))).slice(-40)}`);
21
24
  }
25
+ // src/evm/delegation.ts
26
+ /**
27
+ * MetaMask Delegation Framework EIP7702StatelessDeleGator v1.3.0 — deterministic CREATE2, the same
28
+ * address on every chain that supports it.
29
+ */
30
+ const EVM_DELEGATOR = {
31
+ address: "0x63c0c19a282a1B52b07dD5a65b58948A07DAE32B",
32
+ name: "EIP7702StatelessDeleGator",
33
+ version: "1.3.0"
34
+ };
35
+ /** The EIP-7702 designator byte prefix: `0xef0100 ‖ address` marks a delegated account's code. */
36
+ const EVM_DELEGATION_PREFIX = "0xef0100";
37
+ /** ERC-7821 batch-default execution mode: `0x01` followed by 31 zero bytes. */
38
+ const EXECUTE_BATCH_MODE = "0x0100000000000000000000000000000000000000000000000000000000000000";
39
+ const EXECUTE = AbiFunction.from("function execute(bytes32 mode, bytes executionData)");
40
+ const EXECUTIONS = [{
41
+ type: "tuple[]",
42
+ components: [
43
+ {
44
+ name: "target",
45
+ type: "address"
46
+ },
47
+ {
48
+ name: "value",
49
+ type: "uint256"
50
+ },
51
+ {
52
+ name: "callData",
53
+ type: "bytes"
54
+ }
55
+ ]
56
+ }];
57
+ const hex = (v) => {
58
+ Hex.assert(v);
59
+ return v;
60
+ };
61
+ /** ERC-7821 batch-default self-call payload for `execute` on the delegator. */
62
+ const encodeBatchExecute = (calls) => AbiFunction.encodeData(EXECUTE, [EXECUTE_BATCH_MODE, AbiParameters.encode(EXECUTIONS, [calls.map((c) => ({
63
+ target: hex(checksumEvmAddress(c.to)),
64
+ value: c.value,
65
+ callData: hex(c.data)
66
+ }))])]);
67
+ const list = (v) => Array.isArray(v) ? v : [];
68
+ const isExecution = (e) => typeof e === "object" && e !== null && "target" in e && "value" in e && "callData" in e && typeof e.target === "string" && isEvmAddress(e.target) && typeof e.value === "bigint" && typeof e.callData === "string";
69
+ /** Decodes an `execute` call; undefined unless the encoding is canonical batch-default mode. */
70
+ const decodeBatchExecute = (data) => {
71
+ try {
72
+ const [mode, executionData] = list(AbiFunction.decodeData(EXECUTE, hex(data)));
73
+ if (mode !== "0x0100000000000000000000000000000000000000000000000000000000000000" || typeof executionData !== "string") return;
74
+ const decoded = AbiParameters.decode(EXECUTIONS, hex(executionData));
75
+ const [inner] = list(decoded);
76
+ const executions = [];
77
+ for (const e of list(inner)) {
78
+ if (!isExecution(e)) return;
79
+ executions.push({
80
+ to: checksumEvmAddress(e.target),
81
+ value: e.value,
82
+ data: e.callData
83
+ });
84
+ }
85
+ return encodeBatchExecute(executions).toLowerCase() === data.toLowerCase() ? executions : void 0;
86
+ } catch {
87
+ return;
88
+ }
89
+ };
22
90
  // src/evm/transaction.ts
23
91
  /** Validates a string is `0x`-hex and narrows it to the branded hex type. */
24
92
  function assertHex(value, field) {
@@ -100,6 +168,12 @@ const ALLOWED = {
100
168
  "accessList",
101
169
  "maxFeePerGas",
102
170
  "maxPriorityFeePerGas"
171
+ ],
172
+ eip7702: [
173
+ "accessList",
174
+ "maxFeePerGas",
175
+ "maxPriorityFeePerGas",
176
+ "authorization"
103
177
  ]
104
178
  };
105
179
  const requireFields = (input, fields) => {
@@ -117,7 +191,7 @@ const rejectUnknown = (input, type) => {
117
191
  const normalizeEvmTransaction = (tx) => {
118
192
  if (!isRecord(tx)) throw new ChainError("invalid-request", "tx must be an object");
119
193
  const { type } = tx;
120
- if (type !== "legacy" && type !== "eip2930" && type !== "eip1559") throw new ChainError("unsupported", `transaction type ${String(type)} is not supported (legacy, eip2930 and eip1559 only)`);
194
+ if (type !== "legacy" && type !== "eip2930" && type !== "eip1559" && type !== "eip7702") throw new ChainError("unsupported", `transaction type ${String(type)} is not supported (legacy, eip2930, eip1559 and eip7702 only)`);
121
195
  rejectUnknown(tx, type);
122
196
  requireFields(tx, REQUIRED.base);
123
197
  const chainId = safeInteger(tx["chainId"], "chainId");
@@ -154,12 +228,29 @@ const normalizeEvmTransaction = (tx) => {
154
228
  };
155
229
  }
156
230
  requireFields(tx, [...REQUIRED.accessList, ...REQUIRED.eip1559]);
231
+ const fees = {
232
+ maxFeePerGas: quantity(tx["maxFeePerGas"], "maxFeePerGas"),
233
+ maxPriorityFeePerGas: quantity(tx["maxPriorityFeePerGas"], "maxPriorityFeePerGas")
234
+ };
235
+ const list = accessList(tx["accessList"]);
236
+ if (type === "eip1559") return {
237
+ type,
238
+ ...base,
239
+ accessList: list,
240
+ ...fees
241
+ };
242
+ if (to === void 0) throw new ChainError("invalid-request", "tx.to is required for eip7702");
243
+ const auth = tx["authorization"];
244
+ if (!isRecord(auth) || Object.keys(auth).length !== 1 || typeof auth["address"] !== "string") throw new ChainError("invalid-request", "tx.authorization must be an object with exactly address");
245
+ const authAddress = checksumEvmAddress(auth["address"]);
246
+ if (authAddress !== EVM_DELEGATOR.address && authAddress !== "0x0000000000000000000000000000000000000000") throw new ChainError("unsupported", "authorization address is not supported");
157
247
  return {
158
248
  type,
159
249
  ...base,
160
- accessList: accessList(tx["accessList"]),
161
- maxFeePerGas: quantity(tx["maxFeePerGas"], "maxFeePerGas"),
162
- maxPriorityFeePerGas: quantity(tx["maxPriorityFeePerGas"], "maxPriorityFeePerGas")
250
+ to,
251
+ accessList: list,
252
+ ...fees,
253
+ authorization: { address: authAddress }
163
254
  };
164
255
  };
165
256
  // src/evm/typed-data.ts
@@ -222,6 +313,6 @@ const domainChainId = (domain) => {
222
313
  if (!Number.isSafeInteger(numeric) || numeric < 0) throw new ChainError("invalid-typed-data", "typed-data domain.chainId is malformed");
223
314
  return numeric;
224
315
  };
225
- export { checksumEvmAddress as _, sameFields as a, typedDataMessages as c, canonicalHex as d, isCanonicalHex as f, quantityBigInt as g, normalizeEvmTransaction as h, parseTypedData as i, typedDataUint as l, networkChainId as m, domainChainId as n, typedDataAddress as o, isRecord as p, isTypedDataMessage as r, typedDataBytes as s, MAX_UINT48 as t, assertHex as u, evmAddressFromPublicKey as v, isEvmAddress as y };
316
+ export { isEvmAddress as C, evmAddressFromPublicKey as S, EVM_DELEGATION_PREFIX as _, sameFields as a, encodeBatchExecute as b, typedDataMessages as c, canonicalHex as d, isCanonicalHex as f, quantityBigInt as g, normalizeEvmTransaction as h, parseTypedData as i, typedDataUint as l, networkChainId as m, domainChainId as n, typedDataAddress as o, isRecord as p, isTypedDataMessage as r, typedDataBytes as s, MAX_UINT48 as t, assertHex as u, EVM_DELEGATOR as v, checksumEvmAddress as x, decodeBatchExecute as y };
226
317
 
227
- //# sourceMappingURL=typed-data-J5g2WemC.mjs.map
318
+ //# sourceMappingURL=typed-data-B4PJ1v8F.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typed-data-B4PJ1v8F.mjs","names":[],"sources":["../src/evm/address.ts","../src/evm/delegation.ts","../src/evm/transaction.ts","../src/evm/typed-data.ts"],"sourcesContent":["import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nimport * as Address from \"ox/Address\";\n\nimport { ChainError } from \"../index.ts\";\n\n/** EIP-55 checksummed address, e.g. `0x52908400098527886E0F7030069857D2E4169EE7`. */\nexport const isEvmAddress = (value: string): boolean => /^0x[0-9a-fA-F]{40}$/.test(value);\n\nexport function checksumEvmAddress(address: string): string {\n if (!isEvmAddress(address)) {\n throw new ChainError(\"invalid-address\", \"not an EVM address\");\n }\n const checksummed = Address.checksum(address);\n Address.assert(checksummed, { strict: true });\n return checksummed;\n}\n\n/** `keccak256(pubkey)[12:]` — accepts a 33-byte compressed or 65-byte uncompressed secp256k1 key. */\nexport function evmAddressFromPublicKey(pubkey: Uint8Array): string {\n const uncompressed =\n pubkey.length === 65 && pubkey[0] === 4\n ? pubkey\n : pubkey.length === 33\n ? secp256k1.Point.fromBytes(pubkey).toBytes(false)\n : undefined;\n if (uncompressed === undefined || uncompressed[0] !== 4) {\n throw new ChainError(\"invalid-address\", \"expected a compressed or uncompressed secp256k1 key\");\n }\n return checksumEvmAddress(`0x${bytesToHex(keccak_256(uncompressed.subarray(1))).slice(-40)}`);\n}\n","import * as AbiFunction from \"ox/AbiFunction\";\nimport * as AbiParameters from \"ox/AbiParameters\";\nimport * as Hex from \"ox/Hex\";\n\nimport { checksumEvmAddress, isEvmAddress } from \"./address.ts\";\n\n/**\n * MetaMask Delegation Framework EIP7702StatelessDeleGator v1.3.0 — deterministic CREATE2, the same\n * address on every chain that supports it.\n */\nexport const EVM_DELEGATOR = {\n address: \"0x63c0c19a282a1B52b07dD5a65b58948A07DAE32B\",\n name: \"EIP7702StatelessDeleGator\",\n version: \"1.3.0\",\n} as const;\n\n/** The EIP-7702 designator byte prefix: `0xef0100 ‖ address` marks a delegated account's code. */\nexport const EVM_DELEGATION_PREFIX = \"0xef0100\";\n\n/** ERC-7821 batch-default execution mode: `0x01` followed by 31 zero bytes. */\nexport const EXECUTE_BATCH_MODE =\n \"0x0100000000000000000000000000000000000000000000000000000000000000\";\n\nexport const EXECUTE: AbiFunction.AbiFunction = AbiFunction.from(\n \"function execute(bytes32 mode, bytes executionData)\",\n);\n\nconst EXECUTIONS = [\n {\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"callData\", type: \"bytes\" },\n ],\n },\n] as const;\n\nconst hex = (v: string): `0x${string}` => {\n Hex.assert(v);\n return v;\n};\n\n/** ERC-7821 batch-default self-call payload for `execute` on the delegator. */\nexport const encodeBatchExecute = (\n calls: ReadonlyArray<{ readonly to: string; readonly value: bigint; readonly data: string }>,\n): string =>\n AbiFunction.encodeData(EXECUTE, [\n EXECUTE_BATCH_MODE,\n AbiParameters.encode(EXECUTIONS, [\n calls.map((c) => ({\n target: hex(checksumEvmAddress(c.to)),\n value: c.value,\n callData: hex(c.data),\n })),\n ]),\n ]);\n\ntype Execution = { readonly to: string; readonly value: bigint; readonly data: string };\n\nconst list = (v: unknown): ReadonlyArray<unknown> => (Array.isArray(v) ? v : []);\n\nconst isExecution = (\n e: unknown,\n): e is { readonly target: string; readonly value: bigint; readonly callData: string } =>\n typeof e === \"object\" &&\n e !== null &&\n \"target\" in e &&\n \"value\" in e &&\n \"callData\" in e &&\n typeof e.target === \"string\" &&\n isEvmAddress(e.target) &&\n typeof e.value === \"bigint\" &&\n typeof e.callData === \"string\";\n\n/** Decodes an `execute` call; undefined unless the encoding is canonical batch-default mode. */\nexport const decodeBatchExecute = (data: string): ReadonlyArray<Execution> | undefined => {\n try {\n const args = list(AbiFunction.decodeData(EXECUTE, hex(data)));\n const [mode, executionData] = args;\n if (mode !== EXECUTE_BATCH_MODE || typeof executionData !== \"string\") {\n return undefined;\n }\n const decoded: unknown = AbiParameters.decode(EXECUTIONS, hex(executionData));\n const [inner] = list(decoded);\n const executions: Execution[] = [];\n for (const e of list(inner)) {\n if (!isExecution(e)) {\n return undefined;\n }\n executions.push({\n to: checksumEvmAddress(e.target),\n value: e.value,\n data: e.callData,\n });\n }\n /* Display must equal execution: accept only the canonical encoding the delegator's own\n * calldata decoder would read — a non-canonical payload (trailing bytes, aliased offsets)\n * can decode one way here and another on-chain. */\n return encodeBatchExecute(executions).toLowerCase() === data.toLowerCase()\n ? executions\n : undefined;\n } catch {\n return undefined;\n }\n};\n","import { ChainError } from \"../index.ts\";\nimport type { EvmTransaction, EvmAccessListEntry } from \"../index.ts\";\nimport { checksumEvmAddress, isEvmAddress } from \"./address.ts\";\nimport { EVM_DELEGATOR } from \"./delegation.ts\";\n\n/** Validates a string is `0x`-hex and narrows it to the branded hex type. */\nexport function assertHex(value: string, field: string): asserts value is `0x${string}` {\n if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {\n throw new ChainError(\"invalid-quantity\", `${field} must be 0x-prefixed bytes`);\n }\n}\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst CANONICAL_HEX = /^0x(?:0|[1-9a-f][0-9a-f]*)$/;\n\nexport const isCanonicalHex = (value: string): boolean => CANONICAL_HEX.test(value);\n\nexport const canonicalHex = (value: bigint): string => `0x${value.toString(16)}`;\n\n/** Parses a JSON-RPC quantity: `0x` and at least one hex digit — a bare `\"0x\"` is malformed. */\nexport const quantityBigInt = (value: unknown, field: string): bigint => {\n if (typeof value !== \"string\" || !/^0x[0-9a-fA-F]+$/.test(value)) {\n throw new ChainError(\"invalid-quantity\", `${field} must be a 0x quantity`);\n }\n return BigInt(value);\n};\n\nconst safeInteger = (value: unknown, field: string): number => {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new ChainError(\"invalid-quantity\", `${field} must be a non-negative safe integer`);\n }\n return value;\n};\n\nconst quantity = (value: unknown, field: string): string => {\n if (typeof value !== \"string\") {\n throw new ChainError(\"invalid-quantity\", `${field} must be a 0x quantity string`);\n }\n if (CANONICAL_HEX.test(value)) {\n return value;\n }\n return canonicalHex(quantityBigInt(value, field));\n};\n\nconst hexBytes = (value: unknown, field: string): string => {\n if (typeof value !== \"string\" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {\n throw new ChainError(\"invalid-quantity\", `${field} must be 0x-prefixed bytes`);\n }\n return value.toLowerCase();\n};\n\nconst accessList = (value: unknown): ReadonlyArray<EvmAccessListEntry> => {\n if (!Array.isArray(value)) {\n throw new ChainError(\"invalid-request\", \"accessList must be an array\");\n }\n return value.map((entry): EvmAccessListEntry => {\n if (!isRecord(entry)) {\n throw new ChainError(\"invalid-address\", \"accessList entries must be objects\");\n }\n const keys = Object.keys(entry).sort();\n if (keys.length !== 2 || keys[0] !== \"address\" || keys[1] !== \"storageKeys\") {\n throw new ChainError(\n \"unknown-field\",\n `accessList entry fields must be exactly address+storageKeys, got ${keys.join(\",\")}`,\n );\n }\n const { address, storageKeys } = entry;\n if (typeof address !== \"string\" || !isEvmAddress(address)) {\n throw new ChainError(\"invalid-address\", \"accessList entry has an invalid address\");\n }\n if (!Array.isArray(storageKeys)) {\n throw new ChainError(\"invalid-quantity\", \"accessList storageKeys must be an array\");\n }\n return {\n address: checksumEvmAddress(address),\n storageKeys: storageKeys.map((k) => {\n if (typeof k !== \"string\" || !/^0x[0-9a-fA-F]{64}$/.test(k)) {\n throw new ChainError(\n \"invalid-quantity\",\n \"accessList storageKeys must be 32-byte hex strings\",\n );\n }\n return k.toLowerCase();\n }),\n };\n });\n};\n\n/** The EIP-155 part of a CAIP-2 `network` string, e.g. `eip155:1` → 1. */\nexport const networkChainId = (network: string): number => {\n const match = /^eip155:(\\d+)$/.exec(network);\n const idPart = match?.[1];\n if (idPart === undefined) {\n throw new ChainError(\"chain-id-mismatch\", `network is not an eip155 CAIP-2 id: ${network}`);\n }\n const id = Number(idPart);\n if (!Number.isSafeInteger(id)) {\n throw new ChainError(\"chain-id-mismatch\", `chain id is not a safe integer: ${network}`);\n }\n return id;\n};\n\nconst REQUIRED = {\n base: [\"chainId\", \"nonce\", \"gas\", \"value\", \"data\"],\n gasPrice: [\"gasPrice\"],\n accessList: [\"accessList\"],\n eip1559: [\"maxFeePerGas\", \"maxPriorityFeePerGas\"],\n} as const;\n\nconst ALLOWED = {\n base: [\"type\", \"chainId\", \"nonce\", \"gas\", \"value\", \"data\", \"to\"],\n legacy: [\"gasPrice\"],\n eip2930: [\"gasPrice\", \"accessList\"],\n eip1559: [\"accessList\", \"maxFeePerGas\", \"maxPriorityFeePerGas\"],\n eip7702: [\"accessList\", \"maxFeePerGas\", \"maxPriorityFeePerGas\", \"authorization\"],\n} as const;\n\nconst requireFields = (input: Record<string, unknown>, fields: ReadonlyArray<string>): void => {\n for (const field of fields) {\n if (input[field] === undefined) {\n throw new ChainError(\"invalid-request\", `tx.${field} is required`);\n }\n }\n};\n\nconst rejectUnknown = (\n input: Record<string, unknown>,\n type: \"legacy\" | \"eip2930\" | \"eip1559\" | \"eip7702\",\n): void => {\n const allowed = new Set<string>([...ALLOWED.base, ...ALLOWED[type]]);\n const unknown = Object.keys(input).filter((k) => !allowed.has(k));\n if (unknown.length > 0) {\n throw new ChainError(\n \"unknown-field\",\n `tx has unknown fields for ${type}: ${unknown.sort().join(\", \")}`,\n );\n }\n};\n\n/**\n * Canonicalizes an EVM transaction: exact key sets per type, all required fields present, `0x`\n * canonical quantities, EIP-55 addresses. Idempotent.\n */\nexport const normalizeEvmTransaction = (tx: unknown): EvmTransaction => {\n if (!isRecord(tx)) {\n throw new ChainError(\"invalid-request\", \"tx must be an object\");\n }\n const { type } = tx;\n if (type !== \"legacy\" && type !== \"eip2930\" && type !== \"eip1559\" && type !== \"eip7702\") {\n throw new ChainError(\n \"unsupported\",\n `transaction type ${String(type)} is not supported (legacy, eip2930, eip1559 and eip7702 only)`,\n );\n }\n rejectUnknown(tx, type);\n requireFields(tx, REQUIRED.base);\n const chainId = safeInteger(tx[\"chainId\"], \"chainId\");\n const nonce = safeInteger(tx[\"nonce\"], \"nonce\");\n const gas = quantity(tx[\"gas\"], \"gas\");\n const value = quantity(tx[\"value\"], \"value\");\n const data = hexBytes(tx[\"data\"], \"data\");\n const toRaw = tx[\"to\"];\n const to =\n toRaw === undefined\n ? undefined\n : typeof toRaw === \"string\" && isEvmAddress(toRaw)\n ? checksumEvmAddress(toRaw)\n : undefined;\n if (toRaw !== undefined && to === undefined) {\n throw new ChainError(\"invalid-address\", \"to must be a valid EVM address\");\n }\n const base = { chainId, nonce, gas, value, data, ...(to === undefined ? {} : { to }) };\n if (type === \"legacy\") {\n requireFields(tx, REQUIRED.gasPrice);\n return { type, ...base, gasPrice: quantity(tx[\"gasPrice\"], \"gasPrice\") };\n }\n if (type === \"eip2930\") {\n requireFields(tx, [...REQUIRED.gasPrice, ...REQUIRED.accessList]);\n return {\n type,\n ...base,\n gasPrice: quantity(tx[\"gasPrice\"], \"gasPrice\"),\n accessList: accessList(tx[\"accessList\"]),\n };\n }\n requireFields(tx, [...REQUIRED.accessList, ...REQUIRED.eip1559]);\n const fees = {\n maxFeePerGas: quantity(tx[\"maxFeePerGas\"], \"maxFeePerGas\"),\n maxPriorityFeePerGas: quantity(tx[\"maxPriorityFeePerGas\"], \"maxPriorityFeePerGas\"),\n };\n const list = accessList(tx[\"accessList\"]);\n if (type === \"eip1559\") {\n return { type, ...base, accessList: list, ...fees };\n }\n if (to === undefined) {\n throw new ChainError(\"invalid-request\", \"tx.to is required for eip7702\");\n }\n const auth = tx[\"authorization\"];\n if (!isRecord(auth) || Object.keys(auth).length !== 1 || typeof auth[\"address\"] !== \"string\") {\n throw new ChainError(\n \"invalid-request\",\n \"tx.authorization must be an object with exactly address\",\n );\n }\n const authAddress = checksumEvmAddress(auth[\"address\"]);\n if (\n authAddress !== EVM_DELEGATOR.address &&\n authAddress !== \"0x0000000000000000000000000000000000000000\"\n ) {\n throw new ChainError(\"unsupported\", \"authorization address is not supported\");\n }\n return {\n type,\n ...base,\n to,\n accessList: list,\n ...fees,\n authorization: { address: authAddress },\n };\n};\n","import * as TypedData from \"ox/TypedData\";\n\nimport { ChainError } from \"../index.ts\";\nimport { checksumEvmAddress } from \"./address.ts\";\nimport { isRecord } from \"./transaction.ts\";\n\ntype TypedDataField = {\n readonly name: string;\n readonly type: string;\n};\n\n/**\n * The subset of the EIP-712 document the wallet needs to see before handing it to ox's validator —\n * object with `types`, `primaryType`, `domain` and `message` of the right shapes.\n */\nexport type TypedDataInput = {\n readonly types: Record<string, ReadonlyArray<TypedDataField>>;\n readonly primaryType: string;\n readonly domain: Record<string, unknown>;\n readonly message: Record<string, unknown>;\n};\n\nconst isField = (value: unknown): value is TypedDataField =>\n isRecord(value) && typeof value[\"name\"] === \"string\" && typeof value[\"type\"] === \"string\";\n\nconst isTypedDataInput = (value: unknown): value is TypedDataInput => {\n if (!isRecord(value)) {\n return false;\n }\n const { types, primaryType, domain, message } = value;\n if (!isRecord(types)) {\n return false;\n }\n if (typeof primaryType !== \"string\" || primaryType === \"\") {\n return false;\n }\n if (!isRecord(domain)) {\n return false;\n }\n if (!isRecord(message)) {\n return false;\n }\n return Object.values(types).every((fields) => Array.isArray(fields) && fields.every(isField));\n};\n\nexport type ParsedTypedData = { readonly json: TypedDataInput };\n\n/** A message object inside the document's `message`. */\nexport type TypedDataMessage = Readonly<Record<string, unknown>>;\n\nexport const isTypedDataMessage = (value: unknown): value is TypedDataMessage =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** `value` is an array of message objects (empty allowed). */\nexport const typedDataMessages = (value: unknown): ReadonlyArray<TypedDataMessage> | undefined =>\n Array.isArray(value) && value.every(isTypedDataMessage) ? value : undefined;\n\n/** The `Type field,Type field` signature of struct `name` in `types`. */\nexport const typedDataSignature = (\n types: TypedDataInput[\"types\"],\n name: string,\n): string | undefined => types[name]?.map((field) => `${field.type} ${field.name}`).join(\",\");\n\n/** Struct `name` has exactly `fields`, in order, no more. */\nexport const sameFields = (\n types: TypedDataInput[\"types\"],\n name: string,\n fields: ReadonlyArray<string>,\n): boolean => typedDataSignature(types, name) === fields.join(\",\");\n\n/** A hex `address` field value, checksummed; `undefined` when malformed. */\nexport const typedDataAddress = (value: unknown): string | undefined =>\n typeof value === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(value)\n ? checksumEvmAddress(value)\n : undefined;\n\n/** A uint field value (safe-integer number, decimal or `0x` hex string) ≤ `max`. */\nexport const typedDataUint = (value: unknown, max: bigint): bigint | undefined => {\n let parsed: bigint;\n if (typeof value === \"number\" && Number.isSafeInteger(value)) {\n parsed = BigInt(value);\n } else if (typeof value === \"string\" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(value)) {\n parsed = BigInt(value);\n } else {\n return undefined;\n }\n return parsed >= 0n && parsed <= max ? parsed : undefined;\n};\n\n/** The largest timestamp a permit/order expiry or a Safe field is allowed to carry. */\nexport const MAX_UINT48: bigint = 2n ** 48n - 1n;\n\nconst isHexBytes = (value: unknown): value is `0x${string}` =>\n typeof value === \"string\" && /^0x[0-9a-fA-F]*$/.test(value);\n\n/** A `bytes` field value: `0x`-prefixed hex of even length. */\nexport const typedDataBytes = (value: unknown): `0x${string}` | undefined =>\n isHexBytes(value) ? value : undefined;\n\n/** Parses the EIP-712 JSON source and validates its shape with ox. */\nexport const parseTypedData = (typedData: string): ParsedTypedData => {\n let json: unknown;\n try {\n json = JSON.parse(typedData);\n } catch {\n throw new ChainError(\"invalid-typed-data\", \"typedData is not valid JSON\");\n }\n if (!isTypedDataInput(json)) {\n throw new ChainError(\n \"invalid-typed-data\",\n \"typedData must be a JSON object with types, primaryType, domain and message\",\n );\n }\n try {\n TypedData.validate(json);\n } catch {\n throw new ChainError(\"invalid-typed-data\", \"typedData failed EIP-712 validation\");\n }\n return { json };\n};\n\n/**\n * `domain.chainId` as a number, when present: a safe non-negative integer given as a JSON number, a\n * decimal string or a `0x` hex string.\n */\nexport const domainChainId = (domain: Record<string, unknown>): number | undefined => {\n const { chainId } = domain;\n if (chainId === undefined) {\n return undefined;\n }\n const numeric =\n typeof chainId === \"number\"\n ? chainId\n : typeof chainId === \"string\" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(chainId)\n ? Number(chainId)\n : Number.NaN;\n if (!Number.isSafeInteger(numeric) || numeric < 0) {\n throw new ChainError(\"invalid-typed-data\", \"typed-data domain.chainId is malformed\");\n }\n return numeric;\n};\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,gBAAgB,UAA2B,sBAAsB,KAAK,KAAK;AAExF,SAAgB,mBAAmB,SAAyB;CAC1D,IAAI,CAAC,aAAa,OAAO,GACvB,MAAM,IAAI,WAAW,mBAAmB,oBAAoB;CAE9D,MAAM,cAAc,QAAQ,SAAS,OAAO;CAC5C,QAAQ,OAAO,aAAa,EAAE,QAAQ,KAAK,CAAC;CAC5C,OAAO;AACT;;AAGA,SAAgB,wBAAwB,QAA4B;CAClE,MAAM,eACJ,OAAO,WAAW,MAAM,OAAO,OAAO,IAClC,SACA,OAAO,WAAW,KAChB,UAAU,MAAM,UAAU,MAAM,CAAC,CAAC,QAAQ,KAAK,IAC/C,KAAA;CACR,IAAI,iBAAiB,KAAA,KAAa,aAAa,OAAO,GACpD,MAAM,IAAI,WAAW,mBAAmB,qDAAqD;CAE/F,OAAO,mBAAmB,KAAK,WAAW,WAAW,aAAa,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,GAAG;AAC9F;;;;;;ACrBA,MAAa,gBAAgB;CAC3B,SAAS;CACT,MAAM;CACN,SAAS;AACX;;AAGA,MAAa,wBAAwB;;AAGrC,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F,OAAO,UAAU,MAAM,UAAU,MAAM,SAAS,KAAA;AAClD;;AAGA,MAAa,aAAqB,MAAM,MAAM;AAE9C,MAAM,cAAc,UAClB,OAAO,UAAU,YAAY,mBAAmB,KAAK,KAAK;;AAG5D,MAAa,kBAAkB,UAC7B,WAAW,KAAK,IAAI,QAAQ,KAAA;;AAG9B,MAAa,kBAAkB,cAAuC;CACpE,IAAI;CACJ,IAAI;EACF,OAAO,KAAK,MAAM,SAAS;CAC7B,QAAQ;EACN,MAAM,IAAI,WAAW,sBAAsB,6BAA6B;CAC1E;CACA,IAAI,CAAC,iBAAiB,IAAI,GACxB,MAAM,IAAI,WACR,sBACA,6EACF;CAEF,IAAI;EACF,UAAU,SAAS,IAAI;CACzB,QAAQ;EACN,MAAM,IAAI,WAAW,sBAAsB,qCAAqC;CAClF;CACA,OAAO,EAAE,KAAK;AAChB;;;;;AAMA,MAAa,iBAAiB,WAAwD;CACpF,MAAM,EAAE,YAAY;CACpB,IAAI,YAAY,KAAA,GACd;CAEF,MAAM,UACJ,OAAO,YAAY,WACf,UACA,OAAO,YAAY,YAAY,8BAA8B,KAAK,OAAO,IACvE,OAAO,OAAO,IACd;CACR,IAAI,CAAC,OAAO,cAAc,OAAO,KAAK,UAAU,GAC9C,MAAM,IAAI,WAAW,sBAAsB,wCAAwC;CAErF,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qntx/wallet-chains",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "qntx/wallet chain semantics: SignRequest codecs, display decoding, verifiability and signing for EVM, Solana and Bitcoin",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": "QuantX <x@qntx.org>",