signet.js 0.0.1-beta.5 → 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,27 +0,0 @@
1
- import { chains, assets } from 'chain-registry';
2
- export const fetchChainInfo = async (chainId) => {
3
- const chainInfo = chains.find((chain) => chain.chain_id === chainId);
4
- if (!chainInfo) {
5
- throw new Error(`Chain info not found for chainId: ${chainId}`);
6
- }
7
- const { bech32_prefix: prefix, chain_id: expectedChainId } = chainInfo;
8
- const denom = chainInfo.staking?.staking_tokens?.[0]?.denom;
9
- const rpcUrl = chainInfo.apis?.rpc?.[0]?.address;
10
- const restUrl = chainInfo.apis?.rest?.[0]?.address;
11
- const gasPrice = chainInfo.fees?.fee_tokens?.[0]?.average_gas_price;
12
- if (!prefix ||
13
- !denom ||
14
- !rpcUrl ||
15
- !restUrl ||
16
- !expectedChainId ||
17
- gasPrice === undefined) {
18
- throw new Error(`Missing required chain information for ${chainInfo.chain_name}`);
19
- }
20
- const assetList = assets.find((asset) => asset.chain_name === chainInfo.chain_name);
21
- const asset = assetList?.assets.find((asset) => asset.base === denom);
22
- const decimals = asset?.denom_units.find((unit) => unit.denom === asset.display)?.exponent;
23
- if (decimals === undefined) {
24
- throw new Error(`Could not find decimals for ${denom} on chain ${chainInfo.chain_name}`);
25
- }
26
- return { prefix, denom, rpcUrl, restUrl, expectedChainId, gasPrice, decimals };
27
- };
@@ -1,42 +0,0 @@
1
- import type { MPCPayloads, RSVSignature, KeyDerivationPath } from '../types';
2
- import type { EVMTransactionRequest, EVMUnsignedTransaction } from '../EVM/types';
3
- import type { ChainSignatureContract } from '../ChainSignatureContract';
4
- import { Chain } from '../Chain';
5
- /**
6
- * Implementation of the Chain interface for EVM-compatible networks.
7
- * Handles interactions with Ethereum Virtual Machine based blockchains like Ethereum, BSC, Polygon, etc.
8
- */
9
- export declare class EVM extends Chain<EVMTransactionRequest, EVMUnsignedTransaction> {
10
- private readonly provider;
11
- private readonly contract;
12
- /**
13
- * Creates a new EVM chain instance
14
- * @param params - Configuration parameters
15
- * @param params.rpcUrl - URL of the EVM JSON-RPC provider (e.g., Infura endpoint)
16
- * @param params.contract - Instance of the chain signature contract for MPC operations
17
- */
18
- constructor({ rpcUrl, contract, }: {
19
- rpcUrl: string;
20
- contract: ChainSignatureContract;
21
- });
22
- private attachGasAndNonce;
23
- private parseSignature;
24
- deriveAddressAndPublicKey(predecessor: string, path: KeyDerivationPath): Promise<{
25
- address: string;
26
- publicKey: string;
27
- }>;
28
- getBalance(address: string): Promise<string>;
29
- setTransaction(transaction: EVMUnsignedTransaction, storageKey: string): void;
30
- getTransaction(storageKey: string, options?: {
31
- remove?: boolean;
32
- }): EVMUnsignedTransaction | undefined;
33
- getMPCPayloadAndTransaction(transactionRequest: EVMTransactionRequest): Promise<{
34
- transaction: EVMUnsignedTransaction;
35
- mpcPayloads: MPCPayloads;
36
- }>;
37
- addSignature({ transaction, mpcSignatures, }: {
38
- transaction: EVMUnsignedTransaction;
39
- mpcSignatures: RSVSignature[];
40
- }): string;
41
- broadcastTx(txSerialized: string): Promise<string>;
42
- }
@@ -1,109 +0,0 @@
1
- import { fromHex } from '@cosmjs/encoding';
2
- import { ethers, keccak256 } from 'ethers';
3
- import { Chain } from '../Chain';
4
- import { fetchEVMFeeProperties } from '../EVM/utils';
5
- /**
6
- * Implementation of the Chain interface for EVM-compatible networks.
7
- * Handles interactions with Ethereum Virtual Machine based blockchains like Ethereum, BSC, Polygon, etc.
8
- */
9
- export class EVM extends Chain {
10
- /**
11
- * Creates a new EVM chain instance
12
- * @param params - Configuration parameters
13
- * @param params.rpcUrl - URL of the EVM JSON-RPC provider (e.g., Infura endpoint)
14
- * @param params.contract - Instance of the chain signature contract for MPC operations
15
- */
16
- constructor({ rpcUrl, contract, }) {
17
- super();
18
- this.contract = contract;
19
- this.provider = new ethers.JsonRpcProvider(rpcUrl);
20
- }
21
- async attachGasAndNonce(transaction) {
22
- const fees = await fetchEVMFeeProperties(this.provider._getConnection().url, transaction);
23
- const nonce = await this.provider.getTransactionCount(transaction.from, 'latest');
24
- const { from, ...rest } = transaction;
25
- return {
26
- ...fees,
27
- chainId: this.provider._network.chainId,
28
- nonce,
29
- type: 2,
30
- ...rest,
31
- };
32
- }
33
- parseSignature(signature) {
34
- return ethers.Signature.from({
35
- r: `0x${signature.r}`,
36
- s: `0x${signature.s}`,
37
- v: signature.v,
38
- });
39
- }
40
- async deriveAddressAndPublicKey(predecessor, path) {
41
- const uncompressedPubKey = await this.contract.getDerivedPublicKey({
42
- path,
43
- predecessor,
44
- });
45
- if (!uncompressedPubKey) {
46
- throw new Error('Failed to get derived public key');
47
- }
48
- const publicKeyNoPrefix = uncompressedPubKey.startsWith('04')
49
- ? uncompressedPubKey.substring(2)
50
- : uncompressedPubKey;
51
- const hash = ethers.keccak256(fromHex(publicKeyNoPrefix));
52
- return {
53
- address: `0x${hash.substring(hash.length - 40)}`,
54
- publicKey: uncompressedPubKey,
55
- };
56
- }
57
- async getBalance(address) {
58
- try {
59
- const balance = await this.provider.getBalance(address);
60
- return ethers.formatEther(balance);
61
- }
62
- catch (error) {
63
- console.error(`Failed to fetch balance for address ${address}:`, error);
64
- throw new Error('Failed to fetch balance.');
65
- }
66
- }
67
- setTransaction(transaction, storageKey) {
68
- const serializedTransaction = JSON.stringify(transaction, (_, value) => typeof value === 'bigint' ? value.toString() : value);
69
- window.localStorage.setItem(storageKey, serializedTransaction);
70
- }
71
- getTransaction(storageKey, options) {
72
- const txSerialized = window.localStorage.getItem(storageKey);
73
- if (options?.remove) {
74
- window.localStorage.removeItem(storageKey);
75
- }
76
- return txSerialized ? JSON.parse(txSerialized) : undefined;
77
- }
78
- async getMPCPayloadAndTransaction(transactionRequest) {
79
- const transaction = await this.attachGasAndNonce(transactionRequest);
80
- const txSerialized = ethers.Transaction.from(transaction).unsignedSerialized;
81
- const transactionHash = keccak256(txSerialized);
82
- const txHash = Array.from(ethers.getBytes(transactionHash));
83
- return {
84
- transaction,
85
- mpcPayloads: [
86
- {
87
- index: 0,
88
- payload: txHash,
89
- },
90
- ],
91
- };
92
- }
93
- addSignature({ transaction, mpcSignatures, }) {
94
- return ethers.Transaction.from({
95
- ...transaction,
96
- signature: this.parseSignature(mpcSignatures[0]),
97
- }).serialized;
98
- }
99
- async broadcastTx(txSerialized) {
100
- try {
101
- const txResponse = await this.provider.broadcastTransaction(txSerialized);
102
- return txResponse.hash;
103
- }
104
- catch (error) {
105
- console.error('Transaction broadcast failed:', error);
106
- throw new Error('Failed to broadcast transaction.');
107
- }
108
- }
109
- }
@@ -1,5 +0,0 @@
1
- import type * as ethers from 'ethers';
2
- export type EVMUnsignedTransaction = ethers.TransactionLike;
3
- export type EVMTransactionRequest = Omit<ethers.TransactionLike, 'from'> & {
4
- from: string;
5
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,7 +0,0 @@
1
- import { ethers } from 'ethers';
2
- export declare function fetchEVMFeeProperties(providerUrl: string, transaction: ethers.TransactionLike): Promise<{
3
- gasLimit: bigint;
4
- maxFeePerGas: bigint;
5
- maxPriorityFeePerGas: bigint;
6
- maxFee: bigint;
7
- }>;
@@ -1,14 +0,0 @@
1
- import { ethers } from 'ethers';
2
- export async function fetchEVMFeeProperties(providerUrl, transaction) {
3
- const provider = new ethers.JsonRpcProvider(providerUrl);
4
- const gasLimit = await provider.estimateGas(transaction);
5
- const feeData = await provider.getFeeData();
6
- const maxFeePerGas = feeData.maxFeePerGas ?? ethers.parseUnits('10', 'gwei');
7
- const maxPriorityFeePerGas = feeData.maxPriorityFeePerGas ?? ethers.parseUnits('10', 'gwei');
8
- return {
9
- gasLimit,
10
- maxFeePerGas,
11
- maxPriorityFeePerGas,
12
- maxFee: maxFeePerGas * gasLimit,
13
- };
14
- }
@@ -1,12 +0,0 @@
1
- export { Chain } from './Chain';
2
- export { ChainSignatureContract, type SignArgs } from './ChainSignatureContract';
3
- export * from './types';
4
- export * as utils from './utils';
5
- export { EVM } from './EVM/EVM';
6
- export { fetchEVMFeeProperties } from './EVM/utils';
7
- export type { EVMTransactionRequest, EVMUnsignedTransaction } from './EVM/types';
8
- export { Bitcoin } from './Bitcoin/Bitcoin';
9
- export { BTCRpcAdapters, BTCRpcAdapter } from './Bitcoin/BTCRpcAdapter';
10
- export type { BTCTransactionRequest, BTCUnsignedTransaction, BTCTransaction, BTCOutput, BTCInput, BTCNetworkIds, } from './Bitcoin/types';
11
- export { Cosmos } from './Cosmos/Cosmos';
12
- export type { CosmosNetworkIds, CosmosTransactionRequest, CosmosUnsignedTransaction, } from './Cosmos/types';
@@ -1,12 +0,0 @@
1
- export { Chain } from './Chain';
2
- export { ChainSignatureContract } from './ChainSignatureContract';
3
- export * from './types';
4
- export * as utils from './utils';
5
- // EVM
6
- export { EVM } from './EVM/EVM';
7
- export { fetchEVMFeeProperties } from './EVM/utils';
8
- // Bitcoin
9
- export { Bitcoin } from './Bitcoin/Bitcoin';
10
- export { BTCRpcAdapters, BTCRpcAdapter } from './Bitcoin/BTCRpcAdapter';
11
- // Cosmos
12
- export { Cosmos } from './Cosmos/Cosmos';
@@ -1,31 +0,0 @@
1
- import { type SignArgs } from './ChainSignatureContract';
2
- interface SuccessResponse {
3
- transactionHash: string;
4
- success: true;
5
- }
6
- interface FailureResponse {
7
- success: false;
8
- errorMessage: string;
9
- }
10
- export type Response = SuccessResponse | FailureResponse;
11
- export type MPCPayloads = Array<{
12
- index: number;
13
- payload: SignArgs['payload'];
14
- }>;
15
- export type UncompressedPubKeySEC1 = `04${string}`;
16
- export type KeyDerivationPath = string;
17
- export interface RSVSignature {
18
- r: string;
19
- s: string;
20
- v: number;
21
- }
22
- export interface MPCSignature {
23
- big_r: {
24
- affine_point: string;
25
- };
26
- s: {
27
- scalar: string;
28
- };
29
- recovery_id: number;
30
- }
31
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1,12 +0,0 @@
1
- import { type MPCSignature, type RSVSignature, type UncompressedPubKeySEC1 } from './types';
2
- export declare const toRSV: (signature: MPCSignature) => RSVSignature;
3
- /**
4
- * Compresses an uncompressed public key to its compressed format following SEC1 standards.
5
- * In SEC1, a compressed public key consists of a prefix (02 or 03) followed by the x-coordinate.
6
- * The prefix indicates whether the y-coordinate is even (02) or odd (03).
7
- *
8
- * @param uncompressedPubKeySEC1 - The uncompressed public key in hex format, with or without '04' prefix
9
- * @returns The compressed public key in hex format
10
- * @throws Error if the uncompressed public key length is invalid
11
- */
12
- export declare const compressPubKey: (uncompressedPubKeySEC1: UncompressedPubKeySEC1) => string;
@@ -1,27 +0,0 @@
1
- export const toRSV = (signature) => {
2
- return {
3
- r: signature.big_r.affine_point.substring(2),
4
- s: signature.s.scalar,
5
- v: signature.recovery_id,
6
- };
7
- };
8
- /**
9
- * Compresses an uncompressed public key to its compressed format following SEC1 standards.
10
- * In SEC1, a compressed public key consists of a prefix (02 or 03) followed by the x-coordinate.
11
- * The prefix indicates whether the y-coordinate is even (02) or odd (03).
12
- *
13
- * @param uncompressedPubKeySEC1 - The uncompressed public key in hex format, with or without '04' prefix
14
- * @returns The compressed public key in hex format
15
- * @throws Error if the uncompressed public key length is invalid
16
- */
17
- export const compressPubKey = (uncompressedPubKeySEC1) => {
18
- const slicedPubKey = uncompressedPubKeySEC1.slice(2);
19
- if (slicedPubKey.length !== 128) {
20
- throw new Error('Invalid uncompressed public key length');
21
- }
22
- const x = slicedPubKey.slice(0, 64);
23
- const y = slicedPubKey.slice(64);
24
- const isEven = parseInt(y.slice(-1), 16) % 2 === 0;
25
- const prefix = isEven ? '02' : '03';
26
- return prefix + x;
27
- };
package/src/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export * as utils from './utils';
2
- export * from './chains';
package/src/index.js DELETED
@@ -1,2 +0,0 @@
1
- export * as utils from './utils';
2
- export * from './chains';
@@ -1 +0,0 @@
1
- export * as near from './near';
@@ -1 +0,0 @@
1
- export * as near from './near';
@@ -1,13 +0,0 @@
1
- import { Account } from '@near-js/accounts';
2
- import { KeyPair } from '@near-js/crypto';
3
- type SetConnectionArgs = {
4
- networkId: string;
5
- accountId: string;
6
- keypair: KeyPair;
7
- } | {
8
- networkId: string;
9
- accountId?: never;
10
- keypair?: never;
11
- };
12
- export declare const getNearAccount: ({ networkId, accountId, keypair, }: SetConnectionArgs) => Promise<Account>;
13
- export {};
@@ -1,22 +0,0 @@
1
- import { Account, Connection } from '@near-js/accounts';
2
- import { KeyPair } from '@near-js/crypto';
3
- import { InMemoryKeyStore } from '@near-js/keystores';
4
- import { DONT_CARE_ACCOUNT_ID } from '../../chains/near/constants';
5
- export const getNearAccount = async ({ networkId, accountId = DONT_CARE_ACCOUNT_ID, keypair = KeyPair.fromRandom('ed25519'), }) => {
6
- const keyStore = new InMemoryKeyStore();
7
- await keyStore.setKey(networkId, accountId, keypair);
8
- const connection = Connection.fromConfig({
9
- networkId,
10
- provider: {
11
- type: 'JsonRpcProvider',
12
- args: {
13
- url: {
14
- testnet: 'https://rpc.testnet.near.org',
15
- mainnet: 'https://rpc.mainnet.near.org',
16
- }[networkId],
17
- },
18
- },
19
- signer: { type: 'InMemorySigner', keyStore },
20
- });
21
- return new Account(connection, accountId);
22
- };
@@ -1,3 +0,0 @@
1
- import BN from 'bn.js';
2
- export declare const NEAR_MAX_GAS: BN;
3
- export declare const DONT_CARE_ACCOUNT_ID = "dontcare";
@@ -1,3 +0,0 @@
1
- import BN from 'bn.js';
2
- export const NEAR_MAX_GAS = new BN('300000000000000');
3
- export const DONT_CARE_ACCOUNT_ID = 'dontcare';
@@ -1,40 +0,0 @@
1
- import { type Account } from '@near-js/accounts';
2
- import { KeyPair } from '@near-js/crypto';
3
- import BN from 'bn.js';
4
- import { ChainSignatureContract } from '../../../chains/ChainSignatureContract';
5
- import type { RSVSignature, UncompressedPubKeySEC1 } from '../../../chains/types';
6
- import type { SignArgs } from '../../../chains/ChainSignatureContract';
7
- import { type NearNetworkIds, type ChainSignatureContractIds } from '../../chains/near/types';
8
- interface ChainSignatureContractArgs {
9
- networkId: NearNetworkIds;
10
- contractId: ChainSignatureContractIds;
11
- accountId?: string;
12
- keypair?: KeyPair;
13
- }
14
- /**
15
- * This contract will default to view methods only.
16
- * If you want to use the change methods, you need to provide an account and keypair.
17
- */
18
- export declare class NearChainSignatureContract extends ChainSignatureContract {
19
- private readonly networkId;
20
- private readonly contractId;
21
- private readonly accountId;
22
- private readonly keypair;
23
- constructor({ networkId, contractId, accountId, keypair, }: ChainSignatureContractArgs);
24
- private getContract;
25
- getPublicKey(): Promise<UncompressedPubKeySEC1>;
26
- getCurrentSignatureDeposit(): Promise<BN>;
27
- getDerivedPublicKey(args: {
28
- path: string;
29
- predecessor: string;
30
- }): Promise<UncompressedPubKeySEC1>;
31
- sign(args: SignArgs): Promise<RSVSignature>;
32
- static signWithRelayer({ account, contract, signArgs, deposit, relayerUrl, }: {
33
- account: Account;
34
- contract: ChainSignatureContractIds;
35
- signArgs: SignArgs;
36
- deposit: BN;
37
- relayerUrl: string;
38
- }): Promise<RSVSignature>;
39
- }
40
- export {};
@@ -1,102 +0,0 @@
1
- import { Contract } from '@near-js/accounts';
2
- import { KeyPair } from '@near-js/crypto';
3
- import { actionCreators } from '@near-js/transactions';
4
- import BN from 'bn.js';
5
- import { base_decode } from 'near-api-js/lib/utils/serialize';
6
- import { ChainSignatureContract } from '../../../chains/ChainSignatureContract';
7
- import { utils } from '../../../chains/index.js';
8
- import { chains } from '../../index.js';
9
- import { getNearAccount } from '../../chains/near/account';
10
- import { DONT_CARE_ACCOUNT_ID, NEAR_MAX_GAS, } from '../../chains/near/constants';
11
- import { parseSignedDelegateForRelayer } from '../../chains/near/relayer';
12
- const najToUncompressedPubKey = (najPubKey) => {
13
- return `04${Buffer.from(base_decode(najPubKey.split(':')[1])).toString('hex')}`;
14
- };
15
- const requireAccount = (accountId) => {
16
- if (accountId === DONT_CARE_ACCOUNT_ID) {
17
- throw new Error('A valid account ID and keypair are required for change methods. Please instantiate a new contract with valid credentials.');
18
- }
19
- };
20
- /**
21
- * This contract will default to view methods only.
22
- * If you want to use the change methods, you need to provide an account and keypair.
23
- */
24
- export class NearChainSignatureContract extends ChainSignatureContract {
25
- constructor({ networkId, contractId, accountId = DONT_CARE_ACCOUNT_ID, keypair = KeyPair.fromRandom('ed25519'), }) {
26
- super();
27
- this.networkId = networkId;
28
- this.contractId = contractId;
29
- this.accountId = accountId;
30
- this.keypair = keypair;
31
- }
32
- async getContract() {
33
- const account = await getNearAccount({
34
- networkId: this.networkId,
35
- accountId: this.accountId,
36
- keypair: this.keypair,
37
- });
38
- return new Contract(account, this.contractId, {
39
- viewMethods: [
40
- 'public_key',
41
- 'experimental_signature_deposit',
42
- 'derived_public_key',
43
- ],
44
- changeMethods: ['sign'],
45
- useLocalViewExecution: false,
46
- });
47
- }
48
- async getPublicKey() {
49
- const contract = await this.getContract();
50
- const najPubKey = await contract.public_key();
51
- return najToUncompressedPubKey(najPubKey);
52
- }
53
- async getCurrentSignatureDeposit() {
54
- const contract = await this.getContract();
55
- return new BN((await contract.experimental_signature_deposit()).toLocaleString('fullwide', {
56
- useGrouping: false,
57
- }));
58
- }
59
- async getDerivedPublicKey(args) {
60
- const contract = await this.getContract();
61
- const najPubKey = await contract.derived_public_key(args);
62
- return najToUncompressedPubKey(najPubKey);
63
- }
64
- async sign(args) {
65
- requireAccount(this.accountId);
66
- const contract = await this.getContract();
67
- const deposit = await this.getCurrentSignatureDeposit();
68
- const signature = await contract.sign({
69
- args: { request: args },
70
- gas: NEAR_MAX_GAS,
71
- amount: deposit,
72
- });
73
- return utils.toRSV(signature);
74
- }
75
- static async signWithRelayer({ account, contract, signArgs, deposit, relayerUrl, }) {
76
- const functionCall = actionCreators.functionCall('sign', { request: signArgs }, BigInt(NEAR_MAX_GAS.toString()), BigInt(deposit.toString()));
77
- const signedDelegate = await account.signedDelegate({
78
- receiverId: contract,
79
- actions: [functionCall],
80
- blockHeightTtl: 60,
81
- });
82
- // Remove the cached access key to prevent nonce reuse
83
- delete account.accessKeyByPublicKeyCache[
84
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
85
- signedDelegate.delegateAction.publicKey.toString()];
86
- const res = await fetch(`${relayerUrl}/send_meta_tx_async`, {
87
- method: 'POST',
88
- mode: 'cors',
89
- body: JSON.stringify(parseSignedDelegateForRelayer(signedDelegate)),
90
- headers: new Headers({ 'Content-Type': 'application/json' }),
91
- });
92
- const txHash = await res.text();
93
- const txStatus = await account.connection.provider.txStatus(txHash, account.accountId, 'FINAL');
94
- const signature = chains.near.transactionBuilder.responseToMpcSignature({
95
- response: txStatus,
96
- });
97
- if (!signature) {
98
- throw new Error('Signature error, please retry');
99
- }
100
- return signature;
101
- }
102
- }
@@ -1,3 +0,0 @@
1
- export * as transactionBuilder from './transactionBuilder';
2
- export * as signAndSend from './signAndSend';
3
- export * as contract from './contract';
@@ -1,3 +0,0 @@
1
- export * as transactionBuilder from './transactionBuilder';
2
- export * as signAndSend from './signAndSend';
3
- export * as contract from './contract';
@@ -1 +0,0 @@
1
- export * from './relayer';
@@ -1 +0,0 @@
1
- export * from './relayer';
@@ -1,8 +0,0 @@
1
- import { type SignedDelegate } from '@near-js/transactions';
2
- import { type SignedDelegateRelayerFormat } from './types';
3
- /**
4
- * Parses the signedDelegate object from the Multi-Party Computation (MPC) format to the Relayer format.
5
- * @param signedDelegate - The signedDelegate object in MPC format.
6
- * @returns The signedDelegate object in Relayer format.
7
- */
8
- export declare function parseSignedDelegateForRelayer(signedDelegate: SignedDelegate): SignedDelegateRelayerFormat;
@@ -1,33 +0,0 @@
1
- import bs58 from 'bs58';
2
- /**
3
- * Parses the signedDelegate object from the Multi-Party Computation (MPC) format to the Relayer format.
4
- * @param signedDelegate - The signedDelegate object in MPC format.
5
- * @returns The signedDelegate object in Relayer format.
6
- */
7
- export function parseSignedDelegateForRelayer(signedDelegate) {
8
- return {
9
- delegate_action: {
10
- actions: signedDelegate.delegateAction.actions
11
- .map((action) => {
12
- if (action.functionCall) {
13
- return {
14
- FunctionCall: {
15
- method_name: action.functionCall.methodName,
16
- args: Buffer.from(action.functionCall.args).toString('base64'),
17
- gas: Number(action.functionCall.gas),
18
- deposit: action.functionCall.deposit.toString(),
19
- },
20
- };
21
- }
22
- return undefined;
23
- })
24
- .flatMap((t) => (t ? [t] : [])),
25
- nonce: Number(signedDelegate.delegateAction.nonce),
26
- max_block_height: Number(signedDelegate.delegateAction.maxBlockHeight),
27
- public_key: signedDelegate.delegateAction.publicKey.toString(),
28
- receiver_id: signedDelegate.delegateAction.receiverId,
29
- sender_id: signedDelegate.delegateAction.senderId,
30
- },
31
- signature: `ed25519:${bs58.encode(signedDelegate.signature.data)}`,
32
- };
33
- }
@@ -1,22 +0,0 @@
1
- interface FunctionCallRelayer {
2
- FunctionCall: {
3
- method_name: string;
4
- args: string;
5
- gas: number;
6
- deposit: string;
7
- };
8
- }
9
- type ActionsRelayer = FunctionCallRelayer;
10
- interface DelegateActionRelayerFormat {
11
- actions: ActionsRelayer[];
12
- nonce: number;
13
- max_block_height: number;
14
- public_key: string;
15
- receiver_id: string;
16
- sender_id: string;
17
- }
18
- export interface SignedDelegateRelayerFormat {
19
- delegate_action: DelegateActionRelayerFormat;
20
- signature: string;
21
- }
22
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export * as keypair from './keypair';
@@ -1 +0,0 @@
1
- export * as keypair from './keypair';
@@ -1,6 +0,0 @@
1
- import { type KeyPair } from '@near-js/crypto';
2
- import { type Response } from '../../../../chains/types';
3
- import { type BitcoinRequest, type CosmosRequest, type EVMRequest } from '../../../chains/near/types';
4
- export declare const EVMTransaction: (req: EVMRequest, keyPair: KeyPair) => Promise<Response>;
5
- export declare const BTCTransaction: (req: BitcoinRequest, keyPair: KeyPair) => Promise<Response>;
6
- export declare const CosmosTransaction: (req: CosmosRequest, keyPair: KeyPair) => Promise<Response>;