@qntx/wallet-chains 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account-ref-C2qrDbVT.mjs +22 -0
- package/dist/account-ref-C2qrDbVT.mjs.map +1 -0
- package/dist/bitcoin-sign.d.mts +0 -2
- package/dist/bitcoin-sign.mjs +2 -3
- package/dist/bitcoin.d.mts +0 -10
- package/dist/bitcoin.mjs +33 -51
- package/dist/bitcoin.mjs.map +1 -1
- package/dist/evm-sign.d.mts +0 -2
- package/dist/evm-sign.mjs +2 -3
- package/dist/evm.d.mts +4 -14
- package/dist/evm.mjs +7 -19
- package/dist/evm.mjs.map +1 -1
- package/dist/index.d.mts +0 -2
- package/dist/index.mjs +1 -2
- package/dist/{message-DtIS0ZWB.mjs → message-DuJ5KSRT.mjs} +3 -5
- package/dist/{message-DtIS0ZWB.mjs.map → message-DuJ5KSRT.mjs.map} +1 -1
- package/dist/solana-sign.d.mts +0 -2
- package/dist/solana-sign.mjs +1 -2
- package/dist/solana.d.mts +0 -14
- package/dist/solana.mjs +15 -29
- package/dist/solana.mjs.map +1 -1
- package/dist/{typed-data-C6XANSQF.mjs → typed-data-Cf1g7JVv.mjs} +4 -7
- package/dist/{typed-data-C6XANSQF.mjs.map → typed-data-Cf1g7JVv.mjs.map} +1 -1
- package/package.json +7 -8
package/dist/evm.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ChainError } from "./index.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { n as requestBase } from "./account-ref-C2qrDbVT.mjs";
|
|
3
|
+
import { a as isCanonicalHex, c as normalizeEvmTransaction, d as isEvmAddress, i as canonicalHex, l as checksumEvmAddress, n as typedDataWarnings, o as isRecord, r as assertHex, s as networkChainId, t as parseTypedData, u as evmAddressFromPublicKey } from "./typed-data-Cf1g7JVv.mjs";
|
|
3
4
|
import * as TypedData from "ox/TypedData";
|
|
4
5
|
import * as AbiFunction from "ox/AbiFunction";
|
|
5
6
|
import * as Hex from "ox/Hex";
|
|
@@ -9,7 +10,7 @@ import * as Signature from "ox/Signature";
|
|
|
9
10
|
import * as TxEnvelopeEip1559 from "ox/TxEnvelopeEip1559";
|
|
10
11
|
import * as TxEnvelopeEip2930 from "ox/TxEnvelopeEip2930";
|
|
11
12
|
import * as TxEnvelopeLegacy from "ox/TxEnvelopeLegacy";
|
|
12
|
-
|
|
13
|
+
// src/evm/tokens.ts
|
|
13
14
|
const USDC = Object.freeze({
|
|
14
15
|
symbol: "USDC",
|
|
15
16
|
decimals: 6,
|
|
@@ -37,8 +38,7 @@ const evmTokenTable = Object.freeze({
|
|
|
37
38
|
})
|
|
38
39
|
});
|
|
39
40
|
const lookupEvmToken = (table, chainId, address) => table[String(chainId)]?.[address];
|
|
40
|
-
|
|
41
|
-
//#region src/evm/decode.ts
|
|
41
|
+
// src/evm/decode.ts
|
|
42
42
|
const ERC20_TRANSFER = AbiFunction.from("function transfer(address to, uint256 amount)");
|
|
43
43
|
const ERC20_APPROVE = AbiFunction.from("function approve(address spender, uint256 amount)");
|
|
44
44
|
const ERC20_INCREASE = AbiFunction.from("function increaseAllowance(address spender, uint256 amount)");
|
|
@@ -232,8 +232,7 @@ const decodeEvm = (request, table = evmTokenTable) => {
|
|
|
232
232
|
verifiability: "opaque"
|
|
233
233
|
};
|
|
234
234
|
};
|
|
235
|
-
|
|
236
|
-
//#region src/evm/recover.ts
|
|
235
|
+
// src/evm/recover.ts
|
|
237
236
|
/**
|
|
238
237
|
* Signer recovery for `chain.sign` results: the host re-derives the signer address from a signed
|
|
239
238
|
* envelope or a 65-byte signature and compares it with the account's `wallet.accounts` address — a
|
|
@@ -315,24 +314,14 @@ const recoverEvmSigner = (request, result) => {
|
|
|
315
314
|
}
|
|
316
315
|
throw new ChainError("unsupported", `cannot recover a signer for ${request.kind}`);
|
|
317
316
|
};
|
|
318
|
-
|
|
319
|
-
//#region src/evm/index.ts
|
|
317
|
+
// src/evm/index.ts
|
|
320
318
|
/**
|
|
321
319
|
* Normalizes a SignRequest for the EVM family: exact key sets, chainId vs the CAIP-2 `network`,
|
|
322
320
|
* canonical quantities and EIP-55 addresses. Idempotent.
|
|
323
321
|
*/
|
|
324
|
-
const isAccountRef = (value) => {
|
|
325
|
-
if (!isRecord(value) || typeof value["kind"] !== "string") return false;
|
|
326
|
-
if (value["kind"] === "hd") return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
|
|
327
|
-
if (value["kind"] === "imported") return typeof value["keyId"] === "string" && typeof value["family"] === "string";
|
|
328
|
-
return false;
|
|
329
|
-
};
|
|
330
322
|
const normalizeEvm = (request) => {
|
|
331
323
|
if (!isRecord(request) || typeof request["kind"] !== "string") throw new ChainError("invalid-request", "request must be an object with a kind");
|
|
332
|
-
const { network } = request;
|
|
333
|
-
const { account } = request;
|
|
334
|
-
if (typeof network !== "string") throw new ChainError("invalid-request", "request.network must be a string");
|
|
335
|
-
if (!isAccountRef(account)) throw new ChainError("invalid-request", "request.account must be an AccountRef");
|
|
324
|
+
const { network, account } = requestBase(request);
|
|
336
325
|
const chainId = networkChainId(network);
|
|
337
326
|
if (request["kind"] === "evm.transaction") {
|
|
338
327
|
const tx = normalizeEvmTransaction(request["tx"]);
|
|
@@ -367,7 +356,6 @@ const normalizeEvm = (request) => {
|
|
|
367
356
|
}
|
|
368
357
|
throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
|
|
369
358
|
};
|
|
370
|
-
//#endregion
|
|
371
359
|
export { canonicalHex, checksumEvmAddress, decodeEvm, evmAddressFromPublicKey, evmTokenTable, isCanonicalHex, isEvmAddress, lookupEvmToken, networkChainId, normalizeEvm, normalizeEvmTransaction, parseTypedData, recoverEvmSigner, verifiabilityEvm };
|
|
372
360
|
|
|
373
361
|
//# 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 { ChainError } from \"../index.ts\";\nimport type { AccountRef, 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 */\nconst isAccountRef = (value: unknown): value is AccountRef => {\n if (!isRecord(value) || typeof value[\"kind\"] !== \"string\") {\n return false;\n }\n if (value[\"kind\"] === \"hd\") {\n return (\n typeof value[\"walletId\"] === \"string\" &&\n typeof value[\"groupIndex\"] === \"number\" &&\n typeof value[\"template\"] === \"string\"\n );\n }\n if (value[\"kind\"] === \"imported\") {\n return typeof value[\"keyId\"] === \"string\" && typeof value[\"family\"] === \"string\";\n }\n return false;\n};\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 } = request;\n const { account } = request;\n if (typeof network !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request.network must be a string\");\n }\n if (!isAccountRef(account)) {\n throw new ChainError(\"invalid-request\", \"request.account must be an AccountRef\");\n }\n 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;A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GACvB,MAAM,IAAI,WAAW,mBAAmB,uCAAuC;CAEjF,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/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,MAAM,OAAO;AAEjC,MAAM,cAAc,MAA8B,UAA0B;CAC1E,MAAM,QAAQ,KAAK;CACnB,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AI,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"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/index.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* @qntx/wallet-chains — shared chain semantics for the wallet.
|
|
4
3
|
* Types here are wire-safe: values crossing the main↔kernel protocol are
|
|
@@ -137,6 +136,5 @@ export declare class ChainError extends Error {
|
|
|
137
136
|
readonly code: ChainErrorCode;
|
|
138
137
|
constructor(code: ChainErrorCode, message: string);
|
|
139
138
|
}
|
|
140
|
-
//#endregion
|
|
141
139
|
export {};
|
|
142
140
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/index.ts
|
|
2
2
|
var ChainError = class extends Error {
|
|
3
3
|
code;
|
|
4
4
|
constructor(code, message) {
|
|
@@ -7,7 +7,6 @@ var ChainError = class extends Error {
|
|
|
7
7
|
this.code = code;
|
|
8
8
|
}
|
|
9
9
|
};
|
|
10
|
-
//#endregion
|
|
11
10
|
export { ChainError };
|
|
12
11
|
|
|
13
12
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -3,7 +3,7 @@ import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
|
3
3
|
import { NETWORK, TEST_NETWORK } from "@scure/btc-signer/utils.js";
|
|
4
4
|
import { SigHash, Transaction } from "@scure/btc-signer/transaction.js";
|
|
5
5
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
6
|
-
|
|
6
|
+
// src/bitcoin/networks.ts
|
|
7
7
|
/**
|
|
8
8
|
* Bip122 CAIP-2 networks = `bip122:` + the first 32 hex chars of the genesis hash, verified against
|
|
9
9
|
* Bitcoin Core `src/kernel/chainparams.cpp` (assert(consensus.hashGenesisBlock == ...) per network
|
|
@@ -57,8 +57,7 @@ const bitcoinNetwork = (caip2) => {
|
|
|
57
57
|
if (net === void 0) throw new ChainError("unsupported", `unknown bitcoin network: ${caip2}`);
|
|
58
58
|
return net;
|
|
59
59
|
};
|
|
60
|
-
|
|
61
|
-
//#region src/bitcoin/message.ts
|
|
60
|
+
// src/bitcoin/message.ts
|
|
62
61
|
/**
|
|
63
62
|
* BIP-322 message signing ("simple" + legacy) built on btc-signer primitives.
|
|
64
63
|
* https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki
|
|
@@ -179,7 +178,6 @@ const signLegacyMessage = (message, privateKey) => {
|
|
|
179
178
|
const header = 27 + (recovered[0] ?? 0) + 4;
|
|
180
179
|
return base64(concat(Uint8Array.of(header), recovered.slice(1)));
|
|
181
180
|
};
|
|
182
|
-
//#endregion
|
|
183
181
|
export { bitcoinNetwork as a, BITCOIN_NETWORKS as i, signBip322Simple as n, signLegacyMessage as r, bip322ToSpendTxid as t };
|
|
184
182
|
|
|
185
|
-
//# sourceMappingURL=message-
|
|
183
|
+
//# sourceMappingURL=message-DuJ5KSRT.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message-DtIS0ZWB.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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CAAC;CACnE,OAAO,MAAM,OAAO,GAAG;AACzB;;;;;AAMA,MAAa,qBAAqB,SAAiB,eAAmC;CACpF,MAAM,OAAO,OAAO,SAAS,YAAY,GAAG,SAAS,KAAK,OAAO,CAAC,CAAC;CACnE,MAAM,OAAO,OAAO,OAAO,IAAI,CAAC;CAChC,MAAM,YAAY,UAAU,KAAK,MAAM,YAAY;EAAE,MAAM;EAAM,QAAQ;CAAY,CAAC;CACtF,MAAM,SAAS,MAAM,UAAU,MAAM,KAAK;CAC1C,OAAO,OAAO,OAAO,WAAW,GAAG,MAAM,GAAG,UAAU,MAAM,CAAC,CAAC,CAAC;AACjE"}
|
|
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;AAEA,MAAa,kBAAkB,UAAkC;CAC/D,MAAM,MAAM,iBAAiB;CAC7B,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,WAAW,eAAe,4BAA4B,OAAO;CAEzE,OAAO;AACT;;;;;;ACxDA,MAAM,QAAQ,MAA0B,IAAI,YAAY,CAAC,CAAC,OAAO,CAAC;AAElE,MAAM,aAAa;AACnB,MAAM,eAAe,KAAK,2BAA2B;AAErD,MAAM,UAAU,GAAG,UAAiD;CACl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MAAM,YAAY,aAAa,OAAO;CAOtC,IAAI,CANO,GAAG,QACZ,YACA,GACA,YAAY,CAAC,QAAQ,SAAS,QAAQ,GAAG,IAAI,CAAC,QAAQ,GAAG,GACzD,QAAQ,CAAC,CAEL,GACJ,MAAM,IAAI,WAAW,mBAAmB,oCAAoC;CAE9E,GAAG,YAAY,CAAC;CAChB,MAAM,UAAU,GAAG,SAAS,CAAC,CAAC,CAAC;CAC/B,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,WAAW,mBAAmB,mCAAmC;CAE7E,MAAM,MAAM,OAAO,OAAO,QAAQ,MAAM,GAAG,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACnE,OAAO,MAAM,OAAO,GAAG;AACzB;;;;;AAMA,MAAa,qBAAqB,SAAiB,eAAmC;CACpF,MAAM,OAAO,OAAO,SAAS,YAAY,GAAG,SAAS,KAAK,OAAO,CAAC,CAAC;CACnE,MAAM,OAAO,OAAO,OAAO,IAAI,CAAC;CAChC,MAAM,YAAY,UAAU,KAAK,MAAM,YAAY;EAAE,MAAM;EAAM,QAAQ;CAAY,CAAC;CACtF,MAAM,SAAS,MAAM,UAAU,MAAM,KAAK;CAC1C,OAAO,OAAO,OAAO,WAAW,GAAG,MAAM,GAAG,UAAU,MAAM,CAAC,CAAC,CAAC;AACjE"}
|
package/dist/solana-sign.d.mts
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
//#region src/solana/sign.d.ts
|
|
2
1
|
/** Signs `message` with a 32-byte Ed25519 seed; returns the 64-byte signature. */
|
|
3
2
|
export declare const signSolanaMessage: (message: Uint8Array, privateKey: Uint8Array) => Uint8Array;
|
|
4
|
-
//#endregion
|
|
5
3
|
//# sourceMappingURL=solana-sign.d.mts.map
|
package/dist/solana-sign.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ChainError } from "./index.mjs";
|
|
2
2
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
3
|
-
|
|
3
|
+
// src/solana/sign.ts
|
|
4
4
|
/**
|
|
5
5
|
* /solana/sign — deterministic Ed25519 signing over the compiled message or raw offchain bytes.
|
|
6
6
|
* Inputs must already be normalized: the kernel calls `normalizeSolana` first. No key caching; the
|
|
@@ -14,7 +14,6 @@ const signSolanaMessage = (message, privateKey) => {
|
|
|
14
14
|
if (signature.length !== 64) throw new ChainError("invalid-request", "ed25519 produced a malformed signature");
|
|
15
15
|
return signature;
|
|
16
16
|
};
|
|
17
|
-
//#endregion
|
|
18
17
|
export { signSolanaMessage };
|
|
19
18
|
|
|
20
19
|
//# sourceMappingURL=solana-sign.mjs.map
|
package/dist/solana.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { DisplayIntent, SignRequest, Verifiability } from "./index.mjs";
|
|
2
|
-
//#region src/solana/ids.d.ts
|
|
3
2
|
/** Well-known Solana program ids (base58, 32 bytes) — frozen constants. */
|
|
4
3
|
export declare const PROGRAM_IDS: Readonly<{
|
|
5
4
|
system: string;
|
|
@@ -17,8 +16,6 @@ export declare const SOLANA_NETWORKS: ReadonlyArray<string>;
|
|
|
17
16
|
export declare const isSolanaAddress: (value: string) => boolean;
|
|
18
17
|
/** Base58-encoded address for a 32-byte ed25519 public key. */
|
|
19
18
|
export declare function solanaAddressFromPublicKey(pubkey: Uint8Array): string;
|
|
20
|
-
//#endregion
|
|
21
|
-
//#region src/solana/tokens.d.ts
|
|
22
19
|
/**
|
|
23
20
|
* Built-in SPL token table, keyed by `network` then mint address. An entry makes a
|
|
24
21
|
* `transferChecked` `full`-verifiable (WD-065), so every entry must come from the issuer's own
|
|
@@ -31,8 +28,6 @@ type SolanaToken = {
|
|
|
31
28
|
};
|
|
32
29
|
type SolanaTokenTable = Readonly<Record<string, Readonly<Record<string, SolanaToken>>>>;
|
|
33
30
|
export declare const solanaTokenTable: SolanaTokenTable;
|
|
34
|
-
//#endregion
|
|
35
|
-
//#region src/solana/decode.d.ts
|
|
36
31
|
/** What the signer can guarantee about this request (WD-065). */
|
|
37
32
|
export declare const verifiabilitySolana: (request: Extract<SignRequest, {
|
|
38
33
|
kind: "solana.transaction";
|
|
@@ -40,8 +35,6 @@ export declare const verifiabilitySolana: (request: Extract<SignRequest, {
|
|
|
40
35
|
export declare const decodeSolana: (request: Extract<SignRequest, {
|
|
41
36
|
kind: "solana.transaction";
|
|
42
37
|
}>, signer: string, table?: SolanaTokenTable) => DisplayIntent;
|
|
43
|
-
//#endregion
|
|
44
|
-
//#region src/solana/token2022.d.ts
|
|
45
38
|
/** SPL Token-2022 mint-account TLV extension type numbers (spl-token-2022 `ExtensionType`). */
|
|
46
39
|
export declare const EXT: {
|
|
47
40
|
readonly transferFeeConfig: 1;
|
|
@@ -84,8 +77,6 @@ export declare const parseMintExtensions: (data: Uint8Array, epoch: bigint) => M
|
|
|
84
77
|
* max)`.
|
|
85
78
|
*/
|
|
86
79
|
export declare const netAfterTransferFee: (amount: bigint, bps: number, max: bigint) => bigint;
|
|
87
|
-
//#endregion
|
|
88
|
-
//#region src/solana/message.d.ts
|
|
89
80
|
type CompiledIx = {
|
|
90
81
|
readonly programAddressIndex: number;
|
|
91
82
|
readonly accountIndices: ReadonlyArray<number>;
|
|
@@ -104,12 +95,8 @@ type ParsedSolanaMessage = {
|
|
|
104
95
|
* fee payer is `staticAccounts[0]` — every valid transaction signs it.
|
|
105
96
|
*/
|
|
106
97
|
export declare const parseCompiledMessage: (bytes: Uint8Array) => ParsedSolanaMessage;
|
|
107
|
-
//#endregion
|
|
108
|
-
//#region src/solana/verify.d.ts
|
|
109
98
|
/** Whether `signature` is a valid ed25519 signature of `message` by the key behind `address`. */
|
|
110
99
|
export declare const verifySolanaSignature: (message: Uint8Array, signature: Uint8Array, accountAddress: string) => boolean;
|
|
111
|
-
//#endregion
|
|
112
|
-
//#region src/solana/index.d.ts
|
|
113
100
|
/**
|
|
114
101
|
* Normalizes a Solana sign request. `signer` is the fee payer the wallet is about to sign for — the
|
|
115
102
|
* message must declare it as the first static account. A raw `solana.message` must not decode as a
|
|
@@ -117,6 +104,5 @@ export declare const verifySolanaSignature: (message: Uint8Array, signature: Uin
|
|
|
117
104
|
* is a wallet-drainer). Idempotent.
|
|
118
105
|
*/
|
|
119
106
|
export declare const normalizeSolana: (request: unknown, signer: string) => SignRequest;
|
|
120
|
-
//#endregion
|
|
121
107
|
export type { MintExtensionSummary, SolanaTokenTable };
|
|
122
108
|
//# sourceMappingURL=solana.d.mts.map
|
package/dist/solana.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { ChainError } from "./index.mjs";
|
|
2
|
+
import { n as requestBase, t as isRecord$1 } from "./account-ref-C2qrDbVT.mjs";
|
|
2
3
|
import { address, getAddressDecoder, getAddressEncoder } from "@solana/addresses";
|
|
3
4
|
import { getCompiledTransactionMessageDecoder } from "@solana/transaction-messages";
|
|
4
5
|
import { getU32Decoder, getU64Decoder } from "@solana/codecs";
|
|
5
6
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
6
|
-
|
|
7
|
+
// src/solana/ids.ts
|
|
7
8
|
/** Well-known Solana program ids (base58, 32 bytes) — frozen constants. */
|
|
8
9
|
const PROGRAM_IDS = Object.freeze({
|
|
9
10
|
system: "11111111111111111111111111111111",
|
|
@@ -52,14 +53,14 @@ const parseCompiledMessage = (bytes) => {
|
|
|
52
53
|
lookupAddresses: lookups.map((l) => l.lookupTableAddress)
|
|
53
54
|
};
|
|
54
55
|
};
|
|
55
|
-
const isRecord
|
|
56
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
56
57
|
const isStringArray = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
|
|
57
58
|
const isNumberArray = (value) => Array.isArray(value) && value.every((v) => typeof v === "number");
|
|
58
|
-
const isArrayLike = (value) => isRecord
|
|
59
|
-
const isIx = (value) => isRecord
|
|
60
|
-
const isLookup = (value) => isRecord
|
|
59
|
+
const isArrayLike = (value) => isRecord(value) && typeof value["length"] === "number";
|
|
60
|
+
const isIx = (value) => isRecord(value) && typeof value["programAddressIndex"] === "number" && (value["accountIndices"] === void 0 || isNumberArray(value["accountIndices"]) || isArrayLike(value["accountIndices"])) && value["data"] instanceof Uint8Array;
|
|
61
|
+
const isLookup = (value) => isRecord(value) && typeof value["lookupTableAddress"] === "string" && (isNumberArray(value["readonlyIndexes"]) || value["readonlyIndexes"] instanceof Uint8Array) && (isNumberArray(value["writableIndexes"]) || value["writableIndexes"] instanceof Uint8Array);
|
|
61
62
|
const asCompiledMessage = (value) => {
|
|
62
|
-
if (!isRecord
|
|
63
|
+
if (!isRecord(value) || !isRecord(value["header"])) throw new ChainError("invalid-request", "compiled message failed to decode");
|
|
63
64
|
const { header } = value;
|
|
64
65
|
const { staticAccounts } = value;
|
|
65
66
|
const { instructions } = value;
|
|
@@ -109,8 +110,7 @@ const validateLookupTables = (tables) => {
|
|
|
109
110
|
if (tables === void 0) return;
|
|
110
111
|
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");
|
|
111
112
|
};
|
|
112
|
-
|
|
113
|
-
//#region src/solana/tokens.ts
|
|
113
|
+
// src/solana/tokens.ts
|
|
114
114
|
const USDC = Object.freeze({
|
|
115
115
|
symbol: "USDC",
|
|
116
116
|
decimals: 6,
|
|
@@ -126,8 +126,7 @@ const solanaTokenTable = Object.freeze({ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvd
|
|
|
126
126
|
Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: USDT
|
|
127
127
|
}) });
|
|
128
128
|
const lookupSolanaToken = (table, network, mint) => table[network]?.[mint];
|
|
129
|
-
|
|
130
|
-
//#region src/solana/decode.ts
|
|
129
|
+
// src/solana/decode.ts
|
|
131
130
|
const LAMPORTS_ASSET = "lamports";
|
|
132
131
|
const u32 = getU32Decoder();
|
|
133
132
|
const u64$1 = getU64Decoder();
|
|
@@ -269,8 +268,7 @@ const decodeTransaction = (request, signer, table) => {
|
|
|
269
268
|
/** What the signer can guarantee about this request (WD-065). */
|
|
270
269
|
const verifiabilitySolana = (request, signer, table = solanaTokenTable) => decodeSolana(request, signer, table).verifiability;
|
|
271
270
|
const decodeSolana = (request, signer, table = solanaTokenTable) => decodeTransaction(request, signer, table);
|
|
272
|
-
|
|
273
|
-
//#region src/solana/token2022.ts
|
|
271
|
+
// src/solana/token2022.ts
|
|
274
272
|
/** SPL Token-2022 mint-account TLV extension type numbers (spl-token-2022 `ExtensionType`). */
|
|
275
273
|
const EXT = {
|
|
276
274
|
transferFeeConfig: 1,
|
|
@@ -345,8 +343,7 @@ const netAfterTransferFee = (amount, bps, max) => {
|
|
|
345
343
|
const fee = amount * BigInt(bps) / 10000n;
|
|
346
344
|
return amount - (fee > max ? max : fee);
|
|
347
345
|
};
|
|
348
|
-
|
|
349
|
-
//#region src/solana/verify.ts
|
|
346
|
+
// src/solana/verify.ts
|
|
350
347
|
/**
|
|
351
348
|
* Ed25519 signature verification for `chain.sign` results: the host checks the kernel's 64-byte
|
|
352
349
|
* signature against the message and the account address returned by `wallet.accounts` — a wrong
|
|
@@ -361,14 +358,7 @@ const verifySolanaSignature = (message, signature, accountAddress) => {
|
|
|
361
358
|
return false;
|
|
362
359
|
}
|
|
363
360
|
};
|
|
364
|
-
|
|
365
|
-
//#region src/solana/index.ts
|
|
366
|
-
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
367
|
-
const isAccountRef = (value) => {
|
|
368
|
-
if (!isRecord(value) || typeof value["kind"] !== "string") return false;
|
|
369
|
-
if (value["kind"] === "hd") return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
|
|
370
|
-
return value["kind"] === "imported" && typeof value["keyId"] === "string" && typeof value["family"] === "string";
|
|
371
|
-
};
|
|
361
|
+
// src/solana/index.ts
|
|
372
362
|
const solanaNetwork = (network) => {
|
|
373
363
|
if (!SOLANA_NETWORKS.includes(network)) throw new ChainError("unsupported", `unknown Solana network: ${network}`);
|
|
374
364
|
};
|
|
@@ -376,7 +366,7 @@ const validateLookupTablesRaw = (tables) => {
|
|
|
376
366
|
if (tables === void 0) return;
|
|
377
367
|
if (!Array.isArray(tables)) throw new ChainError("unknown-field", "lookupTables must be an array");
|
|
378
368
|
const parsed = tables.map((t) => {
|
|
379
|
-
if (!isRecord(t) || typeof t["address"] !== "string" || !Array.isArray(t["addresses"])) throw new ChainError("unknown-field", "lookupTables entries must be { address, addresses }");
|
|
369
|
+
if (!isRecord$1(t) || typeof t["address"] !== "string" || !Array.isArray(t["addresses"])) throw new ChainError("unknown-field", "lookupTables entries must be { address, addresses }");
|
|
380
370
|
const addresses = t["addresses"].map((a) => {
|
|
381
371
|
if (typeof a !== "string") throw new ChainError("invalid-address", "lookup table addresses must be strings");
|
|
382
372
|
return a;
|
|
@@ -396,11 +386,8 @@ const validateLookupTablesRaw = (tables) => {
|
|
|
396
386
|
* is a wallet-drainer). Idempotent.
|
|
397
387
|
*/
|
|
398
388
|
const normalizeSolana = (request, signer) => {
|
|
399
|
-
if (!isRecord(request) || typeof request["kind"] !== "string") throw new ChainError("invalid-request", "request must be an object with a kind");
|
|
400
|
-
const { network } = request;
|
|
401
|
-
const { account } = request;
|
|
402
|
-
if (typeof network !== "string") throw new ChainError("invalid-request", "request.network must be a string");
|
|
403
|
-
if (!isAccountRef(account)) throw new ChainError("invalid-request", "request.account must be an AccountRef");
|
|
389
|
+
if (!isRecord$1(request) || typeof request["kind"] !== "string") throw new ChainError("invalid-request", "request must be an object with a kind");
|
|
390
|
+
const { network, account } = requestBase(request);
|
|
404
391
|
solanaNetwork(network);
|
|
405
392
|
if (!isSolanaAddress(signer)) throw new ChainError("invalid-address", "signer is not a base58 address");
|
|
406
393
|
const { message } = request;
|
|
@@ -440,7 +427,6 @@ const normalizeSolana = (request, signer) => {
|
|
|
440
427
|
}
|
|
441
428
|
throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
|
|
442
429
|
};
|
|
443
|
-
//#endregion
|
|
444
430
|
export { EXT, PROGRAM_IDS, SOLANA_NETWORKS, decodeSolana, isSolanaAddress, netAfterTransferFee, normalizeSolana, parseCompiledMessage, parseMintExtensions, solanaAddressFromPublicKey, solanaTokenTable, verifiabilitySolana, verifySolanaSignature };
|
|
445
431
|
|
|
446
432
|
//# sourceMappingURL=solana.mjs.map
|