@qntx/wallet-chains 0.0.0-stage → 0.5.2

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/index.mjs ADDED
@@ -0,0 +1,13 @@
1
+ //#region src/index.ts
2
+ var ChainError = class extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.name = "ChainError";
7
+ this.code = code;
8
+ }
9
+ };
10
+ //#endregion
11
+ export { ChainError };
12
+
13
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * @qntx/wallet-chains — shared chain semantics for the wallet.\n * Types here are wire-safe: values crossing the main↔kernel protocol are\n * Uint8Array, safe integers, strings, booleans, arrays and plain objects.\n * Quantities are canonical `0x` hex (lowercase, no leading zeros, `0x0` for\n * zero), token amounts are decimal strings of the smallest unit.\n */\n\nexport type ChainFamily = \"evm\" | \"solana\" | \"bitcoin\";\n\nexport type AccountRef =\n | {\n readonly kind: \"hd\";\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: string;\n }\n | { readonly kind: \"imported\"; readonly keyId: string; readonly family: ChainFamily };\n\nexport type SignRequest =\n | {\n readonly kind: \"bitcoin.psbt\";\n readonly network: string;\n readonly account: AccountRef;\n readonly psbt: Uint8Array;\n /** Input indices to sign — non-empty, unique, ascending, in range. */\n readonly sign: ReadonlyArray<number>;\n }\n | {\n readonly kind: \"bitcoin.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly address: string;\n readonly message: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n /** Account change chain and index the address is derived at (0 = receive, 1 = change). */\n readonly change: 0 | 1;\n readonly index: number;\n }\n | {\n readonly kind: \"solana.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n /** Compiled wire message (legacy or v0). */\n readonly message: Uint8Array;\n readonly lookupTables?: ReadonlyArray<{\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n }>;\n }\n | {\n readonly kind: \"solana.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n /** Only \"raw\" exists in this layer; offchain formats land with C7. */\n readonly format: \"raw\";\n }\n | {\n readonly kind: \"evm.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n readonly tx: EvmTransaction;\n }\n | {\n readonly kind: \"evm.personal-message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n }\n | {\n readonly kind: \"evm.typed-data\";\n readonly network: string;\n readonly account: AccountRef;\n readonly typedData: string;\n };\n\nexport type EvmAccessListEntry = {\n readonly address: string;\n readonly storageKeys: ReadonlyArray<string>;\n};\n\ntype EvmTransactionBase = {\n readonly chainId: number;\n readonly nonce: number;\n readonly gas: string;\n readonly value: string;\n readonly data: string;\n readonly to?: string;\n};\n\n/**\n * A complete transaction — every field the signer needs is present; `to` absent means contract\n * creation.\n */\nexport type EvmTransaction =\n | (EvmTransactionBase & { readonly type: \"legacy\"; readonly gasPrice: string })\n | (EvmTransactionBase & {\n readonly type: \"eip2930\";\n readonly gasPrice: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n })\n | (EvmTransactionBase & {\n readonly type: \"eip1559\";\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n });\n\nexport type Verifiability = \"full\" | \"partial\" | \"opaque\";\n\nexport type IntentSummary =\n | \"transfer\"\n | \"approve\"\n | \"contract-call\"\n | \"swap\"\n | \"message\"\n | \"authorization\"\n | \"batch\";\n\nexport type AssetAmount = {\n readonly asset: string;\n readonly amount: string;\n readonly decimals?: number;\n readonly symbol?: string;\n};\n\nexport type AssetFlow = {\n readonly to: string;\n readonly amount: AssetAmount;\n readonly verified: boolean;\n};\n\nexport type ApprovalChange = {\n readonly asset: string;\n readonly spender: string;\n readonly amount: string;\n readonly unlimited: boolean;\n readonly verified: boolean;\n};\n\nexport type IntentWarning = {\n readonly kind: string;\n readonly message: string;\n};\n\nexport type DisplayIntent = {\n readonly family: ChainFamily;\n readonly network: string;\n readonly summary: IntentSummary;\n readonly outflows: ReadonlyArray<AssetFlow>;\n readonly approvals: ReadonlyArray<ApprovalChange>;\n readonly fee: { readonly max: AssetAmount } | undefined;\n readonly warnings: ReadonlyArray<IntentWarning>;\n readonly verifiability: Verifiability;\n};\n\nexport type ChainErrorCode =\n | \"unknown-field\"\n | \"chain-id-mismatch\"\n | \"fee-payer-mismatch\"\n | \"invalid-quantity\"\n | \"invalid-address\"\n | \"invalid-typed-data\"\n | \"invalid-request\"\n | \"unsupported\";\n\nexport class ChainError extends Error {\n readonly code: ChainErrorCode;\n constructor(code: ChainErrorCode, message: string) {\n super(message);\n this.name = \"ChainError\";\n this.code = code;\n }\n}\n"],"mappings":";AAuKA,IAAa,aAAb,cAAgC,MAAM;CACpC;CACA,YAAY,MAAsB,SAAiB;EACjD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF"}
@@ -0,0 +1,185 @@
1
+ import { ChainError } from "./index.mjs";
2
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
3
+ import { NETWORK, TEST_NETWORK } from "@scure/btc-signer/utils.js";
4
+ import { SigHash, Transaction } from "@scure/btc-signer/transaction.js";
5
+ import { sha256 } from "@noble/hashes/sha2.js";
6
+ //#region src/bitcoin/networks.ts
7
+ /**
8
+ * Bip122 CAIP-2 networks = `bip122:` + the first 32 hex chars of the genesis hash, verified against
9
+ * Bitcoin Core `src/kernel/chainparams.cpp` (assert(consensus.hashGenesisBlock == ...) per network
10
+ * class).
11
+ */
12
+ const MAINNET_BIP32 = {
13
+ public: 76067358,
14
+ private: 76066276
15
+ };
16
+ const TESTNET_BIP32 = {
17
+ public: 70617039,
18
+ private: 70615956
19
+ };
20
+ const REGTEST_NETWORK = {
21
+ ...TEST_NETWORK,
22
+ bech32: "bcrt"
23
+ };
24
+ const NETWORKS = Object.freeze([
25
+ {
26
+ caip2: "bip122:000000000019d6689c085ae165831e93",
27
+ genesis: "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
28
+ params: NETWORK,
29
+ coinType: 0,
30
+ bip32: MAINNET_BIP32
31
+ },
32
+ {
33
+ caip2: "bip122:00000000da84f2bafbbc53dee25a72ae",
34
+ genesis: "00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043",
35
+ params: TEST_NETWORK,
36
+ coinType: 1,
37
+ bip32: TESTNET_BIP32
38
+ },
39
+ {
40
+ caip2: "bip122:00000008819873e925422c1ff0f99f7c",
41
+ genesis: "00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6",
42
+ params: TEST_NETWORK,
43
+ coinType: 1,
44
+ bip32: TESTNET_BIP32
45
+ },
46
+ {
47
+ caip2: "bip122:0f9188f13cb7b2c71f2a335e3a4fc328",
48
+ genesis: "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206",
49
+ params: REGTEST_NETWORK,
50
+ coinType: 1,
51
+ bip32: TESTNET_BIP32
52
+ }
53
+ ]);
54
+ const BITCOIN_NETWORKS = Object.freeze(Object.fromEntries(NETWORKS.map((n) => [n.caip2, n])));
55
+ const bitcoinNetwork = (caip2) => {
56
+ const net = BITCOIN_NETWORKS[caip2];
57
+ if (net === void 0) throw new ChainError("unsupported", `unknown bitcoin network: ${caip2}`);
58
+ return net;
59
+ };
60
+ //#endregion
61
+ //#region src/bitcoin/message.ts
62
+ /**
63
+ * BIP-322 message signing ("simple" + legacy) built on btc-signer primitives.
64
+ * https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki
65
+ */
66
+ const utf8 = (s) => new TextEncoder().encode(s);
67
+ const BIP322_TAG = "BIP0322-signed-message";
68
+ const LEGACY_MAGIC = utf8("Bitcoin Signed Message:\n");
69
+ const concat = (...parts) => {
70
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
71
+ let o = 0;
72
+ for (const p of parts) {
73
+ out.set(p, o);
74
+ o += p.length;
75
+ }
76
+ return out;
77
+ };
78
+ /** CompactSize length prefix (values here are always < 253). */
79
+ const varint = (n) => Uint8Array.of(n);
80
+ const pushData = (data) => concat(varint(data.length), data);
81
+ const u32le = (n) => Uint8Array.of(n % 256, Math.floor(n / 256) % 256, Math.floor(n / 65536) % 256, Math.floor(n / 16777216) % 256);
82
+ const u64le = (n) => {
83
+ const out = /* @__PURE__ */ new Uint8Array(8);
84
+ let v = n;
85
+ for (let i = 0; i < 8; i++) {
86
+ out[i] = Number(v % 256n);
87
+ v /= 256n;
88
+ }
89
+ return out;
90
+ };
91
+ /** BIP340 tagged hash: sha256(sha256(tag) || sha256(tag) || m). */
92
+ const bip322MessageHash = (message) => {
93
+ const tag = sha256(utf8(BIP322_TAG));
94
+ return sha256(concat(tag, tag, utf8(message)));
95
+ };
96
+ /**
97
+ * Serialized to_spend tx per BIP-322: version 0, one input spending the zero prevout with the
98
+ * message-hash scriptSig, one output paying the message's scriptPubKey. Returns txid (hash256d,
99
+ * big-endian display order).
100
+ */
101
+ const toSpend = (scriptPubKey, messageHash) => {
102
+ const scriptSig = concat(Uint8Array.of(0), pushData(messageHash));
103
+ const raw = concat(u32le(0), varint(1), /* @__PURE__ */ new Uint8Array(32), u32le(4294967295), pushData(scriptSig), u32le(0), varint(1), u64le(0n), pushData(scriptPubKey), u32le(0));
104
+ return {
105
+ txid: sha256(sha256(raw)),
106
+ raw
107
+ };
108
+ };
109
+ /**
110
+ * Display-order (big-endian) txid of the BIP-322 to_spend transaction — exported for vector
111
+ * verification.
112
+ */
113
+ const bip322ToSpendTxid = (scriptPubKey, message) => Uint8Array.from([...toSpend(scriptPubKey, bip322MessageHash(message)).txid].reverse());
114
+ const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
115
+ const b64 = (i) => BASE64[i] ?? "";
116
+ const base64 = (bytes) => {
117
+ const c = b64;
118
+ let out = "";
119
+ for (let i = 0; i < bytes.length; i += 3) {
120
+ const b0 = bytes[i] ?? 0;
121
+ const b1 = bytes[i + 1] ?? 0;
122
+ const b2 = bytes[i + 2] ?? 0;
123
+ out += c(Math.floor(b0 / 4)) + c(b0 % 4 * 16 + Math.floor(b1 / 16));
124
+ out += i + 1 < bytes.length ? c(b1 % 16 * 4 + Math.floor(b2 / 64)) : "=";
125
+ out += i + 2 < bytes.length ? c(b2 % 64) : "=";
126
+ }
127
+ return out;
128
+ };
129
+ /**
130
+ * Signs the BIP-322 to_sign input through a btc-signer Transaction and returns the `smp`-prefixed
131
+ * base64 witness encoding. `scriptPubKey` is the message address's output script (P2WPKH or P2TR).
132
+ */
133
+ const signBip322Simple = (message, scriptPubKey, privateKey, auxRand) => {
134
+ const hash = bip322MessageHash(message);
135
+ const { txid } = toSpend(scriptPubKey, hash);
136
+ const tx = new Transaction({
137
+ version: 0,
138
+ lockTime: 0,
139
+ allowUnknownOutputs: true
140
+ });
141
+ const pub = secp256k1.getPublicKey(privateKey, true);
142
+ tx.addInput({
143
+ txid,
144
+ index: 0,
145
+ sequence: 0,
146
+ witnessUtxo: {
147
+ script: scriptPubKey,
148
+ amount: 0n
149
+ },
150
+ bip32Derivation: [[pub, {
151
+ fingerprint: 0,
152
+ path: []
153
+ }]],
154
+ ...scriptPubKey[0] === 81 ? { tapInternalKey: pub.slice(1) } : {}
155
+ });
156
+ tx.addOutput({
157
+ script: Uint8Array.of(106),
158
+ amount: 0n
159
+ });
160
+ const isTaproot = scriptPubKey[0] === 81;
161
+ if (!tx.signIdx(privateKey, 0, isTaproot ? [SigHash.DEFAULT, SigHash.ALL] : [SigHash.ALL], auxRand(0))) throw new ChainError("invalid-request", "key cannot sign this BIP-322 input");
162
+ tx.finalizeIdx(0);
163
+ const witness = tx.getInput(0).finalScriptWitness;
164
+ if (witness === void 0) throw new ChainError("invalid-request", "BIP-322 input produced no witness");
165
+ const raw = concat(varint(witness.length), ...witness.map(pushData));
166
+ return `smp${base64(raw)}`;
167
+ };
168
+ /**
169
+ * Legacy "Bitcoin Signed Message" compact signature for P2PKH addresses: base64(1-byte header +
170
+ * 64-byte compact ECDSA sig), header = 27 + recovery + 4 (compressed pubkey).
171
+ */
172
+ const signLegacyMessage = (message, privateKey) => {
173
+ const data = concat(pushData(LEGACY_MAGIC), pushData(utf8(message)));
174
+ const hash = sha256(sha256(data));
175
+ const recovered = secp256k1.sign(hash, privateKey, {
176
+ lowS: true,
177
+ format: "recovered"
178
+ });
179
+ const header = 27 + (recovered[0] ?? 0) + 4;
180
+ return base64(concat(Uint8Array.of(header), recovered.slice(1)));
181
+ };
182
+ //#endregion
183
+ export { bitcoinNetwork as a, BITCOIN_NETWORKS as i, signBip322Simple as n, signLegacyMessage as r, bip322ToSpendTxid as t };
184
+
185
+ //# sourceMappingURL=message-DtIS0ZWB.mjs.map
@@ -0,0 +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;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,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gBAAgB,IAAI,MAAM,CAAC,EAAE,IAAI,CAAC;CACrE,CAAC;CACD,GAAG,UAAU;EAAE,QAAQ,WAAW,GAAG,GAAI;EAAG,QAAQ;CAAG,CAAC;CACxD,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"}
@@ -0,0 +1,5 @@
1
+ //#region src/solana/sign.d.ts
2
+ /** Signs `message` with a 32-byte Ed25519 seed; returns the 64-byte signature. */
3
+ export declare const signSolanaMessage: (message: Uint8Array, privateKey: Uint8Array) => Uint8Array;
4
+ //#endregion
5
+ //# sourceMappingURL=solana-sign.d.mts.map
@@ -0,0 +1,20 @@
1
+ import { ChainError } from "./index.mjs";
2
+ import { ed25519 } from "@noble/curves/ed25519.js";
3
+ //#region src/solana/sign.ts
4
+ /**
5
+ * /solana/sign — deterministic Ed25519 signing over the compiled message or raw offchain bytes.
6
+ * Inputs must already be normalized: the kernel calls `normalizeSolana` first. No key caching; the
7
+ * caller wipes key bytes.
8
+ */
9
+ /** Signs `message` with a 32-byte Ed25519 seed; returns the 64-byte signature. */
10
+ const signSolanaMessage = (message, privateKey) => {
11
+ if (privateKey.length !== 32) throw new ChainError("invalid-request", "private key must be a 32-byte seed");
12
+ if (message.length === 0) throw new ChainError("invalid-request", "message must not be empty");
13
+ const signature = ed25519.sign(message, privateKey);
14
+ if (signature.length !== 64) throw new ChainError("invalid-request", "ed25519 produced a malformed signature");
15
+ return signature;
16
+ };
17
+ //#endregion
18
+ export { signSolanaMessage };
19
+
20
+ //# sourceMappingURL=solana-sign.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solana-sign.mjs","names":[],"sources":["../src/solana/sign.ts"],"sourcesContent":["/**\n * /solana/sign — deterministic Ed25519 signing over the compiled message or raw offchain bytes.\n * Inputs must already be normalized: the kernel calls `normalizeSolana` first. No key caching; the\n * caller wipes key bytes.\n */\nimport { ed25519 } from \"@noble/curves/ed25519.js\";\n\nimport { ChainError } from \"../index.ts\";\n\n/** Signs `message` with a 32-byte Ed25519 seed; returns the 64-byte signature. */\nexport const signSolanaMessage = (message: Uint8Array, privateKey: Uint8Array): Uint8Array => {\n if (privateKey.length !== 32) {\n throw new ChainError(\"invalid-request\", \"private key must be a 32-byte seed\");\n }\n if (message.length === 0) {\n throw new ChainError(\"invalid-request\", \"message must not be empty\");\n }\n const signature = ed25519.sign(message, privateKey);\n if (signature.length !== 64) {\n throw new ChainError(\"invalid-request\", \"ed25519 produced a malformed signature\");\n }\n return signature;\n};\n"],"mappings":";;;;;;;;;AAUA,MAAa,qBAAqB,SAAqB,eAAuC;CAC5F,IAAI,WAAW,WAAW,IACxB,MAAM,IAAI,WAAW,mBAAmB,oCAAoC;CAE9E,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,WAAW,mBAAmB,2BAA2B;CAErE,MAAM,YAAY,QAAQ,KAAK,SAAS,UAAU;CAClD,IAAI,UAAU,WAAW,IACvB,MAAM,IAAI,WAAW,mBAAmB,wCAAwC;CAElF,OAAO;AACT"}
@@ -0,0 +1,122 @@
1
+ import { DisplayIntent, SignRequest, Verifiability } from "./index.mjs";
2
+ //#region src/solana/ids.d.ts
3
+ /** Well-known Solana program ids (base58, 32 bytes) — frozen constants. */
4
+ export declare const PROGRAM_IDS: Readonly<{
5
+ system: string;
6
+ computeBudget: string;
7
+ associatedToken: string;
8
+ token: string;
9
+ token2022: string;
10
+ stake: string;
11
+ }>;
12
+ /**
13
+ * CAIP-2 ids the wallet knows. The wire message itself carries no network marker — `network` is the
14
+ * only declaration and cannot be proven from the bytes.
15
+ */
16
+ export declare const SOLANA_NETWORKS: ReadonlyArray<string>;
17
+ export declare const isSolanaAddress: (value: string) => boolean;
18
+ /** Base58-encoded address for a 32-byte ed25519 public key. */
19
+ export declare function solanaAddressFromPublicKey(pubkey: Uint8Array): string;
20
+ //#endregion
21
+ //#region src/solana/tokens.d.ts
22
+ /**
23
+ * Built-in SPL token table, keyed by `network` then mint address. An entry makes a
24
+ * `transferChecked` `full`-verifiable (WD-065), so every entry must come from the issuer's own
25
+ * published list; the source is recorded per issuer below.
26
+ */
27
+ type SolanaToken = {
28
+ readonly symbol: string;
29
+ readonly decimals: number;
30
+ readonly name?: string;
31
+ };
32
+ type SolanaTokenTable = Readonly<Record<string, Readonly<Record<string, SolanaToken>>>>;
33
+ export declare const solanaTokenTable: SolanaTokenTable;
34
+ //#endregion
35
+ //#region src/solana/decode.d.ts
36
+ /** What the signer can guarantee about this request (WD-065). */
37
+ export declare const verifiabilitySolana: (request: Extract<SignRequest, {
38
+ kind: "solana.transaction";
39
+ }>, signer: string, table?: SolanaTokenTable) => Verifiability;
40
+ export declare const decodeSolana: (request: Extract<SignRequest, {
41
+ kind: "solana.transaction";
42
+ }>, signer: string, table?: SolanaTokenTable) => DisplayIntent;
43
+ //#endregion
44
+ //#region src/solana/token2022.d.ts
45
+ /** SPL Token-2022 mint-account TLV extension type numbers (spl-token-2022 `ExtensionType`). */
46
+ export declare const EXT: {
47
+ readonly transferFeeConfig: 1;
48
+ readonly confidentialTransferMint: 4;
49
+ readonly defaultAccountState: 6;
50
+ readonly nonTransferable: 9;
51
+ readonly cpiGuard: 11;
52
+ readonly permanentDelegate: 12;
53
+ readonly transferHook: 14;
54
+ readonly confidentialTransferFee: 16;
55
+ readonly confidentialTransferFeeAmount: 17;
56
+ };
57
+ type MintExtensionSummary = {
58
+ /** The current-epoch fee from TransferFeeConfig (basis points and the maximum fee), if set. */
59
+ readonly transferFee?: {
60
+ readonly basisPoints: number;
61
+ readonly maximumFee: bigint;
62
+ };
63
+ readonly transferHook?: {
64
+ readonly programId: Uint8Array;
65
+ };
66
+ readonly permanentDelegate?: {
67
+ readonly delegate: Uint8Array;
68
+ };
69
+ readonly nonTransferable?: boolean;
70
+ /** True when a ConfidentialTransfer extension is present — confidential amounts are not supported. */
71
+ readonly confidential?: boolean;
72
+ /** Extension type numbers we do not parse (informational). */
73
+ readonly unknown?: ReadonlyArray<number>;
74
+ };
75
+ /**
76
+ * Parse the extension region of a full Token-2022 mint account. The account is the 82-byte mint
77
+ * base, zero padding up to byte 165, the account-type byte (`1` = Mint) at 165, then the TLV region
78
+ * at 166 — each entry `u16 type, u16 len, len bytes`. Returns a typed summary; extensions this
79
+ * layer does not read are reported by type number in `unknown` rather than parsed.
80
+ */
81
+ export declare const parseMintExtensions: (data: Uint8Array, epoch: bigint) => MintExtensionSummary;
82
+ /**
83
+ * Net amount a recipient gets after the current-epoch transfer fee, `amt − min(amt*bps/10000,
84
+ * max)`.
85
+ */
86
+ export declare const netAfterTransferFee: (amount: bigint, bps: number, max: bigint) => bigint;
87
+ //#endregion
88
+ //#region src/solana/message.d.ts
89
+ type CompiledIx = {
90
+ readonly programAddressIndex: number;
91
+ readonly accountIndices: ReadonlyArray<number>;
92
+ readonly data: Uint8Array;
93
+ };
94
+ type ParsedSolanaMessage = {
95
+ readonly version: "legacy" | 0;
96
+ readonly numRequiredSignatures: number;
97
+ readonly staticAccounts: ReadonlyArray<string>;
98
+ readonly instructions: ReadonlyArray<CompiledIx>;
99
+ readonly lookupCount: number;
100
+ readonly lookupAddresses: ReadonlyArray<string>;
101
+ };
102
+ /**
103
+ * Decodes a compiled wire message; rejects trailing bytes and the 1232-byte transaction limit. The
104
+ * fee payer is `staticAccounts[0]` — every valid transaction signs it.
105
+ */
106
+ export declare const parseCompiledMessage: (bytes: Uint8Array) => ParsedSolanaMessage;
107
+ //#endregion
108
+ //#region src/solana/verify.d.ts
109
+ /** Whether `signature` is a valid ed25519 signature of `message` by the key behind `address`. */
110
+ export declare const verifySolanaSignature: (message: Uint8Array, signature: Uint8Array, accountAddress: string) => boolean;
111
+ //#endregion
112
+ //#region src/solana/index.d.ts
113
+ /**
114
+ * Normalizes a Solana sign request. `signer` is the fee payer the wallet is about to sign for — the
115
+ * message must declare it as the first static account. A raw `solana.message` must not decode as a
116
+ * transaction message (chains.mdx rule — a bytes-to-sign path that produces a transaction signature
117
+ * is a wallet-drainer). Idempotent.
118
+ */
119
+ export declare const normalizeSolana: (request: unknown, signer: string) => SignRequest;
120
+ //#endregion
121
+ export type { MintExtensionSummary, SolanaTokenTable };
122
+ //# sourceMappingURL=solana.d.mts.map