@qntx/wallet-chains 0.6.0 → 0.8.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.
- package/dist/account-ref-C2qrDbVT.mjs +22 -0
- package/dist/account-ref-C2qrDbVT.mjs.map +1 -0
- package/dist/bitcoin-sign.d.mts +0 -2
- package/dist/bitcoin-sign.mjs +2 -3
- package/dist/bitcoin.d.mts +0 -10
- package/dist/bitcoin.mjs +33 -51
- package/dist/bitcoin.mjs.map +1 -1
- package/dist/evm-sign.d.mts +0 -2
- package/dist/evm-sign.mjs +2 -3
- package/dist/evm.d.mts +4 -14
- package/dist/evm.mjs +7 -19
- package/dist/evm.mjs.map +1 -1
- package/dist/index.d.mts +0 -2
- package/dist/index.mjs +1 -2
- package/dist/{message-DtIS0ZWB.mjs → message-DuJ5KSRT.mjs} +3 -5
- package/dist/{message-DtIS0ZWB.mjs.map → message-DuJ5KSRT.mjs.map} +1 -1
- package/dist/solana-sign.d.mts +0 -2
- package/dist/solana-sign.mjs +1 -2
- package/dist/solana.d.mts +0 -14
- package/dist/solana.mjs +15 -29
- package/dist/solana.mjs.map +1 -1
- package/dist/{typed-data-C6XANSQF.mjs → typed-data-Cf1g7JVv.mjs} +4 -7
- package/dist/{typed-data-C6XANSQF.mjs.map → typed-data-Cf1g7JVv.mjs.map} +1 -1
- package/package.json +7 -8
package/dist/solana.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"solana.mjs","names":["decoder","isRecord","u64"],"sources":["../src/solana/ids.ts","../src/solana/message.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 lookupCount: number;\n readonly lookupAddresses: ReadonlyArray<string>;\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 lookupCount: lookups.length,\n lookupAddresses: lookups.map((l) => l.lookupTableAddress),\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","/**\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 { 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 LAMPORTS_ASSET = \"lamports\";\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.lookupCount > 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: LAMPORTS_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 approvals.push({\n asset: call.mint ?? \"\",\n spender: call.to ?? \"\",\n amount: (call.amount ?? 0n).toString(10),\n unlimited: false,\n verified: false,\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 ? undefined : { max: { asset: LAMPORTS_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 { ChainError } from \"../index.ts\";\nimport type { AccountRef, 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 { parseCompiledMessage } from \"./message.ts\";\nexport { verifySolanaSignature } from \"./verify.ts\";\nexport type { SolanaTokenTable } from \"./tokens.ts\";\nexport { solanaTokenTable } from \"./tokens.ts\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isAccountRef = (value: unknown): value is AccountRef => {\n if (!isRecord(value) || typeof value[\"kind\"] !== \"string\") {\n return false;\n }\n if (value[\"kind\"] === \"hd\") {\n return (\n typeof value[\"walletId\"] === \"string\" &&\n typeof value[\"groupIndex\"] === \"number\" &&\n typeof value[\"template\"] === \"string\"\n );\n }\n return (\n value[\"kind\"] === \"imported\" &&\n typeof value[\"keyId\"] === \"string\" &&\n typeof value[\"family\"] === \"string\"\n );\n};\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 } = request;\n const { account } = request;\n if (typeof network !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request.network must be a string\");\n }\n if (!isAccountRef(account)) {\n throw new ChainError(\"invalid-request\", \"request.account must be an AccountRef\");\n }\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;ACpBA,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,2BAA2B;CAErE,IAAI;CACJ,IAAI;EACF,UAAU,QAAQ,OAAO,KAAK;CAChC,QAAQ;EACN,MAAM,IAAI,WAAW,mBAAmB,mCAAmC;CAC7E;CACA,MAAM,UAAU,kBAAkB,OAAO;CACzC,MAAM,iBAAiB,CAAC,GAAG,QAAQ,cAAc;CACjD,MAAM,UAAU,QAAQ;CACxB,OAAO;EACL,SAAS,QAAQ;EACjB,uBAAuB,QAAQ;EAC/B;EACA,cAAc,QAAQ;EACtB,aAAa,QAAQ;EACrB,iBAAiB,QAAQ,KAAK,MAAM,EAAE,kBAAkB;CAC1D;AACF;AAcA,MAAMC,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ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BACA,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","u64","isRecord"],"sources":["../src/solana/ids.ts","../src/solana/message.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 lookupCount: number;\n readonly lookupAddresses: ReadonlyArray<string>;\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 lookupCount: lookups.length,\n lookupAddresses: lookups.map((l) => l.lookupTableAddress),\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","/**\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 { 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 LAMPORTS_ASSET = \"lamports\";\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.lookupCount > 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: LAMPORTS_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 approvals.push({\n asset: call.mint ?? \"\",\n spender: call.to ?? \"\",\n amount: (call.amount ?? 0n).toString(10),\n unlimited: false,\n verified: false,\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 ? undefined : { max: { asset: LAMPORTS_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 { parseCompiledMessage } 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;ACpBA,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,2BAA2B;CAErE,IAAI;CACJ,IAAI;EACF,UAAU,QAAQ,OAAO,KAAK;CAChC,QAAQ;EACN,MAAM,IAAI,WAAW,mBAAmB,mCAAmC;CAC7E;CACA,MAAM,UAAU,kBAAkB,OAAO;CACzC,MAAM,iBAAiB,CAAC,GAAG,QAAQ,cAAc;CACjD,MAAM,UAAU,QAAQ;CACxB,OAAO;EACL,SAAS,QAAQ;EACjB,uBAAuB,QAAQ;EAC/B;EACA,cAAc,QAAQ;EACtB,aAAa,QAAQ;EACrB,iBAAiB,QAAQ,KAAK,MAAM,EAAE,kBAAkB;CAC1D;AACF;AAcA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,Q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,IAAI,EAAE,mBAAmB,aACvB,MAAM,IAAI,WAAW,mBAAmB,uBAAuB;CAEjE,IAAI,QAAQ,YAAY,sBAAsB;EAC5C,MAAM,eAAe,wBAAwB,QAAQ,eAAe;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"}
|
|
@@ -4,7 +4,7 @@ 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
6
|
import * as TypedData from "ox/TypedData";
|
|
7
|
-
|
|
7
|
+
// src/evm/address.ts
|
|
8
8
|
/** EIP-55 checksummed address, e.g. `0x52908400098527886E0F7030069857D2E4169EE7`. */
|
|
9
9
|
const isEvmAddress = (value) => /^0x[0-9a-fA-F]{40}$/.test(value);
|
|
10
10
|
function checksumEvmAddress(address) {
|
|
@@ -19,8 +19,7 @@ function evmAddressFromPublicKey(pubkey) {
|
|
|
19
19
|
if (uncompressed === void 0 || uncompressed[0] !== 4) throw new ChainError("invalid-address", "expected a compressed or uncompressed secp256k1 key");
|
|
20
20
|
return checksumEvmAddress(`0x${bytesToHex(keccak_256(uncompressed.subarray(1))).slice(-40)}`);
|
|
21
21
|
}
|
|
22
|
-
|
|
23
|
-
//#region src/evm/transaction.ts
|
|
22
|
+
// src/evm/transaction.ts
|
|
24
23
|
/** Validates a string is `0x`-hex and narrows it to the branded hex type. */
|
|
25
24
|
function assertHex(value, field) {
|
|
26
25
|
if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) throw new ChainError("invalid-quantity", `${field} must be 0x-prefixed bytes`);
|
|
@@ -159,8 +158,7 @@ const normalizeEvmTransaction = (tx) => {
|
|
|
159
158
|
maxPriorityFeePerGas: quantity(tx["maxPriorityFeePerGas"], "maxPriorityFeePerGas")
|
|
160
159
|
};
|
|
161
160
|
};
|
|
162
|
-
|
|
163
|
-
//#region src/evm/typed-data.ts
|
|
161
|
+
// src/evm/typed-data.ts
|
|
164
162
|
const isField = (value) => isRecord(value) && typeof value["name"] === "string" && typeof value["type"] === "string";
|
|
165
163
|
const isTypedDataInput = (value) => {
|
|
166
164
|
if (!isRecord(value)) return false;
|
|
@@ -196,7 +194,6 @@ const typedDataWarnings = (parsed) => parsed.chainIdMismatch ? [{
|
|
|
196
194
|
kind: "chain-id-mismatch",
|
|
197
195
|
message: "typed-data domain.chainId does not match the request network"
|
|
198
196
|
}] : [];
|
|
199
|
-
//#endregion
|
|
200
197
|
export { isCanonicalHex as a, normalizeEvmTransaction as c, isEvmAddress as d, canonicalHex as i, checksumEvmAddress as l, typedDataWarnings as n, isRecord as o, assertHex as r, networkChainId as s, parseTypedData as t, evmAddressFromPublicKey as u };
|
|
201
198
|
|
|
202
|
-
//# sourceMappingURL=typed-data-
|
|
199
|
+
//# sourceMappingURL=typed-data-Cf1g7JVv.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typed-data-C6XANSQF.mjs","names":[],"sources":["../src/evm/address.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 { ChainError } from \"../index.ts\";\nimport type { EvmTransaction, EvmAccessListEntry } from \"../index.ts\";\nimport { checksumEvmAddress, isEvmAddress } from \"./address.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\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 if (/^0x[0-9a-fA-F]+$/.test(value) || value === \"0x\") {\n return canonicalHex(BigInt(value === \"0x\" ? \"0x0\" : value));\n }\n throw new ChainError(\"invalid-quantity\", `${field} must be a 0x quantity`);\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} 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\",\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\") {\n throw new ChainError(\n \"unsupported\",\n `transaction type ${String(type)} is not supported (legacy, eip2930 and eip1559 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 return {\n type,\n ...base,\n accessList: accessList(tx[\"accessList\"]),\n maxFeePerGas: quantity(tx[\"maxFeePerGas\"], \"maxFeePerGas\"),\n maxPriorityFeePerGas: quantity(tx[\"maxPriorityFeePerGas\"], \"maxPriorityFeePerGas\"),\n };\n};\n","import * as TypedData from \"ox/TypedData\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { IntentWarning } from \"../index.ts\";\nimport { isRecord, networkChainId } 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 = {\n readonly json: TypedDataInput;\n /**\n * True when `domain.chainId` disagrees with the request's network — the intent is still signable\n * but renders `opaque` with a warning.\n */\n readonly chainIdMismatch: boolean;\n};\n\n/** Parses the EIP-712 JSON source and validates its shape with ox. */\nexport const parseTypedData = (typedData: string, network: 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 const { chainId } = json.domain;\n const numeric =\n typeof chainId === \"number\"\n ? chainId\n : typeof chainId === \"string\"\n ? Number(chainId)\n : Number.NaN;\n return {\n json,\n chainIdMismatch: Number.isSafeInteger(numeric) && numeric !== networkChainId(network),\n };\n};\n\nexport const typedDataWarnings = (parsed: ParsedTypedData): ReadonlyArray<IntentWarning> =>\n parsed.chainIdMismatch\n ? [\n {\n kind: \"chain-id-mismatch\",\n message: \"typed-data domain.chainId does not match the request network\",\n },\n ]\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;;;;AC1BA,SAAgB,UAAU,OAAe,OAA+C;CACtF,IAAI,CAAC,0BAA0B,KAAK,KAAK,GACvC,MAAM,IAAI,WAAW,oBAAoB,GAAG,MAAM,2BAA2B;AAEjF;AAEA,MAAa,YAAY,UACvB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,gBAAgB;AAEtB,MAAa,kBAAkB,UAA2B,cAAc,KAAK,KAAK;AAElF,MAAa,gBAAgB,UAA0B,KAAK,MAAM,SAAS,EAAE;AAE7E,MAAM,eAAe,OAAgB,UAA0B;CAC7D,IAA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SAAS;AACX,CACF,IACA,CAAC"}
|
|
1
|
+
{"version":3,"file":"typed-data-Cf1g7JVv.mjs","names":[],"sources":["../src/evm/address.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 { ChainError } from \"../index.ts\";\nimport type { EvmTransaction, EvmAccessListEntry } from \"../index.ts\";\nimport { checksumEvmAddress, isEvmAddress } from \"./address.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\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 if (/^0x[0-9a-fA-F]+$/.test(value) || value === \"0x\") {\n return canonicalHex(BigInt(value === \"0x\" ? \"0x0\" : value));\n }\n throw new ChainError(\"invalid-quantity\", `${field} must be a 0x quantity`);\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} 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\",\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\") {\n throw new ChainError(\n \"unsupported\",\n `transaction type ${String(type)} is not supported (legacy, eip2930 and eip1559 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 return {\n type,\n ...base,\n accessList: accessList(tx[\"accessList\"]),\n maxFeePerGas: quantity(tx[\"maxFeePerGas\"], \"maxFeePerGas\"),\n maxPriorityFeePerGas: quantity(tx[\"maxPriorityFeePerGas\"], \"maxPriorityFeePerGas\"),\n };\n};\n","import * as TypedData from \"ox/TypedData\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { IntentWarning } from \"../index.ts\";\nimport { isRecord, networkChainId } 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 = {\n readonly json: TypedDataInput;\n /**\n * True when `domain.chainId` disagrees with the request's network — the intent is still signable\n * but renders `opaque` with a warning.\n */\n readonly chainIdMismatch: boolean;\n};\n\n/** Parses the EIP-712 JSON source and validates its shape with ox. */\nexport const parseTypedData = (typedData: string, network: 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 const { chainId } = json.domain;\n const numeric =\n typeof chainId === \"number\"\n ? chainId\n : typeof chainId === \"string\"\n ? Number(chainId)\n : Number.NaN;\n return {\n json,\n chainIdMismatch: Number.isSafeInteger(numeric) && numeric !== networkChainId(network),\n };\n};\n\nexport const typedDataWarnings = (parsed: ParsedTypedData): ReadonlyArray<IntentWarning> =>\n parsed.chainIdMismatch\n ? [\n {\n kind: \"chain-id-mismatch\",\n message: \"typed-data domain.chainId does not match the request network\",\n },\n ]\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;;;AC1BA,SAAgB,UAAU,OAAe,OAA+C;CACtF,IAAI,CAAC,0BAA0B,KAAK,KAAK,GACvC,MAAM,IAAI,WAAW,oBAAoB,GAAG,MAAM,2BAA2B;AAEjF;AAEA,MAAa,YAAY,UACvB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,gBAAgB;AAEtB,MAAa,kBAAkB,UAA2B,cAAc,KAAK,KAAK;AAElF,MAAa,gBAAgB,UAA0B,KAAK,MAAM,SAAS,EAAE;AAE7E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AChC,OAAO,kBACH,CACE;CACE,MAAM;CACN,SAAS;AACX,CACF,IACA,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@qntx/wallet-chains",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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>",
|
|
@@ -67,8 +67,7 @@
|
|
|
67
67
|
"@solana/addresses": "8.5.0",
|
|
68
68
|
"@solana/codecs": "8.5.0",
|
|
69
69
|
"@solana/transaction-messages": "8.5.0",
|
|
70
|
-
"
|
|
71
|
-
"ox": "1.8.9"
|
|
70
|
+
"ox": "1.8.12"
|
|
72
71
|
},
|
|
73
72
|
"devDependencies": {
|
|
74
73
|
"@arethetypeswrong/cli": "0.18.5",
|
|
@@ -82,13 +81,13 @@
|
|
|
82
81
|
"@solana-program/token-2022": "0.20.0",
|
|
83
82
|
"@solana/kit": "8.5.0",
|
|
84
83
|
"@types/node": "26.6.5",
|
|
85
|
-
"bitcoinjs-lib": "
|
|
86
|
-
"ecpair": "
|
|
84
|
+
"bitcoinjs-lib": "7.0.5",
|
|
85
|
+
"ecpair": "3.0.2",
|
|
87
86
|
"publint": "0.3.25",
|
|
88
|
-
"tiny-secp256k1": "
|
|
87
|
+
"tiny-secp256k1": "2.2.5",
|
|
89
88
|
"typescript": "7.0.2",
|
|
90
|
-
"viem": "2.57.
|
|
91
|
-
"vite-plus": "1.
|
|
89
|
+
"viem": "2.57.12",
|
|
90
|
+
"vite-plus": "1.4.0"
|
|
92
91
|
},
|
|
93
92
|
"devEngines": {
|
|
94
93
|
"packageManager": {
|