@qntx/wallet-chains 0.8.0 → 0.9.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/bitcoin-sign.mjs +1 -1
- package/dist/bitcoin.mjs +1 -1
- package/dist/evm.d.mts +2 -0
- package/dist/evm.mjs +5 -3
- package/dist/evm.mjs.map +1 -1
- package/dist/{message-DuJ5KSRT.mjs → message-Dv18g8ii.mjs} +8 -3
- package/dist/message-Dv18g8ii.mjs.map +1 -0
- package/dist/solana.d.mts +10 -3
- package/dist/solana.mjs +12 -7
- package/dist/solana.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/message-DuJ5KSRT.mjs.map +0 -1
package/dist/bitcoin-sign.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ChainError } from "./index.mjs";
|
|
2
|
-
import { a as bitcoinNetwork, n as signBip322Simple, r as signLegacyMessage } from "./message-
|
|
2
|
+
import { a as bitcoinNetwork, n as signBip322Simple, r as signLegacyMessage } from "./message-Dv18g8ii.mjs";
|
|
3
3
|
import { Address, OutScript } from "@scure/btc-signer/payment.js";
|
|
4
4
|
import { Transaction } from "@scure/btc-signer/transaction.js";
|
|
5
5
|
// src/bitcoin/sign.ts
|
package/dist/bitcoin.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ChainError } from "./index.mjs";
|
|
2
2
|
import { n as requestBase, t as isRecord$2 } from "./account-ref-C2qrDbVT.mjs";
|
|
3
|
-
import { a as bitcoinNetwork, i as BITCOIN_NETWORKS, t as bip322ToSpendTxid } from "./message-
|
|
3
|
+
import { a as bitcoinNetwork, i as BITCOIN_NETWORKS, t as bip322ToSpendTxid } from "./message-Dv18g8ii.mjs";
|
|
4
4
|
import { schnorr, secp256k1 } from "@noble/curves/secp256k1.js";
|
|
5
5
|
import { Address, OutScript, p2pkh, p2sh, p2tr, p2wpkh } from "@scure/btc-signer/payment.js";
|
|
6
6
|
import { taprootTweakPubkey } from "@scure/btc-signer/utils.js";
|
package/dist/evm.d.mts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { DisplayIntent, EvmTransaction, SignRequest, Verifiability } from "./index.mjs";
|
|
2
|
+
/** The native asset id in `AssetFlow` and simulated asset changes. */
|
|
3
|
+
export declare const EVM_NATIVE_ASSET = "native";
|
|
2
4
|
/** EIP-55 checksummed address, e.g. `0x52908400098527886E0F7030069857D2E4169EE7`. */
|
|
3
5
|
export declare const isEvmAddress: (value: string) => boolean;
|
|
4
6
|
export declare function checksumEvmAddress(address: string): string;
|
package/dist/evm.mjs
CHANGED
|
@@ -10,6 +10,9 @@ import * as Signature from "ox/Signature";
|
|
|
10
10
|
import * as TxEnvelopeEip1559 from "ox/TxEnvelopeEip1559";
|
|
11
11
|
import * as TxEnvelopeEip2930 from "ox/TxEnvelopeEip2930";
|
|
12
12
|
import * as TxEnvelopeLegacy from "ox/TxEnvelopeLegacy";
|
|
13
|
+
// src/evm/assets.ts
|
|
14
|
+
/** The native asset id in `AssetFlow` and simulated asset changes. */
|
|
15
|
+
const EVM_NATIVE_ASSET = "native";
|
|
13
16
|
// src/evm/tokens.ts
|
|
14
17
|
const USDC = Object.freeze({
|
|
15
18
|
symbol: "USDC",
|
|
@@ -45,7 +48,6 @@ const ERC20_INCREASE = AbiFunction.from("function increaseAllowance(address spen
|
|
|
45
48
|
const ERC721_TRANSFER_FROM = AbiFunction.from("function transferFrom(address from, address to, uint256 tokenId)");
|
|
46
49
|
const ERC721_SAFE_FROM = AbiFunction.from("function safeTransferFrom(address from, address to, uint256 tokenId)");
|
|
47
50
|
const ERC1155_SAFE_FROM = AbiFunction.from("function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)");
|
|
48
|
-
const NATIVE_ASSET = "native";
|
|
49
51
|
const MAX_UINT256 = 2n ** 256n - 1n;
|
|
50
52
|
const argAddress = (args, index) => {
|
|
51
53
|
const value = args[index];
|
|
@@ -75,7 +77,7 @@ const tryCall = (fn, data) => {
|
|
|
75
77
|
}
|
|
76
78
|
};
|
|
77
79
|
const weiAmount = (wei, symbol, decimals) => ({
|
|
78
|
-
asset:
|
|
80
|
+
asset: EVM_NATIVE_ASSET,
|
|
79
81
|
amount: wei.toString(10),
|
|
80
82
|
...symbol === void 0 ? {} : { symbol },
|
|
81
83
|
...decimals === void 0 ? {} : { decimals }
|
|
@@ -356,6 +358,6 @@ const normalizeEvm = (request) => {
|
|
|
356
358
|
}
|
|
357
359
|
throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
|
|
358
360
|
};
|
|
359
|
-
export { canonicalHex, checksumEvmAddress, decodeEvm, evmAddressFromPublicKey, evmTokenTable, isCanonicalHex, isEvmAddress, lookupEvmToken, networkChainId, normalizeEvm, normalizeEvmTransaction, parseTypedData, recoverEvmSigner, verifiabilityEvm };
|
|
361
|
+
export { EVM_NATIVE_ASSET, canonicalHex, checksumEvmAddress, decodeEvm, evmAddressFromPublicKey, evmTokenTable, isCanonicalHex, isEvmAddress, lookupEvmToken, networkChainId, normalizeEvm, normalizeEvmTransaction, parseTypedData, recoverEvmSigner, verifiabilityEvm };
|
|
360
362
|
|
|
361
363
|
//# sourceMappingURL=evm.mjs.map
|
package/dist/evm.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evm.mjs","names":[],"sources":["../src/evm/tokens.ts","../src/evm/decode.ts","../src/evm/recover.ts","../src/evm/index.ts"],"sourcesContent":["/**\n * Built-in ERC-20 token table, keyed by `chainId` then checksummed address. An entry here makes an\n * ERC-20 `transfer` `full`-verifiable (WD-065), so every entry must come from the issuer's own\n * published list and be reviewed against it; the source is recorded per issuer below.\n */\n\nexport type EvmToken = {\n readonly symbol: string;\n readonly decimals: number;\n readonly name?: string;\n};\n\nexport type EvmTokenTable = Readonly<Record<string, Readonly<Record<string, EvmToken>>>>;\n\n// Circle USDC (native issuance, 6 decimals), from\n// https://developers.circle.com/stablecoins/usdc-contract-addresses (reviewed 2026-10-30). BNB\n// Chain has no Circle-issued USDC (the Binance-pegged token is a different issuer), so it is absent.\nconst USDC: EvmToken = Object.freeze({ symbol: \"USDC\", decimals: 6, name: \"USD Coin\" });\n\n// Tether USDT (6 decimals), from https://tether.to/en/supported-protocols/ (reviewed 2026-10-31):\n// Tether lists USD₮ on Ethereum and Avalanche among our networks; bridged or third-party USDT on\n// other chains is a different issuer and is absent.\nconst USDT: EvmToken = Object.freeze({ symbol: \"USDT\", decimals: 6, name: \"Tether USD\" });\n\n/** The built-in table. */\nexport const evmTokenTable: EvmTokenTable = Object.freeze({\n \"1\": Object.freeze({\n \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\": USDC,\n \"0xdAC17F958D2ee523a2206206994597C13D831ec7\": USDT,\n }),\n \"10\": Object.freeze({ \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\": USDC }),\n \"137\": Object.freeze({ \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\": USDC }),\n \"999\": Object.freeze({ \"0xb88339CB7199b77E23DB6E890353E22632Ba630f\": USDC }),\n \"8453\": Object.freeze({ \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\": USDC }),\n \"42161\": Object.freeze({ \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\": USDC }),\n \"43114\": Object.freeze({\n \"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E\": USDC,\n \"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7\": USDT,\n }),\n});\n\nexport const lookupEvmToken = (\n table: EvmTokenTable,\n chainId: number,\n address: string,\n): EvmToken | undefined => table[String(chainId)]?.[address];\n","import * as AbiFunction from \"ox/AbiFunction\";\n\nimport { ChainError } from \"../index.ts\";\nimport type {\n ApprovalChange,\n AssetFlow,\n DisplayIntent,\n EvmTransaction,\n SignRequest,\n Verifiability,\n} from \"../index.ts\";\nimport { checksumEvmAddress } from \"./address.ts\";\nimport { lookupEvmToken, evmTokenTable } from \"./tokens.ts\";\nimport type { EvmTokenTable } from \"./tokens.ts\";\nimport { assertHex, networkChainId } from \"./transaction.ts\";\nimport { parseTypedData, typedDataWarnings } from \"./typed-data.ts\";\n\nconst ERC20_TRANSFER = AbiFunction.from(\"function transfer(address to, uint256 amount)\");\nconst ERC20_APPROVE = AbiFunction.from(\"function approve(address spender, uint256 amount)\");\nconst ERC20_INCREASE = AbiFunction.from(\n \"function increaseAllowance(address spender, uint256 amount)\",\n);\nconst ERC721_TRANSFER_FROM = AbiFunction.from(\n \"function transferFrom(address from, address to, uint256 tokenId)\",\n);\nconst ERC721_SAFE_FROM = AbiFunction.from(\n \"function safeTransferFrom(address from, address to, uint256 tokenId)\",\n);\nconst ERC1155_SAFE_FROM = AbiFunction.from(\n \"function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)\",\n);\n\nconst NATIVE_ASSET = \"native\";\nconst MAX_UINT256 = 2n ** 256n - 1n;\n\nconst argAddress = (args: ReadonlyArray<unknown>, index: number): string => {\n const value = args[index];\n if (typeof value !== \"string\" || !/^0x[0-9a-fA-F]{40}$/.test(value)) {\n throw new ChainError(\"invalid-request\", \"decoded argument is not an address\");\n }\n return checksumEvmAddress(value);\n};\n\nconst argUint = (args: ReadonlyArray<unknown>, index: number): bigint => {\n const value = args[index];\n if (typeof value !== \"bigint\") {\n throw new ChainError(\"invalid-request\", \"decoded argument is not a uint256\");\n }\n return value;\n};\n\n/**\n * Decodes `data` as `fn` and verifies the encoding is canonical (re-encoding the decoded args\n * reproduces the input byte-for-byte). Returns undefined on selector mismatch, decode failure or a\n * non-canonical encoding — the caller falls through to the next candidate or the opaque class.\n */\nconst tryCall = (fn: AbiFunction.AbiFunction, data: string): ReadonlyArray<unknown> | undefined => {\n const selector = AbiFunction.getSelector(fn);\n if (!data.toLowerCase().startsWith(selector)) {\n return undefined;\n }\n try {\n assertHex(data, \"data\");\n const args: unknown = AbiFunction.decodeData(fn, data);\n if (!Array.isArray(args)) {\n return undefined;\n }\n const reencoded = AbiFunction.encodeData(fn, args);\n return reencoded.toLowerCase() === data.toLowerCase() ? args : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst weiAmount = (wei: bigint, symbol?: string, decimals?: number) => ({\n asset: NATIVE_ASSET,\n amount: wei.toString(10),\n ...(symbol === undefined ? {} : { symbol }),\n ...(decimals === undefined ? {} : { decimals }),\n});\n\nconst feeWei = (tx: EvmTransaction): bigint =>\n BigInt(tx.gas) * (tx.type === \"eip1559\" ? BigInt(tx.maxFeePerGas) : BigInt(tx.gasPrice));\n\nconst nativeOutflow = (tx: EvmTransaction, to: string): ReadonlyArray<AssetFlow> => [\n { to, amount: weiAmount(BigInt(tx.value)), verified: true },\n];\n\nconst tokenFlow = (\n tx: EvmTransaction,\n to: string,\n amount: bigint,\n chainId: number,\n table: EvmTokenTable,\n): { flows: ReadonlyArray<AssetFlow>; verified: boolean } => {\n const token = lookupEvmToken(table, chainId, tx.to ?? \"\");\n return {\n flows: [\n {\n to,\n amount: {\n asset: tx.to ?? \"\",\n amount: amount.toString(10),\n ...(token === undefined ? {} : { symbol: token.symbol, decimals: token.decimals }),\n },\n verified: token !== undefined,\n },\n ],\n verified: token !== undefined,\n };\n};\n\nconst approvalChange = (tx: EvmTransaction, spender: string, amount: bigint): ApprovalChange => ({\n asset: tx.to ?? \"\",\n spender,\n amount: amount.toString(10),\n unlimited: amount === MAX_UINT256,\n verified: false,\n});\n\nconst nftFlow = (asset: string, to: string, id: bigint): ReadonlyArray<AssetFlow> => [\n { to, amount: { asset, amount: id.toString(10) }, verified: false },\n];\n\nconst decodeTransaction = (\n request: Extract<SignRequest, { kind: \"evm.transaction\" }>,\n table: EvmTokenTable,\n): DisplayIntent => {\n const { tx } = request;\n const chainId = networkChainId(request.network);\n const data = tx.data.toLowerCase();\n const fee = { max: weiAmount(feeWei(tx)) };\n const base = { family: \"evm\" as const, network: request.network, approvals: [], warnings: [] };\n\n if (data === \"0x\") {\n if (tx.to === undefined) {\n return { ...base, summary: \"contract-call\", outflows: [], fee, verifiability: \"opaque\" };\n }\n return {\n ...base,\n summary: \"transfer\",\n outflows: nativeOutflow(tx, tx.to),\n fee,\n verifiability: \"full\",\n };\n }\n\n const transferArgs = tryCall(ERC20_TRANSFER, data);\n if (transferArgs !== undefined) {\n const { flows, verified } = tokenFlow(\n tx,\n argAddress(transferArgs, 0),\n argUint(transferArgs, 1),\n chainId,\n table,\n );\n return {\n ...base,\n summary: \"transfer\",\n outflows: flows,\n fee,\n verifiability: verified ? \"full\" : \"partial\",\n };\n }\n const approveArgs = tryCall(ERC20_APPROVE, data);\n if (approveArgs !== undefined) {\n return {\n ...base,\n summary: \"approve\",\n outflows: [],\n approvals: [approvalChange(tx, argAddress(approveArgs, 0), argUint(approveArgs, 1))],\n fee,\n verifiability: \"partial\",\n };\n }\n const increaseArgs = tryCall(ERC20_INCREASE, data);\n if (increaseArgs !== undefined) {\n return {\n ...base,\n summary: \"approve\",\n outflows: [],\n approvals: [approvalChange(tx, argAddress(increaseArgs, 0), argUint(increaseArgs, 1))],\n fee,\n verifiability: \"partial\",\n };\n }\n for (const fn of [ERC721_TRANSFER_FROM, ERC721_SAFE_FROM]) {\n const args = tryCall(fn, data);\n if (args !== undefined) {\n return {\n ...base,\n summary: \"transfer\",\n outflows: nftFlow(tx.to ?? \"\", argAddress(args, 1), argUint(args, 2)),\n fee,\n verifiability: \"partial\",\n };\n }\n }\n const erc1155Args = tryCall(ERC1155_SAFE_FROM, data);\n if (erc1155Args !== undefined) {\n return {\n ...base,\n summary: \"transfer\",\n outflows: nftFlow(tx.to ?? \"\", argAddress(erc1155Args, 1), argUint(erc1155Args, 2)),\n fee,\n verifiability: \"partial\",\n };\n }\n return { ...base, summary: \"contract-call\", outflows: [], fee, verifiability: \"opaque\" };\n};\n\n/** What the signer can guarantee about this request (WD-065). */\nexport const verifiabilityEvm = (request: SignRequest): Verifiability =>\n decodeEvm(request).verifiability;\n\n/**\n * Decodes a normalized request into a DisplayIntent. The token table parameter is for tests;\n * production callers use the built-in table.\n */\nexport const decodeEvm = (\n request: SignRequest,\n table: EvmTokenTable = evmTokenTable,\n): DisplayIntent => {\n if (request.kind === \"evm.transaction\") {\n return decodeTransaction(request, table);\n }\n if (request.kind === \"evm.personal-message\") {\n return {\n family: \"evm\",\n network: request.network,\n summary: \"message\",\n outflows: [],\n approvals: [],\n fee: undefined,\n warnings: [],\n verifiability: \"opaque\",\n };\n }\n if (request.kind !== \"evm.typed-data\") {\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request.kind}`);\n }\n const parsed = parseTypedData(request.typedData, request.network);\n return {\n family: \"evm\",\n network: request.network,\n summary: \"message\",\n outflows: [],\n approvals: [],\n fee: undefined,\n warnings: typedDataWarnings(parsed),\n verifiability: \"opaque\",\n };\n};\n","/**\n * Signer recovery for `chain.sign` results: the host re-derives the signer address from a signed\n * envelope or a 65-byte signature and compares it with the account's `wallet.accounts` address — a\n * kernel returning someone else's signature fails closed.\n */\nimport * as Hex from \"ox/Hex\";\nimport * as PersonalMessage from \"ox/PersonalMessage\";\nimport * as Secp256k1 from \"ox/Secp256k1\";\nimport * as Signature from \"ox/Signature\";\nimport * as TxEnvelopeEip1559 from \"ox/TxEnvelopeEip1559\";\nimport * as TxEnvelopeEip2930 from \"ox/TxEnvelopeEip2930\";\nimport * as TxEnvelopeLegacy from \"ox/TxEnvelopeLegacy\";\nimport * as TypedData from \"ox/TypedData\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { SignRequest } from \"../index.ts\";\nimport { parseTypedData } from \"./typed-data.ts\";\n\nfunction assertEip1559Hex(hex: `0x${string}`): asserts hex is `0x02${string}` {\n if (!hex.startsWith(\"0x02\")) {\n throw new ChainError(\"invalid-request\", \"unrecognized signed transaction envelope\");\n }\n}\nfunction assertEip2930Hex(hex: `0x${string}`): asserts hex is `0x01${string}` {\n if (!hex.startsWith(\"0x01\")) {\n throw new ChainError(\"invalid-request\", \"unrecognized signed transaction envelope\");\n }\n}\n\ntype EnvelopeFields = {\n readonly r?: `0x${string}` | undefined;\n readonly s?: `0x${string}` | undefined;\n readonly yParity?: number | undefined;\n};\n\nconst signatureOf = (env: EnvelopeFields) => {\n const { r, s, yParity } = env;\n if (r === undefined || s === undefined || yParity === undefined) {\n throw new ChainError(\"invalid-request\", \"envelope carries no signature\");\n }\n return Signature.from({ r, s, yParity });\n};\n\n/** Recover the signer's EIP-55 address from a serialized signed transaction envelope. */\nconst signerFromEnvelope = (signedTransaction: Uint8Array): string => {\n const hex = Hex.fromBytes(signedTransaction);\n const [tag] = signedTransaction;\n if (tag === 0x02) {\n assertEip1559Hex(hex);\n const env = TxEnvelopeEip1559.deserialize(hex);\n const payload = TxEnvelopeEip1559.getSignPayload(env);\n return Secp256k1.recoverAddress({ payload, signature: signatureOf(env) });\n }\n if (tag === 0x01) {\n assertEip2930Hex(hex);\n const env = TxEnvelopeEip2930.deserialize(hex);\n const payload = TxEnvelopeEip2930.getSignPayload(env);\n return Secp256k1.recoverAddress({ payload, signature: signatureOf(env) });\n }\n try {\n const env = TxEnvelopeLegacy.deserialize(hex);\n const payload = TxEnvelopeLegacy.getSignPayload(env);\n return Secp256k1.recoverAddress({ payload, signature: signatureOf(env) });\n } catch {\n throw new ChainError(\"invalid-request\", \"unrecognized signed transaction envelope\");\n }\n};\n\n/**\n * The EIP-55 address that produced `result` for `request` — a `chain.sign` round-trip check\n * (`{kind:\"evm.transaction\",signedTransaction}` | `{kind,signature}`).\n */\nexport const recoverEvmSigner = (\n request: Extract<SignRequest, { network: string }>,\n result: { readonly signedTransaction?: Uint8Array; readonly signature?: Uint8Array },\n): string => {\n if (request.kind === \"evm.transaction\") {\n if (result.signedTransaction === undefined) {\n throw new ChainError(\"invalid-request\", \"expected a signed transaction\");\n }\n return signerFromEnvelope(result.signedTransaction);\n }\n if (result.signature === undefined || result.signature.length !== 65) {\n throw new ChainError(\"invalid-request\", \"expected a 65-byte signature\");\n }\n const signature = Signature.from(result.signature);\n if (request.kind === \"evm.personal-message\") {\n const payload = PersonalMessage.getSignPayload(Hex.fromBytes(request.message));\n return Secp256k1.recoverAddress({ payload, signature });\n }\n if (request.kind === \"evm.typed-data\") {\n const { json } = parseTypedData(request.typedData, request.network);\n const payload = TypedData.getSignPayload(json);\n return Secp256k1.recoverAddress({ payload, signature });\n }\n throw new ChainError(\"unsupported\", `cannot recover a signer for ${request.kind}`);\n};\n","import { requestBase } from \"../account-ref.ts\";\nimport { ChainError } from \"../index.ts\";\nimport type { SignRequest } from \"../index.ts\";\nimport { isRecord, networkChainId, normalizeEvmTransaction } from \"./transaction.ts\";\nimport { parseTypedData } from \"./typed-data.ts\";\n\nexport { isEvmAddress, checksumEvmAddress, evmAddressFromPublicKey } from \"./address.ts\";\nexport {\n networkChainId,\n normalizeEvmTransaction,\n canonicalHex,\n isCanonicalHex,\n} from \"./transaction.ts\";\nexport { decodeEvm, verifiabilityEvm } from \"./decode.ts\";\nexport { recoverEvmSigner } from \"./recover.ts\";\nexport { parseTypedData } from \"./typed-data.ts\";\nexport { evmTokenTable, lookupEvmToken } from \"./tokens.ts\";\nexport type { EvmToken, EvmTokenTable } from \"./tokens.ts\";\n\n/**\n * Normalizes a SignRequest for the EVM family: exact key sets, chainId vs the CAIP-2 `network`,\n * canonical quantities and EIP-55 addresses. Idempotent.\n */\nexport const normalizeEvm = (request: unknown): 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 const chainId = networkChainId(network);\n if (request[\"kind\"] === \"evm.transaction\") {\n const tx = normalizeEvmTransaction(request[\"tx\"]);\n if (tx.chainId !== chainId) {\n throw new ChainError(\n \"chain-id-mismatch\",\n `tx.chainId ${tx.chainId} does not match network ${network}`,\n );\n }\n return { kind: \"evm.transaction\", network, account, tx };\n }\n if (request[\"kind\"] === \"evm.personal-message\") {\n const { message } = request;\n if (!(message instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"personal-message payload must be bytes\");\n }\n return { kind: \"evm.personal-message\", network, account, message };\n }\n if (request[\"kind\"] === \"evm.typed-data\") {\n const { typedData } = request;\n if (typeof typedData !== \"string\") {\n throw new ChainError(\"invalid-request\", \"typed-data payload must be the JSON source string\");\n }\n parseTypedData(typedData, network);\n return { kind: \"evm.typed-data\", network, account, typedData };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,OAAiB,OAAO,OAAO;CAAE,QAAQ;CAAQ,UAAU;CAAG,MAAM;AAAW,CAAC;AAKtF,MAAM,OAAiB,OAAO,OAAO;CAAE,QAAQ;CAAQ,UAAU;CAAG,MAAM;AAAa,CAAC;;AAGxF,MAAa,gBAA+B,OAAO,OAAO;CACxD,KAAK,OAAO,OAAO;EACjB,8CAA8C;EAC9C,8CAA8C;CAChD,CAAC;CACD,MAAM,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC1E,OAAO,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC3E,OAAO,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC3E,QAAQ,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC5E,SAAS,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC7E,SAAS,OAAO,OAAO;EACrB,8CAA8C;EAC9C,8CAA8C;CAChD,CAAC;AACH,CAAC;AAED,MAAa,kBACX,OACA,SACA,YACyB,MAAM,OAAO,OAAO,EAAE,GAAG;;AC5BpD,MAAM,iBAAiB,YAAY,KAAK,+CAA+C;AACvF,MAAM,gBAAgB,YAAY,KAAK,mDAAmD;AAC1F,MAAM,iBAAiB,YAAY,KACjC,6DACF;AACA,MAAM,uBAAuB,YAAY,KACvC,kEACF;AACA,MAAM,mBAAmB,YAAY,KACnC,sEACF;AACA,MAAM,oBAAoB,YAAY,KACpC,6FACF;AAEA,MAAM,eAAe;AACrB,MAAM,cAAc,M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F,MAAM,EAAE,SAAS,YAAY,YAAY,OAAO;CAChD,MAAM,UAAU,eAAe,OAAO;CACtC,IAAI,QAAQ,YAAY,mBAAmB;EACzC,MAAM,KAAK,wBAAwB,QAAQ,KAAK;EAChD,IAAI,GAAG,YAAY,SACjB,MAAM,IAAI,WACR,qBACA,cAAc,GAAG,QAAQ,0BAA0B,SACrD;EAEF,OAAO;GAAE,MAAM;GAAmB;GAAS;GAAS;EAAG;CACzD;CACA,IAAI,QAAQ,YAAY,wBAAwB;EAC9C,MAAM,EAAE,YAAY;EACpB,IAAI,EAAE,mBAAmB,aACvB,MAAM,IAAI,WAAW,mBAAmB,wCAAwC;EAElF,OAAO;GAAE,MAAM;GAAwB;GAAS;GAAS;EAAQ;CACnE;CACA,IAAI,QAAQ,YAAY,kBAAkB;EACxC,MAAM,EAAE,cAAc;EACtB,IAAI,OAAO,cAAc,UACvB,MAAM,IAAI,WAAW,mBAAmB,mDAAmD;EAE7F,eAAe,WAAW,OAAO;EACjC,OAAO;GAAE,MAAM;GAAkB;GAAS;GAAS;EAAU;CAC/D;CACA,MAAM,IAAI,WAAW,eAAe,kCAAkC,QAAQ,SAAS;AACzF"}
|
|
1
|
+
{"version":3,"file":"evm.mjs","names":[],"sources":["../src/evm/assets.ts","../src/evm/tokens.ts","../src/evm/decode.ts","../src/evm/recover.ts","../src/evm/index.ts"],"sourcesContent":["/** The native asset id in `AssetFlow` and simulated asset changes. */\nexport const EVM_NATIVE_ASSET = \"native\";\n","/**\n * Built-in ERC-20 token table, keyed by `chainId` then checksummed address. An entry here makes an\n * ERC-20 `transfer` `full`-verifiable (WD-065), so every entry must come from the issuer's own\n * published list and be reviewed against it; the source is recorded per issuer below.\n */\n\nexport type EvmToken = {\n readonly symbol: string;\n readonly decimals: number;\n readonly name?: string;\n};\n\nexport type EvmTokenTable = Readonly<Record<string, Readonly<Record<string, EvmToken>>>>;\n\n// Circle USDC (native issuance, 6 decimals), from\n// https://developers.circle.com/stablecoins/usdc-contract-addresses (reviewed 2026-10-30). BNB\n// Chain has no Circle-issued USDC (the Binance-pegged token is a different issuer), so it is absent.\nconst USDC: EvmToken = Object.freeze({ symbol: \"USDC\", decimals: 6, name: \"USD Coin\" });\n\n// Tether USDT (6 decimals), from https://tether.to/en/supported-protocols/ (reviewed 2026-10-31):\n// Tether lists USD₮ on Ethereum and Avalanche among our networks; bridged or third-party USDT on\n// other chains is a different issuer and is absent.\nconst USDT: EvmToken = Object.freeze({ symbol: \"USDT\", decimals: 6, name: \"Tether USD\" });\n\n/** The built-in table. */\nexport const evmTokenTable: EvmTokenTable = Object.freeze({\n \"1\": Object.freeze({\n \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\": USDC,\n \"0xdAC17F958D2ee523a2206206994597C13D831ec7\": USDT,\n }),\n \"10\": Object.freeze({ \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\": USDC }),\n \"137\": Object.freeze({ \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\": USDC }),\n \"999\": Object.freeze({ \"0xb88339CB7199b77E23DB6E890353E22632Ba630f\": USDC }),\n \"8453\": Object.freeze({ \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\": USDC }),\n \"42161\": Object.freeze({ \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\": USDC }),\n \"43114\": Object.freeze({\n \"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E\": USDC,\n \"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7\": USDT,\n }),\n});\n\nexport const lookupEvmToken = (\n table: EvmTokenTable,\n chainId: number,\n address: string,\n): EvmToken | undefined => table[String(chainId)]?.[address];\n","import * as AbiFunction from \"ox/AbiFunction\";\n\nimport { ChainError } from \"../index.ts\";\nimport type {\n ApprovalChange,\n AssetFlow,\n DisplayIntent,\n EvmTransaction,\n SignRequest,\n Verifiability,\n} from \"../index.ts\";\nimport { checksumEvmAddress } from \"./address.ts\";\nimport { EVM_NATIVE_ASSET } from \"./assets.ts\";\nimport { lookupEvmToken, evmTokenTable } from \"./tokens.ts\";\nimport type { EvmTokenTable } from \"./tokens.ts\";\nimport { assertHex, networkChainId } from \"./transaction.ts\";\nimport { parseTypedData, typedDataWarnings } from \"./typed-data.ts\";\n\nconst ERC20_TRANSFER = AbiFunction.from(\"function transfer(address to, uint256 amount)\");\nconst ERC20_APPROVE = AbiFunction.from(\"function approve(address spender, uint256 amount)\");\nconst ERC20_INCREASE = AbiFunction.from(\n \"function increaseAllowance(address spender, uint256 amount)\",\n);\nconst ERC721_TRANSFER_FROM = AbiFunction.from(\n \"function transferFrom(address from, address to, uint256 tokenId)\",\n);\nconst ERC721_SAFE_FROM = AbiFunction.from(\n \"function safeTransferFrom(address from, address to, uint256 tokenId)\",\n);\nconst ERC1155_SAFE_FROM = AbiFunction.from(\n \"function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)\",\n);\n\nconst MAX_UINT256 = 2n ** 256n - 1n;\n\nconst argAddress = (args: ReadonlyArray<unknown>, index: number): string => {\n const value = args[index];\n if (typeof value !== \"string\" || !/^0x[0-9a-fA-F]{40}$/.test(value)) {\n throw new ChainError(\"invalid-request\", \"decoded argument is not an address\");\n }\n return checksumEvmAddress(value);\n};\n\nconst argUint = (args: ReadonlyArray<unknown>, index: number): bigint => {\n const value = args[index];\n if (typeof value !== \"bigint\") {\n throw new ChainError(\"invalid-request\", \"decoded argument is not a uint256\");\n }\n return value;\n};\n\n/**\n * Decodes `data` as `fn` and verifies the encoding is canonical (re-encoding the decoded args\n * reproduces the input byte-for-byte). Returns undefined on selector mismatch, decode failure or a\n * non-canonical encoding — the caller falls through to the next candidate or the opaque class.\n */\nconst tryCall = (fn: AbiFunction.AbiFunction, data: string): ReadonlyArray<unknown> | undefined => {\n const selector = AbiFunction.getSelector(fn);\n if (!data.toLowerCase().startsWith(selector)) {\n return undefined;\n }\n try {\n assertHex(data, \"data\");\n const args: unknown = AbiFunction.decodeData(fn, data);\n if (!Array.isArray(args)) {\n return undefined;\n }\n const reencoded = AbiFunction.encodeData(fn, args);\n return reencoded.toLowerCase() === data.toLowerCase() ? args : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst weiAmount = (wei: bigint, symbol?: string, decimals?: number) => ({\n asset: EVM_NATIVE_ASSET,\n amount: wei.toString(10),\n ...(symbol === undefined ? {} : { symbol }),\n ...(decimals === undefined ? {} : { decimals }),\n});\n\nconst feeWei = (tx: EvmTransaction): bigint =>\n BigInt(tx.gas) * (tx.type === \"eip1559\" ? BigInt(tx.maxFeePerGas) : BigInt(tx.gasPrice));\n\nconst nativeOutflow = (tx: EvmTransaction, to: string): ReadonlyArray<AssetFlow> => [\n { to, amount: weiAmount(BigInt(tx.value)), verified: true },\n];\n\nconst tokenFlow = (\n tx: EvmTransaction,\n to: string,\n amount: bigint,\n chainId: number,\n table: EvmTokenTable,\n): { flows: ReadonlyArray<AssetFlow>; verified: boolean } => {\n const token = lookupEvmToken(table, chainId, tx.to ?? \"\");\n return {\n flows: [\n {\n to,\n amount: {\n asset: tx.to ?? \"\",\n amount: amount.toString(10),\n ...(token === undefined ? {} : { symbol: token.symbol, decimals: token.decimals }),\n },\n verified: token !== undefined,\n },\n ],\n verified: token !== undefined,\n };\n};\n\nconst approvalChange = (tx: EvmTransaction, spender: string, amount: bigint): ApprovalChange => ({\n asset: tx.to ?? \"\",\n spender,\n amount: amount.toString(10),\n unlimited: amount === MAX_UINT256,\n verified: false,\n});\n\nconst nftFlow = (asset: string, to: string, id: bigint): ReadonlyArray<AssetFlow> => [\n { to, amount: { asset, amount: id.toString(10) }, verified: false },\n];\n\nconst decodeTransaction = (\n request: Extract<SignRequest, { kind: \"evm.transaction\" }>,\n table: EvmTokenTable,\n): DisplayIntent => {\n const { tx } = request;\n const chainId = networkChainId(request.network);\n const data = tx.data.toLowerCase();\n const fee = { max: weiAmount(feeWei(tx)) };\n const base = { family: \"evm\" as const, network: request.network, approvals: [], warnings: [] };\n\n if (data === \"0x\") {\n if (tx.to === undefined) {\n return { ...base, summary: \"contract-call\", outflows: [], fee, verifiability: \"opaque\" };\n }\n return {\n ...base,\n summary: \"transfer\",\n outflows: nativeOutflow(tx, tx.to),\n fee,\n verifiability: \"full\",\n };\n }\n\n const transferArgs = tryCall(ERC20_TRANSFER, data);\n if (transferArgs !== undefined) {\n const { flows, verified } = tokenFlow(\n tx,\n argAddress(transferArgs, 0),\n argUint(transferArgs, 1),\n chainId,\n table,\n );\n return {\n ...base,\n summary: \"transfer\",\n outflows: flows,\n fee,\n verifiability: verified ? \"full\" : \"partial\",\n };\n }\n const approveArgs = tryCall(ERC20_APPROVE, data);\n if (approveArgs !== undefined) {\n return {\n ...base,\n summary: \"approve\",\n outflows: [],\n approvals: [approvalChange(tx, argAddress(approveArgs, 0), argUint(approveArgs, 1))],\n fee,\n verifiability: \"partial\",\n };\n }\n const increaseArgs = tryCall(ERC20_INCREASE, data);\n if (increaseArgs !== undefined) {\n return {\n ...base,\n summary: \"approve\",\n outflows: [],\n approvals: [approvalChange(tx, argAddress(increaseArgs, 0), argUint(increaseArgs, 1))],\n fee,\n verifiability: \"partial\",\n };\n }\n for (const fn of [ERC721_TRANSFER_FROM, ERC721_SAFE_FROM]) {\n const args = tryCall(fn, data);\n if (args !== undefined) {\n return {\n ...base,\n summary: \"transfer\",\n outflows: nftFlow(tx.to ?? \"\", argAddress(args, 1), argUint(args, 2)),\n fee,\n verifiability: \"partial\",\n };\n }\n }\n const erc1155Args = tryCall(ERC1155_SAFE_FROM, data);\n if (erc1155Args !== undefined) {\n return {\n ...base,\n summary: \"transfer\",\n outflows: nftFlow(tx.to ?? \"\", argAddress(erc1155Args, 1), argUint(erc1155Args, 2)),\n fee,\n verifiability: \"partial\",\n };\n }\n return { ...base, summary: \"contract-call\", outflows: [], fee, verifiability: \"opaque\" };\n};\n\n/** What the signer can guarantee about this request (WD-065). */\nexport const verifiabilityEvm = (request: SignRequest): Verifiability =>\n decodeEvm(request).verifiability;\n\n/**\n * Decodes a normalized request into a DisplayIntent. The token table parameter is for tests;\n * production callers use the built-in table.\n */\nexport const decodeEvm = (\n request: SignRequest,\n table: EvmTokenTable = evmTokenTable,\n): DisplayIntent => {\n if (request.kind === \"evm.transaction\") {\n return decodeTransaction(request, table);\n }\n if (request.kind === \"evm.personal-message\") {\n return {\n family: \"evm\",\n network: request.network,\n summary: \"message\",\n outflows: [],\n approvals: [],\n fee: undefined,\n warnings: [],\n verifiability: \"opaque\",\n };\n }\n if (request.kind !== \"evm.typed-data\") {\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request.kind}`);\n }\n const parsed = parseTypedData(request.typedData, request.network);\n return {\n family: \"evm\",\n network: request.network,\n summary: \"message\",\n outflows: [],\n approvals: [],\n fee: undefined,\n warnings: typedDataWarnings(parsed),\n verifiability: \"opaque\",\n };\n};\n","/**\n * Signer recovery for `chain.sign` results: the host re-derives the signer address from a signed\n * envelope or a 65-byte signature and compares it with the account's `wallet.accounts` address — a\n * kernel returning someone else's signature fails closed.\n */\nimport * as Hex from \"ox/Hex\";\nimport * as PersonalMessage from \"ox/PersonalMessage\";\nimport * as Secp256k1 from \"ox/Secp256k1\";\nimport * as Signature from \"ox/Signature\";\nimport * as TxEnvelopeEip1559 from \"ox/TxEnvelopeEip1559\";\nimport * as TxEnvelopeEip2930 from \"ox/TxEnvelopeEip2930\";\nimport * as TxEnvelopeLegacy from \"ox/TxEnvelopeLegacy\";\nimport * as TypedData from \"ox/TypedData\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { SignRequest } from \"../index.ts\";\nimport { parseTypedData } from \"./typed-data.ts\";\n\nfunction assertEip1559Hex(hex: `0x${string}`): asserts hex is `0x02${string}` {\n if (!hex.startsWith(\"0x02\")) {\n throw new ChainError(\"invalid-request\", \"unrecognized signed transaction envelope\");\n }\n}\nfunction assertEip2930Hex(hex: `0x${string}`): asserts hex is `0x01${string}` {\n if (!hex.startsWith(\"0x01\")) {\n throw new ChainError(\"invalid-request\", \"unrecognized signed transaction envelope\");\n }\n}\n\ntype EnvelopeFields = {\n readonly r?: `0x${string}` | undefined;\n readonly s?: `0x${string}` | undefined;\n readonly yParity?: number | undefined;\n};\n\nconst signatureOf = (env: EnvelopeFields) => {\n const { r, s, yParity } = env;\n if (r === undefined || s === undefined || yParity === undefined) {\n throw new ChainError(\"invalid-request\", \"envelope carries no signature\");\n }\n return Signature.from({ r, s, yParity });\n};\n\n/** Recover the signer's EIP-55 address from a serialized signed transaction envelope. */\nconst signerFromEnvelope = (signedTransaction: Uint8Array): string => {\n const hex = Hex.fromBytes(signedTransaction);\n const [tag] = signedTransaction;\n if (tag === 0x02) {\n assertEip1559Hex(hex);\n const env = TxEnvelopeEip1559.deserialize(hex);\n const payload = TxEnvelopeEip1559.getSignPayload(env);\n return Secp256k1.recoverAddress({ payload, signature: signatureOf(env) });\n }\n if (tag === 0x01) {\n assertEip2930Hex(hex);\n const env = TxEnvelopeEip2930.deserialize(hex);\n const payload = TxEnvelopeEip2930.getSignPayload(env);\n return Secp256k1.recoverAddress({ payload, signature: signatureOf(env) });\n }\n try {\n const env = TxEnvelopeLegacy.deserialize(hex);\n const payload = TxEnvelopeLegacy.getSignPayload(env);\n return Secp256k1.recoverAddress({ payload, signature: signatureOf(env) });\n } catch {\n throw new ChainError(\"invalid-request\", \"unrecognized signed transaction envelope\");\n }\n};\n\n/**\n * The EIP-55 address that produced `result` for `request` — a `chain.sign` round-trip check\n * (`{kind:\"evm.transaction\",signedTransaction}` | `{kind,signature}`).\n */\nexport const recoverEvmSigner = (\n request: Extract<SignRequest, { network: string }>,\n result: { readonly signedTransaction?: Uint8Array; readonly signature?: Uint8Array },\n): string => {\n if (request.kind === \"evm.transaction\") {\n if (result.signedTransaction === undefined) {\n throw new ChainError(\"invalid-request\", \"expected a signed transaction\");\n }\n return signerFromEnvelope(result.signedTransaction);\n }\n if (result.signature === undefined || result.signature.length !== 65) {\n throw new ChainError(\"invalid-request\", \"expected a 65-byte signature\");\n }\n const signature = Signature.from(result.signature);\n if (request.kind === \"evm.personal-message\") {\n const payload = PersonalMessage.getSignPayload(Hex.fromBytes(request.message));\n return Secp256k1.recoverAddress({ payload, signature });\n }\n if (request.kind === \"evm.typed-data\") {\n const { json } = parseTypedData(request.typedData, request.network);\n const payload = TypedData.getSignPayload(json);\n return Secp256k1.recoverAddress({ payload, signature });\n }\n throw new ChainError(\"unsupported\", `cannot recover a signer for ${request.kind}`);\n};\n","import { requestBase } from \"../account-ref.ts\";\nimport { ChainError } from \"../index.ts\";\nimport type { SignRequest } from \"../index.ts\";\nimport { isRecord, networkChainId, normalizeEvmTransaction } from \"./transaction.ts\";\nimport { parseTypedData } from \"./typed-data.ts\";\n\nexport { EVM_NATIVE_ASSET } from \"./assets.ts\";\nexport { isEvmAddress, checksumEvmAddress, evmAddressFromPublicKey } from \"./address.ts\";\nexport {\n networkChainId,\n normalizeEvmTransaction,\n canonicalHex,\n isCanonicalHex,\n} from \"./transaction.ts\";\nexport { decodeEvm, verifiabilityEvm } from \"./decode.ts\";\nexport { recoverEvmSigner } from \"./recover.ts\";\nexport { parseTypedData } from \"./typed-data.ts\";\nexport { evmTokenTable, lookupEvmToken } from \"./tokens.ts\";\nexport type { EvmToken, EvmTokenTable } from \"./tokens.ts\";\n\n/**\n * Normalizes a SignRequest for the EVM family: exact key sets, chainId vs the CAIP-2 `network`,\n * canonical quantities and EIP-55 addresses. Idempotent.\n */\nexport const normalizeEvm = (request: unknown): 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 const chainId = networkChainId(network);\n if (request[\"kind\"] === \"evm.transaction\") {\n const tx = normalizeEvmTransaction(request[\"tx\"]);\n if (tx.chainId !== chainId) {\n throw new ChainError(\n \"chain-id-mismatch\",\n `tx.chainId ${tx.chainId} does not match network ${network}`,\n );\n }\n return { kind: \"evm.transaction\", network, account, tx };\n }\n if (request[\"kind\"] === \"evm.personal-message\") {\n const { message } = request;\n if (!(message instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"personal-message payload must be bytes\");\n }\n return { kind: \"evm.personal-message\", network, account, message };\n }\n if (request[\"kind\"] === \"evm.typed-data\") {\n const { typedData } = request;\n if (typeof typedData !== \"string\") {\n throw new ChainError(\"invalid-request\", \"typed-data payload must be the JSON source string\");\n }\n parseTypedData(typedData, network);\n return { kind: \"evm.typed-data\", network, account, typedData };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n"],"mappings":";;;;;;;;;;;;;;AACA,MAAa,mBAAmB;;ACgBhC,MAAM,OAAiB,OAAO,OAAO;CAAE,QAAQ;CAAQ,UAAU;CAAG,MAAM;AAAW,CAAC;AAKtF,MAAM,OAAiB,OAAO,OAAO;CAAE,QAAQ;CAAQ,UAAU;CAAG,MAAM;AAAa,CAAC;;AAGxF,MAAa,gBAA+B,OAAO,OAAO;CACxD,KAAK,OAAO,OAAO;EACjB,8CAA8C;EAC9C,8CAA8C;CAChD,CAAC;CACD,MAAM,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC1E,OAAO,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC3E,OAAO,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC3E,QAAQ,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC5E,SAAS,OAAO,OAAO,EAAE,8CAA8C,KAAK,CAAC;CAC7E,SAAS,OAAO,OAAO;EACrB,8CAA8C;EAC9C,8CAA8C;CAChD,CAAC;AACH,CAAC;AAED,MAAa,kBACX,OACA,SACA,YACyB,MAAM,OAAO,OAAO,EAAE,GAAG;;AC3BpD,MAAM,iBAAiB,YAAY,KAAK,+CAA+C;AACvF,MAAM,gBAAgB,YAAY,KAAK,mDAAmD;AAC1F,MAAM,iBAAiB,YAAY,KACjC,6DACF;AACA,MAAM,uBAAuB,YAAY,KACvC,kEACF;AACA,MAAM,mBAAmB,YAAY,KACnC,sEAC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QAAQ,YAAY,UACnD,MAAM,IAAI,WAAW,mBAAmB,uCAAuC;CAEjF,MAAM,EAAE,SAAS,YAAY,YAAY,OAAO;CAChD,MAAM,UAAU,eAAe,OAAO;CACtC,IAAI,QAAQ,YAAY,mBAAmB;EACzC,MAAM,KAAK,wBAAwB,QAAQ,KAAK;EAChD,IAAI,GAAG,YAAY,SACjB,MAAM,IAAI,WACR,qBACA,cAAc,GAAG,QAAQ,0BAA0B,SACrD;EAEF,OAAO;GAAE,MAAM;GAAmB;GAAS;GAAS;EAAG;CACzD;CACA,IAAI,QAAQ,YAAY,wBAAwB;EAC9C,MAAM,EAAE,YAAY;EACpB,IAAI,EAAE,mBAAmB,aACvB,MAAM,IAAI,WAAW,mBAAmB,wCAAwC;EAElF,OAAO;GAAE,MAAM;GAAwB;GAAS;GAAS;EAAQ;CACnE;CACA,IAAI,QAAQ,YAAY,kBAAkB;EACxC,MAAM,EAAE,cAAc;EACtB,IAAI,OAAO,cAAc,UACvB,MAAM,IAAI,WAAW,mBAAmB,mDAAmD;EAE7F,eAAe,WAAW,OAAO;EACjC,OAAO;GAAE,MAAM;GAAkB;GAAS;GAAS;EAAU;CAC/D;CACA,MAAM,IAAI,WAAW,eAAe,kCAAkC,QAAQ,SAAS;AACzF"}
|
|
@@ -74,9 +74,14 @@ const concat = (...parts) => {
|
|
|
74
74
|
}
|
|
75
75
|
return out;
|
|
76
76
|
};
|
|
77
|
-
/** CompactSize length prefix
|
|
77
|
+
/** CompactSize length prefix for the one-byte form. */
|
|
78
78
|
const varint = (n) => Uint8Array.of(n);
|
|
79
|
-
const
|
|
79
|
+
const COMPACT_SIZE_ONE_BYTE_MAX = 252;
|
|
80
|
+
/** A length-prefixed push; longer data would need a multi-byte CompactSize this code never emits. */
|
|
81
|
+
const pushData = (data) => {
|
|
82
|
+
if (data.length > COMPACT_SIZE_ONE_BYTE_MAX) throw new ChainError("invalid-request", "BIP-322 script data exceeds 252 bytes");
|
|
83
|
+
return concat(varint(data.length), data);
|
|
84
|
+
};
|
|
80
85
|
const u32le = (n) => Uint8Array.of(n % 256, Math.floor(n / 256) % 256, Math.floor(n / 65536) % 256, Math.floor(n / 16777216) % 256);
|
|
81
86
|
const u64le = (n) => {
|
|
82
87
|
const out = /* @__PURE__ */ new Uint8Array(8);
|
|
@@ -180,4 +185,4 @@ const signLegacyMessage = (message, privateKey) => {
|
|
|
180
185
|
};
|
|
181
186
|
export { bitcoinNetwork as a, BITCOIN_NETWORKS as i, signBip322Simple as n, signLegacyMessage as r, bip322ToSpendTxid as t };
|
|
182
187
|
|
|
183
|
-
//# sourceMappingURL=message-
|
|
188
|
+
//# sourceMappingURL=message-Dv18g8ii.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"message-Dv18g8ii.mjs","names":[],"sources":["../src/bitcoin/networks.ts","../src/bitcoin/message.ts"],"sourcesContent":["import { NETWORK, TEST_NETWORK } from \"@scure/btc-signer/utils.js\";\n/**\n * Bip122 CAIP-2 networks = `bip122:` + the first 32 hex chars of the genesis hash, verified against\n * Bitcoin Core `src/kernel/chainparams.cpp` (assert(consensus.hashGenesisBlock == ...) per network\n * class).\n */\n\nimport { ChainError } from \"../index.ts\";\n\nexport type BitcoinNetwork = {\n readonly caip2: string;\n readonly genesis: string;\n readonly params: typeof NETWORK;\n readonly coinType: 0 | 1;\n /** BIP-32 extended-key version bytes: `xpub`/`xprv` on mainnet, `tpub`/`tprv` elsewhere. */\n readonly bip32: { readonly public: number; readonly private: number };\n};\n\nconst MAINNET_BIP32 = { public: 0x0488b21e, private: 0x0488ade4 } as const;\nconst TESTNET_BIP32 = { public: 0x043587cf, private: 0x04358394 } as const;\n\n// btc-signer ships mainnet and testnet parameters only; regtest shares testnet's version bytes but\n// uses the `bcrt` bech32 prefix.\nconst REGTEST_NETWORK: typeof NETWORK = { ...TEST_NETWORK, bech32: \"bcrt\" };\n\nconst NETWORKS: ReadonlyArray<BitcoinNetwork> = Object.freeze([\n {\n caip2: \"bip122:000000000019d6689c085ae165831e93\",\n genesis: \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f\",\n params: NETWORK,\n coinType: 0,\n bip32: MAINNET_BIP32,\n },\n {\n caip2: \"bip122:00000000da84f2bafbbc53dee25a72ae\",\n genesis: \"00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043\",\n params: TEST_NETWORK,\n coinType: 1,\n bip32: TESTNET_BIP32,\n },\n {\n caip2: \"bip122:00000008819873e925422c1ff0f99f7c\",\n genesis: \"00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6\",\n params: TEST_NETWORK,\n coinType: 1,\n bip32: TESTNET_BIP32,\n },\n {\n caip2: \"bip122:0f9188f13cb7b2c71f2a335e3a4fc328\",\n genesis: \"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\",\n params: REGTEST_NETWORK,\n coinType: 1,\n bip32: TESTNET_BIP32,\n },\n] as const);\n\nexport const BITCOIN_NETWORKS: Readonly<Record<string, BitcoinNetwork>> = Object.freeze(\n Object.fromEntries(NETWORKS.map((n) => [n.caip2, n])),\n);\n\nexport const bitcoinNetwork = (caip2: string): BitcoinNetwork => {\n const net = BITCOIN_NETWORKS[caip2];\n if (net === undefined) {\n throw new ChainError(\"unsupported\", `unknown bitcoin network: ${caip2}`);\n }\n return net;\n};\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\n/**\n * BIP-322 message signing (\"simple\" + legacy) built on btc-signer primitives.\n * https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { SigHash, Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\n\nconst utf8 = (s: string): Uint8Array => new TextEncoder().encode(s);\n\nconst BIP322_TAG = \"BIP0322-signed-message\";\nconst LEGACY_MAGIC = utf8(\"Bitcoin Signed Message:\\n\");\n\nconst concat = (...parts: ReadonlyArray<Uint8Array>): Uint8Array => {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let o = 0;\n for (const p of parts) {\n out.set(p, o);\n o += p.length;\n }\n return out;\n};\n\n/** CompactSize length prefix for the one-byte form. */\nconst varint = (n: number): Uint8Array => Uint8Array.of(n);\n\nconst COMPACT_SIZE_ONE_BYTE_MAX = 252;\n\n/** A length-prefixed push; longer data would need a multi-byte CompactSize this code never emits. */\nexport const pushData = (data: Uint8Array): Uint8Array => {\n if (data.length > COMPACT_SIZE_ONE_BYTE_MAX) {\n throw new ChainError(\"invalid-request\", \"BIP-322 script data exceeds 252 bytes\");\n }\n return concat(varint(data.length), data);\n};\n\nconst u32le = (n: number): Uint8Array =>\n Uint8Array.of(\n n % 256,\n Math.floor(n / 256) % 256,\n Math.floor(n / 65536) % 256,\n Math.floor(n / 16777216) % 256,\n );\n\nconst u64le = (n: bigint): Uint8Array => {\n const out = new Uint8Array(8);\n let v = n;\n for (let i = 0; i < 8; i++) {\n out[i] = Number(v % 256n);\n v /= 256n;\n }\n return out;\n};\n\n/** BIP340 tagged hash: sha256(sha256(tag) || sha256(tag) || m). */\nconst bip322MessageHash = (message: string): Uint8Array => {\n const tag = sha256(utf8(BIP322_TAG));\n return sha256(concat(tag, tag, utf8(message)));\n};\n\n/**\n * Serialized to_spend tx per BIP-322: version 0, one input spending the zero prevout with the\n * message-hash scriptSig, one output paying the message's scriptPubKey. Returns txid (hash256d,\n * big-endian display order).\n */\nconst toSpend = (\n scriptPubKey: Uint8Array,\n messageHash: Uint8Array,\n): { txid: Uint8Array; raw: Uint8Array } => {\n const scriptSig = concat(Uint8Array.of(0x00), pushData(messageHash));\n const raw = concat(\n u32le(0),\n varint(1),\n new Uint8Array(32),\n u32le(0xffffffff),\n pushData(scriptSig),\n u32le(0),\n varint(1),\n u64le(0n),\n pushData(scriptPubKey),\n u32le(0),\n );\n const txid = sha256(sha256(raw));\n return { txid, raw };\n};\n\n/**\n * Display-order (big-endian) txid of the BIP-322 to_spend transaction — exported for vector\n * verification.\n */\nexport const bip322ToSpendTxid = (scriptPubKey: Uint8Array, message: string): Uint8Array =>\n Uint8Array.from([...toSpend(scriptPubKey, bip322MessageHash(message)).txid].reverse());\n\nconst BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst b64 = (i: number): string => BASE64[i] ?? \"\";\nconst base64 = (bytes: Uint8Array): string => {\n const c = b64;\n let out = \"\";\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i] ?? 0;\n const b1 = bytes[i + 1] ?? 0;\n const b2 = bytes[i + 2] ?? 0;\n out += c(Math.floor(b0 / 4)) + c((b0 % 4) * 16 + Math.floor(b1 / 16));\n out += i + 1 < bytes.length ? c((b1 % 16) * 4 + Math.floor(b2 / 64)) : \"=\";\n out += i + 2 < bytes.length ? c(b2 % 64) : \"=\";\n }\n return out;\n};\n\n/**\n * Signs the BIP-322 to_sign input through a btc-signer Transaction and returns the `smp`-prefixed\n * base64 witness encoding. `scriptPubKey` is the message address's output script (P2WPKH or P2TR).\n */\nexport const signBip322Simple = (\n message: string,\n scriptPubKey: Uint8Array,\n privateKey: Uint8Array,\n auxRand: (n: number) => Uint8Array,\n): string => {\n const hash = bip322MessageHash(message);\n const { txid } = toSpend(scriptPubKey, hash);\n const tx = new Transaction({ version: 0, lockTime: 0, allowUnknownOutputs: true });\n const pub = secp256k1.getPublicKey(privateKey, true);\n tx.addInput({\n txid,\n index: 0,\n sequence: 0,\n witnessUtxo: { script: scriptPubKey, amount: 0n },\n bip32Derivation: [[pub, { fingerprint: 0, path: [] }]],\n ...(scriptPubKey[0] === 0x51 ? { tapInternalKey: pub.slice(1) } : {}),\n });\n tx.addOutput({ script: Uint8Array.of(0x6a), amount: 0n });\n const isTaproot = scriptPubKey[0] === 0x51;\n const ok = tx.signIdx(\n privateKey,\n 0,\n isTaproot ? [SigHash.DEFAULT, SigHash.ALL] : [SigHash.ALL],\n auxRand(0),\n );\n if (!ok) {\n throw new ChainError(\"invalid-request\", \"key cannot sign this BIP-322 input\");\n }\n tx.finalizeIdx(0);\n const witness = tx.getInput(0).finalScriptWitness;\n if (witness === undefined) {\n throw new ChainError(\"invalid-request\", \"BIP-322 input produced no witness\");\n }\n const raw = concat(varint(witness.length), ...witness.map(pushData));\n return `smp${base64(raw)}`;\n};\n\n/**\n * Legacy \"Bitcoin Signed Message\" compact signature for P2PKH addresses: base64(1-byte header +\n * 64-byte compact ECDSA sig), header = 27 + recovery + 4 (compressed pubkey).\n */\nexport const signLegacyMessage = (message: string, privateKey: Uint8Array): string => {\n const data = concat(pushData(LEGACY_MAGIC), pushData(utf8(message)));\n const hash = sha256(sha256(data));\n const recovered = secp256k1.sign(hash, privateKey, { lowS: true, format: \"recovered\" });\n const header = 27 + (recovered[0] ?? 0) + 4;\n return base64(concat(Uint8Array.of(header), recovered.slice(1)));\n};\n"],"mappings":";;;;;;;;;;;AAkBA,MAAM,gBAAgB;CAAE,QAAQ;CAAY,SAAS;AAAW;AAChE,MAAM,gBAAgB;CAAE,QAAQ;CAAY,SAAS;AAAW;AAIhE,MAAM,kBAAkC;CAAE,GAAG;CAAc,QAAQ;AAAO;AAE1E,MAAM,WAA0C,OAAO,OAAO;CAC5D;EACE,OAAO;EACP,SAAS;EACT,QAAQ;EACR,UAAU;EACV,OAAO;CACT;CACA;EACE,OAAO;EACP,SAAS;EACT,QAAQ;EACR,UAAU;EACV,OAAO;CACT;CACA;EACE,OAAO;EACP,SAAS;EACT,QAAQ;EACR,UAAU;EACV,OAAO;CACT;CACA;EACE,OAAO;EACP,SAAS;EACT,QAAQ;EACR,UAAU;EACV,OAAO;CACT;AACF,CAAU;AAEV,MAAa,mBAA6D,OAAO,OAC/E,OAAO,YAAY,SAAS,KAAK,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CACtD;AAEA,MAAa,kBAAkB,UAAkC;CAC/D,MAAM,MAAM,iBAAiB;CAC7B,IAAI,QA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) => M
|
|
|
77
77
|
* max)`.
|
|
78
78
|
*/
|
|
79
79
|
export declare const netAfterTransferFee: (amount: bigint, bps: number, max: bigint) => bigint;
|
|
80
|
+
/** The native asset id in `AssetFlow` and simulated asset changes. */
|
|
81
|
+
export declare const SOLANA_NATIVE_ASSET = "lamports";
|
|
80
82
|
type CompiledIx = {
|
|
81
83
|
readonly programAddressIndex: number;
|
|
82
84
|
readonly accountIndices: ReadonlyArray<number>;
|
|
@@ -87,8 +89,13 @@ type ParsedSolanaMessage = {
|
|
|
87
89
|
readonly numRequiredSignatures: number;
|
|
88
90
|
readonly staticAccounts: ReadonlyArray<string>;
|
|
89
91
|
readonly instructions: ReadonlyArray<CompiledIx>;
|
|
90
|
-
readonly
|
|
91
|
-
|
|
92
|
+
readonly lookups: ReadonlyArray<LookupReference>;
|
|
93
|
+
};
|
|
94
|
+
/** One address-table lookup: the table and which of its entries the message references. */
|
|
95
|
+
type LookupReference = {
|
|
96
|
+
readonly address: string;
|
|
97
|
+
readonly writableIndexes: ReadonlyArray<number>;
|
|
98
|
+
readonly readonlyIndexes: ReadonlyArray<number>;
|
|
92
99
|
};
|
|
93
100
|
/**
|
|
94
101
|
* Decodes a compiled wire message; rejects trailing bytes and the 1232-byte transaction limit. The
|
|
@@ -104,5 +111,5 @@ export declare const verifySolanaSignature: (message: Uint8Array, signature: Uin
|
|
|
104
111
|
* is a wallet-drainer). Idempotent.
|
|
105
112
|
*/
|
|
106
113
|
export declare const normalizeSolana: (request: unknown, signer: string) => SignRequest;
|
|
107
|
-
export type { MintExtensionSummary, SolanaTokenTable };
|
|
114
|
+
export type { LookupReference, MintExtensionSummary, ParsedSolanaMessage, SolanaTokenTable };
|
|
108
115
|
//# sourceMappingURL=solana.d.mts.map
|
package/dist/solana.mjs
CHANGED
|
@@ -49,8 +49,11 @@ const parseCompiledMessage = (bytes) => {
|
|
|
49
49
|
numRequiredSignatures: message.numSignerAccounts,
|
|
50
50
|
staticAccounts,
|
|
51
51
|
instructions: message.instructions,
|
|
52
|
-
|
|
53
|
-
|
|
52
|
+
lookups: lookups.map((l) => ({
|
|
53
|
+
address: l.lookupTableAddress,
|
|
54
|
+
writableIndexes: l.writableIndexes,
|
|
55
|
+
readonlyIndexes: l.readonlyIndexes
|
|
56
|
+
}))
|
|
54
57
|
};
|
|
55
58
|
};
|
|
56
59
|
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -110,6 +113,9 @@ const validateLookupTables = (tables) => {
|
|
|
110
113
|
if (tables === void 0) return;
|
|
111
114
|
for (const table of tables) if (!isSolanaAddress(table.address) || !table.addresses.every(isSolanaAddress)) throw new ChainError("invalid-address", "lookup table entries must be base58 32-byte addresses");
|
|
112
115
|
};
|
|
116
|
+
// src/solana/assets.ts
|
|
117
|
+
/** The native asset id in `AssetFlow` and simulated asset changes. */
|
|
118
|
+
const SOLANA_NATIVE_ASSET = "lamports";
|
|
113
119
|
// src/solana/tokens.ts
|
|
114
120
|
const USDC = Object.freeze({
|
|
115
121
|
symbol: "USDC",
|
|
@@ -127,7 +133,6 @@ const solanaTokenTable = Object.freeze({ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvd
|
|
|
127
133
|
}) });
|
|
128
134
|
const lookupSolanaToken = (table, network, mint) => table[network]?.[mint];
|
|
129
135
|
// src/solana/decode.ts
|
|
130
|
-
const LAMPORTS_ASSET = "lamports";
|
|
131
136
|
const u32 = getU32Decoder();
|
|
132
137
|
const u64$1 = getU64Decoder();
|
|
133
138
|
const u32le = (data, offset) => u32.decode(data, offset);
|
|
@@ -189,7 +194,7 @@ const FULL_KINDS = /* @__PURE__ */ new Set([
|
|
|
189
194
|
"ata-create-idempotent"
|
|
190
195
|
]);
|
|
191
196
|
const classify = (parsed, calls, network, table) => {
|
|
192
|
-
if (parsed.
|
|
197
|
+
if (parsed.lookups.length > 0) return "partial";
|
|
193
198
|
let allFull = true;
|
|
194
199
|
for (const call of calls) {
|
|
195
200
|
if (call.kind === "other") return "opaque";
|
|
@@ -221,7 +226,7 @@ const decodeTransaction = (request, signer, table) => {
|
|
|
221
226
|
if (source === signer) outflows.push({
|
|
222
227
|
to: call.to,
|
|
223
228
|
amount: {
|
|
224
|
-
asset:
|
|
229
|
+
asset: SOLANA_NATIVE_ASSET,
|
|
225
230
|
amount: (call.amount ?? 0n).toString(10)
|
|
226
231
|
},
|
|
227
232
|
verified: true
|
|
@@ -258,7 +263,7 @@ const decodeTransaction = (request, signer, table) => {
|
|
|
258
263
|
outflows,
|
|
259
264
|
approvals,
|
|
260
265
|
fee: fee === void 0 ? void 0 : { max: {
|
|
261
|
-
asset:
|
|
266
|
+
asset: SOLANA_NATIVE_ASSET,
|
|
262
267
|
amount: fee.toString(10)
|
|
263
268
|
} },
|
|
264
269
|
warnings: [],
|
|
@@ -427,6 +432,6 @@ const normalizeSolana = (request, signer) => {
|
|
|
427
432
|
}
|
|
428
433
|
throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
|
|
429
434
|
};
|
|
430
|
-
export { EXT, PROGRAM_IDS, SOLANA_NETWORKS, decodeSolana, isSolanaAddress, netAfterTransferFee, normalizeSolana, parseCompiledMessage, parseMintExtensions, solanaAddressFromPublicKey, solanaTokenTable, verifiabilitySolana, verifySolanaSignature };
|
|
435
|
+
export { EXT, PROGRAM_IDS, SOLANA_NATIVE_ASSET, SOLANA_NETWORKS, decodeSolana, isSolanaAddress, netAfterTransferFee, normalizeSolana, parseCompiledMessage, parseMintExtensions, solanaAddressFromPublicKey, solanaTokenTable, verifiabilitySolana, verifySolanaSignature };
|
|
431
436
|
|
|
432
437
|
//# sourceMappingURL=solana.mjs.map
|
package/dist/solana.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,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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
|
+
{"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 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\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,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E;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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@qntx/wallet-chains",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.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>",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"message-DuJ5KSRT.mjs","names":[],"sources":["../src/bitcoin/networks.ts","../src/bitcoin/message.ts"],"sourcesContent":["import { NETWORK, TEST_NETWORK } from \"@scure/btc-signer/utils.js\";\n/**\n * Bip122 CAIP-2 networks = `bip122:` + the first 32 hex chars of the genesis hash, verified against\n * Bitcoin Core `src/kernel/chainparams.cpp` (assert(consensus.hashGenesisBlock == ...) per network\n * class).\n */\n\nimport { ChainError } from \"../index.ts\";\n\nexport type BitcoinNetwork = {\n readonly caip2: string;\n readonly genesis: string;\n readonly params: typeof NETWORK;\n readonly coinType: 0 | 1;\n /** BIP-32 extended-key version bytes: `xpub`/`xprv` on mainnet, `tpub`/`tprv` elsewhere. */\n readonly bip32: { readonly public: number; readonly private: number };\n};\n\nconst MAINNET_BIP32 = { public: 0x0488b21e, private: 0x0488ade4 } as const;\nconst TESTNET_BIP32 = { public: 0x043587cf, private: 0x04358394 } as const;\n\n// btc-signer ships mainnet and testnet parameters only; regtest shares testnet's version bytes but\n// uses the `bcrt` bech32 prefix.\nconst REGTEST_NETWORK: typeof NETWORK = { ...TEST_NETWORK, bech32: \"bcrt\" };\n\nconst NETWORKS: ReadonlyArray<BitcoinNetwork> = Object.freeze([\n {\n caip2: \"bip122:000000000019d6689c085ae165831e93\",\n genesis: \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f\",\n params: NETWORK,\n coinType: 0,\n bip32: MAINNET_BIP32,\n },\n {\n caip2: \"bip122:00000000da84f2bafbbc53dee25a72ae\",\n genesis: \"00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043\",\n params: TEST_NETWORK,\n coinType: 1,\n bip32: TESTNET_BIP32,\n },\n {\n caip2: \"bip122:00000008819873e925422c1ff0f99f7c\",\n genesis: \"00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6\",\n params: TEST_NETWORK,\n coinType: 1,\n bip32: TESTNET_BIP32,\n },\n {\n caip2: \"bip122:0f9188f13cb7b2c71f2a335e3a4fc328\",\n genesis: \"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\",\n params: REGTEST_NETWORK,\n coinType: 1,\n bip32: TESTNET_BIP32,\n },\n] as const);\n\nexport const BITCOIN_NETWORKS: Readonly<Record<string, BitcoinNetwork>> = Object.freeze(\n Object.fromEntries(NETWORKS.map((n) => [n.caip2, n])),\n);\n\nexport const bitcoinNetwork = (caip2: string): BitcoinNetwork => {\n const net = BITCOIN_NETWORKS[caip2];\n if (net === undefined) {\n throw new ChainError(\"unsupported\", `unknown bitcoin network: ${caip2}`);\n }\n return net;\n};\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\n/**\n * BIP-322 message signing (\"simple\" + legacy) built on btc-signer primitives.\n * https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { SigHash, Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\n\nconst utf8 = (s: string): Uint8Array => new TextEncoder().encode(s);\n\nconst BIP322_TAG = \"BIP0322-signed-message\";\nconst LEGACY_MAGIC = utf8(\"Bitcoin Signed Message:\\n\");\n\nconst concat = (...parts: ReadonlyArray<Uint8Array>): Uint8Array => {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let o = 0;\n for (const p of parts) {\n out.set(p, o);\n o += p.length;\n }\n return out;\n};\n\n/** CompactSize length prefix (values here are always < 253). */\nconst varint = (n: number): Uint8Array => Uint8Array.of(n);\n\nconst pushData = (data: Uint8Array): Uint8Array => concat(varint(data.length), data);\n\nconst u32le = (n: number): Uint8Array =>\n Uint8Array.of(\n n % 256,\n Math.floor(n / 256) % 256,\n Math.floor(n / 65536) % 256,\n Math.floor(n / 16777216) % 256,\n );\n\nconst u64le = (n: bigint): Uint8Array => {\n const out = new Uint8Array(8);\n let v = n;\n for (let i = 0; i < 8; i++) {\n out[i] = Number(v % 256n);\n v /= 256n;\n }\n return out;\n};\n\n/** BIP340 tagged hash: sha256(sha256(tag) || sha256(tag) || m). */\nconst bip322MessageHash = (message: string): Uint8Array => {\n const tag = sha256(utf8(BIP322_TAG));\n return sha256(concat(tag, tag, utf8(message)));\n};\n\n/**\n * Serialized to_spend tx per BIP-322: version 0, one input spending the zero prevout with the\n * message-hash scriptSig, one output paying the message's scriptPubKey. Returns txid (hash256d,\n * big-endian display order).\n */\nconst toSpend = (\n scriptPubKey: Uint8Array,\n messageHash: Uint8Array,\n): { txid: Uint8Array; raw: Uint8Array } => {\n const scriptSig = concat(Uint8Array.of(0x00), pushData(messageHash));\n const raw = concat(\n u32le(0),\n varint(1),\n new Uint8Array(32),\n u32le(0xffffffff),\n pushData(scriptSig),\n u32le(0),\n varint(1),\n u64le(0n),\n pushData(scriptPubKey),\n u32le(0),\n );\n const txid = sha256(sha256(raw));\n return { txid, raw };\n};\n\n/**\n * Display-order (big-endian) txid of the BIP-322 to_spend transaction — exported for vector\n * verification.\n */\nexport const bip322ToSpendTxid = (scriptPubKey: Uint8Array, message: string): Uint8Array =>\n Uint8Array.from([...toSpend(scriptPubKey, bip322MessageHash(message)).txid].reverse());\n\nconst BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst b64 = (i: number): string => BASE64[i] ?? \"\";\nconst base64 = (bytes: Uint8Array): string => {\n const c = b64;\n let out = \"\";\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i] ?? 0;\n const b1 = bytes[i + 1] ?? 0;\n const b2 = bytes[i + 2] ?? 0;\n out += c(Math.floor(b0 / 4)) + c((b0 % 4) * 16 + Math.floor(b1 / 16));\n out += i + 1 < bytes.length ? c((b1 % 16) * 4 + Math.floor(b2 / 64)) : \"=\";\n out += i + 2 < bytes.length ? c(b2 % 64) : \"=\";\n }\n return out;\n};\n\n/**\n * Signs the BIP-322 to_sign input through a btc-signer Transaction and returns the `smp`-prefixed\n * base64 witness encoding. `scriptPubKey` is the message address's output script (P2WPKH or P2TR).\n */\nexport const signBip322Simple = (\n message: string,\n scriptPubKey: Uint8Array,\n privateKey: Uint8Array,\n auxRand: (n: number) => Uint8Array,\n): string => {\n const hash = bip322MessageHash(message);\n const { txid } = toSpend(scriptPubKey, hash);\n const tx = new Transaction({ version: 0, lockTime: 0, allowUnknownOutputs: true });\n const pub = secp256k1.getPublicKey(privateKey, true);\n tx.addInput({\n txid,\n index: 0,\n sequence: 0,\n witnessUtxo: { script: scriptPubKey, amount: 0n },\n bip32Derivation: [[pub, { fingerprint: 0, path: [] }]],\n ...(scriptPubKey[0] === 0x51 ? { tapInternalKey: pub.slice(1) } : {}),\n });\n tx.addOutput({ script: Uint8Array.of(0x6a), amount: 0n });\n const isTaproot = scriptPubKey[0] === 0x51;\n const ok = tx.signIdx(\n privateKey,\n 0,\n isTaproot ? [SigHash.DEFAULT, SigHash.ALL] : [SigHash.ALL],\n auxRand(0),\n );\n if (!ok) {\n throw new ChainError(\"invalid-request\", \"key cannot sign this BIP-322 input\");\n }\n tx.finalizeIdx(0);\n const witness = tx.getInput(0).finalScriptWitness;\n if (witness === undefined) {\n throw new ChainError(\"invalid-request\", \"BIP-322 input produced no witness\");\n }\n const raw = concat(varint(witness.length), ...witness.map(pushData));\n return `smp${base64(raw)}`;\n};\n\n/**\n * Legacy \"Bitcoin Signed Message\" compact signature for P2PKH addresses: base64(1-byte header +\n * 64-byte compact ECDSA sig), header = 27 + recovery + 4 (compressed pubkey).\n */\nexport const signLegacyMessage = (message: string, privateKey: Uint8Array): string => {\n const data = concat(pushData(LEGACY_MAGIC), pushData(utf8(message)));\n const hash = sha256(sha256(data));\n const recovered = secp256k1.sign(hash, privateKey, { lowS: true, format: \"recovered\" });\n const header = 27 + (recovered[0] ?? 0) + 4;\n return base64(concat(Uint8Array.of(header), recovered.slice(1)));\n};\n"],"mappings":";;;;;;;;;;;AAkBA,MAAM,gBAAgB;CAAE,QAAQ;CAAY,SAAS;AAAW;AAChE,MAAM,gBAAgB;CAAE,QAAQ;CAAY,SAAS;AAAW;AAIhE,MAAM,kBAAkC;CAAE,GAAG;CAAc,QAAQ;AAAO;AAE1E,MAAM,WAA0C,OAAO,OAAO;CAC5D;EACE,OAAO;EACP,SAAS;EACT,QAAQ;EACR,UAAU;EACV,OAAO;CACT;CACA;EACE,OAAO;EACP,SAAS;EACT,QAAQ;EACR,UAAU;EACV,OAAO;CACT;CACA;EACE,OAAO;EACP,SAAS;EACT,QAAQ;EACR,UAAU;EACV,OAAO;CACT;CACA;EACE,OAAO;EACP,SAAS;EACT,QAAQ;EACR,UAAU;EACV,OAAO;CACT;AACF,CAAU;AAEV,MAAa,mBAA6D,OAAO,OAC/E,OAAO,YAAY,SAAS,KAAK,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CACtD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