signet.js 0.0.12-beta1 → 0.2.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/index.js ADDED
@@ -0,0 +1,3014 @@
1
+ import { t as __export } from "./chunk-BAz01cYq.js";
2
+ import { base58 } from "@scure/base";
3
+ import elliptic from "elliptic";
4
+ import { concat, concatHex, createPublicClient, encodeAbiParameters, encodeFunctionData, getAddress, hashMessage, hashTypedData, hexToBigInt, http, isAddress, keccak256, numberToHex, pad, parseAbiParameters, parseTransaction, recoverAddress, serializeTransaction, toBytes, withRetry } from "viem";
5
+ import * as bitcoin from "bitcoinjs-lib";
6
+ import coinselect from "coinselect";
7
+ import { encodeSecp256k1Pubkey } from "@cosmjs/amino";
8
+ import { ripemd160, sha256 } from "@cosmjs/crypto";
9
+ import { fromBase64, fromHex, toBase64 } from "@cosmjs/encoding";
10
+ import { Registry, encodePubkey, makeAuthInfoBytes, makeSignBytes, makeSignDoc } from "@cosmjs/proto-signing";
11
+ import { GasPrice, StargateClient, calculateFee } from "@cosmjs/stargate";
12
+ import { bech32 } from "bech32";
13
+ import { SignMode } from "cosmjs-types/cosmos/tx/signing/v1beta1/signing.js";
14
+ import { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx.js";
15
+ import { assets, chains } from "chain-registry";
16
+ import BN from "bn.js";
17
+ import "viem/chains";
18
+ import * as anchor from "@coral-xyz/anchor";
19
+ import { EventParser, Program } from "@coral-xyz/anchor";
20
+ import { PublicKey, Transaction, TransactionExpiredTimeoutError } from "@solana/web3.js";
21
+
22
+ //#region src/constants.ts
23
+ var constants_exports = /* @__PURE__ */ __export({
24
+ CHAINS: () => CHAINS,
25
+ CONTRACT_ADDRESSES: () => CONTRACT_ADDRESSES,
26
+ ENVS: () => ENVS,
27
+ KDF_CHAIN_IDS: () => KDF_CHAIN_IDS,
28
+ ROOT_PUBLIC_KEYS: () => ROOT_PUBLIC_KEYS
29
+ });
30
+ const ENVS = {
31
+ TESTNET_DEV: "TESTNET_DEV",
32
+ TESTNET: "TESTNET",
33
+ MAINNET: "MAINNET"
34
+ };
35
+ const CHAINS = {
36
+ ETHEREUM: "ETHEREUM",
37
+ SOLANA: "SOLANA"
38
+ };
39
+ /**
40
+ * Root public keys for the Sig Network Smart Contracts across different environments.
41
+ *
42
+ * These keys should never change.
43
+ */
44
+ const ROOT_PUBLIC_KEYS = {
45
+ [ENVS.TESTNET_DEV]: "secp256k1:54hU5wcCmVUPFWLDALXMh1fFToZsVXrx9BbTbHzSfQq1Kd1rJZi52iPa4QQxo6s5TgjWqgpY8HamYuUDzG6fAaUq",
46
+ [ENVS.TESTNET]: "secp256k1:3Ww8iFjqTHufye5aRGUvrQqETegR4gVUcW8FX5xzscaN9ENhpkffojsxJwi6N1RbbHMTxYa9UyKeqK3fsMuwxjR5",
47
+ [ENVS.MAINNET]: "secp256k1:4tY4qMzusmgX5wYdG35663Y3Qar3CTbpApotwk9ZKLoF79XA4DjG8XoByaKdNHKQX9Lz5hd7iJqsWdTKyA7dKa6Z"
48
+ };
49
+ /**
50
+ * Chain IDs used in the key derivation function (KDF) for deriving child public keys to
51
+ * distinguish between different chains.
52
+ *
53
+ * @see {@link deriveChildPublicKey} in cryptography.ts for usage details
54
+ */
55
+ const KDF_CHAIN_IDS = {
56
+ [CHAINS.ETHEREUM]: "eip155:1",
57
+ [CHAINS.SOLANA]: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
58
+ };
59
+ /**
60
+ * Contract addresses for different chains and environments.
61
+ *
62
+ * - Testnet Dev: Used for internal development, very unstable
63
+ * - Testnet: Used for external development, stable
64
+ * - Mainnet: Production contract address
65
+ *
66
+ * @see ChainSignatureContract documentation for implementation details
67
+ */
68
+ const CONTRACT_ADDRESSES = {
69
+ [CHAINS.ETHEREUM]: {
70
+ [ENVS.TESTNET_DEV]: "0x69C6b28Fdc74618817fa380De29a653060e14009",
71
+ [ENVS.TESTNET]: "0x83458E8Bf8206131Fe5c05127007FA164c0948A2",
72
+ [ENVS.MAINNET]: "0xf8bdC0612361a1E49a8E01423d4C0cFc5dF4791A"
73
+ },
74
+ [CHAINS.SOLANA]: {
75
+ [ENVS.TESTNET_DEV]: "SigDuEPNeDjh3oJv7MUraPN7zaTFomS6ZWfpXwjUg4B",
76
+ [ENVS.TESTNET]: "SigTVbfRK9LsXWpSv9KgpabrQcFKr5hDdUwMhYsXyKg",
77
+ [ENVS.MAINNET]: "SigMcRMjKfnC7RDG5q4yUMZM1s5KJ9oYTPP4NmJRDRw"
78
+ }
79
+ };
80
+
81
+ //#endregion
82
+ //#region src/utils/cryptography.ts
83
+ var cryptography_exports = /* @__PURE__ */ __export({
84
+ compressPubKey: () => compressPubKey,
85
+ deriveChildPublicKey: () => deriveChildPublicKey,
86
+ najToUncompressedPubKeySEC1: () => najToUncompressedPubKeySEC1,
87
+ toRSV: () => toRSV,
88
+ verifyRecoveredAddress: () => verifyRecoveredAddress
89
+ });
90
+ const { ec: EC } = elliptic;
91
+ const toRSV = (signature) => {
92
+ if ("bigR" in signature && "x" in signature.bigR && "s" in signature && typeof signature.s === "bigint") return {
93
+ r: signature.bigR.x.toString(16).padStart(64, "0"),
94
+ s: signature.s.toString(16).padStart(64, "0"),
95
+ v: signature.recoveryId + 27
96
+ };
97
+ throw new Error("Invalid signature format");
98
+ };
99
+ /**
100
+ * Compresses an uncompressed public key to its compressed format following SEC1 standards.
101
+ * In SEC1, a compressed public key consists of a prefix (02 or 03) followed by the x-coordinate.
102
+ * The prefix indicates whether the y-coordinate is even (02) or odd (03).
103
+ *
104
+ * @param uncompressedPubKeySEC1 - The uncompressed public key in hex format, with or without '04' prefix
105
+ * @returns The compressed public key in hex format
106
+ * @throws Error if the uncompressed public key length is invalid
107
+ */
108
+ const compressPubKey = (uncompressedPubKeySEC1) => {
109
+ const slicedPubKey = uncompressedPubKeySEC1.slice(2);
110
+ if (slicedPubKey.length !== 128) throw new Error("Invalid uncompressed public key length");
111
+ const x = slicedPubKey.slice(0, 64);
112
+ const y = slicedPubKey.slice(64);
113
+ return (parseInt(y.slice(-1), 16) % 2 === 0 ? "02" : "03") + x;
114
+ };
115
+ /**
116
+ * Converts a NAJ public key to an uncompressed SEC1 public key.
117
+ *
118
+ * @param najPublicKey - The NAJ public key to convert (e.g. secp 256k1:3Ww8iFjqTHufye5aRGUvrQqETegR4gVUcW8FX5xzscaN9ENhpkffojsxJwi6N1RbbHMTxYa9UyKeqK3fsMuwxjR5)
119
+ * @returns The uncompressed SEC1 public key (e.g. 04 || x || y)
120
+ */
121
+ const najToUncompressedPubKeySEC1 = (najPublicKey) => {
122
+ const decodedKey = base58.decode(najPublicKey.split(":")[1]);
123
+ return `04${Buffer.from(decodedKey).toString("hex")}`;
124
+ };
125
+ const EPSILON_DERIVATION_PREFIX_V2 = "sig.network v2.0.0 epsilon derivation";
126
+ /**
127
+ * Derives a child public key from a parent public key using the Sig.Network epsilon derivation scheme.
128
+ * The parent public keys are defined in @constants.ts
129
+ *
130
+ * @param rootUncompressedPubKeySEC1 - The parent public key in uncompressed SEC1 format (e.g. 04 || x || y)
131
+ * @param predecessorId - The predecessor ID is the address of the account calling the signer contract (e.g EOA or Contract Address)
132
+ * @param path - Optional derivation path suffix (defaults to empty string)
133
+ * @param chainId - CAIP-2 chain identifier used for derivation
134
+ * @param keyVersion - Key version controlling which derivation prefix to use (legacy v1 for 0, CAIP-2 v2 otherwise)
135
+ * @returns The derived child public key in uncompressed SEC1 format (04 || x || y)
136
+ */
137
+ function deriveChildPublicKey(rootUncompressedPubKeySEC1, predecessorId, path = "", chainId, keyVersion) {
138
+ const ec = new EC("secp256k1");
139
+ const derivationPath = `${EPSILON_DERIVATION_PREFIX_V2}:${chainId}:${predecessorId}:${path}`;
140
+ let scalarHex = "";
141
+ if (chainId === KDF_CHAIN_IDS.ETHEREUM) scalarHex = keccak256(Buffer.from(derivationPath)).slice(2);
142
+ else if (chainId === KDF_CHAIN_IDS.SOLANA) scalarHex = keccak256(Buffer.from(derivationPath)).slice(2);
143
+ else throw new Error("Invalid chain ID");
144
+ const x = rootUncompressedPubKeySEC1.substring(2, 66);
145
+ const y = rootUncompressedPubKeySEC1.substring(66);
146
+ const oldPublicKeyPoint = ec.curve.point(x, y);
147
+ const scalarTimesG = ec.g.mul(scalarHex);
148
+ const newPublicKeyPoint = oldPublicKeyPoint.add(scalarTimesG);
149
+ return `04${newPublicKeyPoint.getX().toString("hex").padStart(64, "0")}${newPublicKeyPoint.getY().toString("hex").padStart(64, "0")}`;
150
+ }
151
+ /**
152
+ * Verifies that a secp256k1 signature was created by the expected derived address
153
+ * by recovering the signing address and comparing it with the address derived from the contract.
154
+ *
155
+ * @param signature - The RSV signature to verify
156
+ * @param payload - The original message that was signed (as byte array)
157
+ * @param requesterAddress - The address of the requester
158
+ * @param path - The derivation path used for key generation
159
+ * @param contract - The contract instance for deriving addresses
160
+ * @returns Promise resolving to true if the recovered address matches the expected address
161
+ */
162
+ async function verifyRecoveredAddress(signature, payload, requesterAddress, path, contract, keyVersion) {
163
+ try {
164
+ const { address: expectedAddress } = await new EVM({
165
+ publicClient: createPublicClient({ transport: http("https://dontcare.com") }),
166
+ contract
167
+ }).deriveAddressAndPublicKey(requesterAddress, path, keyVersion);
168
+ return (await recoverAddress({
169
+ hash: new Uint8Array(payload),
170
+ signature: {
171
+ r: `0x${signature.r}`,
172
+ s: `0x${signature.s}`,
173
+ yParity: signature.v
174
+ }
175
+ })).toLowerCase() === expectedAddress.toLowerCase();
176
+ } catch (error) {
177
+ console.error("Signature verification failed:", error);
178
+ return false;
179
+ }
180
+ }
181
+
182
+ //#endregion
183
+ //#region src/utils/index.ts
184
+ var utils_exports = /* @__PURE__ */ __export({ cryptography: () => cryptography_exports });
185
+
186
+ //#endregion
187
+ //#region src/chain-adapters/ChainAdapter.ts
188
+ var ChainAdapter = class {};
189
+
190
+ //#endregion
191
+ //#region src/chain-adapters/EVM/utils.ts
192
+ async function fetchEVMFeeProperties(client, transaction) {
193
+ const [gas, feeData] = await Promise.all([client.estimateGas(transaction), client.estimateFeesPerGas()]);
194
+ return {
195
+ gas,
196
+ maxFeePerGas: feeData.maxFeePerGas ?? BigInt(1e10),
197
+ maxPriorityFeePerGas: feeData.maxPriorityFeePerGas ?? BigInt(1e10)
198
+ };
199
+ }
200
+
201
+ //#endregion
202
+ //#region src/chain-adapters/EVM/EVM.ts
203
+ /**
204
+ * Implementation of the ChainAdapter interface for EVM-compatible networks.
205
+ * Handles interactions with Ethereum Virtual Machine based blockchains like Ethereum, BSC, Polygon, etc.
206
+ */
207
+ var EVM = class extends ChainAdapter {
208
+ /**
209
+ * Creates a new EVM chain instance
210
+ * @param params - Configuration parameters
211
+ * @param params.publicClient - A Viem PublicClient instance for reading from the blockchain
212
+ * @param params.contract - Instance of the chain signature contract for MPC operations
213
+ */
214
+ constructor({ publicClient, contract }) {
215
+ super();
216
+ this.contract = contract;
217
+ this.client = publicClient;
218
+ }
219
+ async attachGasAndNonce(transaction) {
220
+ const fees = await fetchEVMFeeProperties(this.client, transaction);
221
+ const nonce = await this.client.getTransactionCount({ address: transaction.from });
222
+ const { from, ...rest } = transaction;
223
+ return {
224
+ ...fees,
225
+ nonce,
226
+ chainId: Number(await this.client.getChainId()),
227
+ type: "eip1559",
228
+ ...rest
229
+ };
230
+ }
231
+ transformRSVSignature(signature) {
232
+ return {
233
+ r: `0x${signature.r}`,
234
+ s: `0x${signature.s}`,
235
+ yParity: signature.v - 27
236
+ };
237
+ }
238
+ assembleSignature(signature) {
239
+ const { r, s, yParity } = this.transformRSVSignature(signature);
240
+ if (yParity === void 0) throw new Error("Missing yParity");
241
+ return concatHex([
242
+ r,
243
+ s,
244
+ numberToHex(yParity + 27, { size: 1 })
245
+ ]);
246
+ }
247
+ async deriveAddressAndPublicKey(predecessor, path, keyVersion) {
248
+ const uncompressedPubKey = await this.contract.getDerivedPublicKey({
249
+ path,
250
+ predecessor,
251
+ keyVersion
252
+ });
253
+ if (!uncompressedPubKey) throw new Error("Failed to get derived public key");
254
+ const publicKeyNoPrefix = uncompressedPubKey.startsWith("04") ? uncompressedPubKey.slice(2) : uncompressedPubKey;
255
+ return {
256
+ address: getAddress(`0x${keccak256(Buffer.from(publicKeyNoPrefix, "hex")).slice(-40)}`),
257
+ publicKey: uncompressedPubKey
258
+ };
259
+ }
260
+ async getBalance(address$1) {
261
+ return {
262
+ balance: await this.client.getBalance({ address: address$1 }),
263
+ decimals: 18
264
+ };
265
+ }
266
+ serializeTransaction(transaction) {
267
+ return serializeTransaction(transaction);
268
+ }
269
+ deserializeTransaction(serialized) {
270
+ return parseTransaction(serialized);
271
+ }
272
+ async prepareTransactionForSigning(transactionRequest) {
273
+ const transaction = await this.attachGasAndNonce(transactionRequest);
274
+ const txHash = toBytes(keccak256(serializeTransaction(transaction)));
275
+ return {
276
+ transaction,
277
+ hashesToSign: [Array.from(txHash)]
278
+ };
279
+ }
280
+ async prepareMessageForSigning(message) {
281
+ return { hashToSign: Array.from(toBytes(hashMessage(message))) };
282
+ }
283
+ async prepareTypedDataForSigning(typedDataRequest) {
284
+ return { hashToSign: Array.from(toBytes(hashTypedData(typedDataRequest))) };
285
+ }
286
+ /**
287
+ * This implementation is a common step for Biconomy and Alchemy.
288
+ * Key differences between implementations:
289
+ * - Signature format: Biconomy omits 0x00 prefix when concatenating, Alchemy includes it
290
+ * - Version support: Biconomy only supports v6, Alchemy supports both v6 and v7
291
+ * - Validation: Biconomy uses modules for signature validation, Alchemy uses built-in validation
292
+ */
293
+ async prepareUserOpForSigning(userOp, entryPointAddress, chainIdArgs) {
294
+ const chainId = chainIdArgs ?? await this.client.getChainId();
295
+ const entryPoint = entryPointAddress || "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
296
+ const userOpHash = keccak256(encodeAbiParameters([
297
+ { type: "bytes32" },
298
+ { type: "address" },
299
+ { type: "uint256" }
300
+ ], [
301
+ keccak256(encodeAbiParameters([
302
+ { type: "address" },
303
+ { type: "uint256" },
304
+ { type: "bytes32" },
305
+ { type: "bytes32" },
306
+ { type: "bytes32" },
307
+ { type: "uint256" },
308
+ { type: "bytes32" },
309
+ { type: "bytes32" }
310
+ ], [
311
+ userOp.sender,
312
+ hexToBigInt(userOp.nonce),
313
+ keccak256("factory" in userOp && "factoryData" in userOp && userOp.factory && userOp.factoryData ? concat([userOp.factory, userOp.factoryData]) : "initCode" in userOp ? userOp.initCode : "0x"),
314
+ keccak256(userOp.callData),
315
+ concat([pad(userOp.verificationGasLimit, { size: 16 }), pad(userOp.callGasLimit, { size: 16 })]),
316
+ hexToBigInt(userOp.preVerificationGas),
317
+ concat([pad(userOp.maxPriorityFeePerGas, { size: 16 }), pad(userOp.maxFeePerGas, { size: 16 })]),
318
+ keccak256("paymaster" in userOp && userOp.paymaster && isAddress(userOp.paymaster) ? concat([
319
+ userOp.paymaster,
320
+ pad(userOp.paymasterVerificationGasLimit, { size: 16 }),
321
+ pad(userOp.paymasterPostOpGasLimit, { size: 16 }),
322
+ userOp.paymasterData
323
+ ]) : "paymasterAndData" in userOp ? userOp.paymasterAndData : "0x")
324
+ ])),
325
+ entryPoint,
326
+ BigInt(chainId)
327
+ ]));
328
+ return {
329
+ userOp,
330
+ hashToSign: Array.from(toBytes(hashMessage({ raw: userOpHash })))
331
+ };
332
+ }
333
+ finalizeTransactionSigning({ transaction, rsvSignatures }) {
334
+ return serializeTransaction(transaction, this.transformRSVSignature(rsvSignatures[0]));
335
+ }
336
+ finalizeMessageSigning({ rsvSignature }) {
337
+ return this.assembleSignature(rsvSignature);
338
+ }
339
+ finalizeTypedDataSigning({ rsvSignature }) {
340
+ return this.assembleSignature(rsvSignature);
341
+ }
342
+ finalizeUserOpSigning({ userOp, rsvSignature }) {
343
+ const { r, s, yParity } = this.transformRSVSignature(rsvSignature);
344
+ if (yParity === void 0) throw new Error("Missing yParity");
345
+ return {
346
+ ...userOp,
347
+ signature: concatHex([
348
+ "0x00",
349
+ r,
350
+ s,
351
+ numberToHex(Number(yParity + 27), { size: 1 })
352
+ ])
353
+ };
354
+ }
355
+ async broadcastTx(txSerialized) {
356
+ try {
357
+ return await this.client.sendRawTransaction({ serializedTransaction: txSerialized });
358
+ } catch (error) {
359
+ console.error("Transaction broadcast failed:", error);
360
+ throw new Error("Failed to broadcast transaction.");
361
+ }
362
+ }
363
+ };
364
+
365
+ //#endregion
366
+ //#region src/chain-adapters/EVM/index.ts
367
+ var EVM_exports = /* @__PURE__ */ __export({
368
+ EVM: () => EVM,
369
+ fetchEVMFeeProperties: () => fetchEVMFeeProperties
370
+ });
371
+
372
+ //#endregion
373
+ //#region src/chain-adapters/Bitcoin/utils.ts
374
+ function parseBTCNetwork(network) {
375
+ switch (network.toLowerCase()) {
376
+ case "mainnet": return bitcoin.networks.bitcoin;
377
+ case "testnet": return bitcoin.networks.testnet;
378
+ case "regtest": return bitcoin.networks.regtest;
379
+ default: throw new Error(`Unknown Bitcoin network: ${network}`);
380
+ }
381
+ }
382
+
383
+ //#endregion
384
+ //#region src/chain-adapters/Bitcoin/Bitcoin.ts
385
+ /**
386
+ * Implementation of the ChainAdapter interface for Bitcoin network.
387
+ * Handles interactions with both Bitcoin mainnet and testnet, supporting P2WPKH transactions.
388
+ */
389
+ var Bitcoin = class Bitcoin extends ChainAdapter {
390
+ static {
391
+ this.SATOSHIS_PER_BTC = 1e8;
392
+ }
393
+ /**
394
+ * Creates a new Bitcoin chain instance
395
+ * @param params - Configuration parameters
396
+ * @param params.network - Network identifier (mainnet/testnet)
397
+ * @param params.contract - Instance of the chain signature contract for MPC operations
398
+ * @param params.btcRpcAdapter - Bitcoin RPC adapter for network interactions
399
+ */
400
+ constructor({ network, contract, btcRpcAdapter }) {
401
+ super();
402
+ this.network = network;
403
+ this.btcRpcAdapter = btcRpcAdapter;
404
+ this.contract = contract;
405
+ }
406
+ /**
407
+ * Converts satoshis to BTC
408
+ * @param satoshis - Amount in satoshis
409
+ * @returns Amount in BTC
410
+ */
411
+ static toBTC(satoshis) {
412
+ return satoshis / Bitcoin.SATOSHIS_PER_BTC;
413
+ }
414
+ /**
415
+ * Converts BTC to satoshis
416
+ * @param btc - Amount in BTC
417
+ * @returns Amount in satoshis (rounded)
418
+ */
419
+ static toSatoshi(btc) {
420
+ return Math.round(btc * Bitcoin.SATOSHIS_PER_BTC);
421
+ }
422
+ async fetchTransaction(transactionId) {
423
+ const data = await this.btcRpcAdapter.getTransaction(transactionId);
424
+ const tx = new bitcoin.Transaction();
425
+ data.vout.forEach((vout) => {
426
+ const scriptPubKey = Buffer.from(vout.scriptpubkey, "hex");
427
+ tx.addOutput(scriptPubKey, Number(vout.value));
428
+ });
429
+ return tx;
430
+ }
431
+ static transformRSVSignature(signature) {
432
+ const r = signature.r.padStart(64, "0");
433
+ const s = signature.s.padStart(64, "0");
434
+ const rawSignature = Buffer.from(r + s, "hex");
435
+ if (rawSignature.length !== 64) throw new Error("Invalid signature length.");
436
+ return rawSignature;
437
+ }
438
+ /**
439
+ * Creates a Partially Signed Bitcoin Transaction (PSBT)
440
+ * @param params - Parameters for creating the PSBT
441
+ * @param params.transactionRequest - Transaction request containing inputs and outputs
442
+ * @returns Created PSBT instance
443
+ */
444
+ async createPSBT({ transactionRequest }) {
445
+ const { inputs, outputs } = transactionRequest.inputs && transactionRequest.outputs ? transactionRequest : await this.btcRpcAdapter.selectUTXOs(transactionRequest.from, [{
446
+ address: transactionRequest.to,
447
+ value: parseFloat(transactionRequest.value)
448
+ }]);
449
+ const psbt = new bitcoin.Psbt({ network: parseBTCNetwork(this.network) });
450
+ await Promise.all(inputs.map(async (input) => {
451
+ if (!input.scriptPubKey) input.scriptPubKey = (await this.fetchTransaction(input.txid)).outs[input.vout].script;
452
+ psbt.addInput({
453
+ hash: input.txid,
454
+ index: input.vout,
455
+ witnessUtxo: {
456
+ script: input.scriptPubKey,
457
+ value: input.value
458
+ }
459
+ });
460
+ }));
461
+ outputs.forEach((out) => {
462
+ if ("address" in out) psbt.addOutput({
463
+ address: out.address,
464
+ value: out.value
465
+ });
466
+ else if ("script" in out) psbt.addOutput({
467
+ script: out.script,
468
+ value: out.value
469
+ });
470
+ else if (transactionRequest.from !== void 0) psbt.addOutput({
471
+ value: Number(out.value),
472
+ address: transactionRequest.from
473
+ });
474
+ });
475
+ return psbt;
476
+ }
477
+ async getBalance(address$1) {
478
+ return {
479
+ balance: BigInt(await this.btcRpcAdapter.getBalance(address$1)),
480
+ decimals: 8
481
+ };
482
+ }
483
+ async deriveAddressAndPublicKey(predecessor, path, keyVersion) {
484
+ const uncompressedPubKey = await this.contract.getDerivedPublicKey({
485
+ path,
486
+ predecessor,
487
+ keyVersion
488
+ });
489
+ if (!uncompressedPubKey) throw new Error("Failed to get derived public key");
490
+ const derivedKey = compressPubKey(uncompressedPubKey);
491
+ const publicKeyBuffer = Buffer.from(derivedKey, "hex");
492
+ const network = parseBTCNetwork(this.network);
493
+ const { address: address$1 } = bitcoin.payments.p2wpkh({
494
+ pubkey: publicKeyBuffer,
495
+ network
496
+ });
497
+ if (!address$1) throw new Error("Failed to generate Bitcoin address");
498
+ return {
499
+ address: address$1,
500
+ publicKey: derivedKey
501
+ };
502
+ }
503
+ serializeTransaction(transaction) {
504
+ return JSON.stringify({
505
+ psbt: transaction.psbt.toHex(),
506
+ publicKey: transaction.publicKey
507
+ });
508
+ }
509
+ deserializeTransaction(serialized) {
510
+ const transactionJSON = JSON.parse(serialized);
511
+ return {
512
+ psbt: bitcoin.Psbt.fromHex(transactionJSON.psbt),
513
+ publicKey: transactionJSON.publicKey
514
+ };
515
+ }
516
+ async prepareTransactionForSigning(transactionRequest) {
517
+ const publicKeyBuffer = Buffer.from(transactionRequest.publicKey, "hex");
518
+ const psbt = await this.createPSBT({ transactionRequest });
519
+ const psbtHex = psbt.toHex();
520
+ const hashesToSign = [];
521
+ const mockKeyPair = (index) => ({
522
+ publicKey: publicKeyBuffer,
523
+ sign: (hash) => {
524
+ hashesToSign[index] = Array.from(hash);
525
+ return Buffer.alloc(64);
526
+ }
527
+ });
528
+ for (let index = 0; index < psbt.inputCount; index++) psbt.signInput(index, mockKeyPair(index));
529
+ return {
530
+ transaction: {
531
+ psbt: bitcoin.Psbt.fromHex(psbtHex),
532
+ publicKey: transactionRequest.publicKey
533
+ },
534
+ hashesToSign
535
+ };
536
+ }
537
+ finalizeTransactionSigning({ transaction: { psbt, publicKey }, rsvSignatures }) {
538
+ const publicKeyBuffer = Buffer.from(publicKey, "hex");
539
+ const keyPair = (index) => ({
540
+ publicKey: publicKeyBuffer,
541
+ sign: () => {
542
+ const mpcSignature = rsvSignatures[index];
543
+ return Bitcoin.transformRSVSignature(mpcSignature);
544
+ }
545
+ });
546
+ for (let index = 0; index < psbt.inputCount; index++) psbt.signInput(index, keyPair(index));
547
+ psbt.finalizeAllInputs();
548
+ return psbt.extractTransaction().toHex();
549
+ }
550
+ async broadcastTx(txSerialized) {
551
+ return await this.btcRpcAdapter.broadcastTransaction(txSerialized);
552
+ }
553
+ };
554
+
555
+ //#endregion
556
+ //#region src/chain-adapters/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.ts
557
+ var BTCRpcAdapter = class {};
558
+
559
+ //#endregion
560
+ //#region src/chain-adapters/Bitcoin/BTCRpcAdapter/Mempool/Mempool.ts
561
+ var Mempool = class extends BTCRpcAdapter {
562
+ constructor(providerUrl) {
563
+ super();
564
+ this.providerUrl = providerUrl;
565
+ }
566
+ async fetchFeeRate(confirmationTarget = 6) {
567
+ const data = await (await fetch(`${this.providerUrl}/v1/fees/recommended`)).json();
568
+ if (confirmationTarget <= 1) return data.fastestFee;
569
+ else if (confirmationTarget <= 3) return data.halfHourFee;
570
+ else if (confirmationTarget <= 6) return data.hourFee;
571
+ else return data.economyFee;
572
+ }
573
+ async fetchUTXOs(address$1) {
574
+ try {
575
+ return await (await fetch(`${this.providerUrl}/address/${address$1}/utxo`)).json();
576
+ } catch (error) {
577
+ console.error("Failed to fetch UTXOs:", error);
578
+ return [];
579
+ }
580
+ }
581
+ async selectUTXOs(from, targets, confirmationTarget = 6) {
582
+ const utxos = await this.fetchUTXOs(from);
583
+ const feeRate = await this.fetchFeeRate(confirmationTarget);
584
+ const ret = coinselect(utxos, targets, Math.ceil(feeRate + 1));
585
+ if (!ret.inputs || !ret.outputs) throw new Error("Invalid transaction: coinselect failed to find a suitable set of inputs and outputs. This could be due to insufficient funds, or no inputs being available that meet the criteria.");
586
+ return {
587
+ inputs: ret.inputs,
588
+ outputs: ret.outputs
589
+ };
590
+ }
591
+ async broadcastTransaction(transactionHex) {
592
+ const response = await fetch(`${this.providerUrl}/tx`, {
593
+ method: "POST",
594
+ body: transactionHex
595
+ });
596
+ if (response.ok) return await response.text();
597
+ throw new Error(`Failed to broadcast transaction: ${await response.text()}`);
598
+ }
599
+ async getBalance(address$1) {
600
+ const data = await (await fetch(`${this.providerUrl}/address/${address$1}`)).json();
601
+ return data.chain_stats.funded_txo_sum - data.chain_stats.spent_txo_sum;
602
+ }
603
+ async getTransaction(txid) {
604
+ return await (await fetch(`${this.providerUrl}/tx/${txid}`)).json();
605
+ }
606
+ };
607
+
608
+ //#endregion
609
+ //#region src/chain-adapters/Bitcoin/BTCRpcAdapter/index.ts
610
+ const BTCRpcAdapters = { Mempool };
611
+
612
+ //#endregion
613
+ //#region src/chain-adapters/Bitcoin/index.ts
614
+ var Bitcoin_exports = /* @__PURE__ */ __export({
615
+ BTCRpcAdapter: () => BTCRpcAdapter,
616
+ BTCRpcAdapters: () => BTCRpcAdapters,
617
+ Bitcoin: () => Bitcoin
618
+ });
619
+
620
+ //#endregion
621
+ //#region src/chain-adapters/Cosmos/utils.ts
622
+ const fetchChainInfo = async (chainId) => {
623
+ const chainInfo = chains.find((chain) => chain.chain_id === chainId);
624
+ if (!chainInfo) throw new Error(`Chain info not found for chainId: ${chainId}`);
625
+ const { bech32_prefix: prefix, chain_id: expectedChainId } = chainInfo;
626
+ const denom = chainInfo.staking?.staking_tokens?.[0]?.denom;
627
+ const rpcUrl = chainInfo.apis?.rpc?.[0]?.address;
628
+ const restUrl = chainInfo.apis?.rest?.[0]?.address;
629
+ const gasPrice = chainInfo.fees?.fee_tokens?.[0]?.average_gas_price;
630
+ if (!prefix || !denom || !rpcUrl || !restUrl || !expectedChainId || gasPrice === void 0) throw new Error(`Missing required chain information for ${chainInfo.chain_name}`);
631
+ const asset = assets.find((asset$1) => asset$1.chain_name === chainInfo.chain_name)?.assets.find((asset$1) => asset$1.base === denom);
632
+ const decimals = asset?.denom_units.find((unit) => unit.denom === asset.display)?.exponent;
633
+ if (decimals === void 0) throw new Error(`Could not find decimals for ${denom} on chain ${chainInfo.chain_name}`);
634
+ return {
635
+ prefix,
636
+ denom,
637
+ rpcUrl,
638
+ restUrl,
639
+ expectedChainId,
640
+ gasPrice,
641
+ decimals
642
+ };
643
+ };
644
+
645
+ //#endregion
646
+ //#region src/chain-adapters/Cosmos/Cosmos.ts
647
+ /**
648
+ * Implementation of the ChainAdapter interface for Cosmos-based networks.
649
+ * Handles interactions with Cosmos SDK chains like Cosmos Hub, Osmosis, etc.
650
+ */
651
+ var Cosmos = class extends ChainAdapter {
652
+ /**
653
+ * Creates a new Cosmos chain instance
654
+ * @param params - Configuration parameters
655
+ * @param params.chainId - Chain id for the Cosmos network
656
+ * @param params.contract - Instance of the chain signature contract for MPC operations
657
+ * @param params.endpoints - Optional RPC and REST endpoints
658
+ * @param params.endpoints.rpcUrl - Optional RPC endpoint URL
659
+ * @param params.endpoints.restUrl - Optional REST endpoint URL
660
+ */
661
+ constructor({ chainId, contract, endpoints }) {
662
+ super();
663
+ this.contract = contract;
664
+ this.registry = new Registry();
665
+ this.chainId = chainId;
666
+ this.endpoints = endpoints;
667
+ }
668
+ transformRSVSignature(rsvSignature) {
669
+ return new Uint8Array([...fromHex(rsvSignature.r), ...fromHex(rsvSignature.s)]);
670
+ }
671
+ async getChainInfo() {
672
+ return {
673
+ ...await fetchChainInfo(this.chainId),
674
+ ...this.endpoints
675
+ };
676
+ }
677
+ async getBalance(address$1) {
678
+ try {
679
+ const { restUrl, denom, decimals } = await this.getChainInfo();
680
+ const response = await fetch(`${restUrl}/cosmos/bank/v1beta1/balances/${address$1}`);
681
+ if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
682
+ const amount = (await response.json()).balances.find((b) => b.denom === denom)?.amount ?? "0";
683
+ return {
684
+ balance: BigInt(amount),
685
+ decimals
686
+ };
687
+ } catch (error) {
688
+ console.error("Failed to fetch Cosmos balance:", error);
689
+ throw new Error("Failed to fetch Cosmos balance");
690
+ }
691
+ }
692
+ async deriveAddressAndPublicKey(predecessor, path, keyVersion) {
693
+ const { prefix } = await this.getChainInfo();
694
+ const uncompressedPubKey = await this.contract.getDerivedPublicKey({
695
+ path,
696
+ predecessor,
697
+ keyVersion
698
+ });
699
+ if (!uncompressedPubKey) throw new Error("Failed to get derived public key");
700
+ const derivedKey = compressPubKey(uncompressedPubKey);
701
+ const ripemd160Hash = ripemd160(sha256(fromHex(derivedKey)));
702
+ return {
703
+ address: bech32.encode(prefix, bech32.toWords(ripemd160Hash)),
704
+ publicKey: derivedKey
705
+ };
706
+ }
707
+ serializeTransaction(transaction) {
708
+ return toBase64(TxRaw.encode(transaction).finish());
709
+ }
710
+ deserializeTransaction(serialized) {
711
+ return TxRaw.decode(fromBase64(serialized));
712
+ }
713
+ async prepareTransactionForSigning(transactionRequest) {
714
+ const { denom, rpcUrl, gasPrice } = await this.getChainInfo();
715
+ const publicKeyBytes = fromHex(transactionRequest.publicKey);
716
+ const fee = calculateFee(transactionRequest.gas || 2e5, GasPrice.fromString(`${gasPrice}${denom}`));
717
+ const accountOnChain = await (await StargateClient.connect(rpcUrl)).getAccount(transactionRequest.address);
718
+ if (!accountOnChain) throw new Error(`Account ${transactionRequest.address} does not exist on chain`);
719
+ const { accountNumber, sequence } = accountOnChain;
720
+ const txBodyEncodeObject = {
721
+ typeUrl: "/cosmos.tx.v1beta1.TxBody",
722
+ value: {
723
+ messages: transactionRequest.messages,
724
+ memo: transactionRequest.memo || ""
725
+ }
726
+ };
727
+ const txBodyBytes = this.registry.encode(txBodyEncodeObject);
728
+ const authInfoBytes = makeAuthInfoBytes([{
729
+ pubkey: encodePubkey(encodeSecp256k1Pubkey(publicKeyBytes)),
730
+ sequence
731
+ }], fee.amount, Number(fee.gas), void 0, void 0, SignMode.SIGN_MODE_DIRECT);
732
+ const signBytes = makeSignBytes(makeSignDoc(txBodyBytes, authInfoBytes, this.chainId, accountNumber));
733
+ const payload = Array.from(sha256(signBytes));
734
+ return {
735
+ transaction: TxRaw.fromPartial({
736
+ bodyBytes: txBodyBytes,
737
+ authInfoBytes,
738
+ signatures: []
739
+ }),
740
+ hashesToSign: [payload]
741
+ };
742
+ }
743
+ finalizeTransactionSigning({ transaction, rsvSignatures }) {
744
+ transaction.signatures = rsvSignatures.map((sig) => this.transformRSVSignature(sig));
745
+ const txBytes = TxRaw.encode(transaction).finish();
746
+ return Buffer.from(txBytes).toString("hex");
747
+ }
748
+ async broadcastTx(txSerialized) {
749
+ try {
750
+ const { rpcUrl } = await this.getChainInfo();
751
+ const client = await StargateClient.connect(rpcUrl);
752
+ const txBytes = fromHex(txSerialized);
753
+ const broadcastResponse = await client.broadcastTx(txBytes);
754
+ if (broadcastResponse.code !== 0) throw new Error(`Broadcast error: ${broadcastResponse.rawLog}`);
755
+ return broadcastResponse.transactionHash;
756
+ } catch (error) {
757
+ console.error("Transaction broadcast failed:", error);
758
+ throw new Error("Failed to broadcast transaction.");
759
+ }
760
+ }
761
+ };
762
+
763
+ //#endregion
764
+ //#region src/chain-adapters/Cosmos/index.ts
765
+ var Cosmos_exports = /* @__PURE__ */ __export({ Cosmos: () => Cosmos });
766
+
767
+ //#endregion
768
+ //#region src/chain-adapters/index.ts
769
+ var chain_adapters_exports = /* @__PURE__ */ __export({
770
+ ChainAdapter: () => ChainAdapter,
771
+ btc: () => Bitcoin_exports,
772
+ cosmos: () => Cosmos_exports,
773
+ evm: () => EVM_exports
774
+ });
775
+
776
+ //#endregion
777
+ //#region src/contracts/ChainSignatureContract.ts
778
+ /**
779
+ * Base contract interface required for compatibility with ChainAdapter instances like EVM and Bitcoin.
780
+ *
781
+ * See {@link EVM} and {@link Bitcoin} for example implementations.
782
+ */
783
+ var BaseChainSignatureContract = class {};
784
+ /**
785
+ * Full contract interface that extends BaseChainSignatureContract to provide all Sig Network Smart Contract capabilities.
786
+ */
787
+ var ChainSignatureContract = class extends BaseChainSignatureContract {};
788
+
789
+ //#endregion
790
+ //#region src/contracts/evm/ChainSignaturesContractABI.ts
791
+ var ChainSignaturesContractABI_exports = /* @__PURE__ */ __export({ abi: () => abi });
792
+ const abi = [
793
+ {
794
+ inputs: [{
795
+ internalType: "address",
796
+ name: "_mpc_network",
797
+ type: "address"
798
+ }, {
799
+ internalType: "uint256",
800
+ name: "_signatureDeposit",
801
+ type: "uint256"
802
+ }],
803
+ stateMutability: "nonpayable",
804
+ type: "constructor"
805
+ },
806
+ {
807
+ inputs: [],
808
+ name: "AccessControlBadConfirmation",
809
+ type: "error"
810
+ },
811
+ {
812
+ inputs: [{
813
+ internalType: "address",
814
+ name: "account",
815
+ type: "address"
816
+ }, {
817
+ internalType: "bytes32",
818
+ name: "neededRole",
819
+ type: "bytes32"
820
+ }],
821
+ name: "AccessControlUnauthorizedAccount",
822
+ type: "error"
823
+ },
824
+ {
825
+ anonymous: false,
826
+ inputs: [
827
+ {
828
+ indexed: true,
829
+ internalType: "bytes32",
830
+ name: "role",
831
+ type: "bytes32"
832
+ },
833
+ {
834
+ indexed: true,
835
+ internalType: "bytes32",
836
+ name: "previousAdminRole",
837
+ type: "bytes32"
838
+ },
839
+ {
840
+ indexed: true,
841
+ internalType: "bytes32",
842
+ name: "newAdminRole",
843
+ type: "bytes32"
844
+ }
845
+ ],
846
+ name: "RoleAdminChanged",
847
+ type: "event"
848
+ },
849
+ {
850
+ anonymous: false,
851
+ inputs: [
852
+ {
853
+ indexed: true,
854
+ internalType: "bytes32",
855
+ name: "role",
856
+ type: "bytes32"
857
+ },
858
+ {
859
+ indexed: true,
860
+ internalType: "address",
861
+ name: "account",
862
+ type: "address"
863
+ },
864
+ {
865
+ indexed: true,
866
+ internalType: "address",
867
+ name: "sender",
868
+ type: "address"
869
+ }
870
+ ],
871
+ name: "RoleGranted",
872
+ type: "event"
873
+ },
874
+ {
875
+ anonymous: false,
876
+ inputs: [
877
+ {
878
+ indexed: true,
879
+ internalType: "bytes32",
880
+ name: "role",
881
+ type: "bytes32"
882
+ },
883
+ {
884
+ indexed: true,
885
+ internalType: "address",
886
+ name: "account",
887
+ type: "address"
888
+ },
889
+ {
890
+ indexed: true,
891
+ internalType: "address",
892
+ name: "sender",
893
+ type: "address"
894
+ }
895
+ ],
896
+ name: "RoleRevoked",
897
+ type: "event"
898
+ },
899
+ {
900
+ anonymous: false,
901
+ inputs: [
902
+ {
903
+ indexed: true,
904
+ internalType: "bytes32",
905
+ name: "requestId",
906
+ type: "bytes32"
907
+ },
908
+ {
909
+ indexed: false,
910
+ internalType: "address",
911
+ name: "responder",
912
+ type: "address"
913
+ },
914
+ {
915
+ indexed: false,
916
+ internalType: "string",
917
+ name: "error",
918
+ type: "string"
919
+ }
920
+ ],
921
+ name: "SignatureError",
922
+ type: "event"
923
+ },
924
+ {
925
+ anonymous: false,
926
+ inputs: [
927
+ {
928
+ indexed: false,
929
+ internalType: "address",
930
+ name: "sender",
931
+ type: "address"
932
+ },
933
+ {
934
+ indexed: false,
935
+ internalType: "bytes32",
936
+ name: "payload",
937
+ type: "bytes32"
938
+ },
939
+ {
940
+ indexed: false,
941
+ internalType: "uint32",
942
+ name: "keyVersion",
943
+ type: "uint32"
944
+ },
945
+ {
946
+ indexed: false,
947
+ internalType: "uint256",
948
+ name: "deposit",
949
+ type: "uint256"
950
+ },
951
+ {
952
+ indexed: false,
953
+ internalType: "uint256",
954
+ name: "chainId",
955
+ type: "uint256"
956
+ },
957
+ {
958
+ indexed: false,
959
+ internalType: "string",
960
+ name: "path",
961
+ type: "string"
962
+ },
963
+ {
964
+ indexed: false,
965
+ internalType: "string",
966
+ name: "algo",
967
+ type: "string"
968
+ },
969
+ {
970
+ indexed: false,
971
+ internalType: "string",
972
+ name: "dest",
973
+ type: "string"
974
+ },
975
+ {
976
+ indexed: false,
977
+ internalType: "string",
978
+ name: "params",
979
+ type: "string"
980
+ }
981
+ ],
982
+ name: "SignatureRequested",
983
+ type: "event"
984
+ },
985
+ {
986
+ anonymous: false,
987
+ inputs: [
988
+ {
989
+ indexed: true,
990
+ internalType: "bytes32",
991
+ name: "requestId",
992
+ type: "bytes32"
993
+ },
994
+ {
995
+ indexed: false,
996
+ internalType: "address",
997
+ name: "responder",
998
+ type: "address"
999
+ },
1000
+ {
1001
+ components: [
1002
+ {
1003
+ components: [{
1004
+ internalType: "uint256",
1005
+ name: "x",
1006
+ type: "uint256"
1007
+ }, {
1008
+ internalType: "uint256",
1009
+ name: "y",
1010
+ type: "uint256"
1011
+ }],
1012
+ internalType: "struct ChainSignatures.AffinePoint",
1013
+ name: "bigR",
1014
+ type: "tuple"
1015
+ },
1016
+ {
1017
+ internalType: "uint256",
1018
+ name: "s",
1019
+ type: "uint256"
1020
+ },
1021
+ {
1022
+ internalType: "uint8",
1023
+ name: "recoveryId",
1024
+ type: "uint8"
1025
+ }
1026
+ ],
1027
+ indexed: false,
1028
+ internalType: "struct ChainSignatures.Signature",
1029
+ name: "signature",
1030
+ type: "tuple"
1031
+ }
1032
+ ],
1033
+ name: "SignatureResponded",
1034
+ type: "event"
1035
+ },
1036
+ {
1037
+ anonymous: false,
1038
+ inputs: [{
1039
+ indexed: true,
1040
+ internalType: "address",
1041
+ name: "owner",
1042
+ type: "address"
1043
+ }, {
1044
+ indexed: false,
1045
+ internalType: "uint256",
1046
+ name: "amount",
1047
+ type: "uint256"
1048
+ }],
1049
+ name: "Withdraw",
1050
+ type: "event"
1051
+ },
1052
+ {
1053
+ inputs: [],
1054
+ name: "DEFAULT_ADMIN_ROLE",
1055
+ outputs: [{
1056
+ internalType: "bytes32",
1057
+ name: "",
1058
+ type: "bytes32"
1059
+ }],
1060
+ stateMutability: "view",
1061
+ type: "function"
1062
+ },
1063
+ {
1064
+ inputs: [{
1065
+ internalType: "bytes32",
1066
+ name: "role",
1067
+ type: "bytes32"
1068
+ }],
1069
+ name: "getRoleAdmin",
1070
+ outputs: [{
1071
+ internalType: "bytes32",
1072
+ name: "",
1073
+ type: "bytes32"
1074
+ }],
1075
+ stateMutability: "view",
1076
+ type: "function"
1077
+ },
1078
+ {
1079
+ inputs: [],
1080
+ name: "getSignatureDeposit",
1081
+ outputs: [{
1082
+ internalType: "uint256",
1083
+ name: "",
1084
+ type: "uint256"
1085
+ }],
1086
+ stateMutability: "view",
1087
+ type: "function"
1088
+ },
1089
+ {
1090
+ inputs: [{
1091
+ internalType: "bytes32",
1092
+ name: "role",
1093
+ type: "bytes32"
1094
+ }, {
1095
+ internalType: "address",
1096
+ name: "account",
1097
+ type: "address"
1098
+ }],
1099
+ name: "grantRole",
1100
+ outputs: [],
1101
+ stateMutability: "nonpayable",
1102
+ type: "function"
1103
+ },
1104
+ {
1105
+ inputs: [{
1106
+ internalType: "bytes32",
1107
+ name: "role",
1108
+ type: "bytes32"
1109
+ }, {
1110
+ internalType: "address",
1111
+ name: "account",
1112
+ type: "address"
1113
+ }],
1114
+ name: "hasRole",
1115
+ outputs: [{
1116
+ internalType: "bool",
1117
+ name: "",
1118
+ type: "bool"
1119
+ }],
1120
+ stateMutability: "view",
1121
+ type: "function"
1122
+ },
1123
+ {
1124
+ inputs: [{
1125
+ internalType: "bytes32",
1126
+ name: "role",
1127
+ type: "bytes32"
1128
+ }, {
1129
+ internalType: "address",
1130
+ name: "callerConfirmation",
1131
+ type: "address"
1132
+ }],
1133
+ name: "renounceRole",
1134
+ outputs: [],
1135
+ stateMutability: "nonpayable",
1136
+ type: "function"
1137
+ },
1138
+ {
1139
+ inputs: [{
1140
+ components: [{
1141
+ internalType: "bytes32",
1142
+ name: "requestId",
1143
+ type: "bytes32"
1144
+ }, {
1145
+ components: [
1146
+ {
1147
+ components: [{
1148
+ internalType: "uint256",
1149
+ name: "x",
1150
+ type: "uint256"
1151
+ }, {
1152
+ internalType: "uint256",
1153
+ name: "y",
1154
+ type: "uint256"
1155
+ }],
1156
+ internalType: "struct ChainSignatures.AffinePoint",
1157
+ name: "bigR",
1158
+ type: "tuple"
1159
+ },
1160
+ {
1161
+ internalType: "uint256",
1162
+ name: "s",
1163
+ type: "uint256"
1164
+ },
1165
+ {
1166
+ internalType: "uint8",
1167
+ name: "recoveryId",
1168
+ type: "uint8"
1169
+ }
1170
+ ],
1171
+ internalType: "struct ChainSignatures.Signature",
1172
+ name: "signature",
1173
+ type: "tuple"
1174
+ }],
1175
+ internalType: "struct ChainSignatures.Response[]",
1176
+ name: "_responses",
1177
+ type: "tuple[]"
1178
+ }],
1179
+ name: "respond",
1180
+ outputs: [],
1181
+ stateMutability: "nonpayable",
1182
+ type: "function"
1183
+ },
1184
+ {
1185
+ inputs: [{
1186
+ components: [{
1187
+ internalType: "bytes32",
1188
+ name: "requestId",
1189
+ type: "bytes32"
1190
+ }, {
1191
+ internalType: "string",
1192
+ name: "errorMessage",
1193
+ type: "string"
1194
+ }],
1195
+ internalType: "struct ChainSignatures.ErrorResponse[]",
1196
+ name: "_errors",
1197
+ type: "tuple[]"
1198
+ }],
1199
+ name: "respondError",
1200
+ outputs: [],
1201
+ stateMutability: "nonpayable",
1202
+ type: "function"
1203
+ },
1204
+ {
1205
+ inputs: [{
1206
+ internalType: "bytes32",
1207
+ name: "role",
1208
+ type: "bytes32"
1209
+ }, {
1210
+ internalType: "address",
1211
+ name: "account",
1212
+ type: "address"
1213
+ }],
1214
+ name: "revokeRole",
1215
+ outputs: [],
1216
+ stateMutability: "nonpayable",
1217
+ type: "function"
1218
+ },
1219
+ {
1220
+ inputs: [{
1221
+ internalType: "uint256",
1222
+ name: "_amount",
1223
+ type: "uint256"
1224
+ }],
1225
+ name: "setSignatureDeposit",
1226
+ outputs: [],
1227
+ stateMutability: "nonpayable",
1228
+ type: "function"
1229
+ },
1230
+ {
1231
+ inputs: [{
1232
+ components: [
1233
+ {
1234
+ internalType: "bytes32",
1235
+ name: "payload",
1236
+ type: "bytes32"
1237
+ },
1238
+ {
1239
+ internalType: "string",
1240
+ name: "path",
1241
+ type: "string"
1242
+ },
1243
+ {
1244
+ internalType: "uint32",
1245
+ name: "keyVersion",
1246
+ type: "uint32"
1247
+ },
1248
+ {
1249
+ internalType: "string",
1250
+ name: "algo",
1251
+ type: "string"
1252
+ },
1253
+ {
1254
+ internalType: "string",
1255
+ name: "dest",
1256
+ type: "string"
1257
+ },
1258
+ {
1259
+ internalType: "string",
1260
+ name: "params",
1261
+ type: "string"
1262
+ }
1263
+ ],
1264
+ internalType: "struct ChainSignatures.SignRequest",
1265
+ name: "_request",
1266
+ type: "tuple"
1267
+ }],
1268
+ name: "sign",
1269
+ outputs: [],
1270
+ stateMutability: "payable",
1271
+ type: "function"
1272
+ },
1273
+ {
1274
+ inputs: [{
1275
+ internalType: "bytes4",
1276
+ name: "interfaceId",
1277
+ type: "bytes4"
1278
+ }],
1279
+ name: "supportsInterface",
1280
+ outputs: [{
1281
+ internalType: "bool",
1282
+ name: "",
1283
+ type: "bool"
1284
+ }],
1285
+ stateMutability: "view",
1286
+ type: "function"
1287
+ },
1288
+ {
1289
+ inputs: [{
1290
+ internalType: "uint256",
1291
+ name: "_amount",
1292
+ type: "uint256"
1293
+ }, {
1294
+ internalType: "address",
1295
+ name: "_receiver",
1296
+ type: "address"
1297
+ }],
1298
+ name: "withdraw",
1299
+ outputs: [],
1300
+ stateMutability: "nonpayable",
1301
+ type: "function"
1302
+ }
1303
+ ];
1304
+
1305
+ //#endregion
1306
+ //#region src/contracts/evm/errors.ts
1307
+ var errors_exports$1 = /* @__PURE__ */ __export({
1308
+ ChainSignatureError: () => ChainSignatureError,
1309
+ SignatureContractError: () => SignatureContractError$1,
1310
+ SignatureNotFoundError: () => SignatureNotFoundError$1,
1311
+ SigningError: () => SigningError$1
1312
+ });
1313
+ var ChainSignatureError = class extends Error {
1314
+ constructor(message, requestId, receipt) {
1315
+ super(message);
1316
+ this.name = "ChainSignatureError";
1317
+ this.requestId = requestId;
1318
+ this.receipt = receipt;
1319
+ }
1320
+ };
1321
+ var SignatureNotFoundError$1 = class extends ChainSignatureError {
1322
+ constructor(requestId, receipt) {
1323
+ super("Signature not found after maximum retries", requestId, receipt);
1324
+ this.name = "SignatureNotFoundError";
1325
+ }
1326
+ };
1327
+ var SignatureContractError$1 = class extends ChainSignatureError {
1328
+ constructor(errorCode, requestId, receipt) {
1329
+ super(`Signature error: ${errorCode}`, requestId, receipt);
1330
+ this.name = "SignatureContractError";
1331
+ this.errorCode = errorCode;
1332
+ }
1333
+ };
1334
+ var SigningError$1 = class extends ChainSignatureError {
1335
+ constructor(requestId, receipt, originalError) {
1336
+ super("Error signing request", requestId, receipt);
1337
+ this.name = "SigningError";
1338
+ this.originalError = originalError;
1339
+ }
1340
+ };
1341
+
1342
+ //#endregion
1343
+ //#region src/utils/publicKey.ts
1344
+ const getRootPublicKey = (contractAddress, chain) => {
1345
+ const environment = Object.entries(CONTRACT_ADDRESSES[chain]).find(([_, address$1]) => address$1.toLowerCase() === contractAddress.toLowerCase())?.[0];
1346
+ if (environment) return ROOT_PUBLIC_KEYS[environment];
1347
+ };
1348
+
1349
+ //#endregion
1350
+ //#region src/contracts/evm/utils.ts
1351
+ const getRequestId = (request) => {
1352
+ return keccak256(encodeAbiParameters([
1353
+ { type: "address" },
1354
+ { type: "bytes" },
1355
+ { type: "string" },
1356
+ { type: "uint32" },
1357
+ { type: "uint256" },
1358
+ { type: "string" },
1359
+ { type: "string" },
1360
+ { type: "string" }
1361
+ ], [
1362
+ request.address,
1363
+ request.payload,
1364
+ request.path,
1365
+ Number(request.keyVersion),
1366
+ request.chainId,
1367
+ request.algo,
1368
+ request.dest,
1369
+ request.params
1370
+ ]));
1371
+ };
1372
+
1373
+ //#endregion
1374
+ //#region src/contracts/evm/ChainSignaturesContract.ts
1375
+ /**
1376
+ * Implementation of the ChainSignatureContract for EVM chains.
1377
+ *
1378
+ * When signing data, the contract emits a SignatureRequested event with a requestId.
1379
+ * This requestId is used to track the signature request and retrieve the signature
1380
+ * once it's available. The sign method handles this process automatically by polling
1381
+ * for the signature using the requestId.
1382
+ */
1383
+ var ChainSignatureContract$2 = class extends ChainSignatureContract {
1384
+ /**
1385
+ * Creates a new instance of the ChainSignatureContract for EVM chains.
1386
+ *
1387
+ * @param args - Configuration options for the contract
1388
+ * @param args.publicClient - A Viem PublicClient instance for reading from the blockchain
1389
+ * @param args.walletClient - A Viem WalletClient instance for sending transactions
1390
+ * @param args.contractAddress - The address of the deployed ChainSignatures contract (e.g. `0x857ED3A242B59cC24144814a0DF41C397a3811E6`)
1391
+ * @param args.rootPublicKey - Optional root public key. If not provided, it will be derived from the contract address
1392
+ */
1393
+ constructor(args) {
1394
+ super();
1395
+ this.publicClient = args.publicClient;
1396
+ this.walletClient = args.walletClient;
1397
+ this.contractAddress = args.contractAddress;
1398
+ const rootPublicKey = args.rootPublicKey || getRootPublicKey(this.contractAddress, CHAINS.ETHEREUM);
1399
+ if (!rootPublicKey) throw new Error(`Invalid public key, please provide a valid root public key or contract address`);
1400
+ this.rootPublicKey = rootPublicKey;
1401
+ }
1402
+ async getCurrentSignatureDeposit() {
1403
+ return new BN((await this.publicClient.readContract({
1404
+ address: this.contractAddress,
1405
+ abi,
1406
+ functionName: "getSignatureDeposit"
1407
+ })).toString());
1408
+ }
1409
+ async getDerivedPublicKey(args) {
1410
+ return deriveChildPublicKey(await this.getPublicKey(), args.predecessor.toLowerCase(), args.path, KDF_CHAIN_IDS.ETHEREUM, args.keyVersion);
1411
+ }
1412
+ async getPublicKey() {
1413
+ return najToUncompressedPubKeySEC1(this.rootPublicKey);
1414
+ }
1415
+ async getLatestKeyVersion() {
1416
+ const version = await this.publicClient.readContract({
1417
+ address: this.contractAddress,
1418
+ abi,
1419
+ functionName: "latestKeyVersion"
1420
+ });
1421
+ return Number(version);
1422
+ }
1423
+ /**
1424
+ * Sends a sign request transaction and return the transaction hash.
1425
+ *
1426
+ * @param args - The signature arguments
1427
+ * @param options - The signing options
1428
+ * @returns The transaction hash
1429
+ */
1430
+ async createSignatureRequest(args, options = { sign: {
1431
+ algo: "",
1432
+ dest: "",
1433
+ params: ""
1434
+ } }) {
1435
+ if (!this.walletClient?.account) throw new Error("Wallet client required for signing operations");
1436
+ const requestParams = await this.getSignRequestParams(args, options.sign);
1437
+ const requestId = this.getRequestId(args, options.sign);
1438
+ return {
1439
+ txHash: await this.walletClient.sendTransaction({
1440
+ ...options.transaction,
1441
+ account: this.walletClient.account,
1442
+ to: requestParams.target,
1443
+ data: requestParams.data,
1444
+ value: requestParams.value,
1445
+ chain: this.walletClient.chain
1446
+ }),
1447
+ requestId
1448
+ };
1449
+ }
1450
+ /**
1451
+ * Sends a transaction to the contract to request a signature, then
1452
+ * polls for the signature result. If the signature is not found within the retry
1453
+ * parameters, it will throw an error.
1454
+ */
1455
+ async sign(args, options = {
1456
+ sign: {
1457
+ algo: "",
1458
+ dest: "",
1459
+ params: ""
1460
+ },
1461
+ retry: {
1462
+ delay: 5e3,
1463
+ retryCount: 12
1464
+ }
1465
+ }) {
1466
+ const { txHash, requestId } = await this.createSignatureRequest(args, options);
1467
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash: txHash });
1468
+ try {
1469
+ const pollResult = await this.pollForRequestId({
1470
+ requestId,
1471
+ payload: args.payload,
1472
+ path: args.path,
1473
+ keyVersion: args.key_version,
1474
+ fromBlock: receipt.blockNumber,
1475
+ options: options.retry
1476
+ });
1477
+ if (!pollResult) throw new SignatureNotFoundError$1(requestId, receipt);
1478
+ if ("error" in pollResult) throw new SignatureContractError$1(pollResult.error, requestId, receipt);
1479
+ return pollResult;
1480
+ } catch (error) {
1481
+ if (error instanceof SignatureNotFoundError$1 || error instanceof SignatureContractError$1) throw error;
1482
+ else throw new SigningError$1(requestId, receipt, error instanceof Error ? error : void 0);
1483
+ }
1484
+ }
1485
+ async pollForRequestId({ requestId, payload, path, keyVersion, fromBlock, options }) {
1486
+ const delay = options?.delay ?? 5e3;
1487
+ const retryCount = options?.retryCount ?? 12;
1488
+ const result = await withRetry(async () => {
1489
+ const result$1 = await this.getSignatureFromEvents(requestId, fromBlock);
1490
+ if (result$1) {
1491
+ if (!await verifyRecoveredAddress(result$1, payload, this.walletClient.account?.address, path, this, keyVersion)) throw new Error("Signature not found yet");
1492
+ return result$1;
1493
+ } else throw new Error("Signature not found yet");
1494
+ }, {
1495
+ delay,
1496
+ retryCount,
1497
+ shouldRetry: ({ count, error }) => {
1498
+ console.log(`Retrying get signature: ${count}/${retryCount}`);
1499
+ return error.message === "Signature not found yet";
1500
+ }
1501
+ });
1502
+ if (result) return result;
1503
+ return await this.getErrorFromEvents(requestId, fromBlock);
1504
+ }
1505
+ async getSignRequestParams(args, options = {
1506
+ algo: "",
1507
+ dest: "",
1508
+ params: ""
1509
+ }) {
1510
+ const request = {
1511
+ payload: `0x${Buffer.from(args.payload).toString("hex")}`,
1512
+ path: args.path,
1513
+ keyVersion: args.key_version,
1514
+ algo: options.algo ?? "",
1515
+ dest: options.dest ?? "",
1516
+ params: options.params ?? ""
1517
+ };
1518
+ return {
1519
+ target: this.contractAddress,
1520
+ data: encodeFunctionData({
1521
+ abi,
1522
+ functionName: "sign",
1523
+ args: [request]
1524
+ }),
1525
+ value: BigInt((await this.getCurrentSignatureDeposit()).toString())
1526
+ };
1527
+ }
1528
+ /**
1529
+ * Generates the request ID for a signature request allowing to track the response.
1530
+ *
1531
+ * @param args - The signature request object containing:
1532
+ * @param args.payload - The data payload to be signed as a hex string
1533
+ * @param args.path - The derivation path for the key
1534
+ * @param args.keyVersion - The version of the key to use
1535
+ * @param options - The signature request object containing:
1536
+ * @param options.algo - The signing algorithm to use
1537
+ * @param options.dest - The destination for the signature
1538
+ * @param options.params - Additional parameters for the signing process
1539
+ * @returns A hex string representing the unique request ID
1540
+ *
1541
+ * @example
1542
+ * ```typescript
1543
+ * const requestId = ChainSignatureContract.getRequestId({
1544
+ * payload: payload: `0x${Buffer.from(args.payload).toString('hex')}`,,
1545
+ * path: '',
1546
+ * keyVersion: 0
1547
+ * });
1548
+ * console.log(requestId); // 0x...
1549
+ * ```
1550
+ */
1551
+ getRequestId(args, options = {
1552
+ algo: "",
1553
+ dest: "",
1554
+ params: ""
1555
+ }) {
1556
+ if (!this.walletClient.account) throw new Error("Wallet client account required to compute requestId");
1557
+ if (!this.publicClient.chain?.id) throw new Error("Public client chain required to compute requestId");
1558
+ return getRequestId({
1559
+ payload: `0x${Buffer.from(args.payload).toString("hex")}`,
1560
+ path: args.path,
1561
+ keyVersion: args.key_version,
1562
+ algo: options.algo ?? "",
1563
+ dest: options.dest ?? "",
1564
+ params: options.params ?? "",
1565
+ address: this.walletClient.account.address,
1566
+ chainId: BigInt(this.publicClient.chain.id)
1567
+ });
1568
+ }
1569
+ async getErrorFromEvents(requestId, fromBlock) {
1570
+ const errorLogs = await this.publicClient.getContractEvents({
1571
+ address: this.contractAddress,
1572
+ abi,
1573
+ eventName: "SignatureError",
1574
+ args: { requestId },
1575
+ fromBlock,
1576
+ toBlock: "latest"
1577
+ });
1578
+ if (errorLogs.length > 0) {
1579
+ const { args: errorData } = errorLogs[errorLogs.length - 1];
1580
+ return errorData;
1581
+ }
1582
+ }
1583
+ /**
1584
+ * Searches for SignatureResponded events that match the given requestId.
1585
+ * It works in conjunction with the getRequestId method which generates the unique
1586
+ * identifier for a signature request.
1587
+ *
1588
+ * @param requestId - The identifier for the signature request
1589
+ * @param fromBlock - The block number to start searching from
1590
+ * @returns The RSV signature if found, undefined otherwise
1591
+ */
1592
+ async getSignatureFromEvents(requestId, fromBlock) {
1593
+ const logs = await this.publicClient.getContractEvents({
1594
+ address: this.contractAddress,
1595
+ abi,
1596
+ eventName: "SignatureResponded",
1597
+ args: { requestId },
1598
+ fromBlock,
1599
+ toBlock: "latest"
1600
+ });
1601
+ if (logs.length > 0) {
1602
+ const { args: signatureData } = logs[logs.length - 1];
1603
+ return toRSV(signatureData.signature);
1604
+ }
1605
+ }
1606
+ };
1607
+
1608
+ //#endregion
1609
+ //#region src/contracts/evm/index.ts
1610
+ var evm_exports = /* @__PURE__ */ __export({
1611
+ ChainSignatureContract: () => ChainSignatureContract$2,
1612
+ utils: () => utils$1
1613
+ });
1614
+ const utils$1 = {
1615
+ ChainSignaturesContractABI: ChainSignaturesContractABI_exports,
1616
+ errors: errors_exports$1
1617
+ };
1618
+
1619
+ //#endregion
1620
+ //#region src/contracts/solana/errors.ts
1621
+ var errors_exports = /* @__PURE__ */ __export({
1622
+ ResponseError: () => ResponseError,
1623
+ SignatureContractError: () => SignatureContractError,
1624
+ SignatureNotFoundError: () => SignatureNotFoundError,
1625
+ SigningError: () => SigningError
1626
+ });
1627
+ var SignatureNotFoundError = class extends Error {
1628
+ constructor(requestId, metadata$1) {
1629
+ const message = requestId ? `Signature not found for request ID: ${requestId}` : "Signature not found";
1630
+ super(message);
1631
+ this.name = "SignatureNotFoundError";
1632
+ this.requestId = requestId;
1633
+ this.hash = metadata$1?.hash;
1634
+ }
1635
+ };
1636
+ var SignatureContractError = class extends Error {
1637
+ constructor(message, requestId, metadata$1) {
1638
+ super(message);
1639
+ this.name = "SignatureContractError";
1640
+ this.requestId = requestId;
1641
+ this.hash = metadata$1?.hash;
1642
+ }
1643
+ };
1644
+ var SigningError = class extends Error {
1645
+ constructor(requestId, metadata$1, originalError) {
1646
+ super(`Signing error for request ID: ${requestId}`);
1647
+ this.name = "SigningError";
1648
+ this.requestId = requestId;
1649
+ this.hash = metadata$1?.hash;
1650
+ this.originalError = originalError;
1651
+ }
1652
+ };
1653
+ var ResponseError = class extends Error {
1654
+ constructor(message) {
1655
+ super(message);
1656
+ this.name = "ResponseError";
1657
+ }
1658
+ };
1659
+
1660
+ //#endregion
1661
+ //#region src/contracts/solana/types/chain_signatures_project.json
1662
+ var chain_signatures_project_exports = /* @__PURE__ */ __export({
1663
+ accounts: () => accounts,
1664
+ address: () => address,
1665
+ default: () => chain_signatures_project_default,
1666
+ errors: () => errors,
1667
+ events: () => events,
1668
+ instructions: () => instructions,
1669
+ metadata: () => metadata,
1670
+ types: () => types
1671
+ });
1672
+ var address = "H5tHfpYoEnarrrzcV7sWBcZhiKMvL2aRpUYvb1ydWkwS";
1673
+ var metadata = {
1674
+ "name": "chain_signatures",
1675
+ "version": "0.4.0",
1676
+ "spec": "0.1.0",
1677
+ "description": "Chain signatures program for cross-chain signing on Solana",
1678
+ "repository": "https://github.com/sig-net/signet-solana-program"
1679
+ };
1680
+ var instructions = [
1681
+ {
1682
+ "name": "get_signature_deposit",
1683
+ "docs": ["* @dev Function to get the current signature deposit amount.\n * @return The current signature deposit amount."],
1684
+ "discriminator": [
1685
+ 45,
1686
+ 243,
1687
+ 86,
1688
+ 86,
1689
+ 58,
1690
+ 57,
1691
+ 172,
1692
+ 253
1693
+ ],
1694
+ "accounts": [{
1695
+ "name": "program_state",
1696
+ "pda": { "seeds": [{
1697
+ "kind": "const",
1698
+ "value": [
1699
+ 112,
1700
+ 114,
1701
+ 111,
1702
+ 103,
1703
+ 114,
1704
+ 97,
1705
+ 109,
1706
+ 45,
1707
+ 115,
1708
+ 116,
1709
+ 97,
1710
+ 116,
1711
+ 101
1712
+ ]
1713
+ }] }
1714
+ }],
1715
+ "args": [],
1716
+ "returns": "u64"
1717
+ },
1718
+ {
1719
+ "name": "initialize",
1720
+ "docs": ["* @dev Function to initialize the program state.\n * @param signature_deposit The deposit required for signature requests.\n * @param chain_id The CAIP-2 chain identifier."],
1721
+ "discriminator": [
1722
+ 175,
1723
+ 175,
1724
+ 109,
1725
+ 31,
1726
+ 13,
1727
+ 152,
1728
+ 155,
1729
+ 237
1730
+ ],
1731
+ "accounts": [
1732
+ {
1733
+ "name": "program_state",
1734
+ "writable": true,
1735
+ "pda": { "seeds": [{
1736
+ "kind": "const",
1737
+ "value": [
1738
+ 112,
1739
+ 114,
1740
+ 111,
1741
+ 103,
1742
+ 114,
1743
+ 97,
1744
+ 109,
1745
+ 45,
1746
+ 115,
1747
+ 116,
1748
+ 97,
1749
+ 116,
1750
+ 101
1751
+ ]
1752
+ }] }
1753
+ },
1754
+ {
1755
+ "name": "admin",
1756
+ "writable": true,
1757
+ "signer": true
1758
+ },
1759
+ {
1760
+ "name": "system_program",
1761
+ "address": "11111111111111111111111111111111"
1762
+ }
1763
+ ],
1764
+ "args": [{
1765
+ "name": "signature_deposit",
1766
+ "type": "u64"
1767
+ }, {
1768
+ "name": "chain_id",
1769
+ "type": "string"
1770
+ }]
1771
+ },
1772
+ {
1773
+ "name": "respond",
1774
+ "docs": ["* @dev Function to respond to signature requests.\n * @param request_ids The array of request IDs.\n * @param signatures The array of signature responses.\n * @notice When multiple entries reuse a request id, events emit in canonical signature order (PSBT-style)."],
1775
+ "discriminator": [
1776
+ 72,
1777
+ 65,
1778
+ 227,
1779
+ 97,
1780
+ 42,
1781
+ 255,
1782
+ 147,
1783
+ 12
1784
+ ],
1785
+ "accounts": [
1786
+ {
1787
+ "name": "responder",
1788
+ "signer": true
1789
+ },
1790
+ {
1791
+ "name": "event_authority",
1792
+ "pda": { "seeds": [{
1793
+ "kind": "const",
1794
+ "value": [
1795
+ 95,
1796
+ 95,
1797
+ 101,
1798
+ 118,
1799
+ 101,
1800
+ 110,
1801
+ 116,
1802
+ 95,
1803
+ 97,
1804
+ 117,
1805
+ 116,
1806
+ 104,
1807
+ 111,
1808
+ 114,
1809
+ 105,
1810
+ 116,
1811
+ 121
1812
+ ]
1813
+ }] }
1814
+ },
1815
+ { "name": "program" }
1816
+ ],
1817
+ "args": [{
1818
+ "name": "request_ids",
1819
+ "type": { "vec": { "array": ["u8", 32] } }
1820
+ }, {
1821
+ "name": "signatures",
1822
+ "type": { "vec": { "defined": { "name": "Signature" } } }
1823
+ }]
1824
+ },
1825
+ {
1826
+ "name": "respond_bidirectional",
1827
+ "docs": ["* @dev Function to finalize bidirectional flow\n * @param request_id The ID of the signature request to respond to\n * @param serialized_output output of the previously executed transaction\n * @param signature ECDSA signature of the serialized output and request_id (keccak256(request_id.concat(serialized_output)))"],
1828
+ "discriminator": [
1829
+ 138,
1830
+ 0,
1831
+ 45,
1832
+ 246,
1833
+ 236,
1834
+ 211,
1835
+ 109,
1836
+ 81
1837
+ ],
1838
+ "accounts": [{
1839
+ "name": "responder",
1840
+ "signer": true
1841
+ }],
1842
+ "args": [
1843
+ {
1844
+ "name": "request_id",
1845
+ "type": { "array": ["u8", 32] }
1846
+ },
1847
+ {
1848
+ "name": "serialized_output",
1849
+ "type": "bytes"
1850
+ },
1851
+ {
1852
+ "name": "signature",
1853
+ "type": { "defined": { "name": "Signature" } }
1854
+ }
1855
+ ]
1856
+ },
1857
+ {
1858
+ "name": "respond_error",
1859
+ "docs": ["* @dev Function to emit signature generation errors.\n * @param errors The array of signature generation errors."],
1860
+ "discriminator": [
1861
+ 3,
1862
+ 170,
1863
+ 41,
1864
+ 132,
1865
+ 72,
1866
+ 184,
1867
+ 252,
1868
+ 69
1869
+ ],
1870
+ "accounts": [{
1871
+ "name": "responder",
1872
+ "signer": true
1873
+ }],
1874
+ "args": [{
1875
+ "name": "errors",
1876
+ "type": { "vec": { "defined": { "name": "ErrorResponse" } } }
1877
+ }]
1878
+ },
1879
+ {
1880
+ "name": "sign",
1881
+ "docs": ["* @dev Function to request a signature.\n * @param payload The payload to be signed.\n * @param key_version The version of the key used for signing.\n * @param path The derivation path for the user account.\n * @param algo The algorithm used for signing.\n * @param dest The response destination.\n * @param params Additional parameters."],
1882
+ "discriminator": [
1883
+ 5,
1884
+ 221,
1885
+ 155,
1886
+ 46,
1887
+ 237,
1888
+ 91,
1889
+ 28,
1890
+ 236
1891
+ ],
1892
+ "accounts": [
1893
+ {
1894
+ "name": "program_state",
1895
+ "writable": true,
1896
+ "pda": { "seeds": [{
1897
+ "kind": "const",
1898
+ "value": [
1899
+ 112,
1900
+ 114,
1901
+ 111,
1902
+ 103,
1903
+ 114,
1904
+ 97,
1905
+ 109,
1906
+ 45,
1907
+ 115,
1908
+ 116,
1909
+ 97,
1910
+ 116,
1911
+ 101
1912
+ ]
1913
+ }] }
1914
+ },
1915
+ {
1916
+ "name": "requester",
1917
+ "writable": true,
1918
+ "signer": true
1919
+ },
1920
+ {
1921
+ "name": "fee_payer",
1922
+ "writable": true,
1923
+ "signer": true,
1924
+ "optional": true
1925
+ },
1926
+ {
1927
+ "name": "system_program",
1928
+ "address": "11111111111111111111111111111111"
1929
+ },
1930
+ {
1931
+ "name": "event_authority",
1932
+ "pda": { "seeds": [{
1933
+ "kind": "const",
1934
+ "value": [
1935
+ 95,
1936
+ 95,
1937
+ 101,
1938
+ 118,
1939
+ 101,
1940
+ 110,
1941
+ 116,
1942
+ 95,
1943
+ 97,
1944
+ 117,
1945
+ 116,
1946
+ 104,
1947
+ 111,
1948
+ 114,
1949
+ 105,
1950
+ 116,
1951
+ 121
1952
+ ]
1953
+ }] }
1954
+ },
1955
+ { "name": "program" }
1956
+ ],
1957
+ "args": [
1958
+ {
1959
+ "name": "payload",
1960
+ "type": { "array": ["u8", 32] }
1961
+ },
1962
+ {
1963
+ "name": "key_version",
1964
+ "type": "u32"
1965
+ },
1966
+ {
1967
+ "name": "path",
1968
+ "type": "string"
1969
+ },
1970
+ {
1971
+ "name": "algo",
1972
+ "type": "string"
1973
+ },
1974
+ {
1975
+ "name": "dest",
1976
+ "type": "string"
1977
+ },
1978
+ {
1979
+ "name": "params",
1980
+ "type": "string"
1981
+ }
1982
+ ]
1983
+ },
1984
+ {
1985
+ "name": "sign_bidirectional",
1986
+ "docs": ["* @dev Function to initiate bidirectional flow\n * @param serialized_transaction transaction to be signed\n * @param caip2_id chain identifier\n * @param key_version The version of the key used for signing.\n * @param path The derivation path for the user account.\n * @param algo The algorithm used for signing.\n * @param dest The response destination.\n * @param params Additional parameters.\n * @param program_id Program ID to callback after execution (not yet enabled).\n * @param output_deserialization_schema schema for transaction output deserialization\n * @param respond_serialization_schema serialization schema for respond_bidirectional payload"],
1987
+ "discriminator": [
1988
+ 21,
1989
+ 104,
1990
+ 182,
1991
+ 213,
1992
+ 189,
1993
+ 143,
1994
+ 219,
1995
+ 48
1996
+ ],
1997
+ "accounts": [
1998
+ {
1999
+ "name": "program_state",
2000
+ "writable": true,
2001
+ "pda": { "seeds": [{
2002
+ "kind": "const",
2003
+ "value": [
2004
+ 112,
2005
+ 114,
2006
+ 111,
2007
+ 103,
2008
+ 114,
2009
+ 97,
2010
+ 109,
2011
+ 45,
2012
+ 115,
2013
+ 116,
2014
+ 97,
2015
+ 116,
2016
+ 101
2017
+ ]
2018
+ }] }
2019
+ },
2020
+ {
2021
+ "name": "requester",
2022
+ "writable": true,
2023
+ "signer": true
2024
+ },
2025
+ {
2026
+ "name": "fee_payer",
2027
+ "writable": true,
2028
+ "signer": true,
2029
+ "optional": true
2030
+ },
2031
+ {
2032
+ "name": "system_program",
2033
+ "address": "11111111111111111111111111111111"
2034
+ },
2035
+ {
2036
+ "name": "instructions",
2037
+ "optional": true
2038
+ },
2039
+ {
2040
+ "name": "event_authority",
2041
+ "pda": { "seeds": [{
2042
+ "kind": "const",
2043
+ "value": [
2044
+ 95,
2045
+ 95,
2046
+ 101,
2047
+ 118,
2048
+ 101,
2049
+ 110,
2050
+ 116,
2051
+ 95,
2052
+ 97,
2053
+ 117,
2054
+ 116,
2055
+ 104,
2056
+ 111,
2057
+ 114,
2058
+ 105,
2059
+ 116,
2060
+ 121
2061
+ ]
2062
+ }] }
2063
+ },
2064
+ { "name": "program" }
2065
+ ],
2066
+ "args": [
2067
+ {
2068
+ "name": "serialized_transaction",
2069
+ "type": "bytes"
2070
+ },
2071
+ {
2072
+ "name": "caip2_id",
2073
+ "type": "string"
2074
+ },
2075
+ {
2076
+ "name": "key_version",
2077
+ "type": "u32"
2078
+ },
2079
+ {
2080
+ "name": "path",
2081
+ "type": "string"
2082
+ },
2083
+ {
2084
+ "name": "algo",
2085
+ "type": "string"
2086
+ },
2087
+ {
2088
+ "name": "dest",
2089
+ "type": "string"
2090
+ },
2091
+ {
2092
+ "name": "params",
2093
+ "type": "string"
2094
+ },
2095
+ {
2096
+ "name": "program_id",
2097
+ "type": "pubkey"
2098
+ },
2099
+ {
2100
+ "name": "output_deserialization_schema",
2101
+ "type": "bytes"
2102
+ },
2103
+ {
2104
+ "name": "respond_serialization_schema",
2105
+ "type": "bytes"
2106
+ }
2107
+ ]
2108
+ },
2109
+ {
2110
+ "name": "update_deposit",
2111
+ "docs": ["* @dev Function to set the signature deposit amount.\n * @param new_deposit The new deposit amount."],
2112
+ "discriminator": [
2113
+ 126,
2114
+ 116,
2115
+ 15,
2116
+ 164,
2117
+ 238,
2118
+ 179,
2119
+ 155,
2120
+ 59
2121
+ ],
2122
+ "accounts": [
2123
+ {
2124
+ "name": "program_state",
2125
+ "writable": true,
2126
+ "pda": { "seeds": [{
2127
+ "kind": "const",
2128
+ "value": [
2129
+ 112,
2130
+ 114,
2131
+ 111,
2132
+ 103,
2133
+ 114,
2134
+ 97,
2135
+ 109,
2136
+ 45,
2137
+ 115,
2138
+ 116,
2139
+ 97,
2140
+ 116,
2141
+ 101
2142
+ ]
2143
+ }] }
2144
+ },
2145
+ {
2146
+ "name": "admin",
2147
+ "writable": true,
2148
+ "signer": true,
2149
+ "relations": ["program_state"]
2150
+ },
2151
+ {
2152
+ "name": "system_program",
2153
+ "address": "11111111111111111111111111111111"
2154
+ }
2155
+ ],
2156
+ "args": [{
2157
+ "name": "new_deposit",
2158
+ "type": "u64"
2159
+ }]
2160
+ },
2161
+ {
2162
+ "name": "withdraw_funds",
2163
+ "docs": ["* @dev Function to withdraw funds from the program.\n * @param amount The amount to withdraw."],
2164
+ "discriminator": [
2165
+ 241,
2166
+ 36,
2167
+ 29,
2168
+ 111,
2169
+ 208,
2170
+ 31,
2171
+ 104,
2172
+ 217
2173
+ ],
2174
+ "accounts": [
2175
+ {
2176
+ "name": "program_state",
2177
+ "writable": true,
2178
+ "pda": { "seeds": [{
2179
+ "kind": "const",
2180
+ "value": [
2181
+ 112,
2182
+ 114,
2183
+ 111,
2184
+ 103,
2185
+ 114,
2186
+ 97,
2187
+ 109,
2188
+ 45,
2189
+ 115,
2190
+ 116,
2191
+ 97,
2192
+ 116,
2193
+ 101
2194
+ ]
2195
+ }] }
2196
+ },
2197
+ {
2198
+ "name": "admin",
2199
+ "writable": true,
2200
+ "signer": true,
2201
+ "relations": ["program_state"]
2202
+ },
2203
+ {
2204
+ "name": "recipient",
2205
+ "docs": ["function by checking it is not the zero address."],
2206
+ "writable": true
2207
+ },
2208
+ {
2209
+ "name": "system_program",
2210
+ "address": "11111111111111111111111111111111"
2211
+ }
2212
+ ],
2213
+ "args": [{
2214
+ "name": "amount",
2215
+ "type": "u64"
2216
+ }]
2217
+ }
2218
+ ];
2219
+ var accounts = [{
2220
+ "name": "ProgramState",
2221
+ "discriminator": [
2222
+ 77,
2223
+ 209,
2224
+ 137,
2225
+ 229,
2226
+ 149,
2227
+ 67,
2228
+ 167,
2229
+ 230
2230
+ ]
2231
+ }];
2232
+ var events = [
2233
+ {
2234
+ "name": "DepositUpdatedEvent",
2235
+ "discriminator": [
2236
+ 215,
2237
+ 193,
2238
+ 53,
2239
+ 27,
2240
+ 221,
2241
+ 101,
2242
+ 249,
2243
+ 108
2244
+ ]
2245
+ },
2246
+ {
2247
+ "name": "FundsWithdrawnEvent",
2248
+ "discriminator": [
2249
+ 86,
2250
+ 232,
2251
+ 194,
2252
+ 4,
2253
+ 211,
2254
+ 69,
2255
+ 172,
2256
+ 202
2257
+ ]
2258
+ },
2259
+ {
2260
+ "name": "RespondBidirectionalEvent",
2261
+ "discriminator": [
2262
+ 195,
2263
+ 195,
2264
+ 28,
2265
+ 1,
2266
+ 102,
2267
+ 100,
2268
+ 189,
2269
+ 234
2270
+ ]
2271
+ },
2272
+ {
2273
+ "name": "SignBidirectionalEvent",
2274
+ "discriminator": [
2275
+ 135,
2276
+ 205,
2277
+ 217,
2278
+ 152,
2279
+ 96,
2280
+ 187,
2281
+ 11,
2282
+ 124
2283
+ ]
2284
+ },
2285
+ {
2286
+ "name": "SignatureErrorEvent",
2287
+ "discriminator": [
2288
+ 42,
2289
+ 28,
2290
+ 210,
2291
+ 105,
2292
+ 9,
2293
+ 196,
2294
+ 189,
2295
+ 51
2296
+ ]
2297
+ },
2298
+ {
2299
+ "name": "SignatureRequestedEvent",
2300
+ "discriminator": [
2301
+ 171,
2302
+ 129,
2303
+ 105,
2304
+ 91,
2305
+ 154,
2306
+ 49,
2307
+ 160,
2308
+ 34
2309
+ ]
2310
+ },
2311
+ {
2312
+ "name": "SignatureRespondedEvent",
2313
+ "discriminator": [
2314
+ 118,
2315
+ 146,
2316
+ 248,
2317
+ 151,
2318
+ 194,
2319
+ 93,
2320
+ 18,
2321
+ 86
2322
+ ]
2323
+ }
2324
+ ];
2325
+ var errors = [
2326
+ {
2327
+ "code": 6e3,
2328
+ "name": "InsufficientDeposit",
2329
+ "msg": "Insufficient deposit amount"
2330
+ },
2331
+ {
2332
+ "code": 6001,
2333
+ "name": "InvalidInputLength",
2334
+ "msg": "Arrays must have the same length"
2335
+ },
2336
+ {
2337
+ "code": 6002,
2338
+ "name": "Unauthorized",
2339
+ "msg": "Unauthorized access"
2340
+ },
2341
+ {
2342
+ "code": 6003,
2343
+ "name": "InsufficientFunds",
2344
+ "msg": "Insufficient funds for withdrawal"
2345
+ },
2346
+ {
2347
+ "code": 6004,
2348
+ "name": "InvalidRecipient",
2349
+ "msg": "Invalid recipient address"
2350
+ },
2351
+ {
2352
+ "code": 6005,
2353
+ "name": "InvalidTransaction",
2354
+ "msg": "Invalid transaction data"
2355
+ },
2356
+ {
2357
+ "code": 6006,
2358
+ "name": "MissingInstructionSysvar",
2359
+ "msg": "Missing instruction sysvar"
2360
+ }
2361
+ ];
2362
+ var types = [
2363
+ {
2364
+ "name": "AffinePoint",
2365
+ "type": {
2366
+ "kind": "struct",
2367
+ "fields": [{
2368
+ "name": "x",
2369
+ "type": { "array": ["u8", 32] }
2370
+ }, {
2371
+ "name": "y",
2372
+ "type": { "array": ["u8", 32] }
2373
+ }]
2374
+ }
2375
+ },
2376
+ {
2377
+ "name": "DepositUpdatedEvent",
2378
+ "docs": ["* @dev Emitted when the deposit amount is updated.\n * @param old_deposit The previous deposit amount.\n * @param new_deposit The new deposit amount."],
2379
+ "type": {
2380
+ "kind": "struct",
2381
+ "fields": [{
2382
+ "name": "old_deposit",
2383
+ "type": "u64"
2384
+ }, {
2385
+ "name": "new_deposit",
2386
+ "type": "u64"
2387
+ }]
2388
+ }
2389
+ },
2390
+ {
2391
+ "name": "ErrorResponse",
2392
+ "type": {
2393
+ "kind": "struct",
2394
+ "fields": [{
2395
+ "name": "request_id",
2396
+ "type": { "array": ["u8", 32] }
2397
+ }, {
2398
+ "name": "error_message",
2399
+ "type": "string"
2400
+ }]
2401
+ }
2402
+ },
2403
+ {
2404
+ "name": "FundsWithdrawnEvent",
2405
+ "docs": ["* @dev Emitted when a withdrawal is made.\n * @param amount The amount withdrawn.\n * @param recipient The address of the recipient."],
2406
+ "type": {
2407
+ "kind": "struct",
2408
+ "fields": [{
2409
+ "name": "amount",
2410
+ "type": "u64"
2411
+ }, {
2412
+ "name": "recipient",
2413
+ "type": "pubkey"
2414
+ }]
2415
+ }
2416
+ },
2417
+ {
2418
+ "name": "ProgramState",
2419
+ "type": {
2420
+ "kind": "struct",
2421
+ "fields": [
2422
+ {
2423
+ "name": "admin",
2424
+ "type": "pubkey"
2425
+ },
2426
+ {
2427
+ "name": "signature_deposit",
2428
+ "type": "u64"
2429
+ },
2430
+ {
2431
+ "name": "chain_id",
2432
+ "type": "string"
2433
+ }
2434
+ ]
2435
+ }
2436
+ },
2437
+ {
2438
+ "name": "RespondBidirectionalEvent",
2439
+ "docs": ["* @dev Emitted when a read response is received.\n * @param request_id The ID of the request. Must be calculated off-chain.\n * @param responder The address of the responder.\n * @param serialized_output The serialized output.\n * @param signature The signature."],
2440
+ "type": {
2441
+ "kind": "struct",
2442
+ "fields": [
2443
+ {
2444
+ "name": "request_id",
2445
+ "type": { "array": ["u8", 32] }
2446
+ },
2447
+ {
2448
+ "name": "responder",
2449
+ "type": "pubkey"
2450
+ },
2451
+ {
2452
+ "name": "serialized_output",
2453
+ "type": "bytes"
2454
+ },
2455
+ {
2456
+ "name": "signature",
2457
+ "type": { "defined": { "name": "Signature" } }
2458
+ }
2459
+ ]
2460
+ }
2461
+ },
2462
+ {
2463
+ "name": "SignBidirectionalEvent",
2464
+ "docs": ["* @dev Emitted when a sign_bidirectional request is made.\n * @param sender The address of the sender.\n * @param serialized_transaction The serialized transaction to be signed.\n * @param caip2_id The SLIP-44 chain ID.\n * @param key_version The version of the key used for signing.\n * @param deposit The deposit amount.\n * @param path The derivation path for the user account.\n * @param algo The algorithm used for signing.\n * @param dest The response destination.\n * @param params Additional parameters.\n * @param program_id Program ID to callback after execution (not yet enabled).\n * @param output_deserialization_schema Schema for transaction output deserialization.\n * @param respond_serialization_schema Serialization schema for respond_bidirectional payload."],
2465
+ "type": {
2466
+ "kind": "struct",
2467
+ "fields": [
2468
+ {
2469
+ "name": "sender",
2470
+ "type": "pubkey"
2471
+ },
2472
+ {
2473
+ "name": "serialized_transaction",
2474
+ "type": "bytes"
2475
+ },
2476
+ {
2477
+ "name": "caip2_id",
2478
+ "type": "string"
2479
+ },
2480
+ {
2481
+ "name": "key_version",
2482
+ "type": "u32"
2483
+ },
2484
+ {
2485
+ "name": "deposit",
2486
+ "type": "u64"
2487
+ },
2488
+ {
2489
+ "name": "path",
2490
+ "type": "string"
2491
+ },
2492
+ {
2493
+ "name": "algo",
2494
+ "type": "string"
2495
+ },
2496
+ {
2497
+ "name": "dest",
2498
+ "type": "string"
2499
+ },
2500
+ {
2501
+ "name": "params",
2502
+ "type": "string"
2503
+ },
2504
+ {
2505
+ "name": "program_id",
2506
+ "type": "pubkey"
2507
+ },
2508
+ {
2509
+ "name": "output_deserialization_schema",
2510
+ "type": "bytes"
2511
+ },
2512
+ {
2513
+ "name": "respond_serialization_schema",
2514
+ "type": "bytes"
2515
+ }
2516
+ ]
2517
+ }
2518
+ },
2519
+ {
2520
+ "name": "Signature",
2521
+ "type": {
2522
+ "kind": "struct",
2523
+ "fields": [
2524
+ {
2525
+ "name": "big_r",
2526
+ "type": { "defined": { "name": "AffinePoint" } }
2527
+ },
2528
+ {
2529
+ "name": "s",
2530
+ "type": { "array": ["u8", 32] }
2531
+ },
2532
+ {
2533
+ "name": "recovery_id",
2534
+ "type": "u8"
2535
+ }
2536
+ ]
2537
+ }
2538
+ },
2539
+ {
2540
+ "name": "SignatureErrorEvent",
2541
+ "docs": ["* @dev Emitted when a signature error is received.\n * @notice Any address can emit this event. Do not rely on it for business logic.\n * @param request_id The ID of the request. Must be calculated off-chain.\n * @param responder The address of the responder.\n * @param error The error message."],
2542
+ "type": {
2543
+ "kind": "struct",
2544
+ "fields": [
2545
+ {
2546
+ "name": "request_id",
2547
+ "type": { "array": ["u8", 32] }
2548
+ },
2549
+ {
2550
+ "name": "responder",
2551
+ "type": "pubkey"
2552
+ },
2553
+ {
2554
+ "name": "error",
2555
+ "type": "string"
2556
+ }
2557
+ ]
2558
+ }
2559
+ },
2560
+ {
2561
+ "name": "SignatureRequestedEvent",
2562
+ "docs": ["* @dev Emitted when a signature is requested.\n * @param sender The address of the sender.\n * @param payload The payload to be signed.\n * @param key_version The version of the key used for signing.\n * @param deposit The deposit amount.\n * @param chain_id The CAIP-2 ID of the blockchain.\n * @param path The derivation path for the user account.\n * @param algo The algorithm used for signing.\n * @param dest The response destination.\n * @param params Additional parameters.\n * @param fee_payer Optional fee payer account."],
2563
+ "type": {
2564
+ "kind": "struct",
2565
+ "fields": [
2566
+ {
2567
+ "name": "sender",
2568
+ "type": "pubkey"
2569
+ },
2570
+ {
2571
+ "name": "payload",
2572
+ "type": { "array": ["u8", 32] }
2573
+ },
2574
+ {
2575
+ "name": "key_version",
2576
+ "type": "u32"
2577
+ },
2578
+ {
2579
+ "name": "deposit",
2580
+ "type": "u64"
2581
+ },
2582
+ {
2583
+ "name": "chain_id",
2584
+ "type": "string"
2585
+ },
2586
+ {
2587
+ "name": "path",
2588
+ "type": "string"
2589
+ },
2590
+ {
2591
+ "name": "algo",
2592
+ "type": "string"
2593
+ },
2594
+ {
2595
+ "name": "dest",
2596
+ "type": "string"
2597
+ },
2598
+ {
2599
+ "name": "params",
2600
+ "type": "string"
2601
+ },
2602
+ {
2603
+ "name": "fee_payer",
2604
+ "type": { "option": "pubkey" }
2605
+ }
2606
+ ]
2607
+ }
2608
+ },
2609
+ {
2610
+ "name": "SignatureRespondedEvent",
2611
+ "docs": ["* @dev Emitted when a signature response is received.\n * @notice Any address can emit this event. Clients should always verify the validity of the signature.\n * @param request_id The ID of the request. Must be calculated off-chain.\n * @param responder The address of the responder.\n * @param signature The signature response."],
2612
+ "type": {
2613
+ "kind": "struct",
2614
+ "fields": [
2615
+ {
2616
+ "name": "request_id",
2617
+ "type": { "array": ["u8", 32] }
2618
+ },
2619
+ {
2620
+ "name": "responder",
2621
+ "type": "pubkey"
2622
+ },
2623
+ {
2624
+ "name": "signature",
2625
+ "type": { "defined": { "name": "Signature" } }
2626
+ }
2627
+ ]
2628
+ }
2629
+ }
2630
+ ];
2631
+ var chain_signatures_project_default = {
2632
+ address,
2633
+ metadata,
2634
+ instructions,
2635
+ accounts,
2636
+ events,
2637
+ errors,
2638
+ types
2639
+ };
2640
+
2641
+ //#endregion
2642
+ //#region src/contracts/solana/CpiEventParser.ts
2643
+ const EMIT_CPI_INSTRUCTION_DISCRIMINATOR = Buffer.from([
2644
+ 228,
2645
+ 69,
2646
+ 165,
2647
+ 46,
2648
+ 81,
2649
+ 203,
2650
+ 154,
2651
+ 29
2652
+ ]);
2653
+ var CpiEventParser = class {
2654
+ /**
2655
+ * Parse CPI events from a transaction (emit_cpi! pattern)
2656
+ */
2657
+ static async parseCpiEvents(connection, signature, targetProgramId, program) {
2658
+ const events$1 = [];
2659
+ try {
2660
+ const tx = await connection.getParsedTransaction(signature, {
2661
+ commitment: "confirmed",
2662
+ maxSupportedTransactionVersion: 0
2663
+ });
2664
+ if (!tx?.meta?.innerInstructions) return events$1;
2665
+ for (const innerIxSet of tx.meta.innerInstructions) for (const instruction of innerIxSet.instructions) {
2666
+ if (!("programId" in instruction) || !("data" in instruction)) continue;
2667
+ if (instruction.programId.toString() !== targetProgramId) continue;
2668
+ const parsedEvent = this.parseInstruction(instruction.data, program);
2669
+ if (parsedEvent) events$1.push(parsedEvent);
2670
+ }
2671
+ } catch {}
2672
+ return events$1;
2673
+ }
2674
+ /**
2675
+ * Parse CPI event from instruction data
2676
+ * Structure: [8 bytes: anchor discriminator][8 bytes: event discriminator][event data]
2677
+ */
2678
+ static parseInstruction(instructionData, program) {
2679
+ try {
2680
+ const ixData = anchor.utils.bytes.bs58.decode(instructionData);
2681
+ if (ixData.length < 16) return null;
2682
+ const ixDiscriminator = ixData.subarray(0, 8);
2683
+ if (Buffer.compare(ixDiscriminator, EMIT_CPI_INSTRUCTION_DISCRIMINATOR) !== 0) return null;
2684
+ const eventDiscriminator = ixData.subarray(8, 16);
2685
+ if (!program.idl.events?.find((event) => {
2686
+ const idlDiscriminator = Buffer.from(event.discriminator);
2687
+ return Buffer.compare(eventDiscriminator, idlDiscriminator) === 0;
2688
+ })) return null;
2689
+ const fullEventData = ixData.subarray(8);
2690
+ return program.coder.events.decode(anchor.utils.bytes.base64.encode(fullEventData));
2691
+ } catch {
2692
+ return null;
2693
+ }
2694
+ }
2695
+ /**
2696
+ * Subscribe to CPI events for a program
2697
+ */
2698
+ static subscribeToCpiEvents(connection, program, eventHandlers) {
2699
+ return connection.onLogs(program.programId, (logs, context) => {
2700
+ if (logs.err) return;
2701
+ (async () => {
2702
+ const events$1 = await this.parseCpiEvents(connection, logs.signature, program.programId.toString(), program);
2703
+ for (const event of events$1) {
2704
+ const handler = eventHandlers.get(event.name);
2705
+ if (handler) try {
2706
+ await handler(event.data, context.slot);
2707
+ } catch {}
2708
+ }
2709
+ })();
2710
+ }, "confirmed");
2711
+ }
2712
+ };
2713
+
2714
+ //#endregion
2715
+ //#region src/contracts/solana/utils.ts
2716
+ function generateRequestIdSolana({ address: address$1, payload, path, keyVersion, chainId, algo, dest, params }) {
2717
+ const payloadHex = "0x" + Buffer.from(payload).toString("hex");
2718
+ return keccak256(encodeAbiParameters(parseAbiParameters("string, bytes, string, uint32, string, string, string, string"), [
2719
+ address$1,
2720
+ payloadHex,
2721
+ path,
2722
+ keyVersion,
2723
+ chainId,
2724
+ algo,
2725
+ dest,
2726
+ params
2727
+ ]));
2728
+ }
2729
+
2730
+ //#endregion
2731
+ //#region src/contracts/solana/ChainSignaturesContract.ts
2732
+ var ChainSignatureContract$1 = class extends ChainSignatureContract {
2733
+ /**
2734
+ * Creates a new instance of the ChainSignatureContract for Solana chains.
2735
+ *
2736
+ * @param args - Configuration options for the contract
2737
+ * @param args.provider - An Anchor Provider for interacting with Solana
2738
+ * @param args.programId - The program ID as a string or PublicKey
2739
+ * @param args.config - Optional configuration
2740
+ * @param args.config.rootPublicKey - Optional root public key. If not provided, it will be derived from the program ID
2741
+ * @param args.config.requesterAddress - Provider wallet address is always the fee payer but requester can be overridden
2742
+ * @param args.config.idl - Optional custom IDL. If not provided, the default ChainSignatures IDL will be used
2743
+ */
2744
+ constructor(args) {
2745
+ super();
2746
+ this.provider = args.provider;
2747
+ this.requesterAddress = args.config?.requesterAddress ?? this.provider.wallet.publicKey.toString();
2748
+ this.programId = typeof args.programId === "string" ? new PublicKey(args.programId) : args.programId;
2749
+ this.program = new Program({
2750
+ ...args.config?.idl || chain_signatures_project_default,
2751
+ address: this.programId.toString()
2752
+ }, this.provider);
2753
+ const rootPublicKey = args.config?.rootPublicKey || getRootPublicKey(this.programId.toString(), CHAINS.SOLANA);
2754
+ if (!rootPublicKey) throw new Error(`Invalid public key, please provide a valid root public key or program ID`);
2755
+ this.rootPublicKey = rootPublicKey;
2756
+ }
2757
+ /**
2758
+ * Gets the connection from the provider
2759
+ */
2760
+ get connection() {
2761
+ return this.provider.connection;
2762
+ }
2763
+ async getCurrentSignatureDeposit() {
2764
+ try {
2765
+ const programStatePDA = await this.getProgramStatePDA();
2766
+ return new BN((await this.program.account.programState.fetch(programStatePDA)).signatureDeposit.toString());
2767
+ } catch (error) {
2768
+ throw new Error(`Failed to get signature deposit: ${error instanceof Error ? error.message : String(error)}`);
2769
+ }
2770
+ }
2771
+ /**
2772
+ * Get the Program State PDA
2773
+ */
2774
+ async getProgramStatePDA() {
2775
+ const [pda] = PublicKey.findProgramAddressSync([Buffer.from("program-state")], this.programId);
2776
+ return pda;
2777
+ }
2778
+ async getDerivedPublicKey(args) {
2779
+ return deriveChildPublicKey(await this.getPublicKey(), args.predecessor, args.path, KDF_CHAIN_IDS.SOLANA, args.keyVersion);
2780
+ }
2781
+ async getPublicKey() {
2782
+ return najToUncompressedPubKeySEC1(this.rootPublicKey);
2783
+ }
2784
+ async getSignRequestInstruction(args, options) {
2785
+ const fixedRemainingAccounts = [{
2786
+ pubkey: PublicKey.findProgramAddressSync([Buffer.from("__event_authority")], this.program.programId)[0],
2787
+ isWritable: false,
2788
+ isSigner: false
2789
+ }, {
2790
+ pubkey: this.program.programId,
2791
+ isWritable: false,
2792
+ isSigner: false
2793
+ }];
2794
+ return await this.program.methods.sign(Array.from(args.payload), args.key_version, args.path, options?.sign?.algo || "", options?.sign?.dest || "", options?.sign?.params || "").accounts({
2795
+ requester: this.requesterAddress,
2796
+ feePayer: this.provider.wallet.publicKey,
2797
+ program: this.programId
2798
+ }).remainingAccounts([...fixedRemainingAccounts, ...options?.remainingAccounts ?? []]).instruction();
2799
+ }
2800
+ /**
2801
+ * Sends a transaction to the program to request a signature, then
2802
+ * polls for the signature result. If the signature is not found within the retry
2803
+ * parameters, it will throw an error.
2804
+ */
2805
+ async sign(args, options) {
2806
+ const algo = options?.sign?.algo ?? "";
2807
+ const dest = options?.sign?.dest ?? "";
2808
+ const params = options?.sign?.params ?? "";
2809
+ const delay = options?.retry?.delay ?? 5e3;
2810
+ const retryCount = options?.retry?.retryCount ?? 12;
2811
+ if (options?.remainingAccounts?.filter((acc) => acc.isSigner)?.some((acc) => !options?.remainingSigners?.some((signer) => signer.publicKey.equals(acc.pubkey)))) throw new Error("All accounts marked as signers must have a corresponding signer");
2812
+ const requestId = this.getRequestId(args, {
2813
+ algo,
2814
+ dest,
2815
+ params
2816
+ });
2817
+ const instruction = await this.getSignRequestInstruction(args, {
2818
+ sign: {
2819
+ algo,
2820
+ dest,
2821
+ params
2822
+ },
2823
+ remainingAccounts: options?.remainingAccounts
2824
+ });
2825
+ const transaction = new Transaction().add(instruction);
2826
+ transaction.feePayer = this.provider.wallet.publicKey;
2827
+ const hash = await this.sendAndConfirmWithoutWebSocket(transaction, options?.remainingSigners);
2828
+ try {
2829
+ const pollResult = await this.pollForRequestId({
2830
+ requestId,
2831
+ payload: args.payload,
2832
+ path: args.path,
2833
+ afterSignature: hash,
2834
+ options: {
2835
+ delay,
2836
+ retryCount
2837
+ }
2838
+ });
2839
+ if (!pollResult) throw new SignatureNotFoundError(requestId, { hash });
2840
+ if ("error" in pollResult) throw new SignatureContractError(pollResult.error, requestId, { hash });
2841
+ if (!await verifyRecoveredAddress(pollResult, args.payload, this.requesterAddress, args.path, this, args.key_version)) throw new SigningError(requestId, { hash }, /* @__PURE__ */ new Error("Signature verification failed: recovered address does not match expected address"));
2842
+ return pollResult;
2843
+ } catch (error) {
2844
+ if (error instanceof SignatureNotFoundError || error instanceof SignatureContractError) throw error;
2845
+ else throw new SigningError(requestId, { hash }, error instanceof Error ? error : void 0);
2846
+ }
2847
+ }
2848
+ async sendAndConfirmWithoutWebSocket(transaction, signers) {
2849
+ const { blockhash } = await this.provider.connection.getLatestBlockhash("confirmed");
2850
+ transaction.recentBlockhash = blockhash;
2851
+ transaction = await this.provider.wallet.signTransaction(transaction);
2852
+ if (signers && signers.length > 0) transaction.partialSign(...signers);
2853
+ const signature = await this.provider.connection.sendRawTransaction(transaction.serialize(), {
2854
+ skipPreflight: false,
2855
+ preflightCommitment: "processed",
2856
+ maxRetries: 3
2857
+ });
2858
+ const startTime = Date.now();
2859
+ const timeout = 3e4;
2860
+ while (Date.now() - startTime < timeout) {
2861
+ const status = await this.provider.connection.getSignatureStatus(signature);
2862
+ if (status.value?.err) throw new Error(`Transaction failed: ${JSON.stringify(status.value.err)}`);
2863
+ if (status.value?.confirmationStatus === "confirmed" || status.value?.confirmationStatus === "finalized") return signature;
2864
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
2865
+ }
2866
+ throw new TransactionExpiredTimeoutError(signature, timeout / 1e3);
2867
+ }
2868
+ /**
2869
+ * Polls for signature or error events matching the given requestId starting from the solana transaction with signature afterSignature.
2870
+ * Returns a signature, error data, or undefined if nothing is found.
2871
+ */
2872
+ async pollForRequestId({ requestId, payload: _payload, path: _path, afterSignature, options }) {
2873
+ const delay = options?.delay ?? 5e3;
2874
+ const retryCount = options?.retryCount ?? 12;
2875
+ let lastCheckedSignature = afterSignature;
2876
+ for (let i = 0; i < retryCount; i++) {
2877
+ try {
2878
+ const signatures = await this.connection.getSignaturesForAddress(this.programId, {
2879
+ until: lastCheckedSignature,
2880
+ limit: 50
2881
+ }, "confirmed");
2882
+ if (signatures.length > 0) lastCheckedSignature = signatures[signatures.length - 1].signature;
2883
+ for (const sig of signatures) {
2884
+ const tx = await this.connection.getParsedTransaction(sig.signature, {
2885
+ commitment: "confirmed",
2886
+ maxSupportedTransactionVersion: 0
2887
+ });
2888
+ if (tx?.meta?.logMessages) {
2889
+ const result = await this.parseLogsForEvents(tx.meta.logMessages, requestId, sig.signature);
2890
+ if (result) return result;
2891
+ }
2892
+ }
2893
+ } catch (error) {
2894
+ console.error("Error checking for events:", error);
2895
+ }
2896
+ if (i < retryCount - 1) {
2897
+ console.log(`Retrying get signature: ${i + 1}/${retryCount}`);
2898
+ await new Promise((resolve) => setTimeout(resolve, delay));
2899
+ }
2900
+ }
2901
+ }
2902
+ /**
2903
+ * Parses transaction logs for signature or error events.
2904
+ */
2905
+ async parseLogsForEvents(logs, requestId, signature) {
2906
+ const cpiEvents = await CpiEventParser.parseCpiEvents(this.connection, signature, this.programId.toString(), this.program);
2907
+ for (const event of cpiEvents) {
2908
+ const mapped = this.mapEventToResult(event.name, event.name === "signatureRespondedEvent" ? event.data : event.data, requestId);
2909
+ if (mapped) return mapped;
2910
+ }
2911
+ const parser = new EventParser(this.program.programId, this.program.coder);
2912
+ for (const evt of parser.parseLogs(logs)) {
2913
+ if (!evt) continue;
2914
+ const mapped = this.mapEventToResult(evt.name, evt.name === "signatureRespondedEvent" ? evt.data : evt.data, requestId);
2915
+ if (mapped) return mapped;
2916
+ }
2917
+ }
2918
+ mapEventToResult(name, data, requestId) {
2919
+ const eventRequestIdHex = "0x" + Buffer.from(data.requestId).toString("hex");
2920
+ if (name === "signatureRespondedEvent" && eventRequestIdHex === requestId) {
2921
+ const d = data;
2922
+ return {
2923
+ r: Buffer.from(d.signature.bigR.x).toString("hex"),
2924
+ s: Buffer.from(d.signature.s).toString("hex"),
2925
+ v: d.signature.recoveryId + 27
2926
+ };
2927
+ }
2928
+ if (name === "signatureErrorEvent" && eventRequestIdHex === requestId) return {
2929
+ requestId: eventRequestIdHex,
2930
+ error: data.error
2931
+ };
2932
+ }
2933
+ /**
2934
+ * Generates the request ID for a signature request allowing to track the response.
2935
+ */
2936
+ getRequestId(args, options = {
2937
+ algo: "",
2938
+ dest: "",
2939
+ params: ""
2940
+ }) {
2941
+ return generateRequestIdSolana({
2942
+ payload: args.payload,
2943
+ path: args.path,
2944
+ keyVersion: args.key_version,
2945
+ algo: options.algo || "",
2946
+ dest: options.dest || "",
2947
+ params: options.params || "",
2948
+ address: this.requesterAddress,
2949
+ chainId: KDF_CHAIN_IDS.SOLANA
2950
+ });
2951
+ }
2952
+ /**
2953
+ * Subscribes to program events using Anchor's EventParser for regular events,
2954
+ * and CPI parsing for emit_cpi!-emitted events. Returns an unsubscribe fn.
2955
+ */
2956
+ async subscribeToEvents(handlers) {
2957
+ const commitment = "confirmed";
2958
+ const cpiHandlers = /* @__PURE__ */ new Map();
2959
+ if (handlers.onSignatureResponded) {
2960
+ const onSignatureResponded = handlers.onSignatureResponded;
2961
+ cpiHandlers.set("signatureRespondedEvent", async (e, s) => {
2962
+ await onSignatureResponded(e, s);
2963
+ });
2964
+ }
2965
+ if (handlers.onSignatureError) {
2966
+ const onSignatureError = handlers.onSignatureError;
2967
+ cpiHandlers.set("signatureErrorEvent", async (e, s) => {
2968
+ await onSignatureError(e, s);
2969
+ });
2970
+ }
2971
+ const cpiSubId = CpiEventParser.subscribeToCpiEvents(this.connection, this.program, cpiHandlers);
2972
+ const parser = new EventParser(this.program.programId, this.program.coder);
2973
+ const subId = this.connection.onLogs(this.program.programId, (logs, context) => {
2974
+ if (logs.err) return;
2975
+ for (const evt of parser.parseLogs(logs.logs)) {
2976
+ if (!evt) continue;
2977
+ if (evt.name === "signatureRespondedEvent") {
2978
+ const onSignatureResponded = handlers.onSignatureResponded;
2979
+ if (onSignatureResponded) onSignatureResponded(evt.data, context.slot);
2980
+ }
2981
+ if (evt.name === "signatureErrorEvent") {
2982
+ const onSignatureError = handlers.onSignatureError;
2983
+ if (onSignatureError) onSignatureError(evt.data, context.slot);
2984
+ }
2985
+ }
2986
+ }, commitment);
2987
+ return async () => {
2988
+ await this.connection.removeOnLogsListener(subId);
2989
+ await this.connection.removeOnLogsListener(cpiSubId);
2990
+ };
2991
+ }
2992
+ };
2993
+
2994
+ //#endregion
2995
+ //#region src/contracts/solana/index.ts
2996
+ var solana_exports = /* @__PURE__ */ __export({
2997
+ ChainSignatureContract: () => ChainSignatureContract$1,
2998
+ utils: () => utils
2999
+ });
3000
+ const utils = {
3001
+ ChainSignaturesContractIdl: chain_signatures_project_exports,
3002
+ errors: errors_exports
3003
+ };
3004
+
3005
+ //#endregion
3006
+ //#region src/contracts/index.ts
3007
+ var contracts_exports = /* @__PURE__ */ __export({
3008
+ ChainSignatureContract: () => ChainSignatureContract,
3009
+ evm: () => evm_exports,
3010
+ solana: () => solana_exports
3011
+ });
3012
+
3013
+ //#endregion
3014
+ export { chain_adapters_exports as chainAdapters, constants_exports as constants, contracts_exports as contracts, utils_exports as utils };