signet.js 0.0.1-beta.6 → 0.0.1-beta.7

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.
Files changed (121) hide show
  1. package/.eslintrc.json +55 -0
  2. package/.prettierrc +1 -0
  3. package/LICENSE +19 -0
  4. package/README.md +42 -14
  5. package/babel.config.js +6 -0
  6. package/docs/pages/chain-signatures-contract.mdx +56 -0
  7. package/docs/pages/chain.mdx +45 -0
  8. package/docs/pages/chains/bitcoin/bitcoin.mdx +191 -0
  9. package/docs/pages/chains/bitcoin/btc-rpc-adapter.mdx +307 -0
  10. package/docs/pages/chains/cosmos.mdx +181 -0
  11. package/docs/pages/chains/evm.mdx +189 -0
  12. package/docs/pages/index.mdx +99 -0
  13. package/docs/snippets/contract.ts +21 -0
  14. package/docs/snippets/env.ts +13 -0
  15. package/jest.config.ts +199 -0
  16. package/package.json +21 -11
  17. package/src/chains/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.ts +11 -0
  18. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/Mempool.ts +96 -0
  19. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/index.ts +1 -0
  20. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/types.ts +72 -0
  21. package/src/chains/Bitcoin/BTCRpcAdapter/index.ts +6 -0
  22. package/src/chains/Bitcoin/Bitcoin.ts +301 -0
  23. package/src/chains/Bitcoin/types.ts +45 -0
  24. package/src/chains/Bitcoin/utils.ts +14 -0
  25. package/src/chains/Chain.ts +96 -0
  26. package/src/chains/ChainSignatureContract.ts +48 -0
  27. package/src/chains/Cosmos/Cosmos.ts +279 -0
  28. package/src/chains/Cosmos/types.ts +35 -0
  29. package/src/chains/Cosmos/utils.ts +45 -0
  30. package/src/chains/EVM/EVM.ts +180 -0
  31. package/src/chains/EVM/types.ts +7 -0
  32. package/src/chains/EVM/utils.ts +26 -0
  33. package/src/chains/index.ts +34 -0
  34. package/src/chains/types.ts +35 -0
  35. package/src/chains/utils.ts +40 -0
  36. package/src/index.ts +2 -0
  37. package/src/utils/chains/index.ts +1 -0
  38. package/src/utils/chains/near/ChainSignatureContract.ts +195 -0
  39. package/src/utils/chains/near/account.ts +42 -0
  40. package/src/utils/chains/near/constants.ts +4 -0
  41. package/src/utils/chains/near/index.ts +3 -0
  42. package/src/utils/chains/near/relayer/index.ts +1 -0
  43. package/src/utils/chains/near/relayer/relayer.ts +39 -0
  44. package/src/utils/chains/near/relayer/types.ts +24 -0
  45. package/src/utils/chains/near/signAndSend/index.ts +1 -0
  46. package/src/utils/chains/near/signAndSend/keypair.ts +180 -0
  47. package/src/utils/chains/near/transactionBuilder.ts +138 -0
  48. package/src/utils/chains/near/types.ts +67 -0
  49. package/src/utils/index.ts +1 -0
  50. package/tsconfig.eslint.json +8 -0
  51. package/tsconfig.json +116 -0
  52. package/vite.config.ts +47 -0
  53. package/vocs.config.ts +60 -0
  54. package/src/chains/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.d.ts +0 -10
  55. package/src/chains/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.js +0 -2
  56. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/Mempool.d.ts +0 -15
  57. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/Mempool.js +0 -69
  58. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/index.d.ts +0 -1
  59. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/index.js +0 -1
  60. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/types.d.ts +0 -69
  61. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/types.js +0 -1
  62. package/src/chains/Bitcoin/BTCRpcAdapter/index.d.ts +0 -5
  63. package/src/chains/Bitcoin/BTCRpcAdapter/index.js +0 -5
  64. package/src/chains/Bitcoin/Bitcoin.d.ts +0 -69
  65. package/src/chains/Bitcoin/Bitcoin.js +0 -198
  66. package/src/chains/Bitcoin/types.d.ts +0 -42
  67. package/src/chains/Bitcoin/types.js +0 -1
  68. package/src/chains/Bitcoin/utils.d.ts +0 -2
  69. package/src/chains/Bitcoin/utils.js +0 -13
  70. package/src/chains/Chain.d.ts +0 -89
  71. package/src/chains/Chain.js +0 -9
  72. package/src/chains/ChainSignatureContract.d.ts +0 -62
  73. package/src/chains/ChainSignatureContract.js +0 -7
  74. package/src/chains/Cosmos/Cosmos.d.ts +0 -51
  75. package/src/chains/Cosmos/Cosmos.js +0 -157
  76. package/src/chains/Cosmos/types.d.ts +0 -30
  77. package/src/chains/Cosmos/types.js +0 -1
  78. package/src/chains/Cosmos/utils.d.ts +0 -2
  79. package/src/chains/Cosmos/utils.js +0 -27
  80. package/src/chains/EVM/EVM.d.ts +0 -42
  81. package/src/chains/EVM/EVM.js +0 -109
  82. package/src/chains/EVM/types.d.ts +0 -5
  83. package/src/chains/EVM/types.js +0 -1
  84. package/src/chains/EVM/utils.d.ts +0 -7
  85. package/src/chains/EVM/utils.js +0 -14
  86. package/src/chains/index.d.ts +0 -12
  87. package/src/chains/index.js +0 -12
  88. package/src/chains/types.d.ts +0 -31
  89. package/src/chains/types.js +0 -1
  90. package/src/chains/utils.d.ts +0 -12
  91. package/src/chains/utils.js +0 -27
  92. package/src/index.d.ts +0 -2
  93. package/src/index.js +0 -2
  94. package/src/utils/chains/index.d.ts +0 -1
  95. package/src/utils/chains/index.js +0 -1
  96. package/src/utils/chains/near/account.d.ts +0 -13
  97. package/src/utils/chains/near/account.js +0 -22
  98. package/src/utils/chains/near/constants.d.ts +0 -3
  99. package/src/utils/chains/near/constants.js +0 -3
  100. package/src/utils/chains/near/contract.d.ts +0 -40
  101. package/src/utils/chains/near/contract.js +0 -102
  102. package/src/utils/chains/near/index.d.ts +0 -3
  103. package/src/utils/chains/near/index.js +0 -3
  104. package/src/utils/chains/near/relayer/index.d.ts +0 -1
  105. package/src/utils/chains/near/relayer/index.js +0 -1
  106. package/src/utils/chains/near/relayer/relayer.d.ts +0 -8
  107. package/src/utils/chains/near/relayer/relayer.js +0 -33
  108. package/src/utils/chains/near/relayer/types.d.ts +0 -22
  109. package/src/utils/chains/near/relayer/types.js +0 -1
  110. package/src/utils/chains/near/signAndSend/index.d.ts +0 -1
  111. package/src/utils/chains/near/signAndSend/index.js +0 -1
  112. package/src/utils/chains/near/signAndSend/keypair.d.ts +0 -6
  113. package/src/utils/chains/near/signAndSend/keypair.js +0 -127
  114. package/src/utils/chains/near/transactionBuilder.d.ts +0 -26
  115. package/src/utils/chains/near/transactionBuilder.js +0 -72
  116. package/src/utils/chains/near/types.d.ts +0 -50
  117. package/src/utils/chains/near/types.js +0 -1
  118. package/src/utils/index.d.ts +0 -1
  119. package/src/utils/index.js +0 -1
  120. package/vocs.config.d.ts +0 -3
  121. package/vocs.config.js +0 -71
@@ -1,198 +0,0 @@
1
- import * as bitcoin from 'bitcoinjs-lib';
2
- import { Chain } from '../Chain';
3
- import { utils } from '../index.js';
4
- import { parseBTCNetwork } from '../Bitcoin/utils';
5
- /**
6
- * Implementation of the Chain interface for Bitcoin network.
7
- * Handles interactions with both Bitcoin mainnet and testnet, supporting P2WPKH transactions.
8
- */
9
- export class Bitcoin extends Chain {
10
- /**
11
- * Creates a new Bitcoin chain instance
12
- * @param params - Configuration parameters
13
- * @param params.network - Network identifier (mainnet/testnet)
14
- * @param params.contract - Instance of the chain signature contract for MPC operations
15
- * @param params.btcRpcAdapter - Bitcoin RPC adapter for network interactions
16
- */
17
- constructor({ network, contract, btcRpcAdapter, }) {
18
- super();
19
- this.network = network;
20
- this.btcRpcAdapter = btcRpcAdapter;
21
- this.contract = contract;
22
- }
23
- /**
24
- * Converts satoshis to BTC
25
- * @param satoshis - Amount in satoshis
26
- * @returns Amount in BTC
27
- */
28
- static toBTC(satoshis) {
29
- return satoshis / Bitcoin.SATOSHIS_PER_BTC;
30
- }
31
- /**
32
- * Converts BTC to satoshis
33
- * @param btc - Amount in BTC
34
- * @returns Amount in satoshis (rounded)
35
- */
36
- static toSatoshi(btc) {
37
- return Math.round(btc * Bitcoin.SATOSHIS_PER_BTC);
38
- }
39
- async fetchTransaction(transactionId) {
40
- const data = await this.btcRpcAdapter.getTransaction(transactionId);
41
- const tx = new bitcoin.Transaction();
42
- data.vout.forEach((vout) => {
43
- const scriptPubKey = Buffer.from(vout.scriptpubkey, 'hex');
44
- tx.addOutput(scriptPubKey, Number(vout.value));
45
- });
46
- return tx;
47
- }
48
- static parseRSVSignature(signature) {
49
- const r = signature.r.padStart(64, '0');
50
- const s = signature.s.padStart(64, '0');
51
- const rawSignature = Buffer.from(r + s, 'hex');
52
- if (rawSignature.length !== 64) {
53
- throw new Error('Invalid signature length.');
54
- }
55
- return rawSignature;
56
- }
57
- /**
58
- * Creates a Partially Signed Bitcoin Transaction (PSBT)
59
- * @param params - Parameters for creating the PSBT
60
- * @param params.transactionRequest - Transaction request containing inputs and outputs
61
- * @returns Created PSBT instance
62
- */
63
- async createPSBT({ transactionRequest, }) {
64
- const { inputs, outputs } = transactionRequest.inputs && transactionRequest.outputs
65
- ? transactionRequest
66
- : await this.btcRpcAdapter.selectUTXOs(transactionRequest.from, [
67
- {
68
- address: transactionRequest.to,
69
- value: parseFloat(transactionRequest.value),
70
- },
71
- ]);
72
- const psbt = new bitcoin.Psbt({ network: parseBTCNetwork(this.network) });
73
- await Promise.all(inputs.map(async (input) => {
74
- if (!input.scriptPubKey) {
75
- const transaction = await this.fetchTransaction(input.txid);
76
- const prevOut = transaction.outs[input.vout];
77
- input.scriptPubKey = prevOut.script;
78
- }
79
- // Prepare the input as P2WPKH
80
- psbt.addInput({
81
- hash: input.txid,
82
- index: input.vout,
83
- witnessUtxo: {
84
- script: input.scriptPubKey,
85
- value: input.value,
86
- },
87
- });
88
- }));
89
- outputs.forEach((out) => {
90
- if (out.address) {
91
- psbt.addOutput({
92
- address: out.address,
93
- value: out.value,
94
- });
95
- }
96
- else if (out.script) {
97
- psbt.addOutput({
98
- script: out.script,
99
- value: out.value,
100
- });
101
- }
102
- });
103
- return psbt;
104
- }
105
- async getBalance(address) {
106
- const balance = await this.btcRpcAdapter.getBalance(address);
107
- return Bitcoin.toBTC(balance).toString();
108
- }
109
- async deriveAddressAndPublicKey(predecessor, path) {
110
- const uncompressedPubKey = await this.contract.getDerivedPublicKey({
111
- path,
112
- predecessor,
113
- });
114
- if (!uncompressedPubKey) {
115
- throw new Error('Failed to get derived public key');
116
- }
117
- const derivedKey = utils.compressPubKey(uncompressedPubKey);
118
- const publicKeyBuffer = Buffer.from(derivedKey, 'hex');
119
- const network = parseBTCNetwork(this.network);
120
- const payment = bitcoin.payments.p2wpkh({
121
- pubkey: publicKeyBuffer,
122
- network,
123
- });
124
- const { address } = payment;
125
- if (!address) {
126
- throw new Error('Failed to generate Bitcoin address');
127
- }
128
- return { address, publicKey: derivedKey };
129
- }
130
- setTransaction(transaction, storageKey) {
131
- window.localStorage.setItem(storageKey, JSON.stringify({
132
- psbt: transaction.psbt.toHex(),
133
- publicKey: transaction.publicKey,
134
- }));
135
- }
136
- getTransaction(storageKey, options) {
137
- const txSerialized = window.localStorage.getItem(storageKey);
138
- if (!txSerialized)
139
- return undefined;
140
- if (options?.remove) {
141
- window.localStorage.removeItem(storageKey);
142
- }
143
- const transactionJSON = JSON.parse(txSerialized);
144
- return {
145
- psbt: bitcoin.Psbt.fromHex(transactionJSON.psbt),
146
- publicKey: transactionJSON.publicKey,
147
- };
148
- }
149
- async getMPCPayloadAndTransaction(transactionRequest) {
150
- const publicKeyBuffer = Buffer.from(transactionRequest.publicKey, 'hex');
151
- const psbt = await this.createPSBT({
152
- transactionRequest,
153
- });
154
- // We can't double sign a PSBT, therefore we serialize the payload before to return it
155
- const psbtHex = psbt.toHex();
156
- const mpcPayloads = [];
157
- const mockKeyPair = (index) => ({
158
- publicKey: publicKeyBuffer,
159
- sign: (hash) => {
160
- mpcPayloads.push({
161
- index,
162
- payload: Array.from(hash),
163
- });
164
- // Return dummy signature to satisfy the interface
165
- return Buffer.alloc(64);
166
- },
167
- });
168
- for (let index = 0; index < psbt.inputCount; index++) {
169
- psbt.signInput(index, mockKeyPair(index));
170
- }
171
- return {
172
- transaction: {
173
- psbt: bitcoin.Psbt.fromHex(psbtHex),
174
- publicKey: transactionRequest.publicKey,
175
- },
176
- mpcPayloads: mpcPayloads.sort((a, b) => a.index - b.index),
177
- };
178
- }
179
- addSignature({ transaction: { psbt, publicKey }, mpcSignatures, }) {
180
- const publicKeyBuffer = Buffer.from(publicKey, 'hex');
181
- const keyPair = (index) => ({
182
- publicKey: publicKeyBuffer,
183
- sign: () => {
184
- const mpcSignature = mpcSignatures[index];
185
- return Bitcoin.parseRSVSignature(mpcSignature);
186
- },
187
- });
188
- for (let index = 0; index < psbt.inputCount; index++) {
189
- psbt.signInput(index, keyPair(index));
190
- }
191
- psbt.finalizeAllInputs();
192
- return psbt.extractTransaction().toHex();
193
- }
194
- async broadcastTx(txSerialized) {
195
- return await this.btcRpcAdapter.broadcastTransaction(txSerialized);
196
- }
197
- }
198
- Bitcoin.SATOSHIS_PER_BTC = 100000000;
@@ -1,42 +0,0 @@
1
- import type * as bitcoin from 'bitcoinjs-lib';
2
- export interface BTCTransaction {
3
- vout: Array<{
4
- scriptpubkey: string;
5
- value: number;
6
- }>;
7
- }
8
- export interface BTCInput {
9
- txid: string;
10
- vout: number;
11
- value: number;
12
- scriptPubKey: Buffer;
13
- }
14
- export type BTCOutput = {
15
- value: number;
16
- } & ({
17
- address: string;
18
- script?: never;
19
- } | {
20
- address?: never;
21
- script: Buffer;
22
- });
23
- export type BTCTransactionRequest = {
24
- publicKey: string;
25
- } & ({
26
- inputs: BTCInput[];
27
- outputs: BTCOutput[];
28
- from?: never;
29
- to?: never;
30
- value?: never;
31
- } | {
32
- inputs?: never;
33
- outputs?: never;
34
- from: string;
35
- to: string;
36
- value: string;
37
- });
38
- export interface BTCUnsignedTransaction {
39
- psbt: bitcoin.Psbt;
40
- publicKey: string;
41
- }
42
- export type BTCNetworkIds = 'mainnet' | 'testnet' | 'regtest';
@@ -1 +0,0 @@
1
- export {};
@@ -1,2 +0,0 @@
1
- import * as bitcoin from 'bitcoinjs-lib';
2
- export declare function parseBTCNetwork(network: string): bitcoin.networks.Network;
@@ -1,13 +0,0 @@
1
- import * as bitcoin from 'bitcoinjs-lib';
2
- export function parseBTCNetwork(network) {
3
- switch (network.toLowerCase()) {
4
- case 'mainnet':
5
- return bitcoin.networks.bitcoin;
6
- case 'testnet':
7
- return bitcoin.networks.testnet;
8
- case 'regtest':
9
- return bitcoin.networks.regtest;
10
- default:
11
- throw new Error(`Unknown Bitcoin network: ${network}`);
12
- }
13
- }
@@ -1,89 +0,0 @@
1
- import type { KeyDerivationPath, MPCPayloads, RSVSignature } from './types';
2
- /**
3
- * Core interface for blockchain implementations.
4
- * Provides a standardized way to interact with different blockchain networks through a common set of methods.
5
- *
6
- * @typeParam TransactionRequest - The type of transaction request specific to the blockchain
7
- * @typeParam UnsignedTransaction - The type of unsigned transaction specific to the blockchain
8
- */
9
- export declare abstract class Chain<TransactionRequest, UnsignedTransaction> {
10
- /**
11
- * Gets the native token balance for a given address
12
- *
13
- * @param address - The blockchain address to check
14
- * @returns Promise resolving to the balance as a string, formatted according to the chain's decimal places (e.g. ETH, BTC, etc.)
15
- * @throws Error if the balance fetch fails or the address is invalid
16
- */
17
- abstract getBalance(address: string): Promise<string>;
18
- /**
19
- * Derives an address and public key from a signer ID and derivation path.
20
- * Uses MPC (Multi-Party Computation) to derive the key pair securely.
21
- *
22
- * @param predecessor - The signer ID used to call the sign function on ChainSignatureContract
23
- * @param path - The derivation path that uniquely identifies this key pair
24
- * @returns Promise resolving to the derived address and its corresponding public key
25
- * @throws Error if key derivation fails or the signer ID is invalid
26
- */
27
- abstract deriveAddressAndPublicKey(predecessor: string, path: KeyDerivationPath): Promise<{
28
- address: string;
29
- publicKey: string;
30
- }>;
31
- /**
32
- * Stores an unsigned transaction in local storage for later use.
33
- * This method persists transaction data between page reloads and browser sessions.
34
- * Particularly useful for browser-based wallets that need to maintain transaction state.
35
- *
36
- * @param transaction - The unsigned transaction to store
37
- * @param storageKey - Unique key to identify the stored transaction
38
- */
39
- abstract setTransaction(transaction: UnsignedTransaction, storageKey: string): void;
40
- /**
41
- * Retrieves a previously stored transaction from local storage.
42
- *
43
- * @param storageKey - The key used to store the transaction
44
- * @param options - Additional options
45
- * @param options.remove - If true, removes the transaction from storage after retrieval
46
- * @returns The stored transaction or undefined if not found
47
- */
48
- abstract getTransaction(storageKey: string, options?: {
49
- remove?: boolean;
50
- }): UnsignedTransaction | undefined;
51
- /**
52
- * Prepares a transaction for MPC signing by creating the necessary payloads.
53
- * This method handles chain-specific transaction preparation including:
54
- * - Fee calculation
55
- * - Nonce/sequence management
56
- * - UTXO selection (for UTXO-based chains)
57
- * - Transaction encoding
58
- *
59
- * @param transactionRequest - The transaction request containing parameters like recipient, amount, etc.
60
- * @returns Promise resolving to the unsigned transaction and MPC payloads for signing
61
- * @throws Error if transaction preparation fails
62
- */
63
- abstract getMPCPayloadAndTransaction(transactionRequest: TransactionRequest): Promise<{
64
- transaction: UnsignedTransaction;
65
- mpcPayloads: MPCPayloads;
66
- }>;
67
- /**
68
- * Adds MPC-generated signatures to an unsigned transaction.
69
- * The signatures are applied according to the chain's specific signing scheme.
70
- *
71
- * @param params - Parameters for adding signatures
72
- * @param params.transaction - The unsigned transaction to sign
73
- * @param params.mpcSignatures - Array of RSV signatures generated through MPC
74
- * @returns The serialized signed transaction ready for broadcast
75
- * @throws Error if signature application fails
76
- */
77
- abstract addSignature(params: {
78
- transaction: UnsignedTransaction;
79
- mpcSignatures: RSVSignature[];
80
- }): string;
81
- /**
82
- * Broadcasts a signed transaction to the network.
83
- *
84
- * @param txSerialized - The serialized signed transaction
85
- * @returns Promise resolving to the transaction hash/ID
86
- * @throws Error if broadcast fails or transaction is rejected
87
- */
88
- abstract broadcastTx(txSerialized: string): Promise<string>;
89
- }
@@ -1,9 +0,0 @@
1
- /**
2
- * Core interface for blockchain implementations.
3
- * Provides a standardized way to interact with different blockchain networks through a common set of methods.
4
- *
5
- * @typeParam TransactionRequest - The type of transaction request specific to the blockchain
6
- * @typeParam UnsignedTransaction - The type of unsigned transaction specific to the blockchain
7
- */
8
- export class Chain {
9
- }
@@ -1,62 +0,0 @@
1
- import type BN from 'bn.js';
2
- import type { RSVSignature, UncompressedPubKeySEC1 } from './types';
3
- /**
4
- * Arguments for the sign method
5
- */
6
- export interface SignArgs {
7
- /** The payload to sign as an array of 32 bytes */
8
- payload: number[];
9
- /** The derivation path for key generation */
10
- path: string;
11
- /** Version of the key to use */
12
- key_version: number;
13
- }
14
- /**
15
- * Abstract class defining the interface for chain signature contracts.
16
- * This contract handles MPC (Multi-Party Computation) operations for secure key derivation and signing.
17
- * It serves as a bridge between the blockchain implementations and the MPC infrastructure.
18
- */
19
- export declare abstract class ChainSignatureContract {
20
- /**
21
- * Gets the current signature deposit required by the contract.
22
- * This deposit amount helps manage network congestion.
23
- *
24
- * @returns Promise resolving to the required deposit amount as a BigNumber
25
- * @throws Error if the deposit check fails
26
- */
27
- abstract getCurrentSignatureDeposit(): Promise<BN>;
28
- /**
29
- * Gets the public key associated with this contract.
30
- * This is the root public key from which child keys can be derived.
31
- *
32
- * @returns Promise resolving to the uncompressed public key
33
- * @throws Error if public key retrieval fails
34
- */
35
- abstract getPublicKey(): Promise<UncompressedPubKeySEC1>;
36
- /**
37
- * Signs a payload using MPC.
38
- * This is the core signing operation that coordinates with the MPC infrastructure.
39
- *
40
- * @param args - Arguments for the signing operation
41
- * @param args.payload - The data to sign
42
- * @param args.path - Derivation path for the signing key
43
- * @param args.key_version - Version of the key to use
44
- * @returns Promise resolving to the RSV signature
45
- * @throws Error if signing fails or is rejected
46
- */
47
- abstract sign(args: SignArgs & Record<string, unknown>): Promise<RSVSignature>;
48
- /**
49
- * Derives a child public key using a derivation path and predecessor.
50
- * This method implements hierarchical deterministic key derivation.
51
- *
52
- * @param args - Arguments for key derivation
53
- * @param args.path - The derivation path to use
54
- * @param args.predecessor - The predecessor key (usually a NEAR account) that controls this derived key
55
- * @returns Promise resolving to the derived uncompressed public key
56
- * @throws Error if key derivation fails
57
- */
58
- abstract getDerivedPublicKey(args: {
59
- path: string;
60
- predecessor: string;
61
- } & Record<string, unknown>): Promise<UncompressedPubKeySEC1>;
62
- }
@@ -1,7 +0,0 @@
1
- /**
2
- * Abstract class defining the interface for chain signature contracts.
3
- * This contract handles MPC (Multi-Party Computation) operations for secure key derivation and signing.
4
- * It serves as a bridge between the blockchain implementations and the MPC infrastructure.
5
- */
6
- export class ChainSignatureContract {
7
- }
@@ -1,51 +0,0 @@
1
- import type { CosmosNetworkIds, CosmosTransactionRequest, CosmosUnsignedTransaction } from '../Cosmos/types';
2
- import type { ChainSignatureContract } from '../ChainSignatureContract';
3
- import type { MPCPayloads, RSVSignature, KeyDerivationPath } from '../types';
4
- import { Chain } from '../Chain';
5
- /**
6
- * Implementation of the Chain interface for Cosmos-based networks.
7
- * Handles interactions with Cosmos SDK chains like Cosmos Hub, Osmosis, etc.
8
- */
9
- export declare class Cosmos extends Chain<CosmosTransactionRequest, CosmosUnsignedTransaction> {
10
- private readonly registry;
11
- private readonly chainId;
12
- private readonly contract;
13
- private readonly endpoints?;
14
- /**
15
- * Creates a new Cosmos chain instance
16
- * @param params - Configuration parameters
17
- * @param params.chainId - Chain id for the Cosmos network
18
- * @param params.contract - Instance of the chain signature contract for MPC operations
19
- * @param params.endpoints - Optional RPC and REST endpoints
20
- * @param params.endpoints.rpcUrl - Optional RPC endpoint URL
21
- * @param params.endpoints.restUrl - Optional REST endpoint URL
22
- */
23
- constructor({ chainId, contract, endpoints, }: {
24
- contract: ChainSignatureContract;
25
- chainId: CosmosNetworkIds;
26
- endpoints?: {
27
- rpcUrl?: string;
28
- restUrl?: string;
29
- };
30
- });
31
- private parseRSVSignature;
32
- private getChainInfo;
33
- getBalance(address: string): Promise<string>;
34
- deriveAddressAndPublicKey(predecessor: string, path: KeyDerivationPath): Promise<{
35
- address: string;
36
- publicKey: string;
37
- }>;
38
- setTransaction(transaction: CosmosUnsignedTransaction, storageKey: string): void;
39
- getTransaction(storageKey: string, options?: {
40
- remove?: boolean;
41
- }): CosmosUnsignedTransaction | undefined;
42
- getMPCPayloadAndTransaction(transactionRequest: CosmosTransactionRequest): Promise<{
43
- transaction: CosmosUnsignedTransaction;
44
- mpcPayloads: MPCPayloads;
45
- }>;
46
- addSignature({ transaction, mpcSignatures, }: {
47
- transaction: CosmosUnsignedTransaction;
48
- mpcSignatures: RSVSignature[];
49
- }): string;
50
- broadcastTx(txSerialized: string): Promise<string>;
51
- }
@@ -1,157 +0,0 @@
1
- import { encodeSecp256k1Pubkey } from '@cosmjs/amino';
2
- import { ripemd160, sha256 } from '@cosmjs/crypto';
3
- import { toBase64, fromBase64, fromHex } from '@cosmjs/encoding';
4
- import { Registry, makeSignBytes, encodePubkey, makeAuthInfoBytes, makeSignDoc, } from '@cosmjs/proto-signing';
5
- import { GasPrice, StargateClient, calculateFee } from '@cosmjs/stargate';
6
- import { bech32 } from 'bech32';
7
- import { SignMode } from 'cosmjs-types/cosmos/tx/signing/v1beta1/signing';
8
- import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
9
- import { Chain } from '../Chain';
10
- import { utils } from '../index.js';
11
- import { fetchChainInfo } from '../Cosmos/utils';
12
- /**
13
- * Implementation of the Chain interface for Cosmos-based networks.
14
- * Handles interactions with Cosmos SDK chains like Cosmos Hub, Osmosis, etc.
15
- */
16
- export class Cosmos extends Chain {
17
- /**
18
- * Creates a new Cosmos chain instance
19
- * @param params - Configuration parameters
20
- * @param params.chainId - Chain id for the Cosmos network
21
- * @param params.contract - Instance of the chain signature contract for MPC operations
22
- * @param params.endpoints - Optional RPC and REST endpoints
23
- * @param params.endpoints.rpcUrl - Optional RPC endpoint URL
24
- * @param params.endpoints.restUrl - Optional REST endpoint URL
25
- */
26
- constructor({ chainId, contract, endpoints, }) {
27
- super();
28
- this.contract = contract;
29
- this.registry = new Registry();
30
- this.chainId = chainId;
31
- this.endpoints = endpoints;
32
- }
33
- parseRSVSignature(rsvSignature) {
34
- return new Uint8Array([
35
- ...fromHex(rsvSignature.r),
36
- ...fromHex(rsvSignature.s),
37
- ]);
38
- }
39
- async getChainInfo() {
40
- return {
41
- ...(await fetchChainInfo(this.chainId)),
42
- ...this.endpoints,
43
- };
44
- }
45
- async getBalance(address) {
46
- try {
47
- const { restUrl, denom, decimals } = await this.getChainInfo();
48
- const response = await fetch(`${restUrl}/cosmos/bank/v1beta1/balances/${address}`);
49
- if (!response.ok) {
50
- throw new Error(`HTTP error! status: ${response.status}`);
51
- }
52
- const data = (await response.json());
53
- const balance = data.balances.find((b) => b.denom === denom);
54
- const amount = balance?.amount ?? '0';
55
- const formattedBalance = (parseInt(amount) / Math.pow(10, decimals)).toString();
56
- return formattedBalance;
57
- }
58
- catch (error) {
59
- console.error('Failed to fetch Cosmos balance:', error);
60
- throw new Error('Failed to fetch Cosmos balance');
61
- }
62
- }
63
- async deriveAddressAndPublicKey(predecessor, path) {
64
- const { prefix } = await this.getChainInfo();
65
- const uncompressedPubKey = await this.contract.getDerivedPublicKey({
66
- path,
67
- predecessor,
68
- });
69
- if (!uncompressedPubKey) {
70
- throw new Error('Failed to get derived public key');
71
- }
72
- const derivedKey = utils.compressPubKey(uncompressedPubKey);
73
- const pubKeySha256 = sha256(fromHex(derivedKey));
74
- const ripemd160Hash = ripemd160(pubKeySha256);
75
- const address = bech32.encode(prefix, bech32.toWords(ripemd160Hash));
76
- return { address, publicKey: derivedKey };
77
- }
78
- setTransaction(transaction, storageKey) {
79
- const serialized = TxRaw.encode(transaction).finish();
80
- window.localStorage.setItem(storageKey, toBase64(serialized));
81
- }
82
- getTransaction(storageKey, options) {
83
- const serialized = window.localStorage.getItem(storageKey);
84
- if (!serialized)
85
- return undefined;
86
- if (options?.remove) {
87
- window.localStorage.removeItem(storageKey);
88
- }
89
- return TxRaw.decode(fromBase64(serialized));
90
- }
91
- async getMPCPayloadAndTransaction(transactionRequest) {
92
- const { denom, rpcUrl, gasPrice } = await this.getChainInfo();
93
- const publicKeyBytes = fromHex(transactionRequest.publicKey);
94
- const gasLimit = transactionRequest.gas || 200000;
95
- const fee = calculateFee(gasLimit, GasPrice.fromString(`${gasPrice}${denom}`));
96
- const client = await StargateClient.connect(rpcUrl);
97
- const accountOnChain = await client.getAccount(transactionRequest.address);
98
- if (!accountOnChain) {
99
- throw new Error(`Account ${transactionRequest.address} does not exist on chain`);
100
- }
101
- const { accountNumber, sequence } = accountOnChain;
102
- const txBodyEncodeObject = {
103
- typeUrl: '/cosmos.tx.v1beta1.TxBody',
104
- value: {
105
- messages: transactionRequest.messages,
106
- memo: transactionRequest.memo || '',
107
- },
108
- };
109
- const txBodyBytes = this.registry.encode(txBodyEncodeObject);
110
- const pubkey = encodePubkey(encodeSecp256k1Pubkey(publicKeyBytes));
111
- // TODO: Allow caller to provide: multiple signers, fee payer, fee granter
112
- const authInfoBytes = makeAuthInfoBytes([
113
- {
114
- pubkey,
115
- sequence,
116
- },
117
- ], fee.amount, Number(fee.gas), undefined, undefined, SignMode.SIGN_MODE_DIRECT);
118
- const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, this.chainId, accountNumber);
119
- const signBytes = makeSignBytes(signDoc);
120
- const payload = Array.from(sha256(signBytes));
121
- return {
122
- transaction: TxRaw.fromPartial({
123
- bodyBytes: txBodyBytes,
124
- authInfoBytes,
125
- signatures: [],
126
- }),
127
- mpcPayloads: [
128
- {
129
- index: 0,
130
- payload,
131
- },
132
- ],
133
- };
134
- }
135
- addSignature({ transaction, mpcSignatures, }) {
136
- // Allow support for multi-sig but the package only supports single-sig
137
- transaction.signatures = mpcSignatures.map((sig) => this.parseRSVSignature(sig));
138
- const txBytes = TxRaw.encode(transaction).finish();
139
- return Buffer.from(txBytes).toString('hex');
140
- }
141
- async broadcastTx(txSerialized) {
142
- try {
143
- const { rpcUrl } = await this.getChainInfo();
144
- const client = await StargateClient.connect(rpcUrl);
145
- const txBytes = fromHex(txSerialized);
146
- const broadcastResponse = await client.broadcastTx(txBytes);
147
- if (broadcastResponse.code !== 0) {
148
- throw new Error(`Broadcast error: ${broadcastResponse.rawLog}`);
149
- }
150
- return broadcastResponse.transactionHash;
151
- }
152
- catch (error) {
153
- console.error('Transaction broadcast failed:', error);
154
- throw new Error('Failed to broadcast transaction.');
155
- }
156
- }
157
- }
@@ -1,30 +0,0 @@
1
- import { type EncodeObject } from '@cosmjs/proto-signing';
2
- import { type TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
3
- export type CosmosNetworkIds = string;
4
- export type CosmosUnsignedTransaction = TxRaw;
5
- export interface CosmosTransactionRequest {
6
- address: string;
7
- publicKey: string;
8
- messages: EncodeObject[];
9
- memo?: string;
10
- gas?: number;
11
- }
12
- export interface BalanceResponse {
13
- balances: Array<{
14
- denom: string;
15
- amount: string;
16
- }>;
17
- pagination: {
18
- next_key: string | null;
19
- total: string;
20
- };
21
- }
22
- export interface ChainInfo {
23
- prefix: string;
24
- denom: string;
25
- rpcUrl: string;
26
- restUrl: string;
27
- expectedChainId: string;
28
- gasPrice: number;
29
- decimals: number;
30
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,2 +0,0 @@
1
- import { type ChainInfo } from '../Cosmos/types';
2
- export declare const fetchChainInfo: (chainId: string) => Promise<ChainInfo>;