@qntx/wallet-chains 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bitcoin-sign.mjs +1 -1
- package/dist/bitcoin.d.mts +2 -2
- package/dist/bitcoin.mjs +31 -14
- package/dist/bitcoin.mjs.map +1 -1
- package/dist/evm-sign.d.mts +1 -1
- package/dist/evm-sign.mjs +28 -2
- package/dist/evm-sign.mjs.map +1 -1
- package/dist/evm.d.mts +111 -5
- package/dist/evm.mjs +570 -21
- package/dist/evm.mjs.map +1 -1
- package/dist/{index-QxoxkD5m.d.mts → index-DpL5hvPl.d.mts} +115 -7
- package/dist/index.d.mts +2 -2
- package/dist/{message-ChhEZ0lx.mjs → message-zf3XHwwc.mjs} +2 -2
- package/dist/{message-ChhEZ0lx.mjs.map → message-zf3XHwwc.mjs.map} +1 -1
- package/dist/solana.d.mts +30 -1
- package/dist/solana.mjs +507 -23
- package/dist/solana.mjs.map +1 -1
- package/dist/src-8NZeEnrW.mjs.map +1 -1
- package/dist/{typed-data-J5g2WemC.mjs → typed-data-B4PJ1v8F.mjs} +97 -6
- package/dist/typed-data-B4PJ1v8F.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/typed-data-J5g2WemC.mjs.map +0 -1
package/dist/bitcoin-sign.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as ChainError } from "./src-8NZeEnrW.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-zf3XHwwc.mjs";
|
|
3
3
|
import { Address, OutScript } from "@scure/btc-signer/payment.js";
|
|
4
4
|
import { SigHash, Transaction } from "@scure/btc-signer/transaction.js";
|
|
5
5
|
// src/bitcoin/sign.ts
|
package/dist/bitcoin.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as BitcoinTemplate, l as DisplayIntent, v as SignRequest, x as Verifiability } from "./index-DpL5hvPl.mjs";
|
|
2
2
|
import { NETWORK } from "@scure/btc-signer/utils.js";
|
|
3
3
|
type BitcoinNetwork = {
|
|
4
4
|
readonly caip2: string;
|
|
@@ -13,7 +13,7 @@ type BitcoinNetwork = {
|
|
|
13
13
|
};
|
|
14
14
|
export declare const BITCOIN_NETWORKS: Readonly<Record<string, BitcoinNetwork>>;
|
|
15
15
|
export declare const bitcoinNetwork: (caip2: string) => BitcoinNetwork;
|
|
16
|
-
type BitcoinAccountTemplate =
|
|
16
|
+
type BitcoinAccountTemplate = BitcoinTemplate;
|
|
17
17
|
/**
|
|
18
18
|
* Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or
|
|
19
19
|
* `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.
|
package/dist/bitcoin.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as ChainError } from "./src-8NZeEnrW.mjs";
|
|
2
2
|
import { n as requestBase, t as isRecord$2 } from "./account-ref-D2rW_qlI.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-zf3XHwwc.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";
|
|
@@ -46,11 +46,18 @@ const checkDerivations = (tx, coinType) => {
|
|
|
46
46
|
};
|
|
47
47
|
const DEFAULT_SIGHASH = 0;
|
|
48
48
|
const SIGHASH_ALL = 1;
|
|
49
|
+
const TEMPLATES = /* @__PURE__ */ new Set([
|
|
50
|
+
"btc.bip44",
|
|
51
|
+
"btc.bip49",
|
|
52
|
+
"btc.bip84",
|
|
53
|
+
"btc.bip86"
|
|
54
|
+
]);
|
|
55
|
+
const isSignEntry = (value) => isRecord$1(value) && typeof value["index"] === "number" && Number.isSafeInteger(value["index"]) && value["index"] >= 0 && typeof value["template"] === "string" && TEMPLATES.has(value["template"]);
|
|
49
56
|
const isTaprootInput = (input) => input.tapInternalKey !== void 0 || getInputType(input).type === "taproot";
|
|
50
57
|
/**
|
|
51
58
|
* Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).
|
|
52
59
|
* `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its
|
|
53
|
-
* outpoint.
|
|
60
|
+
* outpoint. The returned `sign` is sorted ascending by index — a normalized request is canonical.
|
|
54
61
|
*/
|
|
55
62
|
const normalizeBitcoinPsbt = (psbt, sign, network) => {
|
|
56
63
|
const net = bitcoinNetwork(network);
|
|
@@ -60,15 +67,16 @@ const normalizeBitcoinPsbt = (psbt, sign, network) => {
|
|
|
60
67
|
} catch {
|
|
61
68
|
throw new ChainError("invalid-request", "PSBT failed to decode");
|
|
62
69
|
}
|
|
63
|
-
if (!Array.isArray(sign) || sign.length === 0 || !sign.every(
|
|
64
|
-
const
|
|
65
|
-
const
|
|
66
|
-
|
|
70
|
+
if (!Array.isArray(sign) || sign.length === 0 || !sign.every(isSignEntry)) throw new ChainError("invalid-request", "sign must be a non-empty array of {index, template} entries");
|
|
71
|
+
const sorted = [...sign].sort((a, b) => a.index - b.index);
|
|
72
|
+
const indices = new Set(sorted.map((s) => s.index));
|
|
73
|
+
const last = sorted.at(-1)?.index;
|
|
74
|
+
if (indices.size !== sorted.length || last === void 0 || last >= tx.inputsLength) throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
|
|
67
75
|
checkDerivations(tx, net.coinType);
|
|
68
|
-
for (const idx of
|
|
76
|
+
for (const { index: idx, template } of sorted) {
|
|
69
77
|
const input = tx.getInput(idx);
|
|
70
78
|
if (input.witnessUtxo === void 0 && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
|
|
71
|
-
if (input.
|
|
79
|
+
if (template === "btc.bip86" ? input.tapBip32Derivation === void 0 : input.bip32Derivation === void 0) throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
|
|
72
80
|
const { type } = getInputType(input);
|
|
73
81
|
if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
|
|
74
82
|
const sighash = input.sighashType;
|
|
@@ -77,7 +85,7 @@ const normalizeBitcoinPsbt = (psbt, sign, network) => {
|
|
|
77
85
|
}
|
|
78
86
|
return {
|
|
79
87
|
psbt: tx.toPSBT(0),
|
|
80
|
-
sign:
|
|
88
|
+
sign: sorted
|
|
81
89
|
};
|
|
82
90
|
};
|
|
83
91
|
// src/bitcoin/account.ts
|
|
@@ -154,7 +162,7 @@ const decodeOutput = (script, amount) => {
|
|
|
154
162
|
const decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
|
|
155
163
|
const tx = parsePsbt(request.psbt);
|
|
156
164
|
const coder = Address(bitcoinNetwork(request.network).params);
|
|
157
|
-
const signed = new Set(request.sign);
|
|
165
|
+
const signed = new Set(request.sign.map((s) => s.index));
|
|
158
166
|
const outflows = [];
|
|
159
167
|
let canFee = true;
|
|
160
168
|
let outSum = 0n;
|
|
@@ -190,7 +198,7 @@ const decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
|
|
|
190
198
|
}
|
|
191
199
|
const external = tx.inputsLength - signed.size > 0;
|
|
192
200
|
const undecodable = outflows.some((o) => !o.verified);
|
|
193
|
-
const listing = request.sign.some((
|
|
201
|
+
const listing = request.sign.some((s) => tx.getInput(s.index).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
|
|
194
202
|
const verifiability = external ? "opaque" : listing || undecodable ? "partial" : "full";
|
|
195
203
|
return {
|
|
196
204
|
family: "bitcoin",
|
|
@@ -421,19 +429,28 @@ const messageTarget = (address, network, format) => {
|
|
|
421
429
|
*/
|
|
422
430
|
const normalizeBitcoin = (request) => {
|
|
423
431
|
if (!isRecord$2(request) || typeof request["kind"] !== "string") throw new ChainError("invalid-request", "request must be an object with a kind");
|
|
424
|
-
const { network, account } = common(request);
|
|
425
432
|
if (request["kind"] === "bitcoin.psbt") {
|
|
426
|
-
const { psbt } = request;
|
|
433
|
+
const { network, account, psbt } = request;
|
|
434
|
+
if (typeof network !== "string") throw new ChainError("invalid-request", "request.network must be a string");
|
|
435
|
+
bitcoinNetwork(network);
|
|
436
|
+
if (!isRecord$2(account) || account["kind"] !== "hd") throw new ChainError("invalid-request", "request.account must be a wallet group");
|
|
437
|
+
const { walletId, groupIndex } = account;
|
|
438
|
+
if (typeof walletId !== "string" || typeof groupIndex !== "number" || !Number.isSafeInteger(groupIndex) || groupIndex < 0) throw new ChainError("invalid-request", "request.account must be a wallet group");
|
|
427
439
|
if (!(psbt instanceof Uint8Array)) throw new ChainError("invalid-request", "psbt must be bytes");
|
|
428
440
|
const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
|
|
429
441
|
return {
|
|
430
442
|
kind: "bitcoin.psbt",
|
|
431
443
|
network,
|
|
432
|
-
account
|
|
444
|
+
account: {
|
|
445
|
+
kind: "hd",
|
|
446
|
+
walletId,
|
|
447
|
+
groupIndex
|
|
448
|
+
},
|
|
433
449
|
psbt: normalized.psbt,
|
|
434
450
|
sign: normalized.sign
|
|
435
451
|
};
|
|
436
452
|
}
|
|
453
|
+
const { network, account } = common(request);
|
|
437
454
|
if (request["kind"] === "bitcoin.message") {
|
|
438
455
|
const { format } = request;
|
|
439
456
|
const target = messageTarget(request["address"], network, format);
|
package/dist/bitcoin.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bitcoin.mjs","names":["isRecord","SIGHASH_SINGLE_ANYONECANPAY","isRecord"],"sources":["../src/bitcoin/psbt.ts","../src/bitcoin/account.ts","../src/bitcoin/decode.ts","../src/bitcoin/verify.ts","../src/bitcoin/index.ts"],"sourcesContent":["import { Transaction, getInputType } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\n/**\n * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what\n * binds PSBT metadata to the requested network — the raw output scripts themselves carry no network\n * marker.\n */\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Bip32Derivation values are [pubkey, { fingerprint, path }] tuples; tapBip32Derivation values are\n * { hashes, der: { fingerprint, path } }.\n */\nconst derivationPaths = (map: unknown): ReadonlyArray<ReadonlyArray<number>> => {\n const entries =\n map instanceof Map\n ? [...map.values()]\n : Array.isArray(map)\n ? map\n : isRecord(map)\n ? Object.values(map)\n : [];\n const paths: number[][] = [];\n for (const entry of entries) {\n const value: unknown = Array.isArray(entry) ? entry[1] : entry;\n if (!isRecord(value)) {\n continue;\n }\n const der = isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = der;\n if (Array.isArray(path) && path.every((p) => typeof p === \"number\")) {\n paths.push(path);\n }\n }\n return paths;\n};\n\nconst checkPaths = (\n paths: ReadonlyArray<ReadonlyArray<number>>,\n where: string,\n coinType: number,\n): void => {\n for (const path of paths) {\n if (path.length >= 2 && (path[1] ?? -1) - 0x80000000 !== coinType) {\n throw new ChainError(\n \"chain-id-mismatch\",\n `${where} derivation coin type is not this network's`,\n );\n }\n }\n};\n\nconst checkDerivations = (tx: Transaction, coinType: number): void => {\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);\n checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);\n }\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);\n checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);\n }\n};\n\nconst DEFAULT_SIGHASH = 0;\nconst SIGHASH_ALL = 1;\n/** SIGHASH_SINGLE | ANYONECANPAY — the marketplace listing sighash, the only other one accepted. */\nexport const SIGHASH_SINGLE_ANYONECANPAY = 0x83;\n\nconst isTaprootInput = (input: ReturnType<Transaction[\"getInput\"]>): boolean =>\n input.tapInternalKey !== undefined || getInputType(input).type === \"taproot\";\n\n/**\n * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).\n * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its\n * outpoint.\n */\nexport const normalizeBitcoinPsbt = (\n psbt: Uint8Array,\n sign: unknown,\n network: string,\n): { psbt: Uint8Array; sign: ReadonlyArray<number> } => {\n const net = bitcoinNetwork(network);\n let tx: Transaction;\n try {\n tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });\n } catch {\n throw new ChainError(\"invalid-request\", \"PSBT failed to decode\");\n }\n if (\n !Array.isArray(sign) ||\n sign.length === 0 ||\n !sign.every((i) => Number.isSafeInteger(i) && i >= 0)\n ) {\n throw new ChainError(\"invalid-request\", \"sign must be a non-empty array of input indices\");\n }\n const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);\n const last = unique.at(-1);\n if (unique.length !== sign.length || last === undefined || last >= tx.inputsLength) {\n throw new ChainError(\"invalid-request\", \"sign must be unique, ascending, and in range\");\n }\n checkDerivations(tx, net.coinType);\n for (const idx of unique) {\n const input = tx.getInput(idx);\n if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\n \"invalid-request\",\n `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`,\n );\n }\n if (input.bip32Derivation === undefined && input.tapBip32Derivation === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing a bip32 derivation`);\n }\n const { type } = getInputType(input);\n if ((type === \"legacy\" || type === \"nonwitness-script\") && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing nonWitnessUtxo`);\n }\n const sighash = input.sighashType;\n const allowed =\n sighash === undefined ||\n sighash === SIGHASH_ALL ||\n (isTaprootInput(input) && sighash === DEFAULT_SIGHASH) ||\n sighash === SIGHASH_SINGLE_ANYONECANPAY;\n if (!allowed) {\n throw new ChainError(\"unsupported\", `input ${idx} uses a non-default sighash`);\n }\n // SIGHASH_SINGLE signs a constant when the same-index output is missing (the legacy bug).\n if (sighash === SIGHASH_SINGLE_ANYONECANPAY && idx >= tx.outputsLength) {\n throw new ChainError(\n \"unsupported\",\n `input ${idx} uses SIGHASH_SINGLE without a same-index output`,\n );\n }\n }\n return { psbt: tx.toPSBT(0), sign: unique };\n};\n","/** Public-derivation helpers for account-level extended keys — no secrets involved. */\nimport { HDKey } from \"@scure/bip32\";\nimport { p2pkh, p2sh, p2tr, p2wpkh } from \"@scure/btc-signer/payment.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst xpubChild = (xpub: string, network: string, change: 0 | 1, index: number): Uint8Array => {\n if (!Number.isInteger(index) || index < 0) {\n throw new ChainError(\"invalid-request\", \"index must be a non-negative integer\");\n }\n const net = bitcoinNetwork(network);\n let node: HDKey;\n try {\n node = HDKey.fromExtendedKey(xpub, net.bip32);\n } catch (error) {\n throw new ChainError(\n \"invalid-request\",\n `xpub: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const child = node.derive(`m/${change}/${index}`);\n const pub = child.publicKey;\n if (pub === null) {\n throw new ChainError(\"invalid-request\", \"xpub carries no public key\");\n }\n return pub;\n};\n\nexport type BitcoinAccountTemplate = \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n\n/**\n * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or\n * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.\n */\nexport function bitcoinAddressFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): string {\n const net = bitcoinNetwork(network);\n const pub = xpubChild(xpub, network, change, index);\n const address =\n template === \"btc.bip84\"\n ? p2wpkh(pub, net.params).address\n : template === \"btc.bip49\"\n ? p2sh(p2wpkh(pub, net.params), net.params).address\n : template === \"btc.bip44\"\n ? p2pkh(pub, net.params).address\n : p2tr(pub.subarray(1), undefined, net.params).address;\n if (address === undefined) {\n throw new ChainError(\"invalid-request\", \"could not encode the derived address\");\n }\n return address;\n}\n\n/**\n * The compressed (P2WPKH) or x-only (P2TR) public key at `change`/`index` under an account-level\n * xpub — the key placed in a PSBT's bip32Derivation/tapBip32Derivation entry so the signing kernel\n * can re-derive it.\n */\nexport function bitcoinPubkeyFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): Uint8Array {\n const pub = xpubChild(xpub, network, change, index);\n // bip44/bip49 keep the compressed key — the signing kernel needs it for\n // redeemScript/scriptSig; only bip86 derives to the x-only key.\n return template === \"btc.bip86\" ? pub.subarray(1) : pub;\n}\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\nimport { Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { AssetFlow, DisplayIntent, SignRequest, Verifiability } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst SATS = \"sats\";\nconst SIGHASH_SINGLE_ANYONECANPAY = 0x83;\nconst OP_RETURN = 0x6a;\n\n/** Btc-signer's parse failures are foreign exceptions — the request is a malformed PSBT. */\nconst parsePsbt = (psbt: Uint8Array): Transaction => {\n try {\n return Transaction.fromPSBT(psbt);\n } catch (error) {\n throw error instanceof ChainError ? error : new ChainError(\"invalid-request\", \"malformed PSBT\");\n }\n};\n\nconst bytesToHex = (bytes: Uint8Array): string => {\n let out = \"\";\n for (const b of bytes) {\n out += b.toString(16).padStart(2, \"0\");\n }\n return out;\n};\n\ntype DecodedOutput = {\n readonly amount: bigint;\n readonly script: string;\n readonly opReturn: boolean;\n};\n\n/** Decodes an output scriptPubKey; OP_RETURN gets an amount-0 display row. */\nconst decodeOutput = (script: Uint8Array, amount: bigint): DecodedOutput => {\n const hex = bytesToHex(script);\n if (script[0] === OP_RETURN) {\n return { amount, script: hex, opReturn: true };\n }\n return { amount, script: hex, opReturn: false };\n};\n\nexport type BitcoinDisplay = {\n readonly intent: DisplayIntent;\n};\n\n/**\n * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script\n * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving\n * change) — not a display hint.\n */\nexport const decodeBitcoinPsbt = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): DisplayIntent => {\n const tx = parsePsbt(request.psbt);\n const coder = Address(bitcoinNetwork(request.network).params);\n const signed = new Set(request.sign);\n const outflows: AssetFlow[] = [];\n let canFee = true;\n let outSum = 0n;\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const { script } = output;\n const { amount } = output;\n if (script === undefined || amount === undefined) {\n continue;\n }\n const decoded = decodeOutput(script, amount);\n outSum += amount;\n if (decoded.opReturn || ownScripts.has(decoded.script)) {\n continue;\n }\n let addr: string | undefined;\n try {\n const out = OutScript.decode(script);\n addr = out === undefined ? undefined : coder.encode(out);\n } catch {\n addr = undefined;\n }\n outflows.push({\n to: addr ?? decoded.script,\n amount: { asset: SATS, amount: amount.toString(10) },\n verified: addr !== undefined,\n });\n }\n let inSum = 0n;\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n if (input.witnessUtxo === undefined) {\n canFee = false;\n } else {\n inSum += input.witnessUtxo.amount;\n }\n }\n const external = tx.inputsLength - signed.size > 0;\n const undecodable = outflows.some((o) => !o.verified);\n const listing = request.sign.some(\n (i) => tx.getInput(i).sighashType === SIGHASH_SINGLE_ANYONECANPAY,\n );\n const verifiability: Verifiability = external\n ? \"opaque\"\n : listing || undecodable\n ? \"partial\"\n : \"full\";\n return {\n family: \"bitcoin\",\n network: request.network,\n summary: outflows.length > 0 ? \"transfer\" : \"contract-call\",\n outflows,\n approvals: [],\n fee:\n canFee && !listing\n ? { max: { asset: SATS, amount: (inSum - outSum).toString(10) } }\n : undefined,\n warnings: listing\n ? [\n {\n kind: \"sighash-single-anyonecanpay\",\n message:\n \"signed inputs bind only their same-index outputs; the rest of the transaction can change\",\n },\n ]\n : [],\n verifiability,\n };\n};\n\nexport const verifiabilityBitcoin = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): Verifiability => decodeBitcoinPsbt(request, ownScripts).verifiability;\n","/**\n * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the\n * account's xpub — a kernel returning someone else's signature fails closed with `integrity`.\n * `/bitcoin` entry only — no private key material.\n */\nimport { secp256k1, schnorr } from \"@noble/curves/secp256k1.js\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { Address, OutScript, p2tr } from \"@scure/btc-signer/payment.js\";\nimport { SigHash, Transaction } from \"@scure/btc-signer/transaction.js\";\nimport { taprootTweakPubkey } from \"@scure/btc-signer/utils.js\";\n\nimport type { BitcoinAccountTemplate } from \"./account.ts\";\nimport { bip322ToSpendTxid } from \"./message.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);\n\n/** Derive the child's public key from the account xpub at `change/index` (non-hardened). */\nconst childPub = (xpub: string, network: string, change: number, index: number): Uint8Array => {\n const child = HDKey.fromExtendedKey(xpub, bitcoinNetwork(network).bip32)\n .deriveChild(change)\n .deriveChild(index);\n if (child.publicKey === null || child.publicKey === undefined) {\n throw new Error(\"xpub cannot derive this child\");\n }\n return child.publicKey;\n};\n\n/** Extract `[pubkey, {fingerprint, path}]`-shaped entries from either PSBT derivation map. */\nconst derivationOf = (\n map: unknown,\n): ReadonlyArray<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> => {\n const out: Array<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> = [];\n const readEntry = (key: unknown, value: unknown): void => {\n const der = isRecord(value) && isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = isRecord(der) ? der : {};\n if (\n key instanceof Uint8Array &&\n Array.isArray(path) &&\n path.every((p) => typeof p === \"number\")\n ) {\n out.push({ pubkey: key, path });\n }\n };\n if (map instanceof Map) {\n for (const [key, value] of map) {\n readEntry(key, value);\n }\n } else if (Array.isArray(map)) {\n for (const entry of map) {\n if (Array.isArray(entry) && entry.length === 2) {\n readEntry(entry[0], entry[1]);\n }\n }\n }\n return out;\n};\n\n/** The non-hardened `{change, index}` tail of a derivation path, if present and valid. */\nconst tailOf = (path: ReadonlyArray<number>): { change: 0 | 1; index: number } | undefined => {\n const change = path.at(-2);\n const index = path.at(-1);\n if ((change !== 0 && change !== 1) || index === undefined || index < 0 || index >= 0x80000000) {\n return undefined;\n }\n return { change, index };\n};\n\nconst eq = (a: Uint8Array, b: Uint8Array): boolean =>\n a.length === b.length && a.every((v, i) => v === b[i]);\n\n/**\n * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's\n * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must\n * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).\n */\nconst preimageLegacy = (\n tx: Transaction,\n idx: number,\n scriptCode: Uint8Array,\n sighashType: number,\n): Uint8Array => {\n const f: unknown = Reflect.get(tx, \"preimageLegacy\");\n if (typeof f !== \"function\") {\n return new Uint8Array(0);\n }\n const out: unknown = Reflect.apply(f, tx, [idx, scriptCode, sighashType]);\n return out instanceof Uint8Array ? out : new Uint8Array(0);\n};\n\nexport const verifyBitcoinPsbtSignatures = (\n signedPsbt: Uint8Array,\n sign: ReadonlyArray<number>,\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n): boolean => {\n try {\n const tx = Transaction.fromPSBT(signedPsbt);\n const taproot = template === \"btc.bip86\";\n for (const idx of sign) {\n const input = tx.getInput(idx);\n const claimed = derivationOf(taproot ? input.tapBip32Derivation : input.bip32Derivation).find(\n ({ path }) => tailOf(path) !== undefined,\n );\n const tail = claimed === undefined ? undefined : tailOf(claimed.path);\n if (claimed === undefined || tail === undefined) {\n return false;\n }\n const vout = input.index;\n const nw:\n | {\n readonly outputs: ReadonlyArray<{\n readonly script: Uint8Array;\n readonly amount: bigint;\n }>;\n }\n | undefined = input.nonWitnessUtxo;\n const legacyOut = nw === undefined || vout === undefined ? undefined : nw.outputs[vout];\n const prevout = input.witnessUtxo ?? legacyOut;\n if (prevout === undefined) {\n return false;\n }\n const prevScript: Uint8Array = prevout.script;\n const prevAmount: bigint = prevout.amount;\n const pub = childPub(xpub, network, tail.change, tail.index);\n if (taproot) {\n const xonly = pub.slice(1);\n const rawSig = input.tapKeySig;\n if (\n !eq(claimed.pubkey, xonly) ||\n !(rawSig instanceof Uint8Array) ||\n (rawSig.length !== 64 && rawSig.length !== 65) ||\n (input.tapInternalKey !== undefined && !eq(input.tapInternalKey, xonly)) ||\n !eq(prevScript, p2tr(xonly).script)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig[64] ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n const sig = rawSig.slice(0, 64);\n const scripts: Uint8Array[] = [];\n const amounts: bigint[] = [];\n let complete = true;\n for (let i = 0; i < tx.inputsLength; i++) {\n const w = tx.getInput(i).witnessUtxo;\n if (w === undefined) {\n complete = false;\n break;\n }\n scripts.push(w.script);\n amounts.push(w.amount);\n }\n // BIP-341 key-path signatures commit to the tweaked output key, not the internal key.\n const [outputKey] = taprootTweakPubkey(xonly, new Uint8Array());\n if (\n !complete ||\n !schnorr.verify(sig, tx.preimageWitnessV1(idx, scripts, sighashType, amounts), outputKey)\n ) {\n return false;\n }\n } else {\n const partial = input.partialSig;\n const found = Array.isArray(partial)\n ? partial.find(([p]) => p instanceof Uint8Array && eq(p, pub))\n : undefined;\n const rawSig =\n Array.isArray(found) && found[1] instanceof Uint8Array ? found[1] : undefined;\n if (!eq(claimed.pubkey, pub) || rawSig === undefined || rawSig.length === 0) {\n return false;\n }\n const sighashType = input.sighashType ?? rawSig.at(-1) ?? SigHash.ALL;\n // bip49 prevouts are P2SH — the BIP143 scriptCode is the inner P2WPKH\n // redeem script, canonicalized to the equivalent P2PKH script.\n const effective: Uint8Array = input.redeemScript ?? prevScript;\n const decoded = OutScript.decode(effective);\n const scriptCode: Uint8Array =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : effective;\n // P2PKH inputs sign the legacy (non-segwit) preimage — btc-signer exposes it as a\n // private method; the public witness preimages do not apply to non-witness inputs.\n const hash =\n input.nonWitnessUtxo === undefined\n ? tx.preimageWitnessV0(idx, scriptCode, sighashType, prevAmount)\n : preimageLegacy(tx, idx, scriptCode, sighashType);\n if (\n !secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n hash,\n pub,\n { prehash: false },\n )\n ) {\n return false;\n }\n }\n }\n return true;\n } catch {\n return false;\n }\n};\n\n/** Deserialize the `smp`-prefixed base64 witness: count + pushData items. */\nconst witnessOf = (sig: string): ReadonlyArray<Uint8Array> | undefined => {\n if (!sig.startsWith(\"smp\")) {\n return undefined;\n }\n const raw = base64.decode(sig.slice(3));\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n const items: Uint8Array[] = [];\n let off = 1;\n for (let i = 0; i < (raw[0] ?? 0); i++) {\n const len = raw[off];\n if (len === undefined || off + 1 + len > raw.length) {\n return undefined;\n }\n items.push(raw.slice(off + 1, off + 1 + len));\n off += 1 + len;\n }\n return off === raw.length ? items : undefined;\n};\n\n/**\n * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer\n * does, then verify the witness signature (P2WPKH ECDSA / P2TR schnorr) over the input preimage.\n */\nexport const verifyBitcoinMessage = (\n address: string,\n message: string,\n signatureBase64: string,\n network: string,\n): boolean => {\n try {\n const net = bitcoinNetwork(network);\n const scriptPubKey = OutScript.encode(Address(net.params).decode(address));\n const witness = witnessOf(signatureBase64);\n if (witness === undefined || witness.length === 0) {\n return false;\n }\n const tx = new Transaction({ version: 0, lockTime: 0, allowUnknownOutputs: true });\n tx.addInput({\n txid: Uint8Array.from([...bip322ToSpendTxid(scriptPubKey, message)].reverse()),\n index: 0,\n sequence: 0,\n witnessUtxo: { script: scriptPubKey, amount: 0n },\n });\n tx.addOutput({ script: Uint8Array.of(0x6a), amount: 0n });\n if (scriptPubKey.at(0) === 0x51) {\n const [rawSig] = witness;\n const xonly = scriptPubKey.slice(2);\n if (\n rawSig === undefined ||\n xonly.length !== 32 ||\n (rawSig.length !== 64 && rawSig.length !== 65)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig.at(64) ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n return schnorr.verify(\n rawSig.slice(0, 64),\n tx.preimageWitnessV1(0, [scriptPubKey], sighashType, [0n]),\n xonly,\n );\n }\n const [rawSig, pub] = witness;\n if (rawSig === undefined || pub === undefined || pub.length !== 33 || rawSig.length === 0) {\n return false;\n }\n const sighashType = rawSig.at(-1) ?? SigHash.ALL;\n const decoded = OutScript.decode(scriptPubKey);\n const scriptCode =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : scriptPubKey;\n return secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n tx.preimageWitnessV0(0, scriptCode, sighashType, 0n),\n pub,\n { prehash: false },\n );\n } catch {\n return false;\n }\n};\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\n\nimport { isRecord, requestBase } from \"../account-ref.ts\";\nimport { ChainError } from \"../index.ts\";\nimport type { AccountRef, SignRequest } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\nimport { normalizeBitcoinPsbt } from \"./psbt.ts\";\n\nexport { BITCOIN_NETWORKS, bitcoinNetwork } from \"./networks.ts\";\nexport type { BitcoinAccountTemplate } from \"./account.ts\";\nexport { bitcoinAddressFromXpub, bitcoinPubkeyFromXpub } from \"./account.ts\";\nexport { decodeBitcoinPsbt, verifiabilityBitcoin } from \"./decode.ts\";\nexport { verifyBitcoinMessage, verifyBitcoinPsbtSignatures } from \"./verify.ts\";\n\nconst common = (request: Record<string, unknown>): { network: string; account: AccountRef } => {\n const base = requestBase(request);\n bitcoinNetwork(base.network);\n return base;\n};\n\n/** The decoded `address` fields needed by message signers. */\nexport type MessageTarget = {\n readonly type: string;\n readonly address: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n readonly scriptPubKey: Uint8Array;\n};\n\nconst messageTarget = (address: unknown, network: string, format: unknown): MessageTarget => {\n if (typeof address !== \"string\") {\n throw new ChainError(\"invalid-request\", \"address must be a string\");\n }\n const net = bitcoinNetwork(network);\n let decoded: ReturnType<ReturnType<typeof Address>[\"decode\"]>;\n try {\n decoded = Address(net.params).decode(address);\n } catch {\n throw new ChainError(\"invalid-address\", \"address does not belong to this network\");\n }\n if (format === \"bip322-simple\") {\n if (decoded.type !== \"wpkh\" && decoded.type !== \"tr\") {\n throw new ChainError(\"unsupported\", \"bip322-simple is only for P2WPKH/P2TR addresses\");\n }\n } else if (format === \"legacy\") {\n if (decoded.type !== \"pkh\") {\n throw new ChainError(\"unsupported\", \"legacy signing is only for P2PKH addresses\");\n }\n } else {\n throw new ChainError(\"unsupported\", `unsupported message format: ${String(format)}`);\n }\n const scriptPubKey = OutScript.encode(decoded);\n return { type: decoded.type, address, format, scriptPubKey };\n};\n\n/**\n * Normalizes a bitcoin sign request. Idempotent: the returned PSBT is the canonical\n * re-serialization.\n */\nexport const normalizeBitcoin = (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 } = common(request);\n if (request[\"kind\"] === \"bitcoin.psbt\") {\n const { psbt } = request;\n if (!(psbt instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"psbt must be bytes\");\n }\n const normalized = normalizeBitcoinPsbt(psbt, request[\"sign\"], network);\n return { kind: \"bitcoin.psbt\", network, account, psbt: normalized.psbt, sign: normalized.sign };\n }\n if (request[\"kind\"] === \"bitcoin.message\") {\n const { format } = request;\n const target = messageTarget(request[\"address\"], network, format);\n void target;\n const { message, change, index } = request;\n if (typeof message !== \"string\") {\n throw new ChainError(\"invalid-request\", \"message must be a string\");\n }\n if (change !== 0 && change !== 1) {\n throw new ChainError(\"invalid-request\", \"change must be 0 or 1\");\n }\n if (\n typeof index !== \"number\" ||\n !Number.isSafeInteger(index) ||\n index < 0 ||\n index >= 0x80000000\n ) {\n throw new ChainError(\"invalid-request\", \"index must be a non-hardened path index\");\n }\n return {\n kind: \"bitcoin.message\",\n network,\n account,\n address: target.address,\n message,\n format: target.format,\n change,\n index,\n };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n\n/** Decodes the message `address` into the scriptPubKey the signer needs. */\nexport const decodeMessageTarget = (\n request: Extract<SignRequest, { kind: \"bitcoin.message\" }>,\n): MessageTarget => messageTarget(request.address, request.network, request.format);\n"],"mappings":";;;;;;;;;;;;;;;AAUA,MAAMA,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;AAMrE,MAAM,mBAAmB,QAAuD;CAC9E,MAAM,UACJ,eAAe,MACX,CAAC,GAAG,IAAI,OAAO,CAAC,IAChB,MAAM,QAAQ,GAAG,IACf,MACAA,W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B,yCAAyC;EAEnF,OAAO;GACL,MAAM;GACN;GACA;GACA,SAAS,OAAO;GAChB;GACA,QAAQ,OAAO;GACf;GACA;EACF;CACF;CACA,MAAM,IAAI,WAAW,eAAe,kCAAkC,QAAQ,SAAS;AACzF;;AAGA,MAAa,uBACX,YACkB,cAAc,QAAQ,SAAS,QAAQ,SAAS,QAAQ,MAAM"}
|
|
1
|
+
{"version":3,"file":"bitcoin.mjs","names":["isRecord","SIGHASH_SINGLE_ANYONECANPAY","isRecord"],"sources":["../src/bitcoin/psbt.ts","../src/bitcoin/account.ts","../src/bitcoin/decode.ts","../src/bitcoin/verify.ts","../src/bitcoin/index.ts"],"sourcesContent":["import { Transaction, getInputType } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { BitcoinTemplate } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\n/**\n * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what\n * binds PSBT metadata to the requested network — the raw output scripts themselves carry no network\n * marker.\n */\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Bip32Derivation values are [pubkey, { fingerprint, path }] tuples; tapBip32Derivation values are\n * { hashes, der: { fingerprint, path } }.\n */\nconst derivationPaths = (map: unknown): ReadonlyArray<ReadonlyArray<number>> => {\n const entries =\n map instanceof Map\n ? [...map.values()]\n : Array.isArray(map)\n ? map\n : isRecord(map)\n ? Object.values(map)\n : [];\n const paths: number[][] = [];\n for (const entry of entries) {\n const value: unknown = Array.isArray(entry) ? entry[1] : entry;\n if (!isRecord(value)) {\n continue;\n }\n const der = isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = der;\n if (Array.isArray(path) && path.every((p) => typeof p === \"number\")) {\n paths.push(path);\n }\n }\n return paths;\n};\n\nconst checkPaths = (\n paths: ReadonlyArray<ReadonlyArray<number>>,\n where: string,\n coinType: number,\n): void => {\n for (const path of paths) {\n if (path.length >= 2 && (path[1] ?? -1) - 0x80000000 !== coinType) {\n throw new ChainError(\n \"chain-id-mismatch\",\n `${where} derivation coin type is not this network's`,\n );\n }\n }\n};\n\nconst checkDerivations = (tx: Transaction, coinType: number): void => {\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);\n checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);\n }\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);\n checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);\n }\n};\n\nconst DEFAULT_SIGHASH = 0;\nconst SIGHASH_ALL = 1;\n/** SIGHASH_SINGLE | ANYONECANPAY — the marketplace listing sighash, the only other one accepted. */\nexport const SIGHASH_SINGLE_ANYONECANPAY = 0x83;\n\nconst TEMPLATES: ReadonlySet<string> = new Set([\n \"btc.bip44\",\n \"btc.bip49\",\n \"btc.bip84\",\n \"btc.bip86\",\n]);\n\nexport type PsbtSignEntry = { readonly index: number; readonly template: BitcoinTemplate };\n\nconst isSignEntry = (value: unknown): value is PsbtSignEntry =>\n isRecord(value) &&\n typeof value[\"index\"] === \"number\" &&\n Number.isSafeInteger(value[\"index\"]) &&\n value[\"index\"] >= 0 &&\n typeof value[\"template\"] === \"string\" &&\n TEMPLATES.has(value[\"template\"]);\n\nconst isTaprootInput = (input: ReturnType<Transaction[\"getInput\"]>): boolean =>\n input.tapInternalKey !== undefined || getInputType(input).type === \"taproot\";\n\n/**\n * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).\n * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its\n * outpoint. The returned `sign` is sorted ascending by index — a normalized request is canonical.\n */\nexport const normalizeBitcoinPsbt = (\n psbt: Uint8Array,\n sign: unknown,\n network: string,\n): { psbt: Uint8Array; sign: ReadonlyArray<PsbtSignEntry> } => {\n const net = bitcoinNetwork(network);\n let tx: Transaction;\n try {\n tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });\n } catch {\n throw new ChainError(\"invalid-request\", \"PSBT failed to decode\");\n }\n if (!Array.isArray(sign) || sign.length === 0 || !sign.every(isSignEntry)) {\n throw new ChainError(\n \"invalid-request\",\n \"sign must be a non-empty array of {index, template} entries\",\n );\n }\n const sorted = [...sign].sort((a, b) => a.index - b.index);\n const indices = new Set(sorted.map((s) => s.index));\n const last = sorted.at(-1)?.index;\n if (indices.size !== sorted.length || last === undefined || last >= tx.inputsLength) {\n throw new ChainError(\"invalid-request\", \"sign must be unique, ascending, and in range\");\n }\n checkDerivations(tx, net.coinType);\n for (const { index: idx, template } of sorted) {\n const input = tx.getInput(idx);\n if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\n \"invalid-request\",\n `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`,\n );\n }\n // bip86 inputs are taproot: they derive via tapBip32Derivation, the rest via bip32Derivation.\n if (\n template === \"btc.bip86\"\n ? input.tapBip32Derivation === undefined\n : input.bip32Derivation === undefined\n ) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing a bip32 derivation`);\n }\n const { type } = getInputType(input);\n if ((type === \"legacy\" || type === \"nonwitness-script\") && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing nonWitnessUtxo`);\n }\n const sighash = input.sighashType;\n const allowed =\n sighash === undefined ||\n sighash === SIGHASH_ALL ||\n (isTaprootInput(input) && sighash === DEFAULT_SIGHASH) ||\n sighash === SIGHASH_SINGLE_ANYONECANPAY;\n if (!allowed) {\n throw new ChainError(\"unsupported\", `input ${idx} uses a non-default sighash`);\n }\n // SIGHASH_SINGLE signs a constant when the same-index output is missing (the legacy bug).\n if (sighash === SIGHASH_SINGLE_ANYONECANPAY && idx >= tx.outputsLength) {\n throw new ChainError(\n \"unsupported\",\n `input ${idx} uses SIGHASH_SINGLE without a same-index output`,\n );\n }\n }\n return { psbt: tx.toPSBT(0), sign: sorted };\n};\n","/** Public-derivation helpers for account-level extended keys — no secrets involved. */\nimport { HDKey } from \"@scure/bip32\";\nimport { p2pkh, p2sh, p2tr, p2wpkh } from \"@scure/btc-signer/payment.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { BitcoinTemplate } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst xpubChild = (xpub: string, network: string, change: 0 | 1, index: number): Uint8Array => {\n if (!Number.isInteger(index) || index < 0) {\n throw new ChainError(\"invalid-request\", \"index must be a non-negative integer\");\n }\n const net = bitcoinNetwork(network);\n let node: HDKey;\n try {\n node = HDKey.fromExtendedKey(xpub, net.bip32);\n } catch (error) {\n throw new ChainError(\n \"invalid-request\",\n `xpub: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const child = node.derive(`m/${change}/${index}`);\n const pub = child.publicKey;\n if (pub === null) {\n throw new ChainError(\"invalid-request\", \"xpub carries no public key\");\n }\n return pub;\n};\n\nexport type BitcoinAccountTemplate = BitcoinTemplate;\n\n/**\n * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or\n * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.\n */\nexport function bitcoinAddressFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): string {\n const net = bitcoinNetwork(network);\n const pub = xpubChild(xpub, network, change, index);\n const address =\n template === \"btc.bip84\"\n ? p2wpkh(pub, net.params).address\n : template === \"btc.bip49\"\n ? p2sh(p2wpkh(pub, net.params), net.params).address\n : template === \"btc.bip44\"\n ? p2pkh(pub, net.params).address\n : p2tr(pub.subarray(1), undefined, net.params).address;\n if (address === undefined) {\n throw new ChainError(\"invalid-request\", \"could not encode the derived address\");\n }\n return address;\n}\n\n/**\n * The compressed (P2WPKH) or x-only (P2TR) public key at `change`/`index` under an account-level\n * xpub — the key placed in a PSBT's bip32Derivation/tapBip32Derivation entry so the signing kernel\n * can re-derive it.\n */\nexport function bitcoinPubkeyFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): Uint8Array {\n const pub = xpubChild(xpub, network, change, index);\n // bip44/bip49 keep the compressed key — the signing kernel needs it for\n // redeemScript/scriptSig; only bip86 derives to the x-only key.\n return template === \"btc.bip86\" ? pub.subarray(1) : pub;\n}\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\nimport { Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { AssetFlow, DisplayIntent, SignRequest, Verifiability } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst SATS = \"sats\";\nconst SIGHASH_SINGLE_ANYONECANPAY = 0x83;\nconst OP_RETURN = 0x6a;\n\n/** Btc-signer's parse failures are foreign exceptions — the request is a malformed PSBT. */\nconst parsePsbt = (psbt: Uint8Array): Transaction => {\n try {\n return Transaction.fromPSBT(psbt);\n } catch (error) {\n throw error instanceof ChainError ? error : new ChainError(\"invalid-request\", \"malformed PSBT\");\n }\n};\n\nconst bytesToHex = (bytes: Uint8Array): string => {\n let out = \"\";\n for (const b of bytes) {\n out += b.toString(16).padStart(2, \"0\");\n }\n return out;\n};\n\ntype DecodedOutput = {\n readonly amount: bigint;\n readonly script: string;\n readonly opReturn: boolean;\n};\n\n/** Decodes an output scriptPubKey; OP_RETURN gets an amount-0 display row. */\nconst decodeOutput = (script: Uint8Array, amount: bigint): DecodedOutput => {\n const hex = bytesToHex(script);\n if (script[0] === OP_RETURN) {\n return { amount, script: hex, opReturn: true };\n }\n return { amount, script: hex, opReturn: false };\n};\n\nexport type BitcoinDisplay = {\n readonly intent: DisplayIntent;\n};\n\n/**\n * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script\n * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving\n * change) — not a display hint.\n */\nexport const decodeBitcoinPsbt = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): DisplayIntent => {\n const tx = parsePsbt(request.psbt);\n const coder = Address(bitcoinNetwork(request.network).params);\n const signed = new Set(request.sign.map((s) => s.index));\n const outflows: AssetFlow[] = [];\n let canFee = true;\n let outSum = 0n;\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const { script } = output;\n const { amount } = output;\n if (script === undefined || amount === undefined) {\n continue;\n }\n const decoded = decodeOutput(script, amount);\n outSum += amount;\n if (decoded.opReturn || ownScripts.has(decoded.script)) {\n continue;\n }\n let addr: string | undefined;\n try {\n const out = OutScript.decode(script);\n addr = out === undefined ? undefined : coder.encode(out);\n } catch {\n addr = undefined;\n }\n outflows.push({\n to: addr ?? decoded.script,\n amount: { asset: SATS, amount: amount.toString(10) },\n verified: addr !== undefined,\n });\n }\n let inSum = 0n;\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n if (input.witnessUtxo === undefined) {\n canFee = false;\n } else {\n inSum += input.witnessUtxo.amount;\n }\n }\n const external = tx.inputsLength - signed.size > 0;\n const undecodable = outflows.some((o) => !o.verified);\n const listing = request.sign.some(\n (s) => tx.getInput(s.index).sighashType === SIGHASH_SINGLE_ANYONECANPAY,\n );\n const verifiability: Verifiability = external\n ? \"opaque\"\n : listing || undecodable\n ? \"partial\"\n : \"full\";\n return {\n family: \"bitcoin\",\n network: request.network,\n summary: outflows.length > 0 ? \"transfer\" : \"contract-call\",\n outflows,\n approvals: [],\n fee:\n canFee && !listing\n ? { max: { asset: SATS, amount: (inSum - outSum).toString(10) } }\n : undefined,\n warnings: listing\n ? [\n {\n kind: \"sighash-single-anyonecanpay\",\n message:\n \"signed inputs bind only their same-index outputs; the rest of the transaction can change\",\n },\n ]\n : [],\n verifiability,\n };\n};\n\nexport const verifiabilityBitcoin = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): Verifiability => decodeBitcoinPsbt(request, ownScripts).verifiability;\n","/**\n * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the\n * account's xpub — a kernel returning someone else's signature fails closed with `integrity`.\n * `/bitcoin` entry only — no private key material.\n */\nimport { secp256k1, schnorr } from \"@noble/curves/secp256k1.js\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { Address, OutScript, p2tr } from \"@scure/btc-signer/payment.js\";\nimport { SigHash, Transaction } from \"@scure/btc-signer/transaction.js\";\nimport { taprootTweakPubkey } from \"@scure/btc-signer/utils.js\";\n\nimport type { BitcoinAccountTemplate } from \"./account.ts\";\nimport { bip322ToSpendTxid } from \"./message.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);\n\n/** Derive the child's public key from the account xpub at `change/index` (non-hardened). */\nconst childPub = (xpub: string, network: string, change: number, index: number): Uint8Array => {\n const child = HDKey.fromExtendedKey(xpub, bitcoinNetwork(network).bip32)\n .deriveChild(change)\n .deriveChild(index);\n if (child.publicKey === null || child.publicKey === undefined) {\n throw new Error(\"xpub cannot derive this child\");\n }\n return child.publicKey;\n};\n\n/** Extract `[pubkey, {fingerprint, path}]`-shaped entries from either PSBT derivation map. */\nconst derivationOf = (\n map: unknown,\n): ReadonlyArray<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> => {\n const out: Array<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> = [];\n const readEntry = (key: unknown, value: unknown): void => {\n const der = isRecord(value) && isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = isRecord(der) ? der : {};\n if (\n key instanceof Uint8Array &&\n Array.isArray(path) &&\n path.every((p) => typeof p === \"number\")\n ) {\n out.push({ pubkey: key, path });\n }\n };\n if (map instanceof Map) {\n for (const [key, value] of map) {\n readEntry(key, value);\n }\n } else if (Array.isArray(map)) {\n for (const entry of map) {\n if (Array.isArray(entry) && entry.length === 2) {\n readEntry(entry[0], entry[1]);\n }\n }\n }\n return out;\n};\n\n/** The non-hardened `{change, index}` tail of a derivation path, if present and valid. */\nconst tailOf = (path: ReadonlyArray<number>): { change: 0 | 1; index: number } | undefined => {\n const change = path.at(-2);\n const index = path.at(-1);\n if ((change !== 0 && change !== 1) || index === undefined || index < 0 || index >= 0x80000000) {\n return undefined;\n }\n return { change, index };\n};\n\nconst eq = (a: Uint8Array, b: Uint8Array): boolean =>\n a.length === b.length && a.every((v, i) => v === b[i]);\n\n/**\n * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's\n * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must\n * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).\n */\nconst preimageLegacy = (\n tx: Transaction,\n idx: number,\n scriptCode: Uint8Array,\n sighashType: number,\n): Uint8Array => {\n const f: unknown = Reflect.get(tx, \"preimageLegacy\");\n if (typeof f !== \"function\") {\n return new Uint8Array(0);\n }\n const out: unknown = Reflect.apply(f, tx, [idx, scriptCode, sighashType]);\n return out instanceof Uint8Array ? out : new Uint8Array(0);\n};\n\nexport const verifyBitcoinPsbtSignatures = (\n signedPsbt: Uint8Array,\n sign: ReadonlyArray<number>,\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n): boolean => {\n try {\n const tx = Transaction.fromPSBT(signedPsbt);\n const taproot = template === \"btc.bip86\";\n for (const idx of sign) {\n const input = tx.getInput(idx);\n const claimed = derivationOf(taproot ? input.tapBip32Derivation : input.bip32Derivation).find(\n ({ path }) => tailOf(path) !== undefined,\n );\n const tail = claimed === undefined ? undefined : tailOf(claimed.path);\n if (claimed === undefined || tail === undefined) {\n return false;\n }\n const vout = input.index;\n const nw:\n | {\n readonly outputs: ReadonlyArray<{\n readonly script: Uint8Array;\n readonly amount: bigint;\n }>;\n }\n | undefined = input.nonWitnessUtxo;\n const legacyOut = nw === undefined || vout === undefined ? undefined : nw.outputs[vout];\n const prevout = input.witnessUtxo ?? legacyOut;\n if (prevout === undefined) {\n return false;\n }\n const prevScript: Uint8Array = prevout.script;\n const prevAmount: bigint = prevout.amount;\n const pub = childPub(xpub, network, tail.change, tail.index);\n if (taproot) {\n const xonly = pub.slice(1);\n const rawSig = input.tapKeySig;\n if (\n !eq(claimed.pubkey, xonly) ||\n !(rawSig instanceof Uint8Array) ||\n (rawSig.length !== 64 && rawSig.length !== 65) ||\n (input.tapInternalKey !== undefined && !eq(input.tapInternalKey, xonly)) ||\n !eq(prevScript, p2tr(xonly).script)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig[64] ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n const sig = rawSig.slice(0, 64);\n const scripts: Uint8Array[] = [];\n const amounts: bigint[] = [];\n let complete = true;\n for (let i = 0; i < tx.inputsLength; i++) {\n const w = tx.getInput(i).witnessUtxo;\n if (w === undefined) {\n complete = false;\n break;\n }\n scripts.push(w.script);\n amounts.push(w.amount);\n }\n // BIP-341 key-path signatures commit to the tweaked output key, not the internal key.\n const [outputKey] = taprootTweakPubkey(xonly, new Uint8Array());\n if (\n !complete ||\n !schnorr.verify(sig, tx.preimageWitnessV1(idx, scripts, sighashType, amounts), outputKey)\n ) {\n return false;\n }\n } else {\n const partial = input.partialSig;\n const found = Array.isArray(partial)\n ? partial.find(([p]) => p instanceof Uint8Array && eq(p, pub))\n : undefined;\n const rawSig =\n Array.isArray(found) && found[1] instanceof Uint8Array ? found[1] : undefined;\n if (!eq(claimed.pubkey, pub) || rawSig === undefined || rawSig.length === 0) {\n return false;\n }\n const sighashType = input.sighashType ?? rawSig.at(-1) ?? SigHash.ALL;\n // bip49 prevouts are P2SH — the BIP143 scriptCode is the inner P2WPKH\n // redeem script, canonicalized to the equivalent P2PKH script.\n const effective: Uint8Array = input.redeemScript ?? prevScript;\n const decoded = OutScript.decode(effective);\n const scriptCode: Uint8Array =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : effective;\n // P2PKH inputs sign the legacy (non-segwit) preimage — btc-signer exposes it as a\n // private method; the public witness preimages do not apply to non-witness inputs.\n const hash =\n input.nonWitnessUtxo === undefined\n ? tx.preimageWitnessV0(idx, scriptCode, sighashType, prevAmount)\n : preimageLegacy(tx, idx, scriptCode, sighashType);\n if (\n !secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n hash,\n pub,\n { prehash: false },\n )\n ) {\n return false;\n }\n }\n }\n return true;\n } catch {\n return false;\n }\n};\n\n/** Deserialize the `smp`-prefixed base64 witness: count + pushData items. */\nconst witnessOf = (sig: string): ReadonlyArray<Uint8Array> | undefined => {\n if (!sig.startsWith(\"smp\")) {\n return undefined;\n }\n const raw = base64.decode(sig.slice(3));\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n const items: Uint8Array[] = [];\n let off = 1;\n for (let i = 0; i < (raw[0] ?? 0); i++) {\n const len = raw[off];\n if (len === undefined || off + 1 + len > raw.length) {\n return undefined;\n }\n items.push(raw.slice(off + 1, off + 1 + len));\n off += 1 + len;\n }\n return off === raw.length ? items : undefined;\n};\n\n/**\n * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer\n * does, then verify the witness signature (P2WPKH ECDSA / P2TR schnorr) over the input preimage.\n */\nexport const verifyBitcoinMessage = (\n address: string,\n message: string,\n signatureBase64: string,\n network: string,\n): boolean => {\n try {\n const net = bitcoinNetwork(network);\n const scriptPubKey = OutScript.encode(Address(net.params).decode(address));\n const witness = witnessOf(signatureBase64);\n if (witness === undefined || witness.length === 0) {\n return false;\n }\n const tx = new Transaction({ version: 0, lockTime: 0, allowUnknownOutputs: true });\n tx.addInput({\n txid: Uint8Array.from([...bip322ToSpendTxid(scriptPubKey, message)].reverse()),\n index: 0,\n sequence: 0,\n witnessUtxo: { script: scriptPubKey, amount: 0n },\n });\n tx.addOutput({ script: Uint8Array.of(0x6a), amount: 0n });\n if (scriptPubKey.at(0) === 0x51) {\n const [rawSig] = witness;\n const xonly = scriptPubKey.slice(2);\n if (\n rawSig === undefined ||\n xonly.length !== 32 ||\n (rawSig.length !== 64 && rawSig.length !== 65)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig.at(64) ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n return schnorr.verify(\n rawSig.slice(0, 64),\n tx.preimageWitnessV1(0, [scriptPubKey], sighashType, [0n]),\n xonly,\n );\n }\n const [rawSig, pub] = witness;\n if (rawSig === undefined || pub === undefined || pub.length !== 33 || rawSig.length === 0) {\n return false;\n }\n const sighashType = rawSig.at(-1) ?? SigHash.ALL;\n const decoded = OutScript.decode(scriptPubKey);\n const scriptCode =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : scriptPubKey;\n return secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n tx.preimageWitnessV0(0, scriptCode, sighashType, 0n),\n pub,\n { prehash: false },\n );\n } catch {\n return false;\n }\n};\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\n\nimport { isRecord, requestBase } from \"../account-ref.ts\";\nimport { ChainError } from \"../index.ts\";\nimport type { AccountRef, SignRequest } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\nimport { normalizeBitcoinPsbt } from \"./psbt.ts\";\n\nexport { BITCOIN_NETWORKS, bitcoinNetwork } from \"./networks.ts\";\nexport type { BitcoinAccountTemplate } from \"./account.ts\";\nexport { bitcoinAddressFromXpub, bitcoinPubkeyFromXpub } from \"./account.ts\";\nexport { decodeBitcoinPsbt, verifiabilityBitcoin } from \"./decode.ts\";\nexport { verifyBitcoinMessage, verifyBitcoinPsbtSignatures } from \"./verify.ts\";\n\nconst common = (request: Record<string, unknown>): { network: string; account: AccountRef } => {\n const base = requestBase(request);\n bitcoinNetwork(base.network);\n return base;\n};\n\n/** The decoded `address` fields needed by message signers. */\nexport type MessageTarget = {\n readonly type: string;\n readonly address: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n readonly scriptPubKey: Uint8Array;\n};\n\nconst messageTarget = (address: unknown, network: string, format: unknown): MessageTarget => {\n if (typeof address !== \"string\") {\n throw new ChainError(\"invalid-request\", \"address must be a string\");\n }\n const net = bitcoinNetwork(network);\n let decoded: ReturnType<ReturnType<typeof Address>[\"decode\"]>;\n try {\n decoded = Address(net.params).decode(address);\n } catch {\n throw new ChainError(\"invalid-address\", \"address does not belong to this network\");\n }\n if (format === \"bip322-simple\") {\n if (decoded.type !== \"wpkh\" && decoded.type !== \"tr\") {\n throw new ChainError(\"unsupported\", \"bip322-simple is only for P2WPKH/P2TR addresses\");\n }\n } else if (format === \"legacy\") {\n if (decoded.type !== \"pkh\") {\n throw new ChainError(\"unsupported\", \"legacy signing is only for P2PKH addresses\");\n }\n } else {\n throw new ChainError(\"unsupported\", `unsupported message format: ${String(format)}`);\n }\n const scriptPubKey = OutScript.encode(decoded);\n return { type: decoded.type, address, format, scriptPubKey };\n};\n\n/**\n * Normalizes a bitcoin sign request. Idempotent: the returned PSBT is the canonical\n * re-serialization.\n */\nexport const normalizeBitcoin = (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 if (request[\"kind\"] === \"bitcoin.psbt\") {\n const { network, account, psbt } = request;\n if (typeof network !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request.network must be a string\");\n }\n bitcoinNetwork(network);\n if (!isRecord(account) || account[\"kind\"] !== \"hd\") {\n throw new ChainError(\"invalid-request\", \"request.account must be a wallet group\");\n }\n const { walletId, groupIndex } = account;\n if (\n typeof walletId !== \"string\" ||\n typeof groupIndex !== \"number\" ||\n !Number.isSafeInteger(groupIndex) ||\n groupIndex < 0\n ) {\n throw new ChainError(\"invalid-request\", \"request.account must be a wallet group\");\n }\n if (!(psbt instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"psbt must be bytes\");\n }\n const normalized = normalizeBitcoinPsbt(psbt, request[\"sign\"], network);\n return {\n kind: \"bitcoin.psbt\",\n network,\n account: { kind: \"hd\", walletId, groupIndex },\n psbt: normalized.psbt,\n sign: normalized.sign,\n };\n }\n const { network, account } = common(request);\n if (request[\"kind\"] === \"bitcoin.message\") {\n const { format } = request;\n const target = messageTarget(request[\"address\"], network, format);\n void target;\n const { message, change, index } = request;\n if (typeof message !== \"string\") {\n throw new ChainError(\"invalid-request\", \"message must be a string\");\n }\n if (change !== 0 && change !== 1) {\n throw new ChainError(\"invalid-request\", \"change must be 0 or 1\");\n }\n if (\n typeof index !== \"number\" ||\n !Number.isSafeInteger(index) ||\n index < 0 ||\n index >= 0x80000000\n ) {\n throw new ChainError(\"invalid-request\", \"index must be a non-hardened path index\");\n }\n return {\n kind: \"bitcoin.message\",\n network,\n account,\n address: target.address,\n message,\n format: target.format,\n change,\n index,\n };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n\n/** Decodes the message `address` into the scriptPubKey the signer needs. */\nexport const decodeMessageTarget = (\n request: Extract<SignRequest, { kind: \"bitcoin.message\" }>,\n): MessageTarget => messageTarget(request.address, request.network, request.format);\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAMA,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;AAMrE,MAAM,mBAAmB,QAAuD;CAC9E,MAAM,UACJ,eAAe,MACX,CAAC,GAAG,IAAI,OAAO,CAAC,IAChB,MAAM,QAAQ,GAAG,IACf,MACAA,WAAS,GAAG,IACV,OAAO,OAAO,GAAG,IACjB,CAAC;CACX,MAAM,QAAoB,CAAC;CAC3B,KAAK,MAAM,SAAS,SA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AM,aAAa,qBAAqB,MAAM,QAAQ,SAAS,OAAO;EACtE,OAAO;GACL,MAAM;GACN;GACA,SAAS;IAAE,MAAM;IAAM;IAAU;GAAW;GAC5C,MAAM,WAAW;GACjB,MAAM,WAAW;EACnB;CACF;CACA,MAAM,EAAE,SAAS,YAAY,OAAO,OAAO;CAC3C,IAAI,QAAQ,YAAY,mBAAmB;EACzC,MAAM,EAAE,WAAW;EACnB,MAAM,SAAS,cAAc,QAAQ,YAAY,SAAS,MAAM;EAEhE,MAAM,EAAE,SAAS,QAAQ,UAAU;EACnC,IAAI,OAAO,YAAY,UACrB,MAAM,IAAI,WAAW,mBAAmB,0BAA0B;EAEpE,IAAI,WAAW,KAAK,WAAW,GAC7B,MAAM,IAAI,WAAW,mBAAmB,uBAAuB;EAEjE,IACE,OAAO,UAAU,YACjB,CAAC,OAAO,cAAc,KAAK,KAC3B,QAAQ,KACR,SAAS,YAET,MAAM,IAAI,WAAW,mBAAmB,yCAAyC;EAEnF,OAAO;GACL,MAAM;GACN;GACA;GACA,SAAS,OAAO;GAChB;GACA,QAAQ,OAAO;GACf;GACA;EACF;CACF;CACA,MAAM,IAAI,WAAW,eAAe,kCAAkC,QAAQ,SAAS;AACzF;;AAGA,MAAa,uBACX,YACkB,cAAc,QAAQ,SAAS,QAAQ,SAAS,QAAQ,MAAM"}
|
package/dist/evm-sign.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { d as EvmTransaction } from "./index-DpL5hvPl.mjs";
|
|
2
2
|
/** Signs a normalized transaction; returns the serialized signed envelope. */
|
|
3
3
|
export declare const signEvmTransaction: (tx: EvmTransaction, privateKey: Uint8Array) => Uint8Array;
|
|
4
4
|
/** EIP-191 personal_sign; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
|
package/dist/evm-sign.mjs
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { t as ChainError } from "./src-8NZeEnrW.mjs";
|
|
2
|
-
import { i as parseTypedData } from "./typed-data-
|
|
3
|
-
import * as TypedData from "ox/TypedData";
|
|
2
|
+
import { i as parseTypedData } from "./typed-data-B4PJ1v8F.mjs";
|
|
4
3
|
import * as Hex from "ox/Hex";
|
|
4
|
+
import * as TypedData from "ox/TypedData";
|
|
5
|
+
import * as Authorization from "ox/Authorization";
|
|
5
6
|
import * as PersonalMessage from "ox/PersonalMessage";
|
|
6
7
|
import * as Secp256k1 from "ox/Secp256k1";
|
|
7
8
|
import * as Signature from "ox/Signature";
|
|
8
9
|
import * as TxEnvelopeEip1559 from "ox/TxEnvelopeEip1559";
|
|
9
10
|
import * as TxEnvelopeEip2930 from "ox/TxEnvelopeEip2930";
|
|
11
|
+
import * as TxEnvelopeEip7702 from "ox/TxEnvelopeEip7702";
|
|
10
12
|
import * as TxEnvelopeLegacy from "ox/TxEnvelopeLegacy";
|
|
11
13
|
// src/evm/sign.ts
|
|
12
14
|
/**
|
|
@@ -65,6 +67,30 @@ const signEvmTransaction = (tx, privateKey) => {
|
|
|
65
67
|
const signature = sign(TxEnvelopeEip2930.getSignPayload(envelope), privateKeyHex);
|
|
66
68
|
return Hex.toBytes(TxEnvelopeEip2930.serialize(envelope, { signature }));
|
|
67
69
|
}
|
|
70
|
+
if (tx.type === "eip7702") {
|
|
71
|
+
const auth = {
|
|
72
|
+
chainId: tx.chainId,
|
|
73
|
+
address: hex(tx.authorization.address, "authorization.address"),
|
|
74
|
+
nonce: BigInt(tx.nonce + 1)
|
|
75
|
+
};
|
|
76
|
+
const authSignature = sign(Authorization.getSignPayload(auth), privateKeyHex);
|
|
77
|
+
const envelope = {
|
|
78
|
+
...base,
|
|
79
|
+
type: "eip7702",
|
|
80
|
+
to: hex(tx.to, "to"),
|
|
81
|
+
accessList: tx.accessList.map(accessEntry),
|
|
82
|
+
maxFeePerGas: BigInt(tx.maxFeePerGas),
|
|
83
|
+
maxPriorityFeePerGas: BigInt(tx.maxPriorityFeePerGas),
|
|
84
|
+
authorizationList: [{
|
|
85
|
+
...auth,
|
|
86
|
+
r: authSignature.r,
|
|
87
|
+
s: authSignature.s,
|
|
88
|
+
yParity: authSignature.yParity ?? 0
|
|
89
|
+
}]
|
|
90
|
+
};
|
|
91
|
+
const signature = sign(TxEnvelopeEip7702.getSignPayload(envelope), privateKeyHex);
|
|
92
|
+
return Hex.toBytes(TxEnvelopeEip7702.serialize(envelope, { signature }));
|
|
93
|
+
}
|
|
68
94
|
const envelope = {
|
|
69
95
|
...base,
|
|
70
96
|
type: "eip1559",
|
package/dist/evm-sign.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evm-sign.mjs","names":[],"sources":["../src/evm/sign.ts"],"sourcesContent":["/**\n * /evm/sign — deterministic (RFC 6979) ECDSA signing over the chain's canonical payloads. Inputs\n * must already be normalized: the kernel calls `normalizeEvm` first and rejects on a ChainError. No\n * key caching; the caller wipes key bytes.\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 { EvmAccessListEntry, EvmTransaction } from \"../index.ts\";\nimport { parseTypedData } from \"./typed-data.ts\";\n\n/** Validates a string is `0x`-hex and narrows it for ox's branded type. */\nfunction assertHex(value: string, field: string): asserts value is `0x${string}` {\n if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {\n throw new ChainError(\"invalid-quantity\", `${field} must be 0x-prefixed bytes`);\n }\n}\n\nconst hex = (value: string, field: string): `0x${string}` => {\n assertHex(value, field);\n return value;\n};\n\nconst key = (privateKey: Uint8Array): `0x${string}` => {\n if (privateKey.length !== 32) {\n throw new ChainError(\"invalid-request\", \"private key must be 32 bytes\");\n }\n return Hex.fromBytes(privateKey);\n};\n\nconst accessEntry = (entry: EvmAccessListEntry) => ({\n address: hex(entry.address, \"accessList.address\"),\n storageKeys: entry.storageKeys.map((k) => hex(k, \"accessList.storageKeys\")),\n});\n\nconst sign = (payload: `0x${string}`, privateKey: `0x${string}`) =>\n Secp256k1.sign({ payload, privateKey, as: \"Object\" as const });\n\n/** Signs a normalized transaction; returns the serialized signed envelope. */\nexport const signEvmTransaction = (tx: EvmTransaction, privateKey: Uint8Array): Uint8Array => {\n const privateKeyHex = key(privateKey);\n const base = {\n chainId: tx.chainId,\n to: tx.to === undefined ? undefined : hex(tx.to, \"to\"),\n data: hex(tx.data, \"data\"),\n value: BigInt(tx.value),\n nonce: BigInt(tx.nonce),\n gas: BigInt(tx.gas),\n };\n if (tx.type === \"legacy\") {\n const envelope = { ...base, type: \"legacy\" as const, gasPrice: BigInt(tx.gasPrice) };\n const signature = sign(TxEnvelopeLegacy.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeLegacy.serialize(envelope, { signature }));\n }\n if (tx.type === \"eip2930\") {\n const envelope = {\n ...base,\n type: \"eip2930\" as const,\n gasPrice: BigInt(tx.gasPrice),\n accessList: tx.accessList.map(accessEntry),\n };\n const signature = sign(TxEnvelopeEip2930.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeEip2930.serialize(envelope, { signature }));\n }\n const envelope = {\n ...base,\n type: \"eip1559\" as const,\n accessList: tx.accessList.map(accessEntry),\n maxFeePerGas: BigInt(tx.maxFeePerGas),\n maxPriorityFeePerGas: BigInt(tx.maxPriorityFeePerGas),\n };\n const signature = sign(TxEnvelopeEip1559.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeEip1559.serialize(envelope, { signature }));\n};\n\n/** 65-byte r‖s‖v; `Signature.toBytes` emits v = 27 + yParity already. */\nconst rs_v = (signature: Signature.Signature): Uint8Array => Signature.toBytes(signature);\n\n/** EIP-191 personal_sign; returns the 65-byte signature r‖s‖v with v∈{27,28}. */\nexport const signEvmPersonalMessage = (message: Uint8Array, privateKey: Uint8Array): Uint8Array => {\n const payload = PersonalMessage.getSignPayload(Hex.fromBytes(message));\n return rs_v(Signature.from(sign(payload, key(privateKey))));\n};\n\n/** EIP-712 typed data; returns the 65-byte signature r‖s‖v with v∈{27,28}. */\nexport const signEvmTypedData = (typedData: string, privateKey: Uint8Array): Uint8Array => {\n const { json } = parseTypedData(typedData);\n const payload = TypedData.getSignPayload(json);\n return rs_v(Signature.from(sign(payload, key(privateKey))));\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"evm-sign.mjs","names":[],"sources":["../src/evm/sign.ts"],"sourcesContent":["/**\n * /evm/sign — deterministic (RFC 6979) ECDSA signing over the chain's canonical payloads. Inputs\n * must already be normalized: the kernel calls `normalizeEvm` first and rejects on a ChainError. No\n * key caching; the caller wipes key bytes.\n */\nimport * as Authorization from \"ox/Authorization\";\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 TxEnvelopeEip7702 from \"ox/TxEnvelopeEip7702\";\nimport * as TxEnvelopeLegacy from \"ox/TxEnvelopeLegacy\";\nimport * as TypedData from \"ox/TypedData\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { EvmAccessListEntry, EvmTransaction } from \"../index.ts\";\nimport { parseTypedData } from \"./typed-data.ts\";\n\n/** Validates a string is `0x`-hex and narrows it for ox's branded type. */\nfunction assertHex(value: string, field: string): asserts value is `0x${string}` {\n if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {\n throw new ChainError(\"invalid-quantity\", `${field} must be 0x-prefixed bytes`);\n }\n}\n\nconst hex = (value: string, field: string): `0x${string}` => {\n assertHex(value, field);\n return value;\n};\n\nconst key = (privateKey: Uint8Array): `0x${string}` => {\n if (privateKey.length !== 32) {\n throw new ChainError(\"invalid-request\", \"private key must be 32 bytes\");\n }\n return Hex.fromBytes(privateKey);\n};\n\nconst accessEntry = (entry: EvmAccessListEntry) => ({\n address: hex(entry.address, \"accessList.address\"),\n storageKeys: entry.storageKeys.map((k) => hex(k, \"accessList.storageKeys\")),\n});\n\nconst sign = (payload: `0x${string}`, privateKey: `0x${string}`) =>\n Secp256k1.sign({ payload, privateKey, as: \"Object\" as const });\n\n/** Signs a normalized transaction; returns the serialized signed envelope. */\nexport const signEvmTransaction = (tx: EvmTransaction, privateKey: Uint8Array): Uint8Array => {\n const privateKeyHex = key(privateKey);\n const base = {\n chainId: tx.chainId,\n to: tx.to === undefined ? undefined : hex(tx.to, \"to\"),\n data: hex(tx.data, \"data\"),\n value: BigInt(tx.value),\n nonce: BigInt(tx.nonce),\n gas: BigInt(tx.gas),\n };\n if (tx.type === \"legacy\") {\n const envelope = { ...base, type: \"legacy\" as const, gasPrice: BigInt(tx.gasPrice) };\n const signature = sign(TxEnvelopeLegacy.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeLegacy.serialize(envelope, { signature }));\n }\n if (tx.type === \"eip2930\") {\n const envelope = {\n ...base,\n type: \"eip2930\" as const,\n gasPrice: BigInt(tx.gasPrice),\n accessList: tx.accessList.map(accessEntry),\n };\n const signature = sign(TxEnvelopeEip2930.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeEip2930.serialize(envelope, { signature }));\n }\n if (tx.type === \"eip7702\") {\n const auth = {\n chainId: tx.chainId,\n address: hex(tx.authorization.address, \"authorization.address\"),\n nonce: BigInt(tx.nonce + 1),\n };\n const authSignature = sign(Authorization.getSignPayload(auth), privateKeyHex);\n const envelope = {\n ...base,\n type: \"eip7702\" as const,\n to: hex(tx.to, \"to\"),\n accessList: tx.accessList.map(accessEntry),\n maxFeePerGas: BigInt(tx.maxFeePerGas),\n maxPriorityFeePerGas: BigInt(tx.maxPriorityFeePerGas),\n authorizationList: [\n {\n ...auth,\n r: authSignature.r,\n s: authSignature.s,\n yParity: authSignature.yParity ?? 0,\n },\n ],\n };\n const signature = sign(TxEnvelopeEip7702.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeEip7702.serialize(envelope, { signature }));\n }\n const envelope = {\n ...base,\n type: \"eip1559\" as const,\n accessList: tx.accessList.map(accessEntry),\n maxFeePerGas: BigInt(tx.maxFeePerGas),\n maxPriorityFeePerGas: BigInt(tx.maxPriorityFeePerGas),\n };\n const signature = sign(TxEnvelopeEip1559.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeEip1559.serialize(envelope, { signature }));\n};\n\n/** 65-byte r‖s‖v; `Signature.toBytes` emits v = 27 + yParity already. */\nconst rs_v = (signature: Signature.Signature): Uint8Array => Signature.toBytes(signature);\n\n/** EIP-191 personal_sign; returns the 65-byte signature r‖s‖v with v∈{27,28}. */\nexport const signEvmPersonalMessage = (message: Uint8Array, privateKey: Uint8Array): Uint8Array => {\n const payload = PersonalMessage.getSignPayload(Hex.fromBytes(message));\n return rs_v(Signature.from(sign(payload, key(privateKey))));\n};\n\n/** EIP-712 typed data; returns the 65-byte signature r‖s‖v with v∈{27,28}. */\nexport const signEvmTypedData = (typedData: string, privateKey: Uint8Array): Uint8Array => {\n const { json } = parseTypedData(typedData);\n const payload = TypedData.getSignPayload(json);\n return rs_v(Signature.from(sign(payload, key(privateKey))));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,SAAS,UAAU,OAAe,OAA+C;CAC/E,IAAI,CAAC,0BAA0B,KAAK,KAAK,GACvC,MAAM,IAAI,WAAW,oBAAoB,GAAG,MAAM,2BAA2B;AAEjF;AAEA,MAAM,OAAO,OAAe,UAAiC;CAC3D,UAAU,OAAO,KAAK;CACtB,OAAO;AACT;AAE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,CAAC;AAC5D"}
|
package/dist/evm.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { d as EvmTransaction, l as DisplayIntent, r as AssetAmount, v as SignRequest, x as Verifiability } from "./index-DpL5hvPl.mjs";
|
|
2
|
+
import "ox/AbiFunction";
|
|
2
3
|
/** The native asset id in `AssetFlow` and simulated asset changes. */
|
|
3
4
|
export declare const EVM_NATIVE_ASSET = "native";
|
|
4
5
|
/** EIP-55 checksummed address, e.g. `0x52908400098527886E0F7030069857D2E4169EE7`. */
|
|
@@ -29,15 +30,51 @@ type EvmTokenTable = Readonly<Record<string, Readonly<Record<string, EvmToken>>>
|
|
|
29
30
|
/** The built-in table. */
|
|
30
31
|
export declare const evmTokenTable: EvmTokenTable;
|
|
31
32
|
export declare const lookupEvmToken: (table: EvmTokenTable, chainId: number, address: string) => EvmToken | undefined;
|
|
33
|
+
export declare const MAX_UINT256: bigint;
|
|
32
34
|
/** The canonical Permit2 deployment (the same address on every supported chain). */
|
|
33
35
|
export declare const PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
|
|
34
36
|
/** What the signer can guarantee about this request (WD-065). */
|
|
35
|
-
export declare const verifiabilityEvm: (request: SignRequest) => Verifiability;
|
|
37
|
+
export declare const verifiabilityEvm: (request: SignRequest, signer: string) => Verifiability;
|
|
36
38
|
/**
|
|
37
|
-
* Decodes a normalized request into a DisplayIntent.
|
|
38
|
-
*
|
|
39
|
+
* Decodes a normalized request into a DisplayIntent. `signer` is the address of the signing
|
|
40
|
+
* account; the token table parameter is for tests.
|
|
39
41
|
*/
|
|
40
|
-
export declare const decodeEvm: (request: SignRequest, table?: EvmTokenTable) => DisplayIntent;
|
|
42
|
+
export declare const decodeEvm: (request: SignRequest, signer: string, table?: EvmTokenTable) => DisplayIntent;
|
|
43
|
+
/** MetaMask Delegation Framework v1.3.0 DelegationManager — the same address on every chain. */
|
|
44
|
+
export declare const DELEGATION_MANAGER = "0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3";
|
|
45
|
+
/** ERC-4337 EntryPoint v0.8 — the same address on every chain. */
|
|
46
|
+
export declare const ENTRY_POINT_V08 = "0x4337084D9E255Ff0702461CF8895CE9E3b5Ff108";
|
|
47
|
+
/**
|
|
48
|
+
* Typed data whose domain targets an execution context over the signer's account turns a signature
|
|
49
|
+
* into execution rights: a Delegation the DelegationManager redeems, a PackedUserOperation the
|
|
50
|
+
* EntryPoint runs for a delegated 7702 account, or an action the account's own EIP-712 domain
|
|
51
|
+
* authorizes. A generic typed-data request must never produce such a signature.
|
|
52
|
+
*/
|
|
53
|
+
export declare const assertNoExecutionGrant: (domain: Record<string, unknown>, signer: string) => void;
|
|
54
|
+
/**
|
|
55
|
+
* MetaMask Delegation Framework EIP7702StatelessDeleGator v1.3.0 — deterministic CREATE2, the same
|
|
56
|
+
* address on every chain that supports it.
|
|
57
|
+
*/
|
|
58
|
+
export declare const EVM_DELEGATOR: {
|
|
59
|
+
readonly address: "0x63c0c19a282a1B52b07dD5a65b58948A07DAE32B";
|
|
60
|
+
readonly name: "EIP7702StatelessDeleGator";
|
|
61
|
+
readonly version: "1.3.0";
|
|
62
|
+
};
|
|
63
|
+
/** The EIP-7702 designator byte prefix: `0xef0100 ‖ address` marks a delegated account's code. */
|
|
64
|
+
export declare const EVM_DELEGATION_PREFIX = "0xef0100";
|
|
65
|
+
/** ERC-7821 batch-default self-call payload for `execute` on the delegator. */
|
|
66
|
+
export declare const encodeBatchExecute: (calls: ReadonlyArray<{
|
|
67
|
+
readonly to: string;
|
|
68
|
+
readonly value: bigint;
|
|
69
|
+
readonly data: string;
|
|
70
|
+
}>) => string;
|
|
71
|
+
type Execution = {
|
|
72
|
+
readonly to: string;
|
|
73
|
+
readonly value: bigint;
|
|
74
|
+
readonly data: string;
|
|
75
|
+
};
|
|
76
|
+
/** Decodes an `execute` call; undefined unless the encoding is canonical batch-default mode. */
|
|
77
|
+
export declare const decodeBatchExecute: (data: string) => ReadonlyArray<Execution> | undefined;
|
|
41
78
|
type TypedDataField = {
|
|
42
79
|
readonly name: string;
|
|
43
80
|
readonly type: string;
|
|
@@ -72,6 +109,75 @@ export declare const recoverEvmSigner: (request: Extract<SignRequest, {
|
|
|
72
109
|
readonly signedTransaction?: Uint8Array;
|
|
73
110
|
readonly signature?: Uint8Array;
|
|
74
111
|
}) => string;
|
|
112
|
+
/**
|
|
113
|
+
* The 0x AllowanceHolder (`exec`) is deployed at the same address on every chain the taker Settler
|
|
114
|
+
* supports. `exec` grants the caller a one-time allowance of `amount` of `token` to `operator`,
|
|
115
|
+
* then calls `target` with `data` (forwarding `msg.value`).
|
|
116
|
+
*/
|
|
117
|
+
export declare const ALLOWANCE_HOLDER = "0x0000000000001fF3684f28c67538d4D072C22734";
|
|
118
|
+
/** Chains whose AllowanceHolder + Settler deployment this decoder recognises. */
|
|
119
|
+
export declare const ZEROX_CHAINS: ReadonlySet<number>;
|
|
120
|
+
/**
|
|
121
|
+
* Whether `address` is a taker-feature (2) 0x Settler on `chainId`. Settlers deploy as a CREATE2
|
|
122
|
+
* shim whose CREATE child is the contract: `salt = (feature << 128) | (chainId << 64) | nonce`,
|
|
123
|
+
* `shim = CREATE2(deployer, salt, initHash)`, `settler = CREATE(shim, 1)`. Settler is redeployed
|
|
124
|
+
* roughly monthly, so nonces 1..256 leave decades of headroom; the loop runs 512 keccaks and is
|
|
125
|
+
* only reached for an AllowanceHolder `exec`. Feature 5 (bridge) is deliberately not matched.
|
|
126
|
+
*/
|
|
127
|
+
export declare const isZeroExSettler: (chainId: number, address: string) => boolean;
|
|
128
|
+
/**
|
|
129
|
+
* The `DisplayIntent` for a call to AllowanceHolder `exec` on a chain this decoder covers: a swap
|
|
130
|
+
* when the operator calls the taker Settler's own `execute` (operator == target, an on-chain
|
|
131
|
+
* Settler, a canonical inner call) and a generic one-time allowance otherwise. `undefined` when the
|
|
132
|
+
* call is not to AllowanceHolder or not `exec`.
|
|
133
|
+
*/
|
|
134
|
+
export declare const decodeZeroX: (chainId: number, call: {
|
|
135
|
+
readonly to: string | undefined;
|
|
136
|
+
readonly value: bigint;
|
|
137
|
+
readonly data: string;
|
|
138
|
+
}, table: EvmTokenTable) => (Pick<DisplayIntent, "summary" | "outflows" | "approvals" | "verifiability"> & {
|
|
139
|
+
readonly minimumReceived?: DisplayIntent["minimumReceived"];
|
|
140
|
+
}) | undefined;
|
|
141
|
+
/**
|
|
142
|
+
* Across SpokePool proxies per origin chain — UUPS upgradeable, so the kernel recognises them by
|
|
143
|
+
* address only. Verified against the Across deployments registry on 2026-11-08.
|
|
144
|
+
*/
|
|
145
|
+
export declare const ACROSS_SPOKEPOOLS: Readonly<Record<number, string>>;
|
|
146
|
+
/** Each pool's `wrappedNativeToken()` — read on-chain on 2026-11-08. */
|
|
147
|
+
export declare const ACROSS_WRAPPED_NATIVE: Readonly<Record<number, string>>;
|
|
148
|
+
type AcrossBridge = {
|
|
149
|
+
readonly outflows: ReadonlyArray<{
|
|
150
|
+
readonly to: string;
|
|
151
|
+
readonly amount: AssetAmount;
|
|
152
|
+
readonly verified: boolean;
|
|
153
|
+
}>;
|
|
154
|
+
readonly minimumReceived: ReadonlyArray<{
|
|
155
|
+
readonly to: string;
|
|
156
|
+
readonly amount: AssetAmount;
|
|
157
|
+
readonly verified: boolean;
|
|
158
|
+
}>;
|
|
159
|
+
readonly bridge: {
|
|
160
|
+
readonly destinationNetwork: string;
|
|
161
|
+
readonly fillDeadline: number;
|
|
162
|
+
readonly refundTo: string;
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
/**
|
|
166
|
+
* Decodes a `deposit`/`depositV3` to the chain's SpokePool — empty `message` only; bytes32 fields
|
|
167
|
+
* must carry left-padded EVM addresses (non-EVM destinations are not recognised). The deposit
|
|
168
|
+
* guarantees `outputAmount` on the destination chain or a refund to `depositor` after
|
|
169
|
+
* `fillDeadline`, so the intent's `minimumReceived` and `bridge` fields carry those terms.
|
|
170
|
+
*/
|
|
171
|
+
export declare const decodeAcross: (chainId: number, call: {
|
|
172
|
+
to: string | undefined;
|
|
173
|
+
data: string;
|
|
174
|
+
value: bigint;
|
|
175
|
+
}, table?: EvmTokenTable) => AcrossBridge | undefined;
|
|
176
|
+
/** The Lido contracts the kernel recognises by address — Ethereum mainnet only. */
|
|
177
|
+
export declare const LIDO_CHAIN = 1;
|
|
178
|
+
export declare const LIDO_STETH = "0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84";
|
|
179
|
+
export declare const LIDO_WSTETH = "0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0";
|
|
180
|
+
export declare const LIDO_QUEUE = "0x889edC2eDab5f40e902b864aD4d7AdE8E412F9B1";
|
|
75
181
|
/**
|
|
76
182
|
* Normalizes a SignRequest for the EVM family: exact key sets, chainId vs the CAIP-2 `network`,
|
|
77
183
|
* canonical quantities and EIP-55 addresses. Idempotent.
|