signet.js 0.0.10 → 0.0.12
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/browser/index.browser.cjs +2 -2
- package/browser/index.browser.cjs.map +1 -1
- package/browser/index.browser.js +2 -2
- package/browser/index.browser.js.map +1 -1
- package/node/index.node.cjs +2 -2
- package/node/index.node.cjs.map +1 -1
- package/node/index.node.js +2 -2
- package/node/index.node.js.map +1 -1
- package/package.json +3 -1
- package/types/index.d.cts +400 -88
- package/types/index.d.ts +400 -88
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/constants.ts","../../src/utils/index.ts","../../src/utils/cryptography.ts","../../src/chain-adapters/index.ts","../../src/chain-adapters/ChainAdapter.ts","../../src/chain-adapters/EVM/index.ts","../../src/chain-adapters/EVM/EVM.ts","../../src/chain-adapters/EVM/utils.ts","../../src/chain-adapters/Bitcoin/index.ts","../../src/chain-adapters/Bitcoin/utils.ts","../../src/chain-adapters/Bitcoin/Bitcoin.ts","../../src/chain-adapters/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.ts","../../src/chain-adapters/Bitcoin/BTCRpcAdapter/Mempool/Mempool.ts","../../src/chain-adapters/Bitcoin/BTCRpcAdapter/index.ts","../../src/chain-adapters/Cosmos/index.ts","../../src/chain-adapters/Cosmos/utils.ts","../../src/chain-adapters/Cosmos/Cosmos.ts","../../src/contracts/index.ts","../../src/contracts/ChainSignatureContract.ts","../../src/contracts/near/index.ts","../../src/contracts/near/signAndSend/index.ts","../../src/contracts/near/signAndSend/keypair.ts","../../src/contracts/near/account.ts","../../src/contracts/near/constants.ts","../../src/contracts/near/ChainSignatureContract.ts","../../src/utils/publicKey.ts","../../src/contracts/near/transaction.ts","../../src/contracts/evm/index.ts","../../src/contracts/evm/ChainSignaturesContractABI.ts","../../src/contracts/evm/errors.ts","../../src/contracts/evm/utils.ts","../../src/contracts/evm/ChainSignaturesContract.ts"],"names":["constants_exports","__export","CHAINS","CONTRACT_ADDRESSES","ENVS","KDF_CHAIN_IDS","ROOT_PUBLIC_KEYS","utils_exports","cryptography_exports","compressPubKey","deriveChildPublicKey","najToUncompressedPubKeySEC1","toRSV","signature","uncompressedPubKeySEC1","slicedPubKey","x","y","najPublicKey","decodedKey","base58","rootUncompressedPubKeySEC1","predecessorId","path","chainId","ec","EC","derivationPath","scalarHex","keccak256","sha3_256","oldPublicKeyPoint","scalarTimesG","newPublicKeyPoint","newX","newY","chain_adapters_exports","ChainAdapter","Bitcoin_exports","Cosmos_exports","EVM_exports","EVM","fetchEVMFeeProperties","client","transaction","gas","feeData","maxFeePerGas","maxPriorityFeePerGas","publicClient","contract","fees","nonce","from","rest","r","s","yParity","concatHex","numberToHex","predecessor","uncompressedPubKey","publicKeyNoPrefix","hash","getAddress","address","serializeTransaction","serialized","parseTransaction","transactionRequest","serializedTx","txHash","toBytes","message","hashMessage","typedDataRequest","hashTypedData","userOp","entryPointAddress","chainIdArgs","entryPoint","encoded","encodeAbiParameters","hexToBigInt","concat","pad","isAddress","userOpHash","rsvSignatures","rsvSignature","txSerialized","error","BTCRpcAdapter","BTCRpcAdapters","Bitcoin","parseBTCNetwork","network","q","_Bitcoin","btcRpcAdapter","satoshis","btc","transactionId","data","tx","S","vout","scriptPubKey","rawSignature","inputs","outputs","psbt","input","prevOut","out","derivedKey","publicKeyBuffer","payment","transactionJSON","psbtHex","hashesToSign","mockKeyPair","index","publicKey","keyPair","mpcSignature","Mempool","providerUrl","confirmationTarget","targets","utxos","feeRate","ret","coinselect","transactionHex","response","txid","Cosmos","fetchChainInfo","chainInfo","chains","chain","prefix","expectedChainId","denom","rpcUrl","restUrl","gasPrice","asset","assets","decimals","unit","endpoints","Registry","fromHex","amount","b","pubKeySha256","sha256","ripemd160Hash","ripemd160","bech32","TxRaw","toBase64","fromBase64","publicKeyBytes","gasLimit","fee","calculateFee","GasPrice","accountOnChain","StargateClient","accountNumber","sequence","txBodyEncodeObject","txBodyBytes","pubkey","encodePubkey","encodeSecp256k1Pubkey","authInfoBytes","makeAuthInfoBytes","SignMode","signDoc","makeSignDoc","signBytes","makeSignBytes","payload","sig","txBytes","broadcastResponse","contracts_exports","ChainSignatureContract","evm_exports","near_exports","BaseChainSignatureContract","utils","signAndSend_exports","keypair_exports","BTCTransaction","CosmosTransaction","EVMTransaction","NEAR_MAX_GAS","BN","DONT_CARE_ACCOUNT_ID","getNearAccount","networkId","accountId","keypair","KeyPair","keyStore","InMemoryKeyStore","connection","Connection","Account","getRootPublicKey","contractAddress","environment","_","transaction_exports","mpcPayloadsToChainSigTransaction","responseToMpcSignature","sendTransactionUntil","contractId","currentContractFee","getTransactionLastResult","receiverId","actions","options","near","connect","signer","accessKey","recentBlockHash","nearUtils","transactions","nearTransactionSignature","signedTransaction","withRetry","txOutcome","rootPublicKey","sendTransactionOptions","account","Contract","args","najPubKey","deposit","result","actionCreators","req","evm","createPublicClient","http","signatures","cosmos","ChainSignaturesContractABI_exports","abi","errors_exports","ChainSignatureError","SignatureContractError","SignatureNotFoundError","SigningError","requestId","receipt","errorCode","originalError","getRequestId","request","version","count","errorData","fromBlock","errorLogs","logs","signatureData"],"mappings":"4zCAAA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,IAAA,CAAA,IAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,EAAA,CAAA,CAAA,IAAAA,GAAA,GAAAC,CAAAA,CAAAD,EAAA,CAAA,CAAA,MAAA,CAAA,IAAAE,EAAA,kBAAAC,CAAAA,IAAAA,EAAAA,CAAA,IAAAC,CAAAA,IAAAA,CAAAA,CAAA,kBAAAC,CAAA,CAAA,gBAAA,CAAA,IAAAC,KAEO,IAAMF,CAAAA,CAAO,CAClB,WAAa,CAAA,aAAA,CACb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AU,MAAS,CAAA,CAAA,CAAG,CACxB,GAAM,CAAE,IAAMF,CAAAA,CAAU,EAAIE,CAC1BA,CAAAA,CAAAA,CAAU,OAAS,CACrB,CAAA,CAIA,OAAOF,CACT,CAGF,CAWA,MAAM,uBACJR,CACAS,CAAAA,CAAAA,CACmC,CACnC,IAAME,CAAAA,CAAO,MAAM,IAAA,CAAK,aAAa,iBAAkB,CAAA,CACrD,QAAS,IAAK,CAAA,eAAA,CACd,IAAAjB,CACA,CAAA,SAAA,CAAW,oBACX,CAAA,IAAA,CAAM,CACJ,SAAAM,CAAAA,CACF,EACA,SAAAS,CAAAA,CAAAA,CACA,QAAS,QACX,CAAC,CAED,CAAA,GAAIE,EAAK,MAAS,CAAA,CAAA,CAAG,CACnB,GAAM,CAAE,KAAMC,CAAc,CAAA,CAAID,CAAKA,CAAAA,CAAAA,CAAK,OAAS,CAAC,CAAA,CAMpD,OAAOxQ,CAAa,CAAA,KAAA,CAAMyQ,EAAc,SAAS,CACnD,CAGF,CACF,EJ/VA,IAAM9E,EAAAA,CAAQ,CACZ,0BAAA2D,CAAAA,EAAAA,CACA,OAAAE,EACF,CAAA","file":"index.browser.cjs","sourcesContent":["import { type NajPublicKey } from '@types'\n\nexport const ENVS = {\n TESTNET_DEV: 'TESTNET_DEV',\n TESTNET: 'TESTNET',\n MAINNET: 'MAINNET',\n} as const\n\nexport const CHAINS = {\n ETHEREUM: 'ETHEREUM',\n NEAR: 'NEAR',\n} as const\n\n/**\n * Root public keys for the Sig Network Smart Contracts across different environments.\n *\n * These keys should never change.\n */\nexport const ROOT_PUBLIC_KEYS: Record<keyof typeof ENVS, NajPublicKey> = {\n [ENVS.TESTNET_DEV]:\n 'secp256k1:54hU5wcCmVUPFWLDALXMh1fFToZsVXrx9BbTbHzSfQq1Kd1rJZi52iPa4QQxo6s5TgjWqgpY8HamYuUDzG6fAaUq',\n [ENVS.TESTNET]:\n 'secp256k1:3Ww8iFjqTHufye5aRGUvrQqETegR4gVUcW8FX5xzscaN9ENhpkffojsxJwi6N1RbbHMTxYa9UyKeqK3fsMuwxjR5',\n [ENVS.MAINNET]:\n 'secp256k1:4tY4qMzusmgX5wYdG35663Y3Qar3CTbpApotwk9ZKLoF79XA4DjG8XoByaKdNHKQX9Lz5hd7iJqsWdTKyA7dKa6Z',\n}\n\n/**\n * Chain IDs used in the key derivation function (KDF) for deriving child public keys to\n * distinguish between different chains.\n *\n * @see {@link deriveChildPublicKey} in cryptography.ts for usage details\n */\nexport const KDF_CHAIN_IDS = {\n [CHAINS.ETHEREUM]: '0x1',\n [CHAINS.NEAR]: '0x18d',\n} as const\n\n/**\n * Contract addresses for different chains and environments.\n *\n * - Testnet Dev: Used for internal development, very unstable\n * - Testnet: Used for external development, stable\n * - Mainnet: Production contract address\n *\n * @see ChainSignatureContract documentation for implementation details\n */\nexport const CONTRACT_ADDRESSES: Record<\n keyof typeof CHAINS,\n Record<keyof typeof ENVS, string>\n> = {\n [CHAINS.NEAR]: {\n [ENVS.TESTNET_DEV]: 'dev.sig-net.testnet',\n [ENVS.TESTNET]: 'v1.sig-net.testnet',\n [ENVS.MAINNET]: 'v1.sig-net.near',\n },\n [CHAINS.ETHEREUM]: {\n [ENVS.TESTNET_DEV]: '0x69C6b28Fdc74618817fa380De29a653060e14009',\n [ENVS.TESTNET]: '0x83458E8Bf8206131Fe5c05127007FA164c0948A2',\n [ENVS.MAINNET]: '0xf8bdC0612361a1E49a8E01423d4C0cFc5dF4791A',\n },\n}\n","export * as cryptography from './cryptography'\n","import { base58 } from '@scure/base'\nimport { ec as EC } from 'elliptic'\nimport { sha3_256 } from 'js-sha3'\nimport { keccak256 } from 'viem'\n\nimport { KDF_CHAIN_IDS } from '@constants'\nimport {\n type NajPublicKey,\n type MPCSignature,\n type RSVSignature,\n type UncompressedPubKeySEC1,\n} from '@types'\n\nexport const toRSV = (signature: MPCSignature): RSVSignature => {\n // Handle NearNearMpcSignature\n if (\n 'big_r' in signature &&\n typeof signature.big_r === 'object' &&\n 'affine_point' in signature.big_r &&\n 's' in signature &&\n typeof signature.s === 'object' &&\n 'scalar' in signature.s\n ) {\n return {\n r: signature.big_r.affine_point.substring(2),\n s: signature.s.scalar,\n v: signature.recovery_id + 27,\n }\n }\n // Handle SigNetNearMpcSignature\n else if (\n 'big_r' in signature &&\n typeof signature.big_r === 'string' &&\n 's' in signature &&\n typeof signature.s === 'string'\n ) {\n return {\n r: signature.big_r.substring(2),\n s: signature.s,\n v: signature.recovery_id + 27,\n }\n }\n // Handle SigNetEvmMpcSignature\n else if (\n 'bigR' in signature &&\n 'x' in signature.bigR &&\n 's' in signature &&\n typeof signature.s === 'bigint'\n ) {\n return {\n r: signature.bigR.x.toString(16).padStart(64, '0'),\n s: signature.s.toString(16).padStart(64, '0'),\n v: signature.recoveryId + 27,\n }\n }\n\n throw new Error('Invalid signature format')\n}\n\n/**\n * Compresses an uncompressed public key to its compressed format following SEC1 standards.\n * In SEC1, a compressed public key consists of a prefix (02 or 03) followed by the x-coordinate.\n * The prefix indicates whether the y-coordinate is even (02) or odd (03).\n *\n * @param uncompressedPubKeySEC1 - The uncompressed public key in hex format, with or without '04' prefix\n * @returns The compressed public key in hex format\n * @throws Error if the uncompressed public key length is invalid\n */\nexport const compressPubKey = (\n uncompressedPubKeySEC1: UncompressedPubKeySEC1\n): string => {\n const slicedPubKey = uncompressedPubKeySEC1.slice(2)\n\n if (slicedPubKey.length !== 128) {\n throw new Error('Invalid uncompressed public key length')\n }\n\n const x = slicedPubKey.slice(0, 64)\n const y = slicedPubKey.slice(64)\n\n const isEven = parseInt(y.slice(-1), 16) % 2 === 0\n const prefix = isEven ? '02' : '03'\n\n return prefix + x\n}\n\n/**\n * Converts a NAJ public key to an uncompressed SEC1 public key.\n *\n * @param najPublicKey - The NAJ public key to convert (e.g. secp256k1:3Ww8iFjqTHufye5aRGUvrQqETegR4gVUcW8FX5xzscaN9ENhpkffojsxJwi6N1RbbHMTxYa9UyKeqK3fsMuwxjR5)\n * @returns The uncompressed SEC1 public key (e.g. 04 || x || y)\n */\nexport const najToUncompressedPubKeySEC1 = (\n najPublicKey: NajPublicKey\n): UncompressedPubKeySEC1 => {\n const decodedKey = base58.decode(najPublicKey.split(':')[1])\n return `04${Buffer.from(decodedKey).toString('hex')}`\n}\n\n/**\n * Derives a child public key from a parent public key using the sig.network v1.0.0 epsilon derivation scheme.\n * The parent public keys are defined in @constants.ts\n *\n * @param najPublicKey - The parent public key in uncompressed SEC1 format (e.g. 04 || x || y)\n * @param predecessorId - The predecessor ID is the address of the account calling the signer contract (e.g EOA or Contract Address)\n * @param path - Optional derivation path suffix (defaults to empty string)\n * @returns The derived child public key in uncompressed SEC1 format (04 || x || y)\n */\nexport function deriveChildPublicKey(\n rootUncompressedPubKeySEC1: UncompressedPubKeySEC1,\n predecessorId: string,\n path: string = '',\n chainId: string\n): UncompressedPubKeySEC1 {\n const ec = new EC('secp256k1')\n\n const EPSILON_DERIVATION_PREFIX = 'sig.network v1.0.0 epsilon derivation'\n const derivationPath = `${EPSILON_DERIVATION_PREFIX},${chainId},${predecessorId},${path}`\n\n let scalarHex = ''\n\n if (chainId === KDF_CHAIN_IDS.ETHEREUM) {\n scalarHex = keccak256(Buffer.from(derivationPath)).slice(2)\n } else if (chainId === KDF_CHAIN_IDS.NEAR) {\n scalarHex = sha3_256(derivationPath)\n } else {\n throw new Error('Invalid chain ID')\n }\n\n const x = rootUncompressedPubKeySEC1.substring(2, 66)\n const y = rootUncompressedPubKeySEC1.substring(66)\n\n const oldPublicKeyPoint = ec.curve.point(x, y)\n const scalarTimesG = ec.g.mul(scalarHex)\n const newPublicKeyPoint = oldPublicKeyPoint.add(scalarTimesG)\n\n const newX = newPublicKeyPoint.getX().toString('hex').padStart(64, '0')\n const newY = newPublicKeyPoint.getY().toString('hex').padStart(64, '0')\n\n return `04${newX}${newY}`\n}\n","export { ChainAdapter } from './ChainAdapter'\n\nexport * as evm from './EVM'\nexport * as btc from './Bitcoin'\nexport * as cosmos from './Cosmos'\n","import type { KeyDerivationPath, HashToSign, RSVSignature } from '@types'\n\nexport abstract class ChainAdapter<TransactionRequest, UnsignedTransaction> {\n /**\n * Gets the native token balance and decimals for a given address\n *\n * @param address - The address to check\n * @returns Promise resolving to an object containing:\n * - balance: The balance as a bigint, in the chain's base units\n * - decimals: The number of decimals used to format the balance\n */\n abstract getBalance(address: string): Promise<{\n balance: bigint\n decimals: number\n }>\n\n /**\n * Uses Sig Network Key Derivation Function to derive the address and public key. from a signer ID and string path.\n *\n * @param predecessor - The id/address of the account requesting signature\n * @param path - The string path used to derive the key\n * @returns Promise resolving to the derived address and public key\n */\n abstract deriveAddressAndPublicKey(\n predecessor: string,\n path: KeyDerivationPath\n ): Promise<{\n address: string\n publicKey: string\n }>\n\n /**\n * Serializes an unsigned transaction to a string format.\n * This is useful for storing or transmitting the transaction.\n *\n * @param transaction - The unsigned transaction to serialize\n * @returns The serialized transaction string\n */\n abstract serializeTransaction(transaction: UnsignedTransaction): string\n\n /**\n * Deserializes a transaction string back into an unsigned transaction object.\n * This reverses the serialization done by serializeTransaction().\n *\n * @param serialized - The serialized transaction string\n * @returns The deserialized unsigned transaction\n */\n abstract deserializeTransaction(serialized: string): UnsignedTransaction\n\n /**\n * Prepares a transaction for Sig Network MPC signing by creating the necessary payloads.\n * This method handles chain-specific transaction preparation including:\n * - Fee calculation\n * - Nonce/sequence management\n * - UTXO selection (for UTXO-based chains)\n * - Transaction encoding\n *\n * @param transactionRequest - The transaction request containing parameters like recipient, amount, etc.\n * @returns Promise resolving to an object containing:\n * - transaction: The unsigned transaction\n * - hashesToSign: Array of payloads to be signed by MPC. The order of these payloads must match\n * the order of signatures provided to finalizeTransactionSigning()\n */\n abstract prepareTransactionForSigning(\n transactionRequest: TransactionRequest\n ): Promise<{\n transaction: UnsignedTransaction\n hashesToSign: HashToSign[]\n }>\n\n /**\n * Adds Sig Network MPC-generated signatures to an unsigned transaction.\n *\n * @param params - Parameters for adding signatures\n * @param params.transaction - The unsigned transaction to add signatures to\n * @param params.rsvSignatures - Array of RSV signatures generated through MPC. Must be in the same order\n * as the payloads returned by prepareTransactionForSigning()\n * @returns The serialized signed transaction ready for broadcast\n */\n abstract finalizeTransactionSigning(params: {\n transaction: UnsignedTransaction\n rsvSignatures: RSVSignature[]\n }): string\n\n /**\n * Broadcasts a signed transaction to the network.\n *\n * @param txSerialized - The serialized signed transaction\n * @returns Promise resolving to the transaction hash/ID\n */\n abstract broadcastTx(txSerialized: string): Promise<string>\n}\n","// EVM\nexport { EVM } from './EVM'\n\nexport { fetchEVMFeeProperties } from './utils'\n\nexport type {\n EVMTransactionRequest,\n EVMUnsignedTransaction,\n EVMMessage,\n EVMTypedData,\n} from './types'\n","import {\n createPublicClient,\n http,\n parseTransaction,\n type PublicClient,\n hashMessage,\n hashTypedData,\n keccak256,\n toBytes,\n type Hex,\n serializeTransaction,\n type Signature,\n numberToHex,\n getAddress,\n type Address,\n type Hash,\n concatHex,\n encodeAbiParameters,\n hexToBigInt,\n concat,\n pad,\n isAddress,\n} from 'viem'\n\nimport { ChainAdapter } from '@chain-adapters/ChainAdapter'\nimport type {\n EVMTransactionRequest,\n EVMUnsignedTransaction,\n EVMMessage,\n EVMTypedData,\n UserOperationV6,\n UserOperationV7,\n} from '@chain-adapters/EVM/types'\nimport { fetchEVMFeeProperties } from '@chain-adapters/EVM/utils'\nimport type { BaseChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { HashToSign, RSVSignature, KeyDerivationPath } from '@types'\n\n/**\n * Implementation of the ChainAdapter interface for EVM-compatible networks.\n * Handles interactions with Ethereum Virtual Machine based blockchains like Ethereum, BSC, Polygon, etc.\n */\nexport class EVM extends ChainAdapter<\n EVMTransactionRequest,\n EVMUnsignedTransaction\n> {\n private readonly client: PublicClient\n private readonly contract: BaseChainSignatureContract\n\n /**\n * Creates a new EVM chain instance\n * @param params - Configuration parameters\n * @param params.publicClient - A Viem PublicClient instance for reading from the blockchain\n * @param params.contract - Instance of the chain signature contract for MPC operations\n */\n constructor({\n publicClient,\n contract,\n }: {\n publicClient: PublicClient\n contract: BaseChainSignatureContract\n }) {\n super()\n\n this.contract = contract\n this.client = publicClient;\n }\n\n private async attachGasAndNonce(\n transaction: EVMTransactionRequest\n ): Promise<EVMUnsignedTransaction> {\n const fees = await fetchEVMFeeProperties(this.client, transaction)\n const nonce = await this.client.getTransactionCount({\n address: transaction.from,\n })\n\n const { from, ...rest } = transaction\n\n return {\n ...fees,\n nonce,\n chainId: Number(await this.client.getChainId()),\n type: 'eip1559',\n ...rest,\n }\n }\n\n private transformRSVSignature(signature: RSVSignature): Signature {\n return {\n r: `0x${signature.r}`,\n s: `0x${signature.s}`,\n yParity: signature.v - 27,\n }\n }\n\n private assembleSignature(signature: RSVSignature): Hex {\n const { r, s, yParity } = this.transformRSVSignature(signature)\n\n if (yParity === undefined) {\n throw new Error('Missing yParity')\n }\n\n return concatHex([r, s, numberToHex(yParity + 27, { size: 1 })])\n }\n\n async deriveAddressAndPublicKey(\n predecessor: string,\n path: KeyDerivationPath\n ): Promise<{\n address: string\n publicKey: string\n }> {\n const uncompressedPubKey = await this.contract.getDerivedPublicKey({\n path,\n predecessor,\n })\n\n if (!uncompressedPubKey) {\n throw new Error('Failed to get derived public key')\n }\n\n const publicKeyNoPrefix = uncompressedPubKey.startsWith('04')\n ? uncompressedPubKey.slice(2)\n : uncompressedPubKey\n\n const hash = keccak256(Buffer.from(publicKeyNoPrefix, 'hex'))\n const address = getAddress(`0x${hash.slice(-40)}`)\n\n return {\n address,\n publicKey: uncompressedPubKey,\n }\n }\n\n async getBalance(\n address: string\n ): Promise<{ balance: bigint; decimals: number }> {\n const balance = await this.client.getBalance({\n address: address as Address,\n })\n return {\n balance,\n decimals: 18,\n }\n }\n\n serializeTransaction(transaction: EVMUnsignedTransaction): `0x${string}` {\n return serializeTransaction(transaction)\n }\n\n deserializeTransaction(serialized: `0x${string}`): EVMUnsignedTransaction {\n return parseTransaction(serialized) as EVMUnsignedTransaction\n }\n\n async prepareTransactionForSigning(\n transactionRequest: EVMTransactionRequest\n ): Promise<{\n transaction: EVMUnsignedTransaction\n hashesToSign: HashToSign[]\n }> {\n const transaction = await this.attachGasAndNonce(transactionRequest)\n\n const serializedTx = serializeTransaction(transaction)\n const txHash = toBytes(keccak256(serializedTx))\n\n return {\n transaction,\n hashesToSign: [Array.from(txHash)],\n }\n }\n\n async prepareMessageForSigning(message: EVMMessage): Promise<{\n hashToSign: HashToSign\n }> {\n return {\n hashToSign: Array.from(toBytes(hashMessage(message))),\n }\n }\n\n async prepareTypedDataForSigning(typedDataRequest: EVMTypedData): Promise<{\n hashToSign: HashToSign\n }> {\n return {\n hashToSign: Array.from(toBytes(hashTypedData(typedDataRequest))),\n }\n }\n\n /**\n * This implementation is a common step for Biconomy and Alchemy.\n * Key differences between implementations:\n * - Signature format: Biconomy omits 0x00 prefix when concatenating, Alchemy includes it\n * - Version support: Biconomy only supports v6, Alchemy supports both v6 and v7\n * - Validation: Biconomy uses modules for signature validation, Alchemy uses built-in validation\n */\n async prepareUserOpForSigning(\n userOp: UserOperationV7 | UserOperationV6,\n entryPointAddress?: Address,\n chainIdArgs?: number\n ): Promise<{\n userOp: UserOperationV7 | UserOperationV6\n hashToSign: HashToSign\n }> {\n const chainId = chainIdArgs ?? (await this.client.getChainId())\n const entryPoint =\n entryPointAddress || '0x0000000071727De22E5E9d8BAf0edAc6f37da032'\n\n const encoded = encodeAbiParameters(\n [{ type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }],\n [\n keccak256(\n encodeAbiParameters(\n [\n { type: 'address' },\n { type: 'uint256' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n { type: 'uint256' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n ],\n [\n userOp.sender,\n hexToBigInt(userOp.nonce),\n keccak256(\n 'factory' in userOp &&\n 'factoryData' in userOp &&\n userOp.factory &&\n userOp.factoryData\n ? concat([userOp.factory, userOp.factoryData])\n : 'initCode' in userOp\n ? userOp.initCode\n : '0x'\n ),\n keccak256(userOp.callData),\n concat([\n pad(userOp.verificationGasLimit, { size: 16 }),\n pad(userOp.callGasLimit, { size: 16 }),\n ]),\n hexToBigInt(userOp.preVerificationGas),\n concat([\n pad(userOp.maxPriorityFeePerGas, { size: 16 }),\n pad(userOp.maxFeePerGas, { size: 16 }),\n ]),\n keccak256(\n 'paymaster' in userOp &&\n userOp.paymaster &&\n isAddress(userOp.paymaster)\n ? concat([\n userOp.paymaster,\n pad(userOp.paymasterVerificationGasLimit, { size: 16 }),\n pad(userOp.paymasterPostOpGasLimit, { size: 16 }),\n userOp.paymasterData,\n ])\n : 'paymasterAndData' in userOp\n ? userOp.paymasterAndData\n : '0x'\n ),\n ]\n )\n ),\n entryPoint,\n BigInt(chainId),\n ]\n )\n\n const userOpHash = keccak256(encoded)\n\n return {\n userOp,\n hashToSign: Array.from(toBytes(hashMessage({ raw: userOpHash }))),\n }\n }\n\n finalizeTransactionSigning({\n transaction,\n rsvSignatures,\n }: {\n transaction: EVMUnsignedTransaction\n rsvSignatures: RSVSignature[]\n }): `0x02${string}` {\n const signature = this.transformRSVSignature(rsvSignatures[0])\n\n return serializeTransaction(transaction, signature)\n }\n\n finalizeMessageSigning({\n rsvSignature,\n }: {\n rsvSignature: RSVSignature\n }): Hex {\n return this.assembleSignature(rsvSignature)\n }\n\n finalizeTypedDataSigning({\n rsvSignature,\n }: {\n rsvSignature: RSVSignature\n }): Hex {\n return this.assembleSignature(rsvSignature)\n }\n\n finalizeUserOpSigning({\n userOp,\n rsvSignature,\n }: {\n userOp: UserOperationV7 | UserOperationV6\n rsvSignature: RSVSignature\n }): UserOperationV7 | UserOperationV6 {\n const { r, s, yParity } = this.transformRSVSignature(rsvSignature)\n if (yParity === undefined) {\n throw new Error('Missing yParity')\n }\n\n return {\n ...userOp,\n signature: concatHex([\n '0x00', // Alchemy specific implementation. Biconomy doesn't include the 0x00 prefix.\n r,\n s,\n numberToHex(Number(yParity + 27), { size: 1 }),\n ]),\n }\n }\n\n async broadcastTx(txSerialized: `0x${string}`): Promise<Hash> {\n try {\n return await this.client.sendRawTransaction({\n serializedTransaction: txSerialized,\n })\n } catch (error) {\n console.error('Transaction broadcast failed:', error)\n throw new Error('Failed to broadcast transaction.')\n }\n }\n}\n","import { type PublicClient, type TransactionRequest } from 'viem'\n\nexport interface EVMFeeProperties {\n gas: bigint\n maxFeePerGas: bigint\n maxPriorityFeePerGas: bigint\n}\n\nexport async function fetchEVMFeeProperties(\n client: PublicClient,\n transaction: TransactionRequest\n): Promise<EVMFeeProperties> {\n const [gas, feeData] = await Promise.all([\n client.estimateGas(transaction),\n client.estimateFeesPerGas(),\n ])\n\n const maxFeePerGas = feeData.maxFeePerGas ?? BigInt(10_000_000_000) // 10 gwei\n const maxPriorityFeePerGas =\n feeData.maxPriorityFeePerGas ?? BigInt(10_000_000_000) // 10 gwei\n\n return {\n gas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n }\n}\n","// Bitcoin\nexport { Bitcoin } from './Bitcoin'\n\nexport { BTCRpcAdapters, BTCRpcAdapter } from './BTCRpcAdapter'\n\nexport type {\n BTCTransactionRequest,\n BTCUnsignedTransaction,\n BTCTransaction,\n BTCOutput,\n BTCInput,\n BTCNetworkIds,\n} from './types'\n","import * as bitcoin from 'bitcoinjs-lib'\n\nexport function parseBTCNetwork(network: string): bitcoin.networks.Network {\n switch (network.toLowerCase()) {\n case 'mainnet':\n return bitcoin.networks.bitcoin\n case 'testnet':\n return bitcoin.networks.testnet\n case 'regtest':\n return bitcoin.networks.regtest\n default:\n throw new Error(`Unknown Bitcoin network: ${network}`)\n }\n}\n","import * as bitcoin from 'bitcoinjs-lib'\n\nimport { type BTCRpcAdapter } from '@chain-adapters/Bitcoin/BTCRpcAdapter'\nimport type {\n BTCInput,\n BTCNetworkIds,\n BTCOutput,\n BTCTransactionRequest,\n BTCUnsignedTransaction,\n} from '@chain-adapters/Bitcoin/types'\nimport { parseBTCNetwork } from '@chain-adapters/Bitcoin/utils'\nimport { ChainAdapter } from '@chain-adapters/ChainAdapter'\nimport type { BaseChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { HashToSign, RSVSignature, KeyDerivationPath } from '@types'\nimport { cryptography } from '@utils'\n\n/**\n * Implementation of the ChainAdapter interface for Bitcoin network.\n * Handles interactions with both Bitcoin mainnet and testnet, supporting P2WPKH transactions.\n */\nexport class Bitcoin extends ChainAdapter<\n BTCTransactionRequest,\n BTCUnsignedTransaction\n> {\n private static readonly SATOSHIS_PER_BTC = 100_000_000\n\n private readonly network: BTCNetworkIds\n private readonly btcRpcAdapter: BTCRpcAdapter\n private readonly contract: BaseChainSignatureContract\n\n /**\n * Creates a new Bitcoin chain instance\n * @param params - Configuration parameters\n * @param params.network - Network identifier (mainnet/testnet)\n * @param params.contract - Instance of the chain signature contract for MPC operations\n * @param params.btcRpcAdapter - Bitcoin RPC adapter for network interactions\n */\n constructor({\n network,\n contract,\n btcRpcAdapter,\n }: {\n network: BTCNetworkIds\n contract: BaseChainSignatureContract\n btcRpcAdapter: BTCRpcAdapter\n }) {\n super()\n\n this.network = network\n this.btcRpcAdapter = btcRpcAdapter\n this.contract = contract\n }\n\n /**\n * Converts satoshis to BTC\n * @param satoshis - Amount in satoshis\n * @returns Amount in BTC\n */\n static toBTC(satoshis: number): number {\n return satoshis / Bitcoin.SATOSHIS_PER_BTC\n }\n\n /**\n * Converts BTC to satoshis\n * @param btc - Amount in BTC\n * @returns Amount in satoshis (rounded)\n */\n static toSatoshi(btc: number): number {\n return Math.round(btc * Bitcoin.SATOSHIS_PER_BTC)\n }\n\n private async fetchTransaction(\n transactionId: string\n ): Promise<bitcoin.Transaction> {\n const data = await this.btcRpcAdapter.getTransaction(transactionId)\n const tx = new bitcoin.Transaction()\n\n data.vout.forEach((vout) => {\n const scriptPubKey = Buffer.from(vout.scriptpubkey, 'hex')\n tx.addOutput(scriptPubKey, Number(vout.value))\n })\n\n return tx\n }\n\n private static transformRSVSignature(signature: RSVSignature): Buffer {\n const r = signature.r.padStart(64, '0')\n const s = signature.s.padStart(64, '0')\n\n const rawSignature = Buffer.from(r + s, 'hex')\n\n if (rawSignature.length !== 64) {\n throw new Error('Invalid signature length.')\n }\n\n return rawSignature\n }\n\n /**\n * Creates a Partially Signed Bitcoin Transaction (PSBT)\n * @param params - Parameters for creating the PSBT\n * @param params.transactionRequest - Transaction request containing inputs and outputs\n * @returns Created PSBT instance\n */\n async createPSBT({\n transactionRequest,\n }: {\n transactionRequest: BTCTransactionRequest\n }): Promise<bitcoin.Psbt> {\n const { inputs, outputs } =\n transactionRequest.inputs && transactionRequest.outputs\n ? transactionRequest\n : await this.btcRpcAdapter.selectUTXOs(transactionRequest.from, [\n {\n address: transactionRequest.to,\n value: parseFloat(transactionRequest.value),\n },\n ])\n\n const psbt = new bitcoin.Psbt({ network: parseBTCNetwork(this.network) })\n\n await Promise.all(\n inputs.map(async (input: BTCInput) => {\n if (!input.scriptPubKey) {\n const transaction = await this.fetchTransaction(input.txid)\n const prevOut = transaction.outs[input.vout]\n input.scriptPubKey = prevOut.script\n }\n\n // Prepare the input as P2WPKH\n psbt.addInput({\n hash: input.txid,\n index: input.vout,\n witnessUtxo: {\n script: input.scriptPubKey,\n value: input.value,\n },\n })\n })\n )\n\n outputs.forEach((out: BTCOutput) => {\n if ('address' in out) {\n psbt.addOutput({\n address: out.address,\n value: out.value,\n })\n } else if ('script' in out) {\n psbt.addOutput({\n script: out.script,\n value: out.value,\n })\n } else if (transactionRequest.from !== undefined) {\n // Include change address from coinselect\n psbt.addOutput({\n value: Number(out.value),\n address: transactionRequest.from,\n })\n }\n })\n\n return psbt\n }\n\n async getBalance(\n address: string\n ): Promise<{ balance: bigint; decimals: number }> {\n const balance = BigInt(await this.btcRpcAdapter.getBalance(address))\n return {\n balance,\n decimals: 8,\n }\n }\n\n async deriveAddressAndPublicKey(\n predecessor: string,\n path: KeyDerivationPath\n ): Promise<{ address: string; publicKey: string }> {\n const uncompressedPubKey = await this.contract.getDerivedPublicKey({\n path,\n predecessor,\n })\n\n if (!uncompressedPubKey) {\n throw new Error('Failed to get derived public key')\n }\n\n const derivedKey = cryptography.compressPubKey(uncompressedPubKey)\n const publicKeyBuffer = Buffer.from(derivedKey, 'hex')\n const network = parseBTCNetwork(this.network)\n\n const payment = bitcoin.payments.p2wpkh({\n pubkey: publicKeyBuffer,\n network,\n })\n\n const { address } = payment\n\n if (!address) {\n throw new Error('Failed to generate Bitcoin address')\n }\n\n return { address, publicKey: derivedKey }\n }\n\n serializeTransaction(transaction: BTCUnsignedTransaction): string {\n return JSON.stringify({\n psbt: transaction.psbt.toHex(),\n publicKey: transaction.publicKey,\n })\n }\n\n deserializeTransaction(serialized: string): BTCUnsignedTransaction {\n const transactionJSON = JSON.parse(serialized)\n return {\n psbt: bitcoin.Psbt.fromHex(transactionJSON.psbt as string),\n publicKey: transactionJSON.publicKey,\n }\n }\n\n async prepareTransactionForSigning(\n transactionRequest: BTCTransactionRequest\n ): Promise<{\n transaction: BTCUnsignedTransaction\n hashesToSign: HashToSign[]\n }> {\n const publicKeyBuffer = Buffer.from(transactionRequest.publicKey, 'hex')\n const psbt = await this.createPSBT({\n transactionRequest,\n })\n\n // We can't double sign a PSBT, therefore we serialize the payload before to return it\n const psbtHex = psbt.toHex()\n\n const hashesToSign: HashToSign[] = []\n\n const mockKeyPair = (index: number): bitcoin.Signer => ({\n publicKey: publicKeyBuffer,\n sign: (hash: Buffer): Buffer => {\n hashesToSign[index] = Array.from(hash)\n // Return dummy signature to satisfy the interface\n return Buffer.alloc(64)\n },\n })\n\n for (let index = 0; index < psbt.inputCount; index++) {\n psbt.signInput(index, mockKeyPair(index))\n }\n\n return {\n transaction: {\n psbt: bitcoin.Psbt.fromHex(psbtHex),\n publicKey: transactionRequest.publicKey,\n },\n hashesToSign,\n }\n }\n\n finalizeTransactionSigning({\n transaction: { psbt, publicKey },\n rsvSignatures,\n }: {\n transaction: BTCUnsignedTransaction\n rsvSignatures: RSVSignature[]\n }): string {\n const publicKeyBuffer = Buffer.from(publicKey, 'hex')\n\n const keyPair = (index: number): bitcoin.Signer => ({\n publicKey: publicKeyBuffer,\n sign: () => {\n const mpcSignature = rsvSignatures[index]\n return Bitcoin.transformRSVSignature(mpcSignature)\n },\n })\n\n for (let index = 0; index < psbt.inputCount; index++) {\n psbt.signInput(index, keyPair(index))\n }\n\n psbt.finalizeAllInputs()\n return psbt.extractTransaction().toHex()\n }\n\n async broadcastTx(txSerialized: string): Promise<string> {\n return await this.btcRpcAdapter.broadcastTransaction(txSerialized)\n }\n}\n","import type {\n BTCTransaction,\n BTCInput,\n BTCOutput,\n} from '@chain-adapters/Bitcoin/types'\n\nexport abstract class BTCRpcAdapter {\n abstract selectUTXOs(\n from: string,\n targets: BTCOutput[]\n ): Promise<{ inputs: BTCInput[]; outputs: BTCOutput[] }>\n abstract broadcastTransaction(transactionHex: string): Promise<string>\n abstract getBalance(address: string): Promise<number>\n abstract getTransaction(txid: string): Promise<BTCTransaction>\n}\n","// There is no types for coinselect\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-expect-error\n\nimport coinselect from 'coinselect'\n\nimport { BTCRpcAdapter } from '@chain-adapters/Bitcoin/BTCRpcAdapter/BTCRpcAdapter'\nimport {\n type BTCFeeRecommendation,\n type UTXO,\n} from '@chain-adapters/Bitcoin/BTCRpcAdapter/Mempool/types'\nimport type {\n BTCTransaction,\n BTCInput,\n BTCOutput,\n} from '@chain-adapters/Bitcoin/types'\n\nexport class Mempool extends BTCRpcAdapter {\n private readonly providerUrl: string\n\n constructor(providerUrl: string) {\n super()\n this.providerUrl = providerUrl\n }\n\n private async fetchFeeRate(confirmationTarget = 6): Promise<number> {\n const response = await fetch(`${this.providerUrl}/v1/fees/recommended`)\n const data = (await response.json()) as BTCFeeRecommendation\n\n if (confirmationTarget <= 1) {\n return data.fastestFee\n } else if (confirmationTarget <= 3) {\n return data.halfHourFee\n } else if (confirmationTarget <= 6) {\n return data.hourFee\n } else {\n return data.economyFee\n }\n }\n\n private async fetchUTXOs(address: string): Promise<UTXO[]> {\n try {\n const response = await fetch(\n `${this.providerUrl}/address/${address}/utxo`\n )\n return (await response.json()) as UTXO[]\n } catch (error) {\n console.error('Failed to fetch UTXOs:', error)\n return []\n }\n }\n\n async selectUTXOs(\n from: string,\n targets: BTCOutput[],\n confirmationTarget = 6\n ): Promise<{ inputs: BTCInput[]; outputs: BTCOutput[] }> {\n const utxos = await this.fetchUTXOs(from)\n const feeRate = await this.fetchFeeRate(confirmationTarget)\n\n // Add a small amount to the fee rate to ensure the transaction is confirmed\n const ret = coinselect(utxos, targets, Math.ceil(feeRate + 1))\n\n if (!ret.inputs || !ret.outputs) {\n throw new Error(\n '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.'\n )\n }\n\n return {\n inputs: ret.inputs,\n outputs: ret.outputs,\n }\n }\n\n async broadcastTransaction(transactionHex: string): Promise<string> {\n const response = await fetch(`${this.providerUrl}/tx`, {\n method: 'POST',\n body: transactionHex,\n })\n\n if (response.ok) {\n return await response.text()\n }\n\n throw new Error(`Failed to broadcast transaction: ${await response.text()}`)\n }\n\n async getBalance(address: string): Promise<number> {\n const response = await fetch(`${this.providerUrl}/address/${address}`)\n const data = (await response.json()) as {\n chain_stats: { funded_txo_sum: number; spent_txo_sum: number }\n }\n return data.chain_stats.funded_txo_sum - data.chain_stats.spent_txo_sum\n }\n\n async getTransaction(txid: string): Promise<BTCTransaction> {\n const response = await fetch(`${this.providerUrl}/tx/${txid}`)\n return (await response.json()) as BTCTransaction\n }\n}\n","import { Mempool } from './Mempool'\nexport { BTCRpcAdapter } from './BTCRpcAdapter'\n\nexport const BTCRpcAdapters = {\n Mempool,\n}\n","// Cosmos\nexport { Cosmos } from './Cosmos'\n\nexport type {\n CosmosNetworkIds,\n CosmosTransactionRequest,\n CosmosUnsignedTransaction,\n} from './types'\n","import { chains, assets } from 'chain-registry'\n\nimport { type ChainInfo } from '@chain-adapters/Cosmos/types'\n\nexport const fetchChainInfo = async (chainId: string): Promise<ChainInfo> => {\n const chainInfo = chains.find((chain) => chain.chain_id === chainId)\n if (!chainInfo) {\n throw new Error(`Chain info not found for chainId: ${chainId}`)\n }\n\n const { bech32_prefix: prefix, chain_id: expectedChainId } = chainInfo\n const denom = chainInfo.staking?.staking_tokens?.[0]?.denom\n const rpcUrl = chainInfo.apis?.rpc?.[0]?.address\n const restUrl = chainInfo.apis?.rest?.[0]?.address\n const gasPrice = chainInfo.fees?.fee_tokens?.[0]?.average_gas_price\n\n if (\n !prefix ||\n !denom ||\n !rpcUrl ||\n !restUrl ||\n !expectedChainId ||\n gasPrice === undefined\n ) {\n throw new Error(\n `Missing required chain information for ${chainInfo.chain_name}`\n )\n }\n\n const assetList = assets.find(\n (asset) => asset.chain_name === chainInfo.chain_name\n )\n const asset = assetList?.assets.find((asset) => asset.base === denom)\n const decimals = asset?.denom_units.find(\n (unit) => unit.denom === asset.display\n )?.exponent\n\n if (decimals === undefined) {\n throw new Error(\n `Could not find decimals for ${denom} on chain ${chainInfo.chain_name}`\n )\n }\n\n return { prefix, denom, rpcUrl, restUrl, expectedChainId, gasPrice, decimals }\n}\n","import { encodeSecp256k1Pubkey } from '@cosmjs/amino'\nimport { ripemd160, sha256 } from '@cosmjs/crypto'\nimport { toBase64, fromBase64, fromHex } from '@cosmjs/encoding'\nimport {\n Registry,\n makeSignBytes,\n encodePubkey,\n makeAuthInfoBytes,\n makeSignDoc,\n type TxBodyEncodeObject,\n} from '@cosmjs/proto-signing'\nimport { GasPrice, StargateClient, calculateFee } from '@cosmjs/stargate'\nimport { bech32 } from 'bech32'\nimport { SignMode } from 'cosmjs-types/cosmos/tx/signing/v1beta1/signing'\nimport { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx'\n\nimport { ChainAdapter } from '@chain-adapters/ChainAdapter'\nimport type {\n CosmosNetworkIds,\n CosmosTransactionRequest,\n CosmosUnsignedTransaction,\n ChainInfo,\n BalanceResponse,\n} from '@chain-adapters/Cosmos/types'\nimport { fetchChainInfo } from '@chain-adapters/Cosmos/utils'\nimport type { BaseChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { HashToSign, RSVSignature, KeyDerivationPath } from '@types'\nimport { cryptography } from '@utils'\n\n/**\n * Implementation of the ChainAdapter interface for Cosmos-based networks.\n * Handles interactions with Cosmos SDK chains like Cosmos Hub, Osmosis, etc.\n */\nexport class Cosmos extends ChainAdapter<\n CosmosTransactionRequest,\n CosmosUnsignedTransaction\n> {\n private readonly registry: Registry\n private readonly chainId: CosmosNetworkIds\n private readonly contract: BaseChainSignatureContract\n private readonly endpoints?: {\n rpcUrl?: string\n restUrl?: string\n }\n\n /**\n * Creates a new Cosmos chain instance\n * @param params - Configuration parameters\n * @param params.chainId - Chain id for the Cosmos network\n * @param params.contract - Instance of the chain signature contract for MPC operations\n * @param params.endpoints - Optional RPC and REST endpoints\n * @param params.endpoints.rpcUrl - Optional RPC endpoint URL\n * @param params.endpoints.restUrl - Optional REST endpoint URL\n */\n constructor({\n chainId,\n contract,\n endpoints,\n }: {\n contract: BaseChainSignatureContract\n chainId: CosmosNetworkIds\n endpoints?: {\n rpcUrl?: string\n restUrl?: string\n }\n }) {\n super()\n\n this.contract = contract\n this.registry = new Registry()\n this.chainId = chainId\n this.endpoints = endpoints\n }\n\n private transformRSVSignature(rsvSignature: RSVSignature): Uint8Array {\n return new Uint8Array([\n ...fromHex(rsvSignature.r),\n ...fromHex(rsvSignature.s),\n ])\n }\n\n private async getChainInfo(): Promise<ChainInfo> {\n return {\n ...(await fetchChainInfo(this.chainId)),\n ...this.endpoints,\n }\n }\n\n async getBalance(\n address: string\n ): Promise<{ balance: bigint; decimals: number }> {\n try {\n const { restUrl, denom, decimals } = await this.getChainInfo()\n\n const response = await fetch(\n `${restUrl}/cosmos/bank/v1beta1/balances/${address}`\n )\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`)\n }\n\n const data = (await response.json()) as BalanceResponse\n const balance = data.balances.find((b) => b.denom === denom)\n const amount = balance?.amount ?? '0'\n\n return {\n balance: BigInt(amount),\n decimals,\n }\n } catch (error) {\n console.error('Failed to fetch Cosmos balance:', error)\n throw new Error('Failed to fetch Cosmos balance')\n }\n }\n\n async deriveAddressAndPublicKey(\n predecessor: string,\n path: KeyDerivationPath\n ): Promise<{\n address: string\n publicKey: string\n }> {\n const { prefix } = await this.getChainInfo()\n const uncompressedPubKey = await this.contract.getDerivedPublicKey({\n path,\n predecessor,\n })\n\n if (!uncompressedPubKey) {\n throw new Error('Failed to get derived public key')\n }\n\n const derivedKey = cryptography.compressPubKey(uncompressedPubKey)\n const pubKeySha256 = sha256(fromHex(derivedKey))\n const ripemd160Hash = ripemd160(pubKeySha256)\n const address = bech32.encode(prefix, bech32.toWords(ripemd160Hash))\n\n return { address, publicKey: derivedKey }\n }\n\n serializeTransaction(transaction: CosmosUnsignedTransaction): string {\n const serialized = TxRaw.encode(transaction).finish()\n return toBase64(serialized)\n }\n\n deserializeTransaction(serialized: string): CosmosUnsignedTransaction {\n return TxRaw.decode(fromBase64(serialized))\n }\n\n async prepareTransactionForSigning(\n transactionRequest: CosmosTransactionRequest\n ): Promise<{\n transaction: CosmosUnsignedTransaction\n hashesToSign: HashToSign[]\n }> {\n const { denom, rpcUrl, gasPrice } = await this.getChainInfo()\n const publicKeyBytes = fromHex(transactionRequest.publicKey)\n\n const gasLimit = transactionRequest.gas || 200_000\n\n const fee = calculateFee(\n gasLimit,\n GasPrice.fromString(`${gasPrice}${denom}`)\n )\n\n const client = await StargateClient.connect(rpcUrl)\n const accountOnChain = await client.getAccount(transactionRequest.address)\n if (!accountOnChain) {\n throw new Error(\n `Account ${transactionRequest.address} does not exist on chain`\n )\n }\n\n const { accountNumber, sequence } = accountOnChain\n\n const txBodyEncodeObject: TxBodyEncodeObject = {\n typeUrl: '/cosmos.tx.v1beta1.TxBody',\n value: {\n messages: transactionRequest.messages,\n memo: transactionRequest.memo || '',\n },\n }\n\n const txBodyBytes = this.registry.encode(txBodyEncodeObject)\n\n const pubkey = encodePubkey(encodeSecp256k1Pubkey(publicKeyBytes))\n\n // TODO: Allow caller to provide: multiple signers, fee payer, fee granter\n const authInfoBytes = makeAuthInfoBytes(\n [\n {\n pubkey,\n sequence,\n },\n ],\n fee.amount,\n Number(fee.gas),\n undefined,\n undefined,\n SignMode.SIGN_MODE_DIRECT\n )\n\n const signDoc = makeSignDoc(\n txBodyBytes,\n authInfoBytes,\n this.chainId,\n accountNumber\n )\n\n const signBytes = makeSignBytes(signDoc)\n const payload = Array.from(sha256(signBytes))\n\n return {\n transaction: TxRaw.fromPartial({\n bodyBytes: txBodyBytes,\n authInfoBytes,\n signatures: [],\n }),\n hashesToSign: [payload],\n }\n }\n\n finalizeTransactionSigning({\n transaction,\n rsvSignatures,\n }: {\n transaction: CosmosUnsignedTransaction\n rsvSignatures: RSVSignature[]\n }): string {\n // Allow support for multi-sig but the package only supports single-sig\n transaction.signatures = rsvSignatures.map((sig) =>\n this.transformRSVSignature(sig)\n )\n\n const txBytes = TxRaw.encode(transaction).finish()\n return Buffer.from(txBytes).toString('hex')\n }\n\n async broadcastTx(txSerialized: string): Promise<string> {\n try {\n const { rpcUrl } = await this.getChainInfo()\n const client = await StargateClient.connect(rpcUrl)\n\n const txBytes = fromHex(txSerialized)\n const broadcastResponse = await client.broadcastTx(txBytes)\n\n if (broadcastResponse.code !== 0) {\n throw new Error(`Broadcast error: ${broadcastResponse.rawLog}`)\n }\n\n return broadcastResponse.transactionHash\n } catch (error) {\n console.error('Transaction broadcast failed:', error)\n throw new Error('Failed to broadcast transaction.')\n }\n }\n}\n","export { ChainSignatureContract, type SignArgs } from './ChainSignatureContract'\n\nexport * as near from './near'\nexport * as evm from './evm'\n","import type BN from 'bn.js'\n\nimport type { RSVSignature, UncompressedPubKeySEC1 } from '@types'\n\nexport interface SignArgs {\n /** The payload to sign as an array of 32 bytes */\n payload: number[]\n /** The derivation path for key generation */\n path: string\n /** Version of the key to use */\n key_version: number\n}\n\n/**\n * Base contract interface required for compatibility with ChainAdapter instances like EVM and Bitcoin.\n *\n * See {@link EVM} and {@link Bitcoin} for example implementations.\n */\nexport abstract class BaseChainSignatureContract {\n /**\n * Gets the current signature deposit required by the contract.\n * This deposit amount helps manage network congestion.\n *\n * @returns Promise resolving to the required deposit amount as a BigNumber\n */\n abstract getCurrentSignatureDeposit(): Promise<BN>\n\n /**\n * Derives a child public key using a\\ derivation path and predecessor.\n *\n * @param args - Arguments for key derivation\n * @param args.path - The string path to use derive the key\n * @param args.predecessor - The id/address of the account requesting signature\n * @returns Promise resolving to the derived SEC1 uncompressed public key\n */\n abstract getDerivedPublicKey(\n args: {\n path: string\n predecessor: string\n } & Record<string, unknown>\n ): Promise<UncompressedPubKeySEC1>\n}\n\n/**\n * Full contract interface that extends BaseChainSignatureContract to provide all Sig Network Smart Contract capabilities.\n */\nexport abstract class ChainSignatureContract extends BaseChainSignatureContract {\n /**\n * Signs a payload using Sig Network MPC.\n *\n * @param args - Arguments for the signing operation\n * @param args.payload - The data to sign as an array of 32 bytes\n * @param args.path - The string path to use derive the key\n * @param args.key_version - Version of the key to use\n * @returns Promise resolving to the RSV signature\n */\n abstract sign(args: SignArgs & Record<string, unknown>): Promise<RSVSignature>\n\n /**\n * Gets the public key associated with this contract instance.\n *\n * @returns Promise resolving to the SEC1 uncompressed public key\n */\n abstract getPublicKey(): Promise<UncompressedPubKeySEC1>\n}\n","import * as signAndSend from './signAndSend'\nimport * as transaction from './transaction'\nexport * from './ChainSignatureContract'\n\nconst utils = {\n transaction,\n signAndSend,\n}\n\nexport { utils }\n","export * as keypair from './keypair'\n","import { type KeyPair } from '@near-js/crypto'\n\nimport * as chainAdapters from '@chain-adapters'\nimport { BTCRpcAdapters } from '@chain-adapters/Bitcoin/BTCRpcAdapter'\nimport { getNearAccount } from '@contracts/near/account'\nimport { ChainSignatureContract } from '@contracts/near/ChainSignatureContract'\nimport {\n type Response,\n type BitcoinRequest,\n type CosmosRequest,\n type EVMRequest,\n} from '@contracts/near/types'\nimport { createPublicClient, http } from 'viem';\n\nexport const EVMTransaction = async (\n req: EVMRequest,\n keyPair: KeyPair\n): Promise<Response> => {\n try {\n const account = await getNearAccount({\n networkId: req.nearAuthentication.networkId,\n accountId: req.nearAuthentication.accountId,\n keypair: keyPair,\n })\n\n const contract = new ChainSignatureContract({\n networkId: req.nearAuthentication.networkId,\n contractId: req.chainConfig.contract,\n accountId: account.accountId,\n keypair: keyPair,\n })\n\n const evm = new chainAdapters.evm.EVM({\n publicClient: createPublicClient({\n transport: http(req.chainConfig.providerUrl),\n }),\n contract,\n })\n\n const { transaction, hashesToSign } =\n await evm.prepareTransactionForSigning(req.transaction)\n\n const signature = await contract.sign({\n payload: hashesToSign[0],\n path: req.derivationPath,\n key_version: 0,\n })\n\n const txSerialized = evm.finalizeTransactionSigning({\n transaction,\n rsvSignatures: [signature],\n })\n\n const txHash = await evm.broadcastTx(txSerialized)\n\n return {\n transactionHash: txHash,\n success: true,\n }\n } catch (e: unknown) {\n console.error(e)\n return {\n success: false,\n errorMessage: e instanceof Error ? e.message : String(e),\n }\n }\n}\n\nexport const BTCTransaction = async (\n req: BitcoinRequest,\n keyPair: KeyPair\n): Promise<Response> => {\n try {\n const account = await getNearAccount({\n networkId: req.nearAuthentication.networkId,\n accountId: req.nearAuthentication.accountId,\n keypair: keyPair,\n })\n\n const contract = new ChainSignatureContract({\n networkId: req.nearAuthentication.networkId,\n contractId: req.chainConfig.contract,\n accountId: account.accountId,\n keypair: keyPair,\n })\n\n const btc = new chainAdapters.btc.Bitcoin({\n btcRpcAdapter: new BTCRpcAdapters.Mempool(req.chainConfig.providerUrl),\n contract,\n network: req.chainConfig.network,\n })\n\n const { transaction, hashesToSign } =\n await btc.prepareTransactionForSigning(req.transaction)\n\n const signatures = await Promise.all(\n hashesToSign.map(\n async (payload) =>\n await contract.sign({\n payload,\n path: req.derivationPath,\n key_version: 0,\n })\n )\n )\n\n const txSerialized = btc.finalizeTransactionSigning({\n transaction,\n rsvSignatures: signatures,\n })\n\n const txHash = await btc.broadcastTx(txSerialized)\n\n return {\n transactionHash: txHash,\n success: true,\n }\n } catch (e: unknown) {\n return {\n success: false,\n errorMessage: e instanceof Error ? e.message : String(e),\n }\n }\n}\n\nexport const CosmosTransaction = async (\n req: CosmosRequest,\n keyPair: KeyPair\n): Promise<Response> => {\n try {\n const account = await getNearAccount({\n networkId: req.nearAuthentication.networkId,\n accountId: req.nearAuthentication.accountId,\n keypair: keyPair,\n })\n\n const contract = new ChainSignatureContract({\n networkId: req.nearAuthentication.networkId,\n contractId: req.chainConfig.contract,\n accountId: account.accountId,\n keypair: keyPair,\n })\n\n const cosmos = new chainAdapters.cosmos.Cosmos({\n contract,\n chainId: req.chainConfig.chainId,\n })\n\n const { transaction, hashesToSign } =\n await cosmos.prepareTransactionForSigning(req.transaction)\n\n const signatures = await Promise.all(\n hashesToSign.map(\n async (payload) =>\n await contract.sign({\n payload,\n path: req.derivationPath,\n key_version: 0,\n })\n )\n )\n\n const txSerialized = cosmos.finalizeTransactionSigning({\n transaction,\n rsvSignatures: signatures,\n })\n\n const txHash = await cosmos.broadcastTx(txSerialized)\n\n return {\n transactionHash: txHash,\n success: true,\n }\n } catch (e: unknown) {\n console.error(e)\n return {\n success: false,\n errorMessage: e instanceof Error ? e.message : String(e),\n }\n }\n}\n","import { Account, Connection } from '@near-js/accounts'\nimport { KeyPair } from '@near-js/crypto'\nimport { InMemoryKeyStore } from '@near-js/keystores'\n\nimport { DONT_CARE_ACCOUNT_ID } from '@contracts/near/constants'\n\ntype SetConnectionArgs =\n | {\n networkId: string\n accountId: string\n keypair: KeyPair\n }\n | {\n networkId: string\n accountId?: never\n keypair?: never\n }\n\nexport const getNearAccount = async ({\n networkId,\n accountId = DONT_CARE_ACCOUNT_ID,\n keypair = KeyPair.fromRandom('ed25519'),\n}: SetConnectionArgs): Promise<Account> => {\n const keyStore = new InMemoryKeyStore()\n await keyStore.setKey(networkId, accountId, keypair)\n\n const connection = Connection.fromConfig({\n networkId,\n provider: {\n type: 'JsonRpcProvider',\n args: {\n url: {\n testnet: 'https://rpc.testnet.near.org',\n mainnet: 'https://rpc.mainnet.near.org',\n }[networkId],\n },\n },\n signer: { type: 'InMemorySigner', keyStore },\n })\n\n return new Account(connection, accountId)\n}\n","import BN from 'bn.js'\n\nexport const NEAR_MAX_GAS = new BN('300000000000000')\nexport const DONT_CARE_ACCOUNT_ID = 'dontcare'\n","import { Contract } from '@near-js/accounts'\nimport { KeyPair } from '@near-js/crypto'\nimport { actionCreators } from '@near-js/transactions'\nimport { najToUncompressedPubKeySEC1 } from '@utils/cryptography'\nimport { getRootPublicKey } from '@utils/publicKey'\nimport BN from 'bn.js'\n\nimport { CHAINS, KDF_CHAIN_IDS } from '@constants'\nimport { ChainSignatureContract as AbstractChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { SignArgs } from '@contracts/ChainSignatureContract'\nimport { getNearAccount } from '@contracts/near/account'\nimport { DONT_CARE_ACCOUNT_ID, NEAR_MAX_GAS } from '@contracts/near/constants'\nimport {\n responseToMpcSignature,\n type SendTransactionOptions,\n sendTransactionUntil,\n} from '@contracts/near/transaction'\nimport {\n type NearNetworkIds,\n type ChainSignatureContractIds,\n} from '@contracts/near/types'\nimport type { RSVSignature, UncompressedPubKeySEC1, NajPublicKey } from '@types'\nimport { cryptography } from '@utils'\n\ntype NearContract = Contract & {\n public_key: () => Promise<NajPublicKey>\n experimental_signature_deposit: () => Promise<number>\n derived_public_key: (args: {\n path: string\n predecessor: string\n }) => Promise<NajPublicKey>\n}\n\ninterface ChainSignatureContractArgs {\n networkId: NearNetworkIds\n contractId: ChainSignatureContractIds\n accountId?: string\n keypair?: KeyPair\n rootPublicKey?: NajPublicKey\n sendTransactionOptions?: SendTransactionOptions\n}\n\n/**\n * Implementation of the ChainSignatureContract for NEAR chains.\n *\n * This class provides an interface to interact with the ChainSignatures contract\n * deployed on NEAR. It supports both view methods (which don't require authentication)\n * and change methods (which require a valid NEAR account and keypair).\n *\n * @extends AbstractChainSignatureContract\n */\nexport class ChainSignatureContract extends AbstractChainSignatureContract {\n private readonly networkId: NearNetworkIds\n private readonly contractId: ChainSignatureContractIds\n private readonly accountId: string\n private readonly keypair: KeyPair\n private readonly rootPublicKey?: NajPublicKey\n private readonly sendTransactionOptions?: SendTransactionOptions\n /**\n * Creates a new instance of the ChainSignatureContract for NEAR chains.\n *\n * @param args - Configuration options for the contract\n * @param args.networkId - The NEAR network ID (e.g. 'testnet', 'mainnet')\n * @param args.contractId - The contract ID of the deployed ChainSignatures contract\n * @param args.accountId - Optional NEAR account ID for signing transactions. Required for change methods.\n * @param args.keypair - Optional NEAR KeyPair for signing transactions. Required for change methods.\n * @param args.rootPublicKey - Optional root public key for the contract. If not provided, it will be derived from the contract ID.\n * @param args.sendTransactionOptions - Optional configuration for transaction sending behavior.\n */\n constructor({\n networkId,\n contractId,\n accountId = DONT_CARE_ACCOUNT_ID,\n keypair = KeyPair.fromRandom('ed25519'),\n rootPublicKey,\n sendTransactionOptions,\n }: ChainSignatureContractArgs) {\n super()\n\n this.networkId = networkId\n this.contractId = contractId\n this.accountId = accountId\n this.keypair = keypair\n this.sendTransactionOptions = sendTransactionOptions\n\n this.rootPublicKey =\n rootPublicKey || getRootPublicKey(this.contractId, CHAINS.NEAR)\n }\n\n private async getContract(): Promise<NearContract> {\n const account = await getNearAccount({\n networkId: this.networkId,\n accountId: this.accountId,\n keypair: this.keypair,\n })\n\n return new Contract(account, this.contractId, {\n viewMethods: [\n 'public_key',\n 'experimental_signature_deposit',\n 'derived_public_key',\n ],\n // Change methods use the sendTransactionUntil because the internal retry of the Contract class\n // throws on NodeJs.\n changeMethods: [],\n useLocalViewExecution: false,\n }) as unknown as NearContract\n }\n\n async getCurrentSignatureDeposit(): Promise<BN> {\n const contract = await this.getContract()\n return new BN(\n (await contract.experimental_signature_deposit()).toLocaleString(\n 'fullwide',\n {\n useGrouping: false,\n }\n )\n )\n }\n\n async getDerivedPublicKey(args: {\n path: string\n predecessor: string\n }): Promise<UncompressedPubKeySEC1> {\n if (this.rootPublicKey) {\n const pubKey = cryptography.deriveChildPublicKey(\n await this.getPublicKey(),\n args.predecessor.toLowerCase(),\n args.path,\n KDF_CHAIN_IDS.NEAR\n )\n return pubKey\n } else {\n // Support for legacy contract\n const contract = await this.getContract()\n const najPubKey = await contract.derived_public_key(args)\n return najToUncompressedPubKeySEC1(najPubKey)\n }\n }\n\n async getPublicKey(): Promise<UncompressedPubKeySEC1> {\n if (this.rootPublicKey) {\n return najToUncompressedPubKeySEC1(this.rootPublicKey)\n } else {\n // Support for legacy contract\n const contract = await this.getContract()\n const najPubKey = await contract.public_key()\n return najToUncompressedPubKeySEC1(najPubKey)\n }\n }\n\n async sign(\n args: SignArgs,\n options?: {\n nonce?: number\n }\n ): Promise<RSVSignature> {\n this.requireAccount()\n\n const deposit = await this.getCurrentSignatureDeposit()\n\n const result = await sendTransactionUntil({\n accountId: this.accountId,\n keypair: this.keypair,\n networkId: this.networkId,\n receiverId: this.contractId,\n actions: [\n actionCreators.functionCall(\n 'sign',\n { request: args },\n BigInt(NEAR_MAX_GAS.toString()),\n BigInt(deposit.toString())\n ),\n ],\n nonce: options?.nonce,\n options: this.sendTransactionOptions,\n })\n\n const signature = responseToMpcSignature({ response: result })\n\n if (!signature) {\n throw new Error('Transaction failed')\n }\n\n return signature\n }\n\n private requireAccount(): void {\n if (this.accountId === DONT_CARE_ACCOUNT_ID) {\n throw new Error(\n 'A valid account ID and keypair are required for change methods. Please instantiate a new contract with valid credentials.'\n )\n }\n }\n}\n","import { CONTRACT_ADDRESSES, ROOT_PUBLIC_KEYS, type CHAINS } from '@constants'\nimport type { NajPublicKey } from '@types'\n\nexport const getRootPublicKey = (\n contractAddress: string,\n chain: keyof typeof CHAINS\n): NajPublicKey | undefined => {\n const environment = Object.entries(CONTRACT_ADDRESSES[chain]).find(\n ([_, address]) => address.toLowerCase() === contractAddress.toLowerCase()\n )?.[0] as keyof typeof ROOT_PUBLIC_KEYS | undefined\n\n if (environment) {\n return ROOT_PUBLIC_KEYS[environment]\n }\n\n return undefined\n}\n","import { InMemoryKeyStore } from '@near-js/keystores'\nimport type { Action as TransactionAction } from '@near-js/transactions'\nimport type { TxExecutionStatus } from '@near-js/types'\nimport type {\n Action as WalletAction,\n FinalExecutionOutcome,\n NetworkId,\n} from '@near-wallet-selector/core'\nimport BN from 'bn.js'\nimport {\n transactions,\n utils as nearUtils,\n connect,\n type KeyPair,\n} from 'near-api-js'\nimport { getTransactionLastResult } from 'near-api-js/lib/providers'\nimport { withRetry } from 'viem'\n\nimport { ChainSignatureContract } from '@contracts/near/ChainSignatureContract'\nimport { NEAR_MAX_GAS } from '@contracts/near/constants'\nimport { type ChainSignatureContractIds } from '@contracts/near/types'\nimport {\n type RSVSignature,\n type KeyDerivationPath,\n type MPCSignature,\n type HashToSign,\n} from '@types'\nimport { cryptography } from '@utils'\n\nexport const mpcPayloadsToChainSigTransaction = async ({\n networkId,\n contractId,\n hashesToSign,\n path,\n}: {\n networkId: NetworkId\n contractId: ChainSignatureContractIds\n hashesToSign: HashToSign[]\n path: KeyDerivationPath\n}): Promise<{\n receiverId: string\n actions: WalletAction[]\n}> => {\n const contract = new ChainSignatureContract({\n networkId,\n contractId,\n })\n\n const currentContractFee = await contract.getCurrentSignatureDeposit()\n\n return {\n receiverId: contractId,\n actions: hashesToSign.map((payload) => ({\n type: 'FunctionCall',\n params: {\n methodName: 'sign',\n args: {\n request: {\n payload: Array.from(payload),\n path,\n key_version: 0,\n },\n },\n gas: NEAR_MAX_GAS.div(new BN(hashesToSign.length)).toString(),\n deposit: currentContractFee?.toString() || '1',\n },\n })),\n }\n}\n\nexport const responseToMpcSignature = ({\n response,\n}: {\n response: FinalExecutionOutcome\n}): RSVSignature | undefined => {\n const signature = getTransactionLastResult(response) as MPCSignature\n\n if (signature) {\n return cryptography.toRSV(signature)\n } else {\n return undefined\n }\n}\n\nexport interface SendTransactionOptions {\n until: TxExecutionStatus\n retryCount: number\n delay: number\n nodeUrl: string\n}\n\nexport const sendTransactionUntil = async ({\n accountId,\n keypair,\n networkId,\n receiverId,\n actions,\n nonce,\n options = {\n until: 'EXECUTED_OPTIMISTIC',\n retryCount: 3,\n delay: 5000, // Near RPC timeout\n nodeUrl:\n networkId === 'testnet'\n ? 'https://test.rpc.fastnear.com'\n : 'https://free.rpc.fastnear.com',\n },\n}: {\n accountId: string\n keypair: KeyPair\n networkId: NetworkId\n receiverId: string\n actions: TransactionAction[]\n nonce?: number\n options?: SendTransactionOptions\n}): Promise<FinalExecutionOutcome> => {\n const keyStore = new InMemoryKeyStore()\n await keyStore.setKey(networkId, accountId, keypair)\n\n const near = await connect({\n networkId,\n keyStore,\n nodeUrl: options.nodeUrl,\n })\n\n const { signer } = near.connection\n const publicKey = await signer.getPublicKey(\n accountId,\n near.connection.networkId\n )\n\n const accessKey = (await near.connection.provider.query(\n `access_key/${accountId}/${publicKey.toString()}`,\n ''\n )) as unknown as {\n block_hash: string\n block_height: number\n nonce: number\n permission: string\n }\n\n const recentBlockHash = nearUtils.serialize.base_decode(accessKey.block_hash)\n\n const tx = transactions.createTransaction(\n accountId,\n publicKey,\n receiverId,\n nonce ?? ++accessKey.nonce,\n actions,\n recentBlockHash\n )\n\n const serializedTx = nearUtils.serialize.serialize(\n transactions.SCHEMA.Transaction,\n tx\n )\n\n const nearTransactionSignature = await signer.signMessage(\n serializedTx,\n accountId,\n near.connection.networkId\n )\n\n const signedTransaction = new transactions.SignedTransaction({\n transaction: tx,\n signature: new transactions.Signature({\n keyType: tx.publicKey.keyType,\n data: nearTransactionSignature.signature,\n }),\n })\n\n const { transaction } = await near.connection.provider.sendTransactionUntil(\n signedTransaction,\n 'INCLUDED_FINAL'\n )\n\n const txHash = transaction.hash as string | undefined\n\n if (!txHash) {\n throw new Error('No transaction hash found')\n }\n\n return await withRetry(\n async () => {\n const txOutcome = await near.connection.provider.txStatus(\n txHash,\n accountId,\n options.until\n )\n\n if (txOutcome) {\n return txOutcome\n }\n\n throw new Error('Transaction not found')\n },\n {\n retryCount: options.retryCount,\n delay: options.delay,\n }\n )\n}\n","import * as ChainSignaturesContractABI from './ChainSignaturesContractABI'\nimport * as errors from './errors'\nexport * from './ChainSignaturesContract'\n\nconst utils = {\n ChainSignaturesContractABI,\n errors,\n}\n\nexport { utils }\n","export const abi = [\n {\n inputs: [\n { internalType: 'address', name: '_mpc_network', type: 'address' },\n { internalType: 'uint256', name: '_signatureDeposit', type: 'uint256' },\n ],\n stateMutability: 'nonpayable',\n type: 'constructor',\n },\n { inputs: [], name: 'AccessControlBadConfirmation', type: 'error' },\n {\n inputs: [\n { internalType: 'address', name: 'account', type: 'address' },\n { internalType: 'bytes32', name: 'neededRole', type: 'bytes32' },\n ],\n name: 'AccessControlUnauthorizedAccount',\n type: 'error',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: 'bytes32', name: 'role', type: 'bytes32' },\n {\n indexed: true,\n internalType: 'bytes32',\n name: 'previousAdminRole',\n type: 'bytes32',\n },\n {\n indexed: true,\n internalType: 'bytes32',\n name: 'newAdminRole',\n type: 'bytes32',\n },\n ],\n name: 'RoleAdminChanged',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: 'bytes32', name: 'role', type: 'bytes32' },\n {\n indexed: true,\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n ],\n name: 'RoleGranted',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: 'bytes32', name: 'role', type: 'bytes32' },\n {\n indexed: true,\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n ],\n name: 'RoleRevoked',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'bytes32',\n name: 'requestId',\n type: 'bytes32',\n },\n {\n indexed: false,\n internalType: 'address',\n name: 'responder',\n type: 'address',\n },\n { indexed: false, internalType: 'string', name: 'error', type: 'string' },\n ],\n name: 'SignatureError',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'bytes32',\n name: 'payload',\n type: 'bytes32',\n },\n {\n indexed: false,\n internalType: 'uint32',\n name: 'keyVersion',\n type: 'uint32',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'deposit',\n type: 'uint256',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'chainId',\n type: 'uint256',\n },\n { indexed: false, internalType: 'string', name: 'path', type: 'string' },\n { indexed: false, internalType: 'string', name: 'algo', type: 'string' },\n { indexed: false, internalType: 'string', name: 'dest', type: 'string' },\n {\n indexed: false,\n internalType: 'string',\n name: 'params',\n type: 'string',\n },\n ],\n name: 'SignatureRequested',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'bytes32',\n name: 'requestId',\n type: 'bytes32',\n },\n {\n indexed: false,\n internalType: 'address',\n name: 'responder',\n type: 'address',\n },\n {\n components: [\n {\n components: [\n { internalType: 'uint256', name: 'x', type: 'uint256' },\n { internalType: 'uint256', name: 'y', type: 'uint256' },\n ],\n internalType: 'struct ChainSignatures.AffinePoint',\n name: 'bigR',\n type: 'tuple',\n },\n { internalType: 'uint256', name: 's', type: 'uint256' },\n { internalType: 'uint8', name: 'recoveryId', type: 'uint8' },\n ],\n indexed: false,\n internalType: 'struct ChainSignatures.Signature',\n name: 'signature',\n type: 'tuple',\n },\n ],\n name: 'SignatureResponded',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'owner',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'Withdraw',\n type: 'event',\n },\n {\n inputs: [],\n name: 'DEFAULT_ADMIN_ROLE',\n outputs: [{ internalType: 'bytes32', name: '', type: 'bytes32' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ internalType: 'bytes32', name: 'role', type: 'bytes32' }],\n name: 'getRoleAdmin',\n outputs: [{ internalType: 'bytes32', name: '', type: 'bytes32' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'getSignatureDeposit',\n outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'bytes32', name: 'role', type: 'bytes32' },\n { internalType: 'address', name: 'account', type: 'address' },\n ],\n name: 'grantRole',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'bytes32', name: 'role', type: 'bytes32' },\n { internalType: 'address', name: 'account', type: 'address' },\n ],\n name: 'hasRole',\n outputs: [{ internalType: 'bool', name: '', type: 'bool' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'bytes32', name: 'role', type: 'bytes32' },\n { internalType: 'address', name: 'callerConfirmation', type: 'address' },\n ],\n name: 'renounceRole',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n components: [\n { internalType: 'bytes32', name: 'requestId', type: 'bytes32' },\n {\n components: [\n {\n components: [\n { internalType: 'uint256', name: 'x', type: 'uint256' },\n { internalType: 'uint256', name: 'y', type: 'uint256' },\n ],\n internalType: 'struct ChainSignatures.AffinePoint',\n name: 'bigR',\n type: 'tuple',\n },\n { internalType: 'uint256', name: 's', type: 'uint256' },\n { internalType: 'uint8', name: 'recoveryId', type: 'uint8' },\n ],\n internalType: 'struct ChainSignatures.Signature',\n name: 'signature',\n type: 'tuple',\n },\n ],\n internalType: 'struct ChainSignatures.Response[]',\n name: '_responses',\n type: 'tuple[]',\n },\n ],\n name: 'respond',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n components: [\n { internalType: 'bytes32', name: 'requestId', type: 'bytes32' },\n { internalType: 'string', name: 'errorMessage', type: 'string' },\n ],\n internalType: 'struct ChainSignatures.ErrorResponse[]',\n name: '_errors',\n type: 'tuple[]',\n },\n ],\n name: 'respondError',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'bytes32', name: 'role', type: 'bytes32' },\n { internalType: 'address', name: 'account', type: 'address' },\n ],\n name: 'revokeRole',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [{ internalType: 'uint256', name: '_amount', type: 'uint256' }],\n name: 'setSignatureDeposit',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n components: [\n { internalType: 'bytes32', name: 'payload', type: 'bytes32' },\n { internalType: 'string', name: 'path', type: 'string' },\n { internalType: 'uint32', name: 'keyVersion', type: 'uint32' },\n { internalType: 'string', name: 'algo', type: 'string' },\n { internalType: 'string', name: 'dest', type: 'string' },\n { internalType: 'string', name: 'params', type: 'string' },\n ],\n internalType: 'struct ChainSignatures.SignRequest',\n name: '_request',\n type: 'tuple',\n },\n ],\n name: 'sign',\n outputs: [],\n stateMutability: 'payable',\n type: 'function',\n },\n {\n inputs: [{ internalType: 'bytes4', name: 'interfaceId', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ internalType: 'bool', name: '', type: 'bool' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'uint256', name: '_amount', type: 'uint256' },\n { internalType: 'address', name: '_receiver', type: 'address' },\n ],\n name: 'withdraw',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n]\n","import type { TransactionReceipt } from 'viem'\n\nexport class ChainSignatureError extends Error {\n requestId: `0x${string}`\n receipt: TransactionReceipt\n\n constructor(\n message: string,\n requestId: `0x${string}`,\n receipt: TransactionReceipt\n ) {\n super(message)\n this.name = 'ChainSignatureError'\n this.requestId = requestId\n this.receipt = receipt\n }\n}\n\nexport class SignatureNotFoundError extends ChainSignatureError {\n constructor(requestId: `0x${string}`, receipt: TransactionReceipt) {\n super('Signature not found after maximum retries', requestId, receipt)\n this.name = 'SignatureNotFoundError'\n }\n}\n\nexport class SignatureContractError extends ChainSignatureError {\n errorCode: string\n\n constructor(\n errorCode: string,\n requestId: `0x${string}`,\n receipt: TransactionReceipt\n ) {\n super(`Signature error: ${errorCode}`, requestId, receipt)\n this.name = 'SignatureContractError'\n this.errorCode = errorCode\n }\n}\n\nexport class SigningError extends ChainSignatureError {\n originalError?: Error\n\n constructor(\n requestId: `0x${string}`,\n receipt: TransactionReceipt,\n originalError?: Error\n ) {\n super('Error signing request', requestId, receipt)\n this.name = 'SigningError'\n this.originalError = originalError\n }\n}\n","import { encodeAbiParameters, keccak256 } from 'viem'\nimport * as chains from 'viem/chains'\nimport type { Chain } from 'viem/chains'\n\nimport { type RequestIdArgs } from './types'\n\nexport const getChain = (chainId: number): Chain => {\n for (const chain of Object.values(chains)) {\n if (chain.id === chainId) {\n return chain\n }\n }\n throw new Error('Chain not found')\n}\n\nexport const getRequestId = (request: RequestIdArgs): `0x${string}` => {\n const encoded = encodeAbiParameters(\n [\n { type: 'address' },\n { type: 'bytes' },\n { type: 'string' },\n { type: 'uint32' },\n { type: 'uint256' },\n { type: 'string' },\n { type: 'string' },\n { type: 'string' },\n ],\n [\n request.address,\n request.payload,\n request.path,\n Number(request.keyVersion),\n request.chainId,\n request.algo,\n request.dest,\n request.params,\n ]\n )\n\n return keccak256(encoded)\n}\n","import { najToUncompressedPubKeySEC1 } from '@utils/cryptography'\nimport { getRootPublicKey } from '@utils/publicKey'\nimport BN from 'bn.js'\nimport { withRetry, type PublicClient, type WalletClient, type Hex } from 'viem'\n\nimport { CHAINS, KDF_CHAIN_IDS } from '@constants'\nimport { ChainSignatureContract as AbstractChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { SignArgs } from '@contracts/ChainSignatureContract'\nimport type {\n NajPublicKey,\n RSVSignature,\n SigNetEvmMpcSignature,\n UncompressedPubKeySEC1,\n} from '@types'\nimport { cryptography } from '@utils'\n\nimport { abi } from './ChainSignaturesContractABI'\nimport {\n SignatureNotFoundError,\n SignatureContractError,\n SigningError,\n} from './errors'\nimport type {\n RequestIdArgs,\n SignOptions,\n SignRequest,\n SignatureErrorData,\n} from './types'\nimport { getRequestId } from './utils'\n\n/**\n * Implementation of the ChainSignatureContract for EVM chains.\n *\n * When signing data, the contract emits a SignatureRequested event with a requestId.\n * This requestId is used to track the signature request and retrieve the signature\n * once it's available. The sign method handles this process automatically by polling\n * for the signature using the requestId.\n */\nexport class ChainSignatureContract extends AbstractChainSignatureContract {\n private readonly publicClient: PublicClient\n private readonly walletClient: WalletClient\n private readonly contractAddress: Hex\n private readonly rootPublicKey: NajPublicKey\n\n /**\n * Creates a new instance of the ChainSignatureContract for EVM chains.\n *\n * @param args - Configuration options for the contract\n * @param args.publicClient - A Viem PublicClient instance for reading from the blockchain\n * @param args.walletClient - A Viem WalletClient instance for sending transactions\n * @param args.contractAddress - The address of the deployed ChainSignatures contract (e.g. `0x857ED3A242B59cC24144814a0DF41C397a3811E6`)\n * @param args.rootPublicKey - Optional root public key. If not provided, it will be derived from the contract address\n */\n constructor(args: {\n publicClient: PublicClient\n walletClient: WalletClient\n contractAddress: Hex\n rootPublicKey?: NajPublicKey\n }) {\n super()\n this.publicClient = args.publicClient\n this.walletClient = args.walletClient\n this.contractAddress = args.contractAddress\n\n const rootPublicKey =\n args.rootPublicKey ||\n getRootPublicKey(this.contractAddress, CHAINS.ETHEREUM)\n\n if (!rootPublicKey) {\n throw new Error(\n `Invalid public key, please provide a valid root public key or contract address`\n )\n }\n\n this.rootPublicKey = rootPublicKey\n }\n\n async getCurrentSignatureDeposit(): Promise<BN> {\n const deposit = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi,\n functionName: 'getSignatureDeposit',\n })) as bigint\n\n return new BN(deposit.toString())\n }\n\n async getDerivedPublicKey(args: {\n path: string\n predecessor: string\n }): Promise<UncompressedPubKeySEC1> {\n const pubKey = cryptography.deriveChildPublicKey(\n await this.getPublicKey(),\n args.predecessor.toLowerCase(),\n args.path,\n KDF_CHAIN_IDS.ETHEREUM\n )\n\n return pubKey\n }\n\n async getPublicKey(): Promise<UncompressedPubKeySEC1> {\n return najToUncompressedPubKeySEC1(this.rootPublicKey)\n }\n\n async getLatestKeyVersion(): Promise<number> {\n const version = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi,\n functionName: 'latestKeyVersion',\n })) as bigint\n\n return Number(version)\n }\n\n /**\n * Sends a sign request transaction and return the transaction hash.\n *\n * @param args - The signature arguments\n * @param options - The signing options\n * @returns The transaction hash\n */\n async createSignatureRequest(\n args: SignArgs,\n options: Pick<SignOptions, 'sign'> = {\n sign: {\n algo: '',\n dest: '',\n params: '',\n },\n }\n ): Promise<{\n txHash: Hex\n requestId: Hex\n }> {\n if (!this.walletClient?.account) {\n throw new Error('Wallet client required for signing operations')\n }\n\n const request: SignRequest = {\n payload: `0x${Buffer.from(args.payload).toString('hex')}`,\n path: args.path,\n keyVersion: args.key_version,\n algo: options.sign.algo ?? '',\n dest: options.sign.dest ?? '',\n params: options.sign.params ?? '',\n }\n\n const requestId = this.getRequestId({\n ...request,\n address: this.walletClient.account.address,\n chainId: this.publicClient.chain?.id\n ? BigInt(this.publicClient.chain.id)\n : 0n,\n })\n\n const hash = await this.walletClient.writeContract({\n address: this.contractAddress,\n abi,\n chain: this.publicClient.chain,\n account: this.walletClient.account,\n functionName: 'sign',\n args: [request],\n value: BigInt((await this.getCurrentSignatureDeposit()).toString()),\n })\n\n return {\n txHash: hash,\n requestId,\n }\n }\n\n /**\n * Sends a transaction to the contract to request a signature, then\n * polls for the signature result. If the signature is not found within the retry\n * parameters, it will throw an error.\n */\n async sign(\n args: SignArgs,\n options: SignOptions = {\n sign: {\n algo: '',\n dest: '',\n params: '',\n },\n retry: {\n delay: 5000,\n retryCount: 12,\n },\n }\n ): Promise<RSVSignature> {\n const { txHash, requestId } = await this.createSignatureRequest(\n args,\n options\n )\n\n const receipt = await this.publicClient.waitForTransactionReceipt({\n hash: txHash,\n })\n\n try {\n const result = await withRetry(\n async () => {\n const result = await this.getSignatureFromEvents(\n requestId,\n receipt.blockNumber\n )\n\n // TODO: Validate if this is the signature corresponding to the transaction as anybody can call respond on the contract\n\n if (result) {\n return result\n } else {\n throw new Error('Signature not found yet')\n }\n },\n {\n delay: options.retry.delay,\n retryCount: options.retry.retryCount,\n shouldRetry: ({ count, error }) => {\n // TODO: Should be enabled only on debug mode\n console.log(\n `Retrying get signature: ${count}/${options.retry.retryCount}`\n )\n return error.message === 'Signature not found yet'\n },\n }\n )\n\n if (result) {\n return result\n } else {\n const errorData = await this.getErrorFromEvents(\n requestId,\n receipt.blockNumber\n )\n if (errorData) {\n throw new SignatureContractError(errorData.error, requestId, receipt)\n } else {\n throw new SignatureNotFoundError(requestId, receipt)\n }\n }\n } catch (error) {\n if (\n error instanceof SignatureNotFoundError ||\n error instanceof SignatureContractError\n ) {\n throw error\n } else {\n throw new SigningError(\n requestId,\n receipt,\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n /**\n * Generates the request ID for a signature request allowing to track the response.\n *\n * @param request - The signature request object containing:\n * @param request.address - The contract/wallet address calling the signing contract\n * @param request.payload - The data payload to be signed as a hex string\n * @param request.path - The derivation path for the key\n * @param request.keyVersion - The version of the key to use\n * @param request.chainId - The chain ID as a bigint\n * @param request.algo - The signing algorithm to use\n * @param request.dest - The destination for the signature\n * @param request.params - Additional parameters for the signing process\n * @returns A hex string representing the unique request ID\n *\n * @example\n * ```typescript\n * const requestId = ChainSignatureContract.getRequestId({\n * address: walletClient.account.address,\n * payload: payload: `0x${Buffer.from(args.payload).toString('hex')}`,,\n * path: '',\n * keyVersion: 0,\n * chainId: 1n,\n * algo: '',\n * dest: '',\n * params: ''\n * });\n * console.log(requestId); // 0x...\n * ```\n */\n getRequestId(request: RequestIdArgs): Hex {\n return getRequestId(request)\n }\n\n async getErrorFromEvents(\n requestId: Hex,\n fromBlock: bigint\n ): Promise<SignatureErrorData | undefined> {\n const errorLogs = await this.publicClient.getContractEvents({\n address: this.contractAddress,\n abi,\n eventName: 'SignatureError',\n args: {\n requestId,\n },\n fromBlock,\n toBlock: 'latest',\n })\n\n if (errorLogs.length > 0) {\n const { args: errorData } = errorLogs[\n errorLogs.length - 1\n ] as unknown as {\n args: SignatureErrorData\n }\n\n return errorData\n }\n\n return undefined\n }\n\n /**\n * Searches for SignatureResponded events that match the given requestId.\n * It works in conjunction with the getRequestId method which generates the unique\n * identifier for a signature request.\n *\n * @param requestId - The identifier for the signature request\n * @param fromBlock - The block number to start searching from\n * @returns The RSV signature if found, undefined otherwise\n */\n async getSignatureFromEvents(\n requestId: Hex,\n fromBlock: bigint\n ): Promise<RSVSignature | undefined> {\n const logs = await this.publicClient.getContractEvents({\n address: this.contractAddress,\n abi,\n eventName: 'SignatureResponded',\n args: {\n requestId,\n },\n fromBlock,\n toBlock: 'latest',\n })\n\n if (logs.length > 0) {\n const { args: signatureData } = logs[logs.length - 1] as unknown as {\n args: {\n signature: SigNetEvmMpcSignature\n }\n }\n\n return cryptography.toRSV(signatureData.signature)\n }\n\n return undefined\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/constants.ts","../../src/utils/index.ts","../../src/utils/cryptography.ts","../../src/chain-adapters/index.ts","../../src/chain-adapters/ChainAdapter.ts","../../src/chain-adapters/EVM/index.ts","../../src/chain-adapters/EVM/EVM.ts","../../src/chain-adapters/EVM/utils.ts","../../src/chain-adapters/Bitcoin/index.ts","../../src/chain-adapters/Bitcoin/Bitcoin.ts","../../src/chain-adapters/Bitcoin/utils.ts","../../src/chain-adapters/Bitcoin/BTCRpcAdapter/Mempool/Mempool.ts","../../src/chain-adapters/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.ts","../../src/chain-adapters/Bitcoin/BTCRpcAdapter/index.ts","../../src/chain-adapters/Cosmos/index.ts","../../src/chain-adapters/Cosmos/Cosmos.ts","../../src/chain-adapters/Cosmos/utils.ts","../../src/contracts/index.ts","../../src/contracts/ChainSignatureContract.ts","../../src/contracts/near/index.ts","../../src/contracts/near/signAndSend/index.ts","../../src/contracts/near/signAndSend/keypair.ts","../../src/contracts/near/account.ts","../../src/contracts/near/constants.ts","../../src/utils/publicKey.ts","../../src/contracts/near/ChainSignatureContract.ts","../../src/contracts/near/transaction.ts","../../src/contracts/evm/index.ts","../../src/contracts/evm/ChainSignaturesContractABI.ts","../../src/contracts/evm/errors.ts","../../src/contracts/evm/utils.ts","../../src/contracts/evm/ChainSignaturesContract.ts","../../src/contracts/solana/index.ts","../../src/contracts/solana/types/chain_signatures_project.json","../../src/contracts/solana/errors.ts","../../src/contracts/solana/utils.ts","../../src/contracts/solana/ChainSignaturesContract.ts"],"names":["constants_exports","__export","CHAINS","CONTRACT_ADDRESSES","ENVS","KDF_CHAIN_IDS","ROOT_PUBLIC_KEYS","utils_exports","cryptography_exports","compressPubKey","deriveChildPublicKey","najToUncompressedPubKeySEC1","toRSV","signature","uncompressedPubKeySEC1","slicedPubKey","x","y","najPublicKey","decodedKey","base58","rootUncompressedPubKeySEC1","predecessorId","path","chainId","ec","EC","derivationPath","scalarHex","keccak256","sha3_256","oldPublicKeyPoint","scalarTimesG","newPublicKeyPoint","newX","newY","chain_adapters_exports","ChainAdapter","Bitcoin_exports","Cosmos_exports","EVM_exports","EVM","fetchEVMFeeProperties","client","transaction","gas","feeData","maxFeePerGas","maxPriorityFeePerGas","publicClient","contract","fees","nonce","from","rest","r","s","yParity","concatHex","numberToHex","predecessor","uncompressedPubKey","publicKeyNoPrefix","hash","getAddress","address","serializeTransaction","serialized","parseTransaction","transactionRequest","serializedTx","txHash","toBytes","message","hashMessage","typedDataRequest","hashTypedData","userOp","entryPointAddress","chainIdArgs","entryPoint","encoded","encodeAbiParameters","hexToBigInt","concat","pad","isAddress","userOpHash","rsvSignatures","rsvSignature","txSerialized","error","BTCRpcAdapter","BTCRpcAdapters","Bitcoin","parseBTCNetwork","network","re","_Bitcoin","btcRpcAdapter","satoshis","btc","transactionId","data","tx","P","vout","scriptPubKey","rawSignature","inputs","outputs","psbt","input","prevOut","out","derivedKey","publicKeyBuffer","payment","transactionJSON","psbtHex","hashesToSign","mockKeyPair","index","publicKey","keyPair","mpcSignature","Mempool","providerUrl","confirmationTarget","targets","utxos","feeRate","ret","coinselect","transactionHex","response","txid","Cosmos","fetchChainInfo","chainInfo","chains","chain","prefix","expectedChainId","denom","rpcUrl","restUrl","gasPrice","asset","assets","decimals","unit","endpoints","Registry","fromHex","amount","b","pubKeySha256","sha256","ripemd160Hash","ripemd160","bech32","TxRaw","toBase64","fromBase64","publicKeyBytes","gasLimit","fee","calculateFee","GasPrice","accountOnChain","StargateClient","accountNumber","sequence","txBodyEncodeObject","txBodyBytes","pubkey","encodePubkey","encodeSecp256k1Pubkey","authInfoBytes","makeAuthInfoBytes","SignMode","signDoc","makeSignDoc","signBytes","makeSignBytes","payload","sig","txBytes","broadcastResponse","contracts_exports","ChainSignatureContract","evm_exports","near_exports","solana_exports","BaseChainSignatureContract","utils","signAndSend_exports","keypair_exports","BTCTransaction","CosmosTransaction","EVMTransaction","NEAR_MAX_GAS","BN","DONT_CARE_ACCOUNT_ID","getNearAccount","networkId","accountId","keypair","KeyPair","keyStore","InMemoryKeyStore","connection","Connection","Account","getRootPublicKey","contractAddress","environment","_","transaction_exports","mpcPayloadsToChainSigTransaction","responseToMpcSignature","sendTransactionUntil","contractId","currentContractFee","getTransactionLastResult","receiverId","actions","options","near","connect","signer","accessKey","recentBlockHash","nearUtils","transactions","nearTransactionSignature","signedTransaction","withRetry","txOutcome","rootPublicKey","sendTransactionOptions","account","Contract","args","najPubKey","deposit","result","actionCreators","req","evm","createPublicClient","http","e","signatures","cosmos","ChainSignaturesContractABI_exports","abi","errors_exports","ChainSignatureError","SignatureContractError","SignatureNotFoundError","SigningError","requestId","receipt","errorCode","originalError","getRequestId","request","version","requestParams","pollResult","fromBlock","delay","retryCount","padHex","recoveredAddress","recoverAddress","expectedAddress","count","encodeFunctionData","errorLogs","errorData","logs","signatureData","chain_signatures_project_exports","accounts","chain_signatures_project_default","errors","events","instructions","metadata","types","ResponseError","generateRequestIdSolana","keyVersion","algo","dest","params","payloadHex","parseAbiParameters","PublicKey","Program","programStatePDA","programState","pda","eventPromise","instruction","Transaction","timeout","resolve","reject","resolved","signatureListener","errorListener","timeoutId","event","bigRx","recoveryId"],"mappings":"s+CAAAA,IAAAA,EAAAA,CAAA,GAAAC,CAAAA,CAAAD,EAAA,CAAA,CAAA,MAAA,CAAA,IAAAE,CAAA,CAAA,kBAAA,CAAA,IAAAC,EAAA,CAAA,IAAA,CAAA,IAAAC,CAAA,CAAA,aAAA,CAAA,IAAAC,CAAA,CAAA,gBAAA,CAAA,IAAAC,KAEO,IAAMF,CAAAA,CAAO,CAClB,WAAA,CAAa,aACb,CAAA,OAAA,CAAS,SACT,CAAA,OAAA,CAAS,SACX,CAAA,CAEaF,CAAS,CAAA,CACpB,QAAU,CAAA,UAAA,CACV,KAAM,MACN,CAAA,MAAA,CAAQ,QACV,CAAA,CAOaI,EAA4D,CAAA,CACvE,CAACF,CAAAA,CAAK,WAAW,EACf,oGACF,CAAA,CAACA,CAAK,CAAA,OAAO,EACX,oGACF,CAAA,CAACA,CAAK,CAAA,OAAO,EACX,oGACJ,CAQaC,CAAAA,CAAAA,CAAgB,CAC3B,CAACH,CAAO,CAAA,QAAQ,EAAG,KAAA,CACnB,CAACA,CAAO,CAAA,IAAI,EAAG,OAAA,CACf,CAACA,CAAAA,CAAO,MAAM,EAAG,YACnB,CAAA,CAWaC,EAGT,CAAA,CACF,CAACD,CAAAA,CAAO,IAAI,EAAG,CACb,CAACE,CAAAA,CAAK,WAAW,EAAG,qBACpB,CAAA,CAACA,CAAK,CAAA,OAAO,EAAG,oBAAA,CAChB,CAACA,CAAAA,CAAK,OAAO,EAAG,iBAClB,CACA,CAAA,CAACF,CAAO,CAAA,QAAQ,EAAG,CACjB,CAACE,CAAAA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A,CACExE,CACAhB,CAAAA,CAAAA,CAA+B,CAC7B,IAAA,CAAM,GACN,IAAM,CAAA,EAAA,CACN,MAAQ,CAAA,EACV,CACQ,CAAA,CACR,OAAOkE,EAAAA,CAAwB,CAC7B,OAAA,CAASlD,CAAK,CAAA,OAAA,CACd,IAAMA,CAAAA,CAAAA,CAAK,KACX,UAAYA,CAAAA,CAAAA,CAAK,WACjB,CAAA,IAAA,CAAMhB,CAAQ,CAAA,IAAA,EAAQ,EACtB,CAAA,IAAA,CAAMA,CAAQ,CAAA,IAAA,EAAQ,EACtB,CAAA,MAAA,CAAQA,CAAQ,CAAA,MAAA,EAAU,EAC1B,CAAA,OAAA,CAAS,IAAK,CAAA,gBAChB,CAAC,CACH,CACF,CAAA,CJ7WA,IAAMhC,EAAAA,CAAQ,CACZ,0BAAA,CAAAyF,EACA,CAAA,MAAA,CAAA3B,EACF,CAAA","file":"index.browser.cjs","sourcesContent":["import { type NajPublicKey } from '@types'\n\nexport const ENVS = {\n TESTNET_DEV: 'TESTNET_DEV',\n TESTNET: 'TESTNET',\n MAINNET: 'MAINNET'\n} as const\n\nexport const CHAINS = {\n ETHEREUM: 'ETHEREUM',\n NEAR: 'NEAR',\n SOLANA: 'SOLANA',\n} as const\n\n/**\n * Root public keys for the Sig Network Smart Contracts across different environments.\n *\n * These keys should never change.\n */\nexport const ROOT_PUBLIC_KEYS: Record<keyof typeof ENVS, NajPublicKey> = {\n [ENVS.TESTNET_DEV]:\n 'secp256k1:54hU5wcCmVUPFWLDALXMh1fFToZsVXrx9BbTbHzSfQq1Kd1rJZi52iPa4QQxo6s5TgjWqgpY8HamYuUDzG6fAaUq',\n [ENVS.TESTNET]:\n 'secp256k1:3Ww8iFjqTHufye5aRGUvrQqETegR4gVUcW8FX5xzscaN9ENhpkffojsxJwi6N1RbbHMTxYa9UyKeqK3fsMuwxjR5',\n [ENVS.MAINNET]:\n 'secp256k1:4tY4qMzusmgX5wYdG35663Y3Qar3CTbpApotwk9ZKLoF79XA4DjG8XoByaKdNHKQX9Lz5hd7iJqsWdTKyA7dKa6Z',\n}\n\n/**\n * Chain IDs used in the key derivation function (KDF) for deriving child public keys to\n * distinguish between different chains.\n *\n * @see {@link deriveChildPublicKey} in cryptography.ts for usage details\n */\nexport const KDF_CHAIN_IDS = {\n [CHAINS.ETHEREUM]: '0x1',\n [CHAINS.NEAR]: '0x18d',\n [CHAINS.SOLANA]: '0x800001f5',\n} as const\n\n/**\n * Contract addresses for different chains and environments.\n *\n * - Testnet Dev: Used for internal development, very unstable\n * - Testnet: Used for external development, stable\n * - Mainnet: Production contract address\n *\n * @see ChainSignatureContract documentation for implementation details\n */\nexport const CONTRACT_ADDRESSES: Record<\n keyof typeof CHAINS,\n Record<keyof typeof ENVS, string>\n> = {\n [CHAINS.NEAR]: {\n [ENVS.TESTNET_DEV]: 'dev.sig-net.testnet',\n [ENVS.TESTNET]: 'v1.sig-net.testnet',\n [ENVS.MAINNET]: 'v1.sig-net.near',\n },\n [CHAINS.ETHEREUM]: {\n [ENVS.TESTNET_DEV]: '0x69C6b28Fdc74618817fa380De29a653060e14009',\n [ENVS.TESTNET]: '0x83458E8Bf8206131Fe5c05127007FA164c0948A2',\n [ENVS.MAINNET]: '0xf8bdC0612361a1E49a8E01423d4C0cFc5dF4791A',\n },\n [CHAINS.SOLANA]: {\n [ENVS.TESTNET_DEV]: '',\n [ENVS.TESTNET]: '',\n [ENVS.MAINNET]: '',\n }\n}\n","export * as cryptography from './cryptography'\n","import { base58 } from '@scure/base'\nimport { ec as EC } from 'elliptic'\nimport { sha3_256 } from 'js-sha3'\nimport { keccak256 } from 'viem'\n\nimport { KDF_CHAIN_IDS } from '@constants'\nimport {\n type NajPublicKey,\n type MPCSignature,\n type RSVSignature,\n type UncompressedPubKeySEC1,\n} from '@types'\n\nexport const toRSV = (signature: MPCSignature): RSVSignature => {\n // Handle NearNearMpcSignature\n if (\n 'big_r' in signature &&\n typeof signature.big_r === 'object' &&\n 'affine_point' in signature.big_r &&\n 's' in signature &&\n typeof signature.s === 'object' &&\n 'scalar' in signature.s\n ) {\n return {\n r: signature.big_r.affine_point.substring(2),\n s: signature.s.scalar,\n v: signature.recovery_id + 27,\n }\n }\n // Handle SigNetNearMpcSignature\n else if (\n 'big_r' in signature &&\n typeof signature.big_r === 'string' &&\n 's' in signature &&\n typeof signature.s === 'string'\n ) {\n return {\n r: signature.big_r.substring(2),\n s: signature.s,\n v: signature.recovery_id + 27,\n }\n }\n // Handle SigNetEvmMpcSignature\n else if (\n 'bigR' in signature &&\n 'x' in signature.bigR &&\n 's' in signature &&\n typeof signature.s === 'bigint'\n ) {\n return {\n r: signature.bigR.x.toString(16).padStart(64, '0'),\n s: signature.s.toString(16).padStart(64, '0'),\n v: signature.recoveryId + 27,\n }\n }\n\n throw new Error('Invalid signature format')\n}\n\n/**\n * Compresses an uncompressed public key to its compressed format following SEC1 standards.\n * In SEC1, a compressed public key consists of a prefix (02 or 03) followed by the x-coordinate.\n * The prefix indicates whether the y-coordinate is even (02) or odd (03).\n *\n * @param uncompressedPubKeySEC1 - The uncompressed public key in hex format, with or without '04' prefix\n * @returns The compressed public key in hex format\n * @throws Error if the uncompressed public key length is invalid\n */\nexport const compressPubKey = (\n uncompressedPubKeySEC1: UncompressedPubKeySEC1\n): string => {\n const slicedPubKey = uncompressedPubKeySEC1.slice(2)\n\n if (slicedPubKey.length !== 128) {\n throw new Error('Invalid uncompressed public key length')\n }\n\n const x = slicedPubKey.slice(0, 64)\n const y = slicedPubKey.slice(64)\n\n const isEven = parseInt(y.slice(-1), 16) % 2 === 0\n const prefix = isEven ? '02' : '03'\n\n return prefix + x\n}\n\n/**\n * Converts a NAJ public key to an uncompressed SEC1 public key.\n *\n * @param najPublicKey - The NAJ public key to convert (e.g. secp256k1:3Ww8iFjqTHufye5aRGUvrQqETegR4gVUcW8FX5xzscaN9ENhpkffojsxJwi6N1RbbHMTxYa9UyKeqK3fsMuwxjR5)\n * @returns The uncompressed SEC1 public key (e.g. 04 || x || y)\n */\nexport const najToUncompressedPubKeySEC1 = (\n najPublicKey: NajPublicKey\n): UncompressedPubKeySEC1 => {\n const decodedKey = base58.decode(najPublicKey.split(':')[1])\n return `04${Buffer.from(decodedKey).toString('hex')}`\n}\n\n/**\n * Derives a child public key from a parent public key using the sig.network v1.0.0 epsilon derivation scheme.\n * The parent public keys are defined in @constants.ts\n *\n * @param najPublicKey - The parent public key in uncompressed SEC1 format (e.g. 04 || x || y)\n * @param predecessorId - The predecessor ID is the address of the account calling the signer contract (e.g EOA or Contract Address)\n * @param path - Optional derivation path suffix (defaults to empty string)\n * @returns The derived child public key in uncompressed SEC1 format (04 || x || y)\n */\nexport function deriveChildPublicKey(\n rootUncompressedPubKeySEC1: UncompressedPubKeySEC1,\n predecessorId: string,\n path: string = '',\n chainId: string\n): UncompressedPubKeySEC1 {\n const ec = new EC('secp256k1')\n\n const EPSILON_DERIVATION_PREFIX = 'sig.network v1.0.0 epsilon derivation'\n const derivationPath = `${EPSILON_DERIVATION_PREFIX},${chainId},${predecessorId},${path}`\n\n let scalarHex = ''\n\n if (chainId === KDF_CHAIN_IDS.ETHEREUM) {\n scalarHex = keccak256(Buffer.from(derivationPath)).slice(2)\n } else if (chainId === KDF_CHAIN_IDS.NEAR) {\n scalarHex = sha3_256(derivationPath)\n } else if (chainId === KDF_CHAIN_IDS.SOLANA) {\n scalarHex = keccak256(Buffer.from(derivationPath)).slice(2)\n } else {\n throw new Error('Invalid chain ID')\n }\n\n const x = rootUncompressedPubKeySEC1.substring(2, 66)\n const y = rootUncompressedPubKeySEC1.substring(66)\n\n const oldPublicKeyPoint = ec.curve.point(x, y)\n const scalarTimesG = ec.g.mul(scalarHex)\n const newPublicKeyPoint = oldPublicKeyPoint.add(scalarTimesG)\n\n const newX = newPublicKeyPoint.getX().toString('hex').padStart(64, '0')\n const newY = newPublicKeyPoint.getY().toString('hex').padStart(64, '0')\n\n return `04${newX}${newY}`\n}\n","export { ChainAdapter } from './ChainAdapter'\n\nexport * as evm from './EVM'\nexport * as btc from './Bitcoin'\nexport * as cosmos from './Cosmos'\n","import type { KeyDerivationPath, HashToSign, RSVSignature } from '@types'\n\nexport abstract class ChainAdapter<TransactionRequest, UnsignedTransaction> {\n /**\n * Gets the native token balance and decimals for a given address\n *\n * @param address - The address to check\n * @returns Promise resolving to an object containing:\n * - balance: The balance as a bigint, in the chain's base units\n * - decimals: The number of decimals used to format the balance\n */\n abstract getBalance(address: string): Promise<{\n balance: bigint\n decimals: number\n }>\n\n /**\n * Uses Sig Network Key Derivation Function to derive the address and public key. from a signer ID and string path.\n *\n * @param predecessor - The id/address of the account requesting signature\n * @param path - The string path used to derive the key\n * @returns Promise resolving to the derived address and public key\n */\n abstract deriveAddressAndPublicKey(\n predecessor: string,\n path: KeyDerivationPath\n ): Promise<{\n address: string\n publicKey: string\n }>\n\n /**\n * Serializes an unsigned transaction to a string format.\n * This is useful for storing or transmitting the transaction.\n *\n * @param transaction - The unsigned transaction to serialize\n * @returns The serialized transaction string\n */\n abstract serializeTransaction(transaction: UnsignedTransaction): string\n\n /**\n * Deserializes a transaction string back into an unsigned transaction object.\n * This reverses the serialization done by serializeTransaction().\n *\n * @param serialized - The serialized transaction string\n * @returns The deserialized unsigned transaction\n */\n abstract deserializeTransaction(serialized: string): UnsignedTransaction\n\n /**\n * Prepares a transaction for Sig Network MPC signing by creating the necessary payloads.\n * This method handles chain-specific transaction preparation including:\n * - Fee calculation\n * - Nonce/sequence management\n * - UTXO selection (for UTXO-based chains)\n * - Transaction encoding\n *\n * @param transactionRequest - The transaction request containing parameters like recipient, amount, etc.\n * @returns Promise resolving to an object containing:\n * - transaction: The unsigned transaction\n * - hashesToSign: Array of payloads to be signed by MPC. The order of these payloads must match\n * the order of signatures provided to finalizeTransactionSigning()\n */\n abstract prepareTransactionForSigning(\n transactionRequest: TransactionRequest\n ): Promise<{\n transaction: UnsignedTransaction\n hashesToSign: HashToSign[]\n }>\n\n /**\n * Adds Sig Network MPC-generated signatures to an unsigned transaction.\n *\n * @param params - Parameters for adding signatures\n * @param params.transaction - The unsigned transaction to add signatures to\n * @param params.rsvSignatures - Array of RSV signatures generated through MPC. Must be in the same order\n * as the payloads returned by prepareTransactionForSigning()\n * @returns The serialized signed transaction ready for broadcast\n */\n abstract finalizeTransactionSigning(params: {\n transaction: UnsignedTransaction\n rsvSignatures: RSVSignature[]\n }): string\n\n /**\n * Broadcasts a signed transaction to the network.\n *\n * @param txSerialized - The serialized signed transaction\n * @returns Promise resolving to the transaction hash/ID\n */\n abstract broadcastTx(txSerialized: string): Promise<string>\n}\n","// EVM\nexport { EVM } from './EVM'\n\nexport { fetchEVMFeeProperties } from './utils'\n\nexport type {\n EVMTransactionRequest,\n EVMUnsignedTransaction,\n EVMMessage,\n EVMTypedData,\n} from './types'\n","import {\n createPublicClient,\n http,\n parseTransaction,\n type PublicClient,\n hashMessage,\n hashTypedData,\n keccak256,\n toBytes,\n type Hex,\n serializeTransaction,\n type Signature,\n numberToHex,\n getAddress,\n type Address,\n type Hash,\n concatHex,\n encodeAbiParameters,\n hexToBigInt,\n concat,\n pad,\n isAddress,\n} from 'viem'\n\nimport { ChainAdapter } from '@chain-adapters/ChainAdapter'\nimport type {\n EVMTransactionRequest,\n EVMUnsignedTransaction,\n EVMMessage,\n EVMTypedData,\n UserOperationV6,\n UserOperationV7,\n} from '@chain-adapters/EVM/types'\nimport { fetchEVMFeeProperties } from '@chain-adapters/EVM/utils'\nimport type { BaseChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { HashToSign, RSVSignature, KeyDerivationPath } from '@types'\n\n/**\n * Implementation of the ChainAdapter interface for EVM-compatible networks.\n * Handles interactions with Ethereum Virtual Machine based blockchains like Ethereum, BSC, Polygon, etc.\n */\nexport class EVM extends ChainAdapter<\n EVMTransactionRequest,\n EVMUnsignedTransaction\n> {\n private readonly client: PublicClient\n private readonly contract: BaseChainSignatureContract\n\n /**\n * Creates a new EVM chain instance\n * @param params - Configuration parameters\n * @param params.publicClient - A Viem PublicClient instance for reading from the blockchain\n * @param params.contract - Instance of the chain signature contract for MPC operations\n */\n constructor({\n publicClient,\n contract,\n }: {\n publicClient: PublicClient\n contract: BaseChainSignatureContract\n }) {\n super()\n\n this.contract = contract\n this.client = publicClient;\n }\n\n private async attachGasAndNonce(\n transaction: EVMTransactionRequest\n ): Promise<EVMUnsignedTransaction> {\n const fees = await fetchEVMFeeProperties(this.client, transaction)\n const nonce = await this.client.getTransactionCount({\n address: transaction.from,\n })\n\n const { from, ...rest } = transaction\n\n return {\n ...fees,\n nonce,\n chainId: Number(await this.client.getChainId()),\n type: 'eip1559',\n ...rest,\n }\n }\n\n private transformRSVSignature(signature: RSVSignature): Signature {\n return {\n r: `0x${signature.r}`,\n s: `0x${signature.s}`,\n yParity: signature.v - 27,\n }\n }\n\n private assembleSignature(signature: RSVSignature): Hex {\n const { r, s, yParity } = this.transformRSVSignature(signature)\n\n if (yParity === undefined) {\n throw new Error('Missing yParity')\n }\n\n return concatHex([r, s, numberToHex(yParity + 27, { size: 1 })])\n }\n\n async deriveAddressAndPublicKey(\n predecessor: string,\n path: KeyDerivationPath\n ): Promise<{\n address: string\n publicKey: string\n }> {\n const uncompressedPubKey = await this.contract.getDerivedPublicKey({\n path,\n predecessor,\n })\n\n if (!uncompressedPubKey) {\n throw new Error('Failed to get derived public key')\n }\n\n const publicKeyNoPrefix = uncompressedPubKey.startsWith('04')\n ? uncompressedPubKey.slice(2)\n : uncompressedPubKey\n\n const hash = keccak256(Buffer.from(publicKeyNoPrefix, 'hex'))\n const address = getAddress(`0x${hash.slice(-40)}`)\n\n return {\n address,\n publicKey: uncompressedPubKey,\n }\n }\n\n async getBalance(\n address: string\n ): Promise<{ balance: bigint; decimals: number }> {\n const balance = await this.client.getBalance({\n address: address as Address,\n })\n return {\n balance,\n decimals: 18,\n }\n }\n\n serializeTransaction(transaction: EVMUnsignedTransaction): `0x${string}` {\n return serializeTransaction(transaction)\n }\n\n deserializeTransaction(serialized: `0x${string}`): EVMUnsignedTransaction {\n return parseTransaction(serialized) as EVMUnsignedTransaction\n }\n\n async prepareTransactionForSigning(\n transactionRequest: EVMTransactionRequest\n ): Promise<{\n transaction: EVMUnsignedTransaction\n hashesToSign: HashToSign[]\n }> {\n const transaction = await this.attachGasAndNonce(transactionRequest)\n\n const serializedTx = serializeTransaction(transaction)\n const txHash = toBytes(keccak256(serializedTx))\n\n return {\n transaction,\n hashesToSign: [Array.from(txHash)],\n }\n }\n\n async prepareMessageForSigning(message: EVMMessage): Promise<{\n hashToSign: HashToSign\n }> {\n return {\n hashToSign: Array.from(toBytes(hashMessage(message))),\n }\n }\n\n async prepareTypedDataForSigning(typedDataRequest: EVMTypedData): Promise<{\n hashToSign: HashToSign\n }> {\n return {\n hashToSign: Array.from(toBytes(hashTypedData(typedDataRequest))),\n }\n }\n\n /**\n * This implementation is a common step for Biconomy and Alchemy.\n * Key differences between implementations:\n * - Signature format: Biconomy omits 0x00 prefix when concatenating, Alchemy includes it\n * - Version support: Biconomy only supports v6, Alchemy supports both v6 and v7\n * - Validation: Biconomy uses modules for signature validation, Alchemy uses built-in validation\n */\n async prepareUserOpForSigning(\n userOp: UserOperationV7 | UserOperationV6,\n entryPointAddress?: Address,\n chainIdArgs?: number\n ): Promise<{\n userOp: UserOperationV7 | UserOperationV6\n hashToSign: HashToSign\n }> {\n const chainId = chainIdArgs ?? (await this.client.getChainId())\n const entryPoint =\n entryPointAddress || '0x0000000071727De22E5E9d8BAf0edAc6f37da032'\n\n const encoded = encodeAbiParameters(\n [{ type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }],\n [\n keccak256(\n encodeAbiParameters(\n [\n { type: 'address' },\n { type: 'uint256' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n { type: 'uint256' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n ],\n [\n userOp.sender,\n hexToBigInt(userOp.nonce),\n keccak256(\n 'factory' in userOp &&\n 'factoryData' in userOp &&\n userOp.factory &&\n userOp.factoryData\n ? concat([userOp.factory, userOp.factoryData])\n : 'initCode' in userOp\n ? userOp.initCode\n : '0x'\n ),\n keccak256(userOp.callData),\n concat([\n pad(userOp.verificationGasLimit, { size: 16 }),\n pad(userOp.callGasLimit, { size: 16 }),\n ]),\n hexToBigInt(userOp.preVerificationGas),\n concat([\n pad(userOp.maxPriorityFeePerGas, { size: 16 }),\n pad(userOp.maxFeePerGas, { size: 16 }),\n ]),\n keccak256(\n 'paymaster' in userOp &&\n userOp.paymaster &&\n isAddress(userOp.paymaster)\n ? concat([\n userOp.paymaster,\n pad(userOp.paymasterVerificationGasLimit, { size: 16 }),\n pad(userOp.paymasterPostOpGasLimit, { size: 16 }),\n userOp.paymasterData,\n ])\n : 'paymasterAndData' in userOp\n ? userOp.paymasterAndData\n : '0x'\n ),\n ]\n )\n ),\n entryPoint,\n BigInt(chainId),\n ]\n )\n\n const userOpHash = keccak256(encoded)\n\n return {\n userOp,\n hashToSign: Array.from(toBytes(hashMessage({ raw: userOpHash }))),\n }\n }\n\n finalizeTransactionSigning({\n transaction,\n rsvSignatures,\n }: {\n transaction: EVMUnsignedTransaction\n rsvSignatures: RSVSignature[]\n }): `0x02${string}` {\n const signature = this.transformRSVSignature(rsvSignatures[0])\n\n return serializeTransaction(transaction, signature)\n }\n\n finalizeMessageSigning({\n rsvSignature,\n }: {\n rsvSignature: RSVSignature\n }): Hex {\n return this.assembleSignature(rsvSignature)\n }\n\n finalizeTypedDataSigning({\n rsvSignature,\n }: {\n rsvSignature: RSVSignature\n }): Hex {\n return this.assembleSignature(rsvSignature)\n }\n\n finalizeUserOpSigning({\n userOp,\n rsvSignature,\n }: {\n userOp: UserOperationV7 | UserOperationV6\n rsvSignature: RSVSignature\n }): UserOperationV7 | UserOperationV6 {\n const { r, s, yParity } = this.transformRSVSignature(rsvSignature)\n if (yParity === undefined) {\n throw new Error('Missing yParity')\n }\n\n return {\n ...userOp,\n signature: concatHex([\n '0x00', // Alchemy specific implementation. Biconomy doesn't include the 0x00 prefix.\n r,\n s,\n numberToHex(Number(yParity + 27), { size: 1 }),\n ]),\n }\n }\n\n async broadcastTx(txSerialized: `0x${string}`): Promise<Hash> {\n try {\n return await this.client.sendRawTransaction({\n serializedTransaction: txSerialized,\n })\n } catch (error) {\n console.error('Transaction broadcast failed:', error)\n throw new Error('Failed to broadcast transaction.')\n }\n }\n}\n","import { type PublicClient, type TransactionRequest } from 'viem'\n\nexport interface EVMFeeProperties {\n gas: bigint\n maxFeePerGas: bigint\n maxPriorityFeePerGas: bigint\n}\n\nexport async function fetchEVMFeeProperties(\n client: PublicClient,\n transaction: TransactionRequest\n): Promise<EVMFeeProperties> {\n const [gas, feeData] = await Promise.all([\n client.estimateGas(transaction),\n client.estimateFeesPerGas(),\n ])\n\n const maxFeePerGas = feeData.maxFeePerGas ?? BigInt(10_000_000_000) // 10 gwei\n const maxPriorityFeePerGas =\n feeData.maxPriorityFeePerGas ?? BigInt(10_000_000_000) // 10 gwei\n\n return {\n gas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n }\n}\n","// Bitcoin\nexport { Bitcoin } from './Bitcoin'\n\nexport { BTCRpcAdapters, BTCRpcAdapter } from './BTCRpcAdapter'\n\nexport type {\n BTCTransactionRequest,\n BTCUnsignedTransaction,\n BTCTransaction,\n BTCOutput,\n BTCInput,\n BTCNetworkIds,\n} from './types'\n","import * as bitcoin from 'bitcoinjs-lib'\n\nimport { type BTCRpcAdapter } from '@chain-adapters/Bitcoin/BTCRpcAdapter'\nimport type {\n BTCInput,\n BTCNetworkIds,\n BTCOutput,\n BTCTransactionRequest,\n BTCUnsignedTransaction,\n} from '@chain-adapters/Bitcoin/types'\nimport { parseBTCNetwork } from '@chain-adapters/Bitcoin/utils'\nimport { ChainAdapter } from '@chain-adapters/ChainAdapter'\nimport type { BaseChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { HashToSign, RSVSignature, KeyDerivationPath } from '@types'\nimport { cryptography } from '@utils'\n\n/**\n * Implementation of the ChainAdapter interface for Bitcoin network.\n * Handles interactions with both Bitcoin mainnet and testnet, supporting P2WPKH transactions.\n */\nexport class Bitcoin extends ChainAdapter<\n BTCTransactionRequest,\n BTCUnsignedTransaction\n> {\n private static readonly SATOSHIS_PER_BTC = 100_000_000\n\n private readonly network: BTCNetworkIds\n private readonly btcRpcAdapter: BTCRpcAdapter\n private readonly contract: BaseChainSignatureContract\n\n /**\n * Creates a new Bitcoin chain instance\n * @param params - Configuration parameters\n * @param params.network - Network identifier (mainnet/testnet)\n * @param params.contract - Instance of the chain signature contract for MPC operations\n * @param params.btcRpcAdapter - Bitcoin RPC adapter for network interactions\n */\n constructor({\n network,\n contract,\n btcRpcAdapter,\n }: {\n network: BTCNetworkIds\n contract: BaseChainSignatureContract\n btcRpcAdapter: BTCRpcAdapter\n }) {\n super()\n\n this.network = network\n this.btcRpcAdapter = btcRpcAdapter\n this.contract = contract\n }\n\n /**\n * Converts satoshis to BTC\n * @param satoshis - Amount in satoshis\n * @returns Amount in BTC\n */\n static toBTC(satoshis: number): number {\n return satoshis / Bitcoin.SATOSHIS_PER_BTC\n }\n\n /**\n * Converts BTC to satoshis\n * @param btc - Amount in BTC\n * @returns Amount in satoshis (rounded)\n */\n static toSatoshi(btc: number): number {\n return Math.round(btc * Bitcoin.SATOSHIS_PER_BTC)\n }\n\n private async fetchTransaction(\n transactionId: string\n ): Promise<bitcoin.Transaction> {\n const data = await this.btcRpcAdapter.getTransaction(transactionId)\n const tx = new bitcoin.Transaction()\n\n data.vout.forEach((vout) => {\n const scriptPubKey = Buffer.from(vout.scriptpubkey, 'hex')\n tx.addOutput(scriptPubKey, Number(vout.value))\n })\n\n return tx\n }\n\n private static transformRSVSignature(signature: RSVSignature): Buffer {\n const r = signature.r.padStart(64, '0')\n const s = signature.s.padStart(64, '0')\n\n const rawSignature = Buffer.from(r + s, 'hex')\n\n if (rawSignature.length !== 64) {\n throw new Error('Invalid signature length.')\n }\n\n return rawSignature\n }\n\n /**\n * Creates a Partially Signed Bitcoin Transaction (PSBT)\n * @param params - Parameters for creating the PSBT\n * @param params.transactionRequest - Transaction request containing inputs and outputs\n * @returns Created PSBT instance\n */\n async createPSBT({\n transactionRequest,\n }: {\n transactionRequest: BTCTransactionRequest\n }): Promise<bitcoin.Psbt> {\n const { inputs, outputs } =\n transactionRequest.inputs && transactionRequest.outputs\n ? transactionRequest\n : await this.btcRpcAdapter.selectUTXOs(transactionRequest.from, [\n {\n address: transactionRequest.to,\n value: parseFloat(transactionRequest.value),\n },\n ])\n\n const psbt = new bitcoin.Psbt({ network: parseBTCNetwork(this.network) })\n\n await Promise.all(\n inputs.map(async (input: BTCInput) => {\n if (!input.scriptPubKey) {\n const transaction = await this.fetchTransaction(input.txid)\n const prevOut = transaction.outs[input.vout]\n input.scriptPubKey = prevOut.script\n }\n\n // Prepare the input as P2WPKH\n psbt.addInput({\n hash: input.txid,\n index: input.vout,\n witnessUtxo: {\n script: input.scriptPubKey,\n value: input.value,\n },\n })\n })\n )\n\n outputs.forEach((out: BTCOutput) => {\n if ('address' in out) {\n psbt.addOutput({\n address: out.address,\n value: out.value,\n })\n } else if ('script' in out) {\n psbt.addOutput({\n script: out.script,\n value: out.value,\n })\n } else if (transactionRequest.from !== undefined) {\n // Include change address from coinselect\n psbt.addOutput({\n value: Number(out.value),\n address: transactionRequest.from,\n })\n }\n })\n\n return psbt\n }\n\n async getBalance(\n address: string\n ): Promise<{ balance: bigint; decimals: number }> {\n const balance = BigInt(await this.btcRpcAdapter.getBalance(address))\n return {\n balance,\n decimals: 8,\n }\n }\n\n async deriveAddressAndPublicKey(\n predecessor: string,\n path: KeyDerivationPath\n ): Promise<{ address: string; publicKey: string }> {\n const uncompressedPubKey = await this.contract.getDerivedPublicKey({\n path,\n predecessor,\n })\n\n if (!uncompressedPubKey) {\n throw new Error('Failed to get derived public key')\n }\n\n const derivedKey = cryptography.compressPubKey(uncompressedPubKey)\n const publicKeyBuffer = Buffer.from(derivedKey, 'hex')\n const network = parseBTCNetwork(this.network)\n\n const payment = bitcoin.payments.p2wpkh({\n pubkey: publicKeyBuffer,\n network,\n })\n\n const { address } = payment\n\n if (!address) {\n throw new Error('Failed to generate Bitcoin address')\n }\n\n return { address, publicKey: derivedKey }\n }\n\n serializeTransaction(transaction: BTCUnsignedTransaction): string {\n return JSON.stringify({\n psbt: transaction.psbt.toHex(),\n publicKey: transaction.publicKey,\n })\n }\n\n deserializeTransaction(serialized: string): BTCUnsignedTransaction {\n const transactionJSON = JSON.parse(serialized)\n return {\n psbt: bitcoin.Psbt.fromHex(transactionJSON.psbt as string),\n publicKey: transactionJSON.publicKey,\n }\n }\n\n async prepareTransactionForSigning(\n transactionRequest: BTCTransactionRequest\n ): Promise<{\n transaction: BTCUnsignedTransaction\n hashesToSign: HashToSign[]\n }> {\n const publicKeyBuffer = Buffer.from(transactionRequest.publicKey, 'hex')\n const psbt = await this.createPSBT({\n transactionRequest,\n })\n\n // We can't double sign a PSBT, therefore we serialize the payload before to return it\n const psbtHex = psbt.toHex()\n\n const hashesToSign: HashToSign[] = []\n\n const mockKeyPair = (index: number): bitcoin.Signer => ({\n publicKey: publicKeyBuffer,\n sign: (hash: Buffer): Buffer => {\n hashesToSign[index] = Array.from(hash)\n // Return dummy signature to satisfy the interface\n return Buffer.alloc(64)\n },\n })\n\n for (let index = 0; index < psbt.inputCount; index++) {\n psbt.signInput(index, mockKeyPair(index))\n }\n\n return {\n transaction: {\n psbt: bitcoin.Psbt.fromHex(psbtHex),\n publicKey: transactionRequest.publicKey,\n },\n hashesToSign,\n }\n }\n\n finalizeTransactionSigning({\n transaction: { psbt, publicKey },\n rsvSignatures,\n }: {\n transaction: BTCUnsignedTransaction\n rsvSignatures: RSVSignature[]\n }): string {\n const publicKeyBuffer = Buffer.from(publicKey, 'hex')\n\n const keyPair = (index: number): bitcoin.Signer => ({\n publicKey: publicKeyBuffer,\n sign: () => {\n const mpcSignature = rsvSignatures[index]\n return Bitcoin.transformRSVSignature(mpcSignature)\n },\n })\n\n for (let index = 0; index < psbt.inputCount; index++) {\n psbt.signInput(index, keyPair(index))\n }\n\n psbt.finalizeAllInputs()\n return psbt.extractTransaction().toHex()\n }\n\n async broadcastTx(txSerialized: string): Promise<string> {\n return await this.btcRpcAdapter.broadcastTransaction(txSerialized)\n }\n}\n","import * as bitcoin from 'bitcoinjs-lib'\n\nexport function parseBTCNetwork(network: string): bitcoin.networks.Network {\n switch (network.toLowerCase()) {\n case 'mainnet':\n return bitcoin.networks.bitcoin\n case 'testnet':\n return bitcoin.networks.testnet\n case 'regtest':\n return bitcoin.networks.regtest\n default:\n throw new Error(`Unknown Bitcoin network: ${network}`)\n }\n}\n","// There is no types for coinselect\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-expect-error\n\nimport coinselect from 'coinselect'\n\nimport { BTCRpcAdapter } from '@chain-adapters/Bitcoin/BTCRpcAdapter/BTCRpcAdapter'\nimport {\n type BTCFeeRecommendation,\n type UTXO,\n} from '@chain-adapters/Bitcoin/BTCRpcAdapter/Mempool/types'\nimport type {\n BTCTransaction,\n BTCInput,\n BTCOutput,\n} from '@chain-adapters/Bitcoin/types'\n\nexport class Mempool extends BTCRpcAdapter {\n private readonly providerUrl: string\n\n constructor(providerUrl: string) {\n super()\n this.providerUrl = providerUrl\n }\n\n private async fetchFeeRate(confirmationTarget = 6): Promise<number> {\n const response = await fetch(`${this.providerUrl}/v1/fees/recommended`)\n const data = (await response.json()) as BTCFeeRecommendation\n\n if (confirmationTarget <= 1) {\n return data.fastestFee\n } else if (confirmationTarget <= 3) {\n return data.halfHourFee\n } else if (confirmationTarget <= 6) {\n return data.hourFee\n } else {\n return data.economyFee\n }\n }\n\n private async fetchUTXOs(address: string): Promise<UTXO[]> {\n try {\n const response = await fetch(\n `${this.providerUrl}/address/${address}/utxo`\n )\n return (await response.json()) as UTXO[]\n } catch (error) {\n console.error('Failed to fetch UTXOs:', error)\n return []\n }\n }\n\n async selectUTXOs(\n from: string,\n targets: BTCOutput[],\n confirmationTarget = 6\n ): Promise<{ inputs: BTCInput[]; outputs: BTCOutput[] }> {\n const utxos = await this.fetchUTXOs(from)\n const feeRate = await this.fetchFeeRate(confirmationTarget)\n\n // Add a small amount to the fee rate to ensure the transaction is confirmed\n const ret = coinselect(utxos, targets, Math.ceil(feeRate + 1))\n\n if (!ret.inputs || !ret.outputs) {\n throw new Error(\n '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.'\n )\n }\n\n return {\n inputs: ret.inputs,\n outputs: ret.outputs,\n }\n }\n\n async broadcastTransaction(transactionHex: string): Promise<string> {\n const response = await fetch(`${this.providerUrl}/tx`, {\n method: 'POST',\n body: transactionHex,\n })\n\n if (response.ok) {\n return await response.text()\n }\n\n throw new Error(`Failed to broadcast transaction: ${await response.text()}`)\n }\n\n async getBalance(address: string): Promise<number> {\n const response = await fetch(`${this.providerUrl}/address/${address}`)\n const data = (await response.json()) as {\n chain_stats: { funded_txo_sum: number; spent_txo_sum: number }\n }\n return data.chain_stats.funded_txo_sum - data.chain_stats.spent_txo_sum\n }\n\n async getTransaction(txid: string): Promise<BTCTransaction> {\n const response = await fetch(`${this.providerUrl}/tx/${txid}`)\n return (await response.json()) as BTCTransaction\n }\n}\n","import type {\n BTCTransaction,\n BTCInput,\n BTCOutput,\n} from '@chain-adapters/Bitcoin/types'\n\nexport abstract class BTCRpcAdapter {\n abstract selectUTXOs(\n from: string,\n targets: BTCOutput[]\n ): Promise<{ inputs: BTCInput[]; outputs: BTCOutput[] }>\n abstract broadcastTransaction(transactionHex: string): Promise<string>\n abstract getBalance(address: string): Promise<number>\n abstract getTransaction(txid: string): Promise<BTCTransaction>\n}\n","import { Mempool } from './Mempool'\nexport { BTCRpcAdapter } from './BTCRpcAdapter'\n\nexport const BTCRpcAdapters = {\n Mempool,\n}\n","// Cosmos\nexport { Cosmos } from './Cosmos'\n\nexport type {\n CosmosNetworkIds,\n CosmosTransactionRequest,\n CosmosUnsignedTransaction,\n} from './types'\n","import { encodeSecp256k1Pubkey } from '@cosmjs/amino'\nimport { ripemd160, sha256 } from '@cosmjs/crypto'\nimport { toBase64, fromBase64, fromHex } from '@cosmjs/encoding'\nimport {\n Registry,\n makeSignBytes,\n encodePubkey,\n makeAuthInfoBytes,\n makeSignDoc,\n type TxBodyEncodeObject,\n} from '@cosmjs/proto-signing'\nimport { GasPrice, StargateClient, calculateFee } from '@cosmjs/stargate'\nimport { bech32 } from 'bech32'\nimport { SignMode } from 'cosmjs-types/cosmos/tx/signing/v1beta1/signing'\nimport { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx'\n\nimport { ChainAdapter } from '@chain-adapters/ChainAdapter'\nimport type {\n CosmosNetworkIds,\n CosmosTransactionRequest,\n CosmosUnsignedTransaction,\n ChainInfo,\n BalanceResponse,\n} from '@chain-adapters/Cosmos/types'\nimport { fetchChainInfo } from '@chain-adapters/Cosmos/utils'\nimport type { BaseChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { HashToSign, RSVSignature, KeyDerivationPath } from '@types'\nimport { cryptography } from '@utils'\n\n/**\n * Implementation of the ChainAdapter interface for Cosmos-based networks.\n * Handles interactions with Cosmos SDK chains like Cosmos Hub, Osmosis, etc.\n */\nexport class Cosmos extends ChainAdapter<\n CosmosTransactionRequest,\n CosmosUnsignedTransaction\n> {\n private readonly registry: Registry\n private readonly chainId: CosmosNetworkIds\n private readonly contract: BaseChainSignatureContract\n private readonly endpoints?: {\n rpcUrl?: string\n restUrl?: string\n }\n\n /**\n * Creates a new Cosmos chain instance\n * @param params - Configuration parameters\n * @param params.chainId - Chain id for the Cosmos network\n * @param params.contract - Instance of the chain signature contract for MPC operations\n * @param params.endpoints - Optional RPC and REST endpoints\n * @param params.endpoints.rpcUrl - Optional RPC endpoint URL\n * @param params.endpoints.restUrl - Optional REST endpoint URL\n */\n constructor({\n chainId,\n contract,\n endpoints,\n }: {\n contract: BaseChainSignatureContract\n chainId: CosmosNetworkIds\n endpoints?: {\n rpcUrl?: string\n restUrl?: string\n }\n }) {\n super()\n\n this.contract = contract\n this.registry = new Registry()\n this.chainId = chainId\n this.endpoints = endpoints\n }\n\n private transformRSVSignature(rsvSignature: RSVSignature): Uint8Array {\n return new Uint8Array([\n ...fromHex(rsvSignature.r),\n ...fromHex(rsvSignature.s),\n ])\n }\n\n private async getChainInfo(): Promise<ChainInfo> {\n return {\n ...(await fetchChainInfo(this.chainId)),\n ...this.endpoints,\n }\n }\n\n async getBalance(\n address: string\n ): Promise<{ balance: bigint; decimals: number }> {\n try {\n const { restUrl, denom, decimals } = await this.getChainInfo()\n\n const response = await fetch(\n `${restUrl}/cosmos/bank/v1beta1/balances/${address}`\n )\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`)\n }\n\n const data = (await response.json()) as BalanceResponse\n const balance = data.balances.find((b) => b.denom === denom)\n const amount = balance?.amount ?? '0'\n\n return {\n balance: BigInt(amount),\n decimals,\n }\n } catch (error) {\n console.error('Failed to fetch Cosmos balance:', error)\n throw new Error('Failed to fetch Cosmos balance')\n }\n }\n\n async deriveAddressAndPublicKey(\n predecessor: string,\n path: KeyDerivationPath\n ): Promise<{\n address: string\n publicKey: string\n }> {\n const { prefix } = await this.getChainInfo()\n const uncompressedPubKey = await this.contract.getDerivedPublicKey({\n path,\n predecessor,\n })\n\n if (!uncompressedPubKey) {\n throw new Error('Failed to get derived public key')\n }\n\n const derivedKey = cryptography.compressPubKey(uncompressedPubKey)\n const pubKeySha256 = sha256(fromHex(derivedKey))\n const ripemd160Hash = ripemd160(pubKeySha256)\n const address = bech32.encode(prefix, bech32.toWords(ripemd160Hash))\n\n return { address, publicKey: derivedKey }\n }\n\n serializeTransaction(transaction: CosmosUnsignedTransaction): string {\n const serialized = TxRaw.encode(transaction).finish()\n return toBase64(serialized)\n }\n\n deserializeTransaction(serialized: string): CosmosUnsignedTransaction {\n return TxRaw.decode(fromBase64(serialized))\n }\n\n async prepareTransactionForSigning(\n transactionRequest: CosmosTransactionRequest\n ): Promise<{\n transaction: CosmosUnsignedTransaction\n hashesToSign: HashToSign[]\n }> {\n const { denom, rpcUrl, gasPrice } = await this.getChainInfo()\n const publicKeyBytes = fromHex(transactionRequest.publicKey)\n\n const gasLimit = transactionRequest.gas || 200_000\n\n const fee = calculateFee(\n gasLimit,\n GasPrice.fromString(`${gasPrice}${denom}`)\n )\n\n const client = await StargateClient.connect(rpcUrl)\n const accountOnChain = await client.getAccount(transactionRequest.address)\n if (!accountOnChain) {\n throw new Error(\n `Account ${transactionRequest.address} does not exist on chain`\n )\n }\n\n const { accountNumber, sequence } = accountOnChain\n\n const txBodyEncodeObject: TxBodyEncodeObject = {\n typeUrl: '/cosmos.tx.v1beta1.TxBody',\n value: {\n messages: transactionRequest.messages,\n memo: transactionRequest.memo || '',\n },\n }\n\n const txBodyBytes = this.registry.encode(txBodyEncodeObject)\n\n const pubkey = encodePubkey(encodeSecp256k1Pubkey(publicKeyBytes))\n\n // TODO: Allow caller to provide: multiple signers, fee payer, fee granter\n const authInfoBytes = makeAuthInfoBytes(\n [\n {\n pubkey,\n sequence,\n },\n ],\n fee.amount,\n Number(fee.gas),\n undefined,\n undefined,\n SignMode.SIGN_MODE_DIRECT\n )\n\n const signDoc = makeSignDoc(\n txBodyBytes,\n authInfoBytes,\n this.chainId,\n accountNumber\n )\n\n const signBytes = makeSignBytes(signDoc)\n const payload = Array.from(sha256(signBytes))\n\n return {\n transaction: TxRaw.fromPartial({\n bodyBytes: txBodyBytes,\n authInfoBytes,\n signatures: [],\n }),\n hashesToSign: [payload],\n }\n }\n\n finalizeTransactionSigning({\n transaction,\n rsvSignatures,\n }: {\n transaction: CosmosUnsignedTransaction\n rsvSignatures: RSVSignature[]\n }): string {\n // Allow support for multi-sig but the package only supports single-sig\n transaction.signatures = rsvSignatures.map((sig) =>\n this.transformRSVSignature(sig)\n )\n\n const txBytes = TxRaw.encode(transaction).finish()\n return Buffer.from(txBytes).toString('hex')\n }\n\n async broadcastTx(txSerialized: string): Promise<string> {\n try {\n const { rpcUrl } = await this.getChainInfo()\n const client = await StargateClient.connect(rpcUrl)\n\n const txBytes = fromHex(txSerialized)\n const broadcastResponse = await client.broadcastTx(txBytes)\n\n if (broadcastResponse.code !== 0) {\n throw new Error(`Broadcast error: ${broadcastResponse.rawLog}`)\n }\n\n return broadcastResponse.transactionHash\n } catch (error) {\n console.error('Transaction broadcast failed:', error)\n throw new Error('Failed to broadcast transaction.')\n }\n }\n}\n","import { chains, assets } from 'chain-registry'\n\nimport { type ChainInfo } from '@chain-adapters/Cosmos/types'\n\nexport const fetchChainInfo = async (chainId: string): Promise<ChainInfo> => {\n const chainInfo = chains.find((chain) => chain.chain_id === chainId)\n if (!chainInfo) {\n throw new Error(`Chain info not found for chainId: ${chainId}`)\n }\n\n const { bech32_prefix: prefix, chain_id: expectedChainId } = chainInfo\n const denom = chainInfo.staking?.staking_tokens?.[0]?.denom\n const rpcUrl = chainInfo.apis?.rpc?.[0]?.address\n const restUrl = chainInfo.apis?.rest?.[0]?.address\n const gasPrice = chainInfo.fees?.fee_tokens?.[0]?.average_gas_price\n\n if (\n !prefix ||\n !denom ||\n !rpcUrl ||\n !restUrl ||\n !expectedChainId ||\n gasPrice === undefined\n ) {\n throw new Error(\n `Missing required chain information for ${chainInfo.chain_name}`\n )\n }\n\n const assetList = assets.find(\n (asset) => asset.chain_name === chainInfo.chain_name\n )\n const asset = assetList?.assets.find((asset) => asset.base === denom)\n const decimals = asset?.denom_units.find(\n (unit) => unit.denom === asset.display\n )?.exponent\n\n if (decimals === undefined) {\n throw new Error(\n `Could not find decimals for ${denom} on chain ${chainInfo.chain_name}`\n )\n }\n\n return { prefix, denom, rpcUrl, restUrl, expectedChainId, gasPrice, decimals }\n}\n","export { ChainSignatureContract, type SignArgs } from './ChainSignatureContract'\n\nexport * as near from './near'\nexport * as evm from './evm'\nexport * as solana from './solana'\n","import type BN from 'bn.js'\n\nimport type { RSVSignature, UncompressedPubKeySEC1 } from '@types'\n\nexport interface SignArgs {\n /** The payload to sign as an array of 32 bytes */\n payload: number[]\n /** The derivation path for key generation */\n path: string\n /** Version of the key to use */\n key_version: number\n}\n\n/**\n * Base contract interface required for compatibility with ChainAdapter instances like EVM and Bitcoin.\n *\n * See {@link EVM} and {@link Bitcoin} for example implementations.\n */\nexport abstract class BaseChainSignatureContract {\n /**\n * Gets the current signature deposit required by the contract.\n * This deposit amount helps manage network congestion.\n *\n * @returns Promise resolving to the required deposit amount as a BigNumber\n */\n abstract getCurrentSignatureDeposit(): Promise<BN>\n\n /**\n * Derives a child public key using a\\ derivation path and predecessor.\n *\n * @param args - Arguments for key derivation\n * @param args.path - The string path to use derive the key\n * @param args.predecessor - The id/address of the account requesting signature\n * @returns Promise resolving to the derived SEC1 uncompressed public key\n */\n abstract getDerivedPublicKey(\n args: {\n path: string\n predecessor: string\n } & Record<string, unknown>\n ): Promise<UncompressedPubKeySEC1>\n}\n\n/**\n * Full contract interface that extends BaseChainSignatureContract to provide all Sig Network Smart Contract capabilities.\n */\nexport abstract class ChainSignatureContract extends BaseChainSignatureContract {\n /**\n * Signs a payload using Sig Network MPC.\n *\n * @param args - Arguments for the signing operation\n * @param args.payload - The data to sign as an array of 32 bytes\n * @param args.path - The string path to use derive the key\n * @param args.key_version - Version of the key to use\n * @returns Promise resolving to the RSV signature\n */\n abstract sign(args: SignArgs & Record<string, unknown>): Promise<RSVSignature>\n\n /**\n * Gets the public key associated with this contract instance.\n *\n * @returns Promise resolving to the SEC1 uncompressed public key\n */\n abstract getPublicKey(): Promise<UncompressedPubKeySEC1>\n}\n","import * as signAndSend from './signAndSend'\nimport * as transaction from './transaction'\nexport * from './ChainSignatureContract'\n\nconst utils = {\n transaction,\n signAndSend,\n}\n\nexport { utils }\n","export * as keypair from './keypair'\n","import { type KeyPair } from '@near-js/crypto'\n\nimport * as chainAdapters from '@chain-adapters'\nimport { BTCRpcAdapters } from '@chain-adapters/Bitcoin/BTCRpcAdapter'\nimport { getNearAccount } from '@contracts/near/account'\nimport { ChainSignatureContract } from '@contracts/near/ChainSignatureContract'\nimport {\n type Response,\n type BitcoinRequest,\n type CosmosRequest,\n type EVMRequest,\n} from '@contracts/near/types'\nimport { createPublicClient, http } from 'viem';\n\nexport const EVMTransaction = async (\n req: EVMRequest,\n keyPair: KeyPair\n): Promise<Response> => {\n try {\n const account = await getNearAccount({\n networkId: req.nearAuthentication.networkId,\n accountId: req.nearAuthentication.accountId,\n keypair: keyPair,\n })\n\n const contract = new ChainSignatureContract({\n networkId: req.nearAuthentication.networkId,\n contractId: req.chainConfig.contract,\n accountId: account.accountId,\n keypair: keyPair,\n })\n\n const evm = new chainAdapters.evm.EVM({\n publicClient: createPublicClient({\n transport: http(req.chainConfig.providerUrl),\n }),\n contract,\n })\n\n const { transaction, hashesToSign } =\n await evm.prepareTransactionForSigning(req.transaction)\n\n const signature = await contract.sign({\n payload: hashesToSign[0],\n path: req.derivationPath,\n key_version: 0,\n })\n\n const txSerialized = evm.finalizeTransactionSigning({\n transaction,\n rsvSignatures: [signature],\n })\n\n const txHash = await evm.broadcastTx(txSerialized)\n\n return {\n transactionHash: txHash,\n success: true,\n }\n } catch (e: unknown) {\n console.error(e)\n return {\n success: false,\n errorMessage: e instanceof Error ? e.message : String(e),\n }\n }\n}\n\nexport const BTCTransaction = async (\n req: BitcoinRequest,\n keyPair: KeyPair\n): Promise<Response> => {\n try {\n const account = await getNearAccount({\n networkId: req.nearAuthentication.networkId,\n accountId: req.nearAuthentication.accountId,\n keypair: keyPair,\n })\n\n const contract = new ChainSignatureContract({\n networkId: req.nearAuthentication.networkId,\n contractId: req.chainConfig.contract,\n accountId: account.accountId,\n keypair: keyPair,\n })\n\n const btc = new chainAdapters.btc.Bitcoin({\n btcRpcAdapter: new BTCRpcAdapters.Mempool(req.chainConfig.providerUrl),\n contract,\n network: req.chainConfig.network,\n })\n\n const { transaction, hashesToSign } =\n await btc.prepareTransactionForSigning(req.transaction)\n\n const signatures = await Promise.all(\n hashesToSign.map(\n async (payload) =>\n await contract.sign({\n payload,\n path: req.derivationPath,\n key_version: 0,\n })\n )\n )\n\n const txSerialized = btc.finalizeTransactionSigning({\n transaction,\n rsvSignatures: signatures,\n })\n\n const txHash = await btc.broadcastTx(txSerialized)\n\n return {\n transactionHash: txHash,\n success: true,\n }\n } catch (e: unknown) {\n return {\n success: false,\n errorMessage: e instanceof Error ? e.message : String(e),\n }\n }\n}\n\nexport const CosmosTransaction = async (\n req: CosmosRequest,\n keyPair: KeyPair\n): Promise<Response> => {\n try {\n const account = await getNearAccount({\n networkId: req.nearAuthentication.networkId,\n accountId: req.nearAuthentication.accountId,\n keypair: keyPair,\n })\n\n const contract = new ChainSignatureContract({\n networkId: req.nearAuthentication.networkId,\n contractId: req.chainConfig.contract,\n accountId: account.accountId,\n keypair: keyPair,\n })\n\n const cosmos = new chainAdapters.cosmos.Cosmos({\n contract,\n chainId: req.chainConfig.chainId,\n })\n\n const { transaction, hashesToSign } =\n await cosmos.prepareTransactionForSigning(req.transaction)\n\n const signatures = await Promise.all(\n hashesToSign.map(\n async (payload) =>\n await contract.sign({\n payload,\n path: req.derivationPath,\n key_version: 0,\n })\n )\n )\n\n const txSerialized = cosmos.finalizeTransactionSigning({\n transaction,\n rsvSignatures: signatures,\n })\n\n const txHash = await cosmos.broadcastTx(txSerialized)\n\n return {\n transactionHash: txHash,\n success: true,\n }\n } catch (e: unknown) {\n console.error(e)\n return {\n success: false,\n errorMessage: e instanceof Error ? e.message : String(e),\n }\n }\n}\n","import { Account, Connection } from '@near-js/accounts'\nimport { KeyPair } from '@near-js/crypto'\nimport { InMemoryKeyStore } from '@near-js/keystores'\n\nimport { DONT_CARE_ACCOUNT_ID } from '@contracts/near/constants'\n\ntype SetConnectionArgs =\n | {\n networkId: string\n accountId: string\n keypair: KeyPair\n }\n | {\n networkId: string\n accountId?: never\n keypair?: never\n }\n\nexport const getNearAccount = async ({\n networkId,\n accountId = DONT_CARE_ACCOUNT_ID,\n keypair = KeyPair.fromRandom('ed25519'),\n}: SetConnectionArgs): Promise<Account> => {\n const keyStore = new InMemoryKeyStore()\n await keyStore.setKey(networkId, accountId, keypair)\n\n const connection = Connection.fromConfig({\n networkId,\n provider: {\n type: 'JsonRpcProvider',\n args: {\n url: {\n testnet: 'https://rpc.testnet.near.org',\n mainnet: 'https://rpc.mainnet.near.org',\n }[networkId],\n },\n },\n signer: { type: 'InMemorySigner', keyStore },\n })\n\n return new Account(connection, accountId)\n}\n","import BN from 'bn.js'\n\nexport const NEAR_MAX_GAS = new BN('300000000000000')\nexport const DONT_CARE_ACCOUNT_ID = 'dontcare'\n","import { CONTRACT_ADDRESSES, ROOT_PUBLIC_KEYS, type CHAINS } from '@constants'\nimport type { NajPublicKey } from '@types'\n\nexport const getRootPublicKey = (\n contractAddress: string,\n chain: keyof typeof CHAINS\n): NajPublicKey | undefined => {\n const environment = Object.entries(CONTRACT_ADDRESSES[chain]).find(\n ([_, address]) => address.toLowerCase() === contractAddress.toLowerCase()\n )?.[0] as keyof typeof ROOT_PUBLIC_KEYS | undefined\n\n if (environment) {\n return ROOT_PUBLIC_KEYS[environment]\n }\n\n return undefined\n}\n","import { Contract } from '@near-js/accounts'\nimport { KeyPair } from '@near-js/crypto'\nimport { actionCreators } from '@near-js/transactions'\nimport { najToUncompressedPubKeySEC1 } from '@utils/cryptography'\nimport { getRootPublicKey } from '@utils/publicKey'\nimport BN from 'bn.js'\n\nimport { CHAINS, KDF_CHAIN_IDS } from '@constants'\nimport { ChainSignatureContract as AbstractChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { SignArgs } from '@contracts/ChainSignatureContract'\nimport { getNearAccount } from '@contracts/near/account'\nimport { DONT_CARE_ACCOUNT_ID, NEAR_MAX_GAS } from '@contracts/near/constants'\nimport {\n responseToMpcSignature,\n type SendTransactionOptions,\n sendTransactionUntil,\n} from '@contracts/near/transaction'\nimport {\n type NearNetworkIds,\n type ChainSignatureContractIds,\n} from '@contracts/near/types'\nimport type { RSVSignature, UncompressedPubKeySEC1, NajPublicKey } from '@types'\nimport { cryptography } from '@utils'\n\ntype NearContract = Contract & {\n public_key: () => Promise<NajPublicKey>\n experimental_signature_deposit: () => Promise<number>\n derived_public_key: (args: {\n path: string\n predecessor: string\n }) => Promise<NajPublicKey>\n}\n\ninterface ChainSignatureContractArgs {\n networkId: NearNetworkIds\n contractId: ChainSignatureContractIds\n accountId?: string\n keypair?: KeyPair\n rootPublicKey?: NajPublicKey\n sendTransactionOptions?: SendTransactionOptions\n}\n\n/**\n * Implementation of the ChainSignatureContract for NEAR chains.\n *\n * This class provides an interface to interact with the ChainSignatures contract\n * deployed on NEAR. It supports both view methods (which don't require authentication)\n * and change methods (which require a valid NEAR account and keypair).\n *\n * @extends AbstractChainSignatureContract\n */\nexport class ChainSignatureContract extends AbstractChainSignatureContract {\n private readonly networkId: NearNetworkIds\n private readonly contractId: ChainSignatureContractIds\n private readonly accountId: string\n private readonly keypair: KeyPair\n private readonly rootPublicKey?: NajPublicKey\n private readonly sendTransactionOptions?: SendTransactionOptions\n /**\n * Creates a new instance of the ChainSignatureContract for NEAR chains.\n *\n * @param args - Configuration options for the contract\n * @param args.networkId - The NEAR network ID (e.g. 'testnet', 'mainnet')\n * @param args.contractId - The contract ID of the deployed ChainSignatures contract\n * @param args.accountId - Optional NEAR account ID for signing transactions. Required for change methods.\n * @param args.keypair - Optional NEAR KeyPair for signing transactions. Required for change methods.\n * @param args.rootPublicKey - Optional root public key for the contract. If not provided, it will be derived from the contract ID.\n * @param args.sendTransactionOptions - Optional configuration for transaction sending behavior.\n */\n constructor({\n networkId,\n contractId,\n accountId = DONT_CARE_ACCOUNT_ID,\n keypair = KeyPair.fromRandom('ed25519'),\n rootPublicKey,\n sendTransactionOptions,\n }: ChainSignatureContractArgs) {\n super()\n\n this.networkId = networkId\n this.contractId = contractId\n this.accountId = accountId\n this.keypair = keypair\n this.sendTransactionOptions = sendTransactionOptions\n\n this.rootPublicKey =\n rootPublicKey || getRootPublicKey(this.contractId, CHAINS.NEAR)\n }\n\n private async getContract(): Promise<NearContract> {\n const account = await getNearAccount({\n networkId: this.networkId,\n accountId: this.accountId,\n keypair: this.keypair,\n })\n\n return new Contract(account, this.contractId, {\n viewMethods: [\n 'public_key',\n 'experimental_signature_deposit',\n 'derived_public_key',\n ],\n // Change methods use the sendTransactionUntil because the internal retry of the Contract class\n // throws on NodeJs.\n changeMethods: [],\n useLocalViewExecution: false,\n }) as unknown as NearContract\n }\n\n async getCurrentSignatureDeposit(): Promise<BN> {\n const contract = await this.getContract()\n return new BN(\n (await contract.experimental_signature_deposit()).toLocaleString(\n 'fullwide',\n {\n useGrouping: false,\n }\n )\n )\n }\n\n async getDerivedPublicKey(args: {\n path: string\n predecessor: string\n }): Promise<UncompressedPubKeySEC1> {\n if (this.rootPublicKey) {\n const pubKey = cryptography.deriveChildPublicKey(\n await this.getPublicKey(),\n args.predecessor.toLowerCase(),\n args.path,\n KDF_CHAIN_IDS.NEAR\n )\n return pubKey\n } else {\n // Support for legacy contract\n const contract = await this.getContract()\n const najPubKey = await contract.derived_public_key(args)\n return najToUncompressedPubKeySEC1(najPubKey)\n }\n }\n\n async getPublicKey(): Promise<UncompressedPubKeySEC1> {\n if (this.rootPublicKey) {\n return najToUncompressedPubKeySEC1(this.rootPublicKey)\n } else {\n // Support for legacy contract\n const contract = await this.getContract()\n const najPubKey = await contract.public_key()\n return najToUncompressedPubKeySEC1(najPubKey)\n }\n }\n\n async sign(\n args: SignArgs,\n options?: {\n nonce?: number\n }\n ): Promise<RSVSignature> {\n this.requireAccount()\n\n const deposit = await this.getCurrentSignatureDeposit()\n\n const result = await sendTransactionUntil({\n accountId: this.accountId,\n keypair: this.keypair,\n networkId: this.networkId,\n receiverId: this.contractId,\n actions: [\n actionCreators.functionCall(\n 'sign',\n { request: args },\n BigInt(NEAR_MAX_GAS.toString()),\n BigInt(deposit.toString())\n ),\n ],\n nonce: options?.nonce,\n options: this.sendTransactionOptions,\n })\n\n const signature = responseToMpcSignature({ response: result })\n\n if (!signature) {\n throw new Error('Transaction failed')\n }\n\n return signature\n }\n\n private requireAccount(): void {\n if (this.accountId === DONT_CARE_ACCOUNT_ID) {\n throw new Error(\n 'A valid account ID and keypair are required for change methods. Please instantiate a new contract with valid credentials.'\n )\n }\n }\n}\n","import { InMemoryKeyStore } from '@near-js/keystores'\nimport type { Action as TransactionAction } from '@near-js/transactions'\nimport type { TxExecutionStatus } from '@near-js/types'\nimport type {\n Action as WalletAction,\n FinalExecutionOutcome,\n NetworkId,\n} from '@near-wallet-selector/core'\nimport BN from 'bn.js'\nimport {\n transactions,\n utils as nearUtils,\n connect,\n type KeyPair,\n} from 'near-api-js'\nimport { getTransactionLastResult } from 'near-api-js/lib/providers'\nimport { withRetry } from 'viem'\n\nimport { ChainSignatureContract } from '@contracts/near/ChainSignatureContract'\nimport { NEAR_MAX_GAS } from '@contracts/near/constants'\nimport { type ChainSignatureContractIds } from '@contracts/near/types'\nimport {\n type RSVSignature,\n type KeyDerivationPath,\n type MPCSignature,\n type HashToSign,\n} from '@types'\nimport { cryptography } from '@utils'\n\nexport const mpcPayloadsToChainSigTransaction = async ({\n networkId,\n contractId,\n hashesToSign,\n path,\n}: {\n networkId: NetworkId\n contractId: ChainSignatureContractIds\n hashesToSign: HashToSign[]\n path: KeyDerivationPath\n}): Promise<{\n receiverId: string\n actions: WalletAction[]\n}> => {\n const contract = new ChainSignatureContract({\n networkId,\n contractId,\n })\n\n const currentContractFee = await contract.getCurrentSignatureDeposit()\n\n return {\n receiverId: contractId,\n actions: hashesToSign.map((payload) => ({\n type: 'FunctionCall',\n params: {\n methodName: 'sign',\n args: {\n request: {\n payload: Array.from(payload),\n path,\n key_version: 0,\n },\n },\n gas: NEAR_MAX_GAS.div(new BN(hashesToSign.length)).toString(),\n deposit: currentContractFee?.toString() || '1',\n },\n })),\n }\n}\n\nexport const responseToMpcSignature = ({\n response,\n}: {\n response: FinalExecutionOutcome\n}): RSVSignature | undefined => {\n const signature = getTransactionLastResult(response) as MPCSignature\n\n if (signature) {\n return cryptography.toRSV(signature)\n } else {\n return undefined\n }\n}\n\nexport interface SendTransactionOptions {\n until: TxExecutionStatus\n retryCount: number\n delay: number\n nodeUrl: string\n}\n\nexport const sendTransactionUntil = async ({\n accountId,\n keypair,\n networkId,\n receiverId,\n actions,\n nonce,\n options = {\n until: 'EXECUTED_OPTIMISTIC',\n retryCount: 3,\n delay: 5000, // Near RPC timeout\n nodeUrl:\n networkId === 'testnet'\n ? 'https://test.rpc.fastnear.com'\n : 'https://free.rpc.fastnear.com',\n },\n}: {\n accountId: string\n keypair: KeyPair\n networkId: NetworkId\n receiverId: string\n actions: TransactionAction[]\n nonce?: number\n options?: SendTransactionOptions\n}): Promise<FinalExecutionOutcome> => {\n const keyStore = new InMemoryKeyStore()\n await keyStore.setKey(networkId, accountId, keypair)\n\n const near = await connect({\n networkId,\n keyStore,\n nodeUrl: options.nodeUrl,\n })\n\n const { signer } = near.connection\n const publicKey = await signer.getPublicKey(\n accountId,\n near.connection.networkId\n )\n\n const accessKey = (await near.connection.provider.query(\n `access_key/${accountId}/${publicKey.toString()}`,\n ''\n )) as unknown as {\n block_hash: string\n block_height: number\n nonce: number\n permission: string\n }\n\n const recentBlockHash = nearUtils.serialize.base_decode(accessKey.block_hash)\n\n const tx = transactions.createTransaction(\n accountId,\n publicKey,\n receiverId,\n nonce ?? ++accessKey.nonce,\n actions,\n recentBlockHash\n )\n\n const serializedTx = nearUtils.serialize.serialize(\n transactions.SCHEMA.Transaction,\n tx\n )\n\n const nearTransactionSignature = await signer.signMessage(\n serializedTx,\n accountId,\n near.connection.networkId\n )\n\n const signedTransaction = new transactions.SignedTransaction({\n transaction: tx,\n signature: new transactions.Signature({\n keyType: tx.publicKey.keyType,\n data: nearTransactionSignature.signature,\n }),\n })\n\n const { transaction } = await near.connection.provider.sendTransactionUntil(\n signedTransaction,\n 'INCLUDED_FINAL'\n )\n\n const txHash = transaction.hash as string | undefined\n\n if (!txHash) {\n throw new Error('No transaction hash found')\n }\n\n return await withRetry(\n async () => {\n const txOutcome = await near.connection.provider.txStatus(\n txHash,\n accountId,\n options.until\n )\n\n if (txOutcome) {\n return txOutcome\n }\n\n throw new Error('Transaction not found')\n },\n {\n retryCount: options.retryCount,\n delay: options.delay,\n }\n )\n}\n","import * as ChainSignaturesContractABI from './ChainSignaturesContractABI'\nimport * as errors from './errors'\nexport * from './ChainSignaturesContract'\n\nconst utils = {\n ChainSignaturesContractABI,\n errors,\n}\n\nexport { utils }\n","export const abi = [\n {\n inputs: [\n { internalType: 'address', name: '_mpc_network', type: 'address' },\n { internalType: 'uint256', name: '_signatureDeposit', type: 'uint256' },\n ],\n stateMutability: 'nonpayable',\n type: 'constructor',\n },\n { inputs: [], name: 'AccessControlBadConfirmation', type: 'error' },\n {\n inputs: [\n { internalType: 'address', name: 'account', type: 'address' },\n { internalType: 'bytes32', name: 'neededRole', type: 'bytes32' },\n ],\n name: 'AccessControlUnauthorizedAccount',\n type: 'error',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: 'bytes32', name: 'role', type: 'bytes32' },\n {\n indexed: true,\n internalType: 'bytes32',\n name: 'previousAdminRole',\n type: 'bytes32',\n },\n {\n indexed: true,\n internalType: 'bytes32',\n name: 'newAdminRole',\n type: 'bytes32',\n },\n ],\n name: 'RoleAdminChanged',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: 'bytes32', name: 'role', type: 'bytes32' },\n {\n indexed: true,\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n ],\n name: 'RoleGranted',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: 'bytes32', name: 'role', type: 'bytes32' },\n {\n indexed: true,\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n ],\n name: 'RoleRevoked',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'bytes32',\n name: 'requestId',\n type: 'bytes32',\n },\n {\n indexed: false,\n internalType: 'address',\n name: 'responder',\n type: 'address',\n },\n { indexed: false, internalType: 'string', name: 'error', type: 'string' },\n ],\n name: 'SignatureError',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'bytes32',\n name: 'payload',\n type: 'bytes32',\n },\n {\n indexed: false,\n internalType: 'uint32',\n name: 'keyVersion',\n type: 'uint32',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'deposit',\n type: 'uint256',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'chainId',\n type: 'uint256',\n },\n { indexed: false, internalType: 'string', name: 'path', type: 'string' },\n { indexed: false, internalType: 'string', name: 'algo', type: 'string' },\n { indexed: false, internalType: 'string', name: 'dest', type: 'string' },\n {\n indexed: false,\n internalType: 'string',\n name: 'params',\n type: 'string',\n },\n ],\n name: 'SignatureRequested',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'bytes32',\n name: 'requestId',\n type: 'bytes32',\n },\n {\n indexed: false,\n internalType: 'address',\n name: 'responder',\n type: 'address',\n },\n {\n components: [\n {\n components: [\n { internalType: 'uint256', name: 'x', type: 'uint256' },\n { internalType: 'uint256', name: 'y', type: 'uint256' },\n ],\n internalType: 'struct ChainSignatures.AffinePoint',\n name: 'bigR',\n type: 'tuple',\n },\n { internalType: 'uint256', name: 's', type: 'uint256' },\n { internalType: 'uint8', name: 'recoveryId', type: 'uint8' },\n ],\n indexed: false,\n internalType: 'struct ChainSignatures.Signature',\n name: 'signature',\n type: 'tuple',\n },\n ],\n name: 'SignatureResponded',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'owner',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'Withdraw',\n type: 'event',\n },\n {\n inputs: [],\n name: 'DEFAULT_ADMIN_ROLE',\n outputs: [{ internalType: 'bytes32', name: '', type: 'bytes32' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ internalType: 'bytes32', name: 'role', type: 'bytes32' }],\n name: 'getRoleAdmin',\n outputs: [{ internalType: 'bytes32', name: '', type: 'bytes32' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'getSignatureDeposit',\n outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'bytes32', name: 'role', type: 'bytes32' },\n { internalType: 'address', name: 'account', type: 'address' },\n ],\n name: 'grantRole',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'bytes32', name: 'role', type: 'bytes32' },\n { internalType: 'address', name: 'account', type: 'address' },\n ],\n name: 'hasRole',\n outputs: [{ internalType: 'bool', name: '', type: 'bool' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'bytes32', name: 'role', type: 'bytes32' },\n { internalType: 'address', name: 'callerConfirmation', type: 'address' },\n ],\n name: 'renounceRole',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n components: [\n { internalType: 'bytes32', name: 'requestId', type: 'bytes32' },\n {\n components: [\n {\n components: [\n { internalType: 'uint256', name: 'x', type: 'uint256' },\n { internalType: 'uint256', name: 'y', type: 'uint256' },\n ],\n internalType: 'struct ChainSignatures.AffinePoint',\n name: 'bigR',\n type: 'tuple',\n },\n { internalType: 'uint256', name: 's', type: 'uint256' },\n { internalType: 'uint8', name: 'recoveryId', type: 'uint8' },\n ],\n internalType: 'struct ChainSignatures.Signature',\n name: 'signature',\n type: 'tuple',\n },\n ],\n internalType: 'struct ChainSignatures.Response[]',\n name: '_responses',\n type: 'tuple[]',\n },\n ],\n name: 'respond',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n components: [\n { internalType: 'bytes32', name: 'requestId', type: 'bytes32' },\n { internalType: 'string', name: 'errorMessage', type: 'string' },\n ],\n internalType: 'struct ChainSignatures.ErrorResponse[]',\n name: '_errors',\n type: 'tuple[]',\n },\n ],\n name: 'respondError',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'bytes32', name: 'role', type: 'bytes32' },\n { internalType: 'address', name: 'account', type: 'address' },\n ],\n name: 'revokeRole',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [{ internalType: 'uint256', name: '_amount', type: 'uint256' }],\n name: 'setSignatureDeposit',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n components: [\n { internalType: 'bytes32', name: 'payload', type: 'bytes32' },\n { internalType: 'string', name: 'path', type: 'string' },\n { internalType: 'uint32', name: 'keyVersion', type: 'uint32' },\n { internalType: 'string', name: 'algo', type: 'string' },\n { internalType: 'string', name: 'dest', type: 'string' },\n { internalType: 'string', name: 'params', type: 'string' },\n ],\n internalType: 'struct ChainSignatures.SignRequest',\n name: '_request',\n type: 'tuple',\n },\n ],\n name: 'sign',\n outputs: [],\n stateMutability: 'payable',\n type: 'function',\n },\n {\n inputs: [{ internalType: 'bytes4', name: 'interfaceId', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ internalType: 'bool', name: '', type: 'bool' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'uint256', name: '_amount', type: 'uint256' },\n { internalType: 'address', name: '_receiver', type: 'address' },\n ],\n name: 'withdraw',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n]\n","import type { TransactionReceipt } from 'viem'\n\nexport class ChainSignatureError extends Error {\n requestId: `0x${string}`\n receipt: TransactionReceipt\n\n constructor(\n message: string,\n requestId: `0x${string}`,\n receipt: TransactionReceipt\n ) {\n super(message)\n this.name = 'ChainSignatureError'\n this.requestId = requestId\n this.receipt = receipt\n }\n}\n\nexport class SignatureNotFoundError extends ChainSignatureError {\n constructor(requestId: `0x${string}`, receipt: TransactionReceipt) {\n super('Signature not found after maximum retries', requestId, receipt)\n this.name = 'SignatureNotFoundError'\n }\n}\n\nexport class SignatureContractError extends ChainSignatureError {\n errorCode: string\n\n constructor(\n errorCode: string,\n requestId: `0x${string}`,\n receipt: TransactionReceipt\n ) {\n super(`Signature error: ${errorCode}`, requestId, receipt)\n this.name = 'SignatureContractError'\n this.errorCode = errorCode\n }\n}\n\nexport class SigningError extends ChainSignatureError {\n originalError?: Error\n\n constructor(\n requestId: `0x${string}`,\n receipt: TransactionReceipt,\n originalError?: Error\n ) {\n super('Error signing request', requestId, receipt)\n this.name = 'SigningError'\n this.originalError = originalError\n }\n}\n","import { encodeAbiParameters, keccak256 } from 'viem'\nimport * as chains from 'viem/chains'\nimport type { Chain } from 'viem/chains'\n\nimport { type RequestIdArgs } from './types'\n\nexport const getChain = (chainId: number): Chain => {\n for (const chain of Object.values(chains)) {\n if (chain.id === chainId) {\n return chain\n }\n }\n throw new Error('Chain not found')\n}\n\nexport const getRequestId = (request: RequestIdArgs): `0x${string}` => {\n const encoded = encodeAbiParameters(\n [\n { type: 'address' },\n { type: 'bytes' },\n { type: 'string' },\n { type: 'uint32' },\n { type: 'uint256' },\n { type: 'string' },\n { type: 'string' },\n { type: 'string' },\n ],\n [\n request.address,\n request.payload,\n request.path,\n Number(request.keyVersion),\n request.chainId,\n request.algo,\n request.dest,\n request.params,\n ]\n )\n\n return keccak256(encoded)\n}\n","import { najToUncompressedPubKeySEC1 } from '@utils/cryptography'\nimport { getRootPublicKey } from '@utils/publicKey'\nimport BN from 'bn.js'\nimport { withRetry, type PublicClient, type WalletClient, type Hex, padHex, concat, recoverAddress, encodeFunctionData } from 'viem'\n\nimport { CHAINS, KDF_CHAIN_IDS } from '@constants'\nimport { ChainSignatureContract as AbstractChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { SignArgs } from '@contracts/ChainSignatureContract'\nimport type {\n NajPublicKey,\n RSVSignature,\n SigNetEvmMpcSignature,\n UncompressedPubKeySEC1,\n} from '@types'\nimport { cryptography } from '@utils'\n\nimport { abi } from './ChainSignaturesContractABI'\nimport {\n SignatureNotFoundError,\n SignatureContractError,\n SigningError,\n} from './errors'\nimport type {\n RetryOptions,\n SignOptions,\n SignRequest,\n SignatureErrorData,\n} from './types'\nimport { getRequestId } from './utils'\nimport { chainAdapters } from '../..'\n\n/**\n * Implementation of the ChainSignatureContract for EVM chains.\n *\n * When signing data, the contract emits a SignatureRequested event with a requestId.\n * This requestId is used to track the signature request and retrieve the signature\n * once it's available. The sign method handles this process automatically by polling\n * for the signature using the requestId.\n */\nexport class ChainSignatureContract extends AbstractChainSignatureContract {\n private readonly publicClient: PublicClient\n private readonly walletClient: WalletClient\n private readonly contractAddress: Hex\n private readonly rootPublicKey: NajPublicKey\n\n /**\n * Creates a new instance of the ChainSignatureContract for EVM chains.\n *\n * @param args - Configuration options for the contract\n * @param args.publicClient - A Viem PublicClient instance for reading from the blockchain\n * @param args.walletClient - A Viem WalletClient instance for sending transactions\n * @param args.contractAddress - The address of the deployed ChainSignatures contract (e.g. `0x857ED3A242B59cC24144814a0DF41C397a3811E6`)\n * @param args.rootPublicKey - Optional root public key. If not provided, it will be derived from the contract address\n */\n constructor(args: {\n publicClient: PublicClient\n walletClient: WalletClient\n contractAddress: Hex\n rootPublicKey?: NajPublicKey\n }) {\n super()\n this.publicClient = args.publicClient\n this.walletClient = args.walletClient\n this.contractAddress = args.contractAddress\n\n const rootPublicKey =\n args.rootPublicKey ||\n getRootPublicKey(this.contractAddress, CHAINS.ETHEREUM)\n\n if (!rootPublicKey) {\n throw new Error(\n `Invalid public key, please provide a valid root public key or contract address`\n )\n }\n\n this.rootPublicKey = rootPublicKey\n }\n\n async getCurrentSignatureDeposit(): Promise<BN> {\n const deposit = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi,\n functionName: 'getSignatureDeposit',\n })) as bigint\n\n return new BN(deposit.toString())\n }\n\n async getDerivedPublicKey(args: {\n path: string\n predecessor: string\n }): Promise<UncompressedPubKeySEC1> {\n const pubKey = cryptography.deriveChildPublicKey(\n await this.getPublicKey(),\n args.predecessor.toLowerCase(),\n args.path,\n KDF_CHAIN_IDS.ETHEREUM\n )\n\n return pubKey\n }\n\n async getPublicKey(): Promise<UncompressedPubKeySEC1> {\n return najToUncompressedPubKeySEC1(this.rootPublicKey)\n }\n\n async getLatestKeyVersion(): Promise<number> {\n const version = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi,\n functionName: 'latestKeyVersion',\n })) as bigint\n\n return Number(version)\n }\n\n /**\n * Sends a sign request transaction and return the transaction hash.\n *\n * @param args - The signature arguments\n * @param options - The signing options\n * @returns The transaction hash\n */\n async createSignatureRequest(\n args: SignArgs,\n options: Pick<SignOptions, 'sign'> = {\n sign: {\n algo: '',\n dest: '',\n params: '',\n },\n }\n ): Promise<{\n txHash: Hex\n requestId: Hex\n }> {\n if (!this.walletClient?.account) {\n throw new Error('Wallet client required for signing operations')\n }\n\n const requestParams = await this.getSignRequestParams(args, options.sign)\n\n const requestId = this.getRequestId(args, options.sign)\n\n const hash = await this.walletClient.sendTransaction({\n account: this.walletClient.account,\n to: requestParams.target,\n data: requestParams.data,\n value: requestParams.value,\n chain: this.walletClient.chain,\n })\n\n return {\n txHash: hash,\n requestId,\n }\n }\n\n /**\n * Sends a transaction to the contract to request a signature, then\n * polls for the signature result. If the signature is not found within the retry\n * parameters, it will throw an error.\n */\n async sign(\n args: SignArgs,\n options: SignOptions = {\n sign: {\n algo: '',\n dest: '',\n params: '',\n },\n retry: {\n delay: 5000,\n retryCount: 12,\n },\n }\n ): Promise<RSVSignature> {\n const { txHash, requestId } = await this.createSignatureRequest(\n args,\n options\n )\n\n const receipt = await this.publicClient.waitForTransactionReceipt({\n hash: txHash,\n })\n\n try {\n const pollResult = await this.pollForRequestId({\n requestId,\n payload: args.payload,\n path: args.path,\n fromBlock: receipt.blockNumber,\n options: options.retry,\n });\n\n if (!pollResult) {\n throw new SignatureNotFoundError(requestId, receipt)\n }\n\n if(pollResult.hasOwnProperty('error')) {\n throw new SignatureContractError((pollResult as SignatureErrorData).error, requestId, receipt)\n }\n\n return pollResult as RSVSignature;\n } catch (error) {\n if (\n error instanceof SignatureNotFoundError ||\n error instanceof SignatureContractError\n ) {\n throw error\n } else {\n throw new SigningError(\n requestId,\n receipt,\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n async pollForRequestId({\n requestId,\n payload,\n path,\n fromBlock,\n options,\n }: {\n requestId: Hex\n payload: number[]\n path: string\n fromBlock: bigint\n options?: RetryOptions\n }): Promise<RSVSignature | SignatureErrorData | undefined> {\n const delay = options?.delay ?? 5000\n const retryCount = options?.retryCount ?? 12\n\n const result = await withRetry(\n async () => {\n const result = await this.getSignatureFromEvents(requestId, fromBlock)\n\n if (result) {\n // Verify the signature using ecrecover\n const signature = concat([\n padHex(`0x${result.r}`, { size: 32 }),\n padHex(`0x${result.s}`, { size: 32 }),\n `0x${result.v.toString(16)}`,\n ])\n const recoveredAddress = await recoverAddress({\n hash: new Uint8Array(payload),\n signature,\n })\n const evm = new chainAdapters.evm.EVM({\n publicClient: this.publicClient,\n contract: this,\n })\n\n const { address: expectedAddress } =\n await evm.deriveAddressAndPublicKey(\n this.walletClient.account?.address as string,\n path\n )\n\n if (\n recoveredAddress.toLowerCase() !== expectedAddress.toLowerCase()\n ) {\n throw new Error('Signature not found yet')\n }\n return result\n } else {\n throw new Error('Signature not found yet')\n }\n },\n {\n delay,\n retryCount,\n shouldRetry: ({ count, error }) => {\n // TODO: Should be enabled only on debug mode\n console.log(`Retrying get signature: ${count}/${retryCount}`)\n return error.message === 'Signature not found yet'\n },\n }\n )\n\n if(result) {\n return result\n }\n\n return this.getErrorFromEvents(requestId, fromBlock)\n }\n\n async getSignRequestParams(\n args: SignArgs,\n options: SignOptions['sign'] = {\n algo: '',\n dest: '',\n params: '',\n }\n ): Promise<{\n target: Hex\n data: Hex\n value: bigint\n }> {\n const request: SignRequest = {\n payload: `0x${Buffer.from(args.payload).toString('hex')}`,\n path: args.path,\n keyVersion: args.key_version,\n algo: options.algo ?? '',\n dest: options.dest ?? '',\n params: options.params ?? '',\n }\n\n return {\n target: this.contractAddress,\n data: encodeFunctionData({\n abi,\n functionName: 'sign',\n args: [\n request,\n ],\n }),\n value: BigInt((await this.getCurrentSignatureDeposit()).toString()),\n }\n }\n\n /**\n * Generates the request ID for a signature request allowing to track the response.\n *\n * @param args - The signature request object containing:\n * @param args.payload - The data payload to be signed as a hex string\n * @param args.path - The derivation path for the key\n * @param args.keyVersion - The version of the key to use\n * @param options - The signature request object containing:\n * @param options.algo - The signing algorithm to use\n * @param options.dest - The destination for the signature\n * @param options.params - Additional parameters for the signing process\n * @returns A hex string representing the unique request ID\n *\n * @example\n * ```typescript\n * const requestId = ChainSignatureContract.getRequestId({\n * payload: payload: `0x${Buffer.from(args.payload).toString('hex')}`,,\n * path: '',\n * keyVersion: 0\n * });\n * console.log(requestId); // 0x...\n * ```\n */\n getRequestId(\n args: SignArgs,\n options: SignOptions['sign'] = {\n algo: '',\n dest: '',\n params: '',\n }\n ): Hex {\n if (!this.walletClient.account) {\n throw new Error('Wallet client account required to compute requestId')\n }\n if (!this.publicClient.chain?.id) {\n throw new Error('Public client chain required to compute requestId')\n }\n return getRequestId({\n payload: `0x${Buffer.from(args.payload).toString('hex')}`,\n path: args.path,\n keyVersion: args.key_version,\n algo: options.algo ?? '',\n dest: options.dest ?? '',\n params: options.params ?? '',\n address: this.walletClient.account.address,\n chainId: BigInt(this.publicClient.chain.id),\n })\n }\n\n async getErrorFromEvents(\n requestId: Hex,\n fromBlock: bigint\n ): Promise<SignatureErrorData | undefined> {\n const errorLogs = await this.publicClient.getContractEvents({\n address: this.contractAddress,\n abi,\n eventName: 'SignatureError',\n args: {\n requestId,\n },\n fromBlock,\n toBlock: 'latest',\n })\n\n if (errorLogs.length > 0) {\n const { args: errorData } = errorLogs[\n errorLogs.length - 1\n ] as unknown as {\n args: SignatureErrorData\n }\n\n return errorData\n }\n\n return undefined\n }\n\n /**\n * Searches for SignatureResponded events that match the given requestId.\n * It works in conjunction with the getRequestId method which generates the unique\n * identifier for a signature request.\n *\n * @param requestId - The identifier for the signature request\n * @param fromBlock - The block number to start searching from\n * @returns The RSV signature if found, undefined otherwise\n */\n async getSignatureFromEvents(\n requestId: Hex,\n fromBlock: bigint\n ): Promise<RSVSignature | undefined> {\n const logs = await this.publicClient.getContractEvents({\n address: this.contractAddress,\n abi,\n eventName: 'SignatureResponded',\n args: {\n requestId,\n },\n fromBlock,\n toBlock: 'latest',\n })\n\n if (logs.length > 0) {\n const { args: signatureData } = logs[logs.length - 1] as unknown as {\n args: {\n signature: SigNetEvmMpcSignature\n }\n }\n\n return cryptography.toRSV(signatureData.signature)\n }\n\n return undefined\n }\n}\n","import * as ChainSignaturesContractIdl from './types/chain_signatures_project.json'\nimport * as errors from './errors'\nexport * from './ChainSignaturesContract'\n\nconst utils = {\n ChainSignaturesContractIdl,\n errors,\n}\n\nexport { utils }\n","{\n \"address\": \"4uvZW8K4g4jBg7dzPNbb9XDxJLFBK7V6iC76uofmYvEU\",\n \"metadata\": {\n \"name\": \"chain_signatures_project\",\n \"version\": \"0.1.0\",\n \"spec\": \"0.1.0\",\n \"description\": \"Created with Anchor\"\n },\n \"instructions\": [\n {\n \"name\": \"initialize\",\n \"discriminator\": [\n 175,\n 175,\n 109,\n 31,\n 13,\n 152,\n 155,\n 237\n ],\n \"accounts\": [\n {\n \"name\": \"program_state\",\n \"writable\": true,\n \"pda\": {\n \"seeds\": [\n {\n \"kind\": \"const\",\n \"value\": [\n 112,\n 114,\n 111,\n 103,\n 114,\n 97,\n 109,\n 45,\n 115,\n 116,\n 97,\n 116,\n 101\n ]\n }\n ]\n }\n },\n {\n \"name\": \"admin\",\n \"writable\": true,\n \"signer\": true\n },\n {\n \"name\": \"system_program\",\n \"address\": \"11111111111111111111111111111111\"\n }\n ],\n \"args\": [\n {\n \"name\": \"signature_deposit\",\n \"type\": \"u64\"\n }\n ]\n },\n {\n \"name\": \"respond\",\n \"discriminator\": [\n 72,\n 65,\n 227,\n 97,\n 42,\n 255,\n 147,\n 12\n ],\n \"accounts\": [\n {\n \"name\": \"responder\",\n \"signer\": true\n }\n ],\n \"args\": [\n {\n \"name\": \"request_ids\",\n \"type\": {\n \"vec\": {\n \"array\": [\n \"u8\",\n 32\n ]\n }\n }\n },\n {\n \"name\": \"signatures\",\n \"type\": {\n \"vec\": {\n \"defined\": {\n \"name\": \"Signature\"\n }\n }\n }\n }\n ]\n },\n {\n \"name\": \"respond_error\",\n \"discriminator\": [\n 3,\n 170,\n 41,\n 132,\n 72,\n 184,\n 252,\n 69\n ],\n \"accounts\": [\n {\n \"name\": \"responder\",\n \"signer\": true\n }\n ],\n \"args\": [\n {\n \"name\": \"request_ids\",\n \"type\": {\n \"vec\": {\n \"array\": [\n \"u8\",\n 32\n ]\n }\n }\n },\n {\n \"name\": \"errors\",\n \"type\": {\n \"vec\": \"string\"\n }\n }\n ]\n },\n {\n \"name\": \"sign\",\n \"discriminator\": [\n 5,\n 221,\n 155,\n 46,\n 237,\n 91,\n 28,\n 236\n ],\n \"accounts\": [\n {\n \"name\": \"program_state\",\n \"writable\": true,\n \"pda\": {\n \"seeds\": [\n {\n \"kind\": \"const\",\n \"value\": [\n 112,\n 114,\n 111,\n 103,\n 114,\n 97,\n 109,\n 45,\n 115,\n 116,\n 97,\n 116,\n 101\n ]\n }\n ]\n }\n },\n {\n \"name\": \"requester\",\n \"writable\": true,\n \"signer\": true\n },\n {\n \"name\": \"fee_payer\",\n \"writable\": true,\n \"signer\": true,\n \"optional\": true\n },\n {\n \"name\": \"system_program\",\n \"address\": \"11111111111111111111111111111111\"\n }\n ],\n \"args\": [\n {\n \"name\": \"payload\",\n \"type\": {\n \"array\": [\n \"u8\",\n 32\n ]\n }\n },\n {\n \"name\": \"key_version\",\n \"type\": \"u32\"\n },\n {\n \"name\": \"path\",\n \"type\": \"string\"\n },\n {\n \"name\": \"algo\",\n \"type\": \"string\"\n },\n {\n \"name\": \"dest\",\n \"type\": \"string\"\n },\n {\n \"name\": \"params\",\n \"type\": \"string\"\n }\n ]\n },\n {\n \"name\": \"update_deposit\",\n \"discriminator\": [\n 126,\n 116,\n 15,\n 164,\n 238,\n 179,\n 155,\n 59\n ],\n \"accounts\": [\n {\n \"name\": \"program_state\",\n \"writable\": true,\n \"pda\": {\n \"seeds\": [\n {\n \"kind\": \"const\",\n \"value\": [\n 112,\n 114,\n 111,\n 103,\n 114,\n 97,\n 109,\n 45,\n 115,\n 116,\n 97,\n 116,\n 101\n ]\n }\n ]\n }\n },\n {\n \"name\": \"admin\",\n \"writable\": true,\n \"signer\": true,\n \"relations\": [\n \"program_state\"\n ]\n },\n {\n \"name\": \"system_program\",\n \"address\": \"11111111111111111111111111111111\"\n }\n ],\n \"args\": [\n {\n \"name\": \"new_deposit\",\n \"type\": \"u64\"\n }\n ]\n },\n {\n \"name\": \"withdraw_funds\",\n \"discriminator\": [\n 241,\n 36,\n 29,\n 111,\n 208,\n 31,\n 104,\n 217\n ],\n \"accounts\": [\n {\n \"name\": \"program_state\",\n \"writable\": true,\n \"pda\": {\n \"seeds\": [\n {\n \"kind\": \"const\",\n \"value\": [\n 112,\n 114,\n 111,\n 103,\n 114,\n 97,\n 109,\n 45,\n 115,\n 116,\n 97,\n 116,\n 101\n ]\n }\n ]\n }\n },\n {\n \"name\": \"admin\",\n \"writable\": true,\n \"signer\": true,\n \"relations\": [\n \"program_state\"\n ]\n },\n {\n \"name\": \"recipient\",\n \"docs\": [\n \"function by checking it is not the zero address.\"\n ],\n \"writable\": true\n },\n {\n \"name\": \"system_program\",\n \"address\": \"11111111111111111111111111111111\"\n }\n ],\n \"args\": [\n {\n \"name\": \"amount\",\n \"type\": \"u64\"\n }\n ]\n }\n ],\n \"accounts\": [\n {\n \"name\": \"ProgramState\",\n \"discriminator\": [\n 77,\n 209,\n 137,\n 229,\n 149,\n 67,\n 167,\n 230\n ]\n }\n ],\n \"events\": [\n {\n \"name\": \"DepositUpdatedEvent\",\n \"discriminator\": [\n 215,\n 193,\n 53,\n 27,\n 221,\n 101,\n 249,\n 108\n ]\n },\n {\n \"name\": \"FundsWithdrawnEvent\",\n \"discriminator\": [\n 86,\n 232,\n 194,\n 4,\n 211,\n 69,\n 172,\n 202\n ]\n },\n {\n \"name\": \"SignatureErrorEvent\",\n \"discriminator\": [\n 42,\n 28,\n 210,\n 105,\n 9,\n 196,\n 189,\n 51\n ]\n },\n {\n \"name\": \"SignatureRequestedEvent\",\n \"discriminator\": [\n 171,\n 129,\n 105,\n 91,\n 154,\n 49,\n 160,\n 34\n ]\n },\n {\n \"name\": \"SignatureRespondedEvent\",\n \"discriminator\": [\n 118,\n 146,\n 248,\n 151,\n 194,\n 93,\n 18,\n 86\n ]\n }\n ],\n \"errors\": [\n {\n \"code\": 6000,\n \"name\": \"InsufficientDeposit\",\n \"msg\": \"Insufficient deposit amount\"\n },\n {\n \"code\": 6001,\n \"name\": \"InvalidInputLength\",\n \"msg\": \"Arrays must have the same length\"\n },\n {\n \"code\": 6002,\n \"name\": \"Unauthorized\",\n \"msg\": \"Unauthorized access\"\n },\n {\n \"code\": 6003,\n \"name\": \"InsufficientFunds\",\n \"msg\": \"Insufficient funds for withdrawal\"\n },\n {\n \"code\": 6004,\n \"name\": \"InvalidRecipient\",\n \"msg\": \"Invalid recipient address\"\n }\n ],\n \"types\": [\n {\n \"name\": \"AffinePoint\",\n \"type\": {\n \"kind\": \"struct\",\n \"fields\": [\n {\n \"name\": \"x\",\n \"type\": {\n \"array\": [\n \"u8\",\n 32\n ]\n }\n },\n {\n \"name\": \"y\",\n \"type\": {\n \"array\": [\n \"u8\",\n 32\n ]\n }\n }\n ]\n }\n },\n {\n \"name\": \"DepositUpdatedEvent\",\n \"type\": {\n \"kind\": \"struct\",\n \"fields\": [\n {\n \"name\": \"old_deposit\",\n \"type\": \"u64\"\n },\n {\n \"name\": \"new_deposit\",\n \"type\": \"u64\"\n }\n ]\n }\n },\n {\n \"name\": \"FundsWithdrawnEvent\",\n \"type\": {\n \"kind\": \"struct\",\n \"fields\": [\n {\n \"name\": \"amount\",\n \"type\": \"u64\"\n },\n {\n \"name\": \"recipient\",\n \"type\": \"pubkey\"\n }\n ]\n }\n },\n {\n \"name\": \"ProgramState\",\n \"type\": {\n \"kind\": \"struct\",\n \"fields\": [\n {\n \"name\": \"admin\",\n \"type\": \"pubkey\"\n },\n {\n \"name\": \"signature_deposit\",\n \"type\": \"u64\"\n }\n ]\n }\n },\n {\n \"name\": \"Signature\",\n \"type\": {\n \"kind\": \"struct\",\n \"fields\": [\n {\n \"name\": \"big_r\",\n \"type\": {\n \"defined\": {\n \"name\": \"AffinePoint\"\n }\n }\n },\n {\n \"name\": \"s\",\n \"type\": {\n \"array\": [\n \"u8\",\n 32\n ]\n }\n },\n {\n \"name\": \"recovery_id\",\n \"type\": \"u8\"\n }\n ]\n }\n },\n {\n \"name\": \"SignatureErrorEvent\",\n \"type\": {\n \"kind\": \"struct\",\n \"fields\": [\n {\n \"name\": \"request_id\",\n \"type\": {\n \"array\": [\n \"u8\",\n 32\n ]\n }\n },\n {\n \"name\": \"responder\",\n \"type\": \"pubkey\"\n },\n {\n \"name\": \"error\",\n \"type\": \"string\"\n }\n ]\n }\n },\n {\n \"name\": \"SignatureRequestedEvent\",\n \"type\": {\n \"kind\": \"struct\",\n \"fields\": [\n {\n \"name\": \"sender\",\n \"type\": \"pubkey\"\n },\n {\n \"name\": \"payload\",\n \"type\": {\n \"array\": [\n \"u8\",\n 32\n ]\n }\n },\n {\n \"name\": \"key_version\",\n \"type\": \"u32\"\n },\n {\n \"name\": \"deposit\",\n \"type\": \"u64\"\n },\n {\n \"name\": \"chain_id\",\n \"type\": \"u64\"\n },\n {\n \"name\": \"path\",\n \"type\": \"string\"\n },\n {\n \"name\": \"algo\",\n \"type\": \"string\"\n },\n {\n \"name\": \"dest\",\n \"type\": \"string\"\n },\n {\n \"name\": \"params\",\n \"type\": \"string\"\n },\n {\n \"name\": \"fee_payer\",\n \"type\": {\n \"option\": \"pubkey\"\n }\n }\n ]\n }\n },\n {\n \"name\": \"SignatureRespondedEvent\",\n \"type\": {\n \"kind\": \"struct\",\n \"fields\": [\n {\n \"name\": \"request_id\",\n \"type\": {\n \"array\": [\n \"u8\",\n 32\n ]\n }\n },\n {\n \"name\": \"responder\",\n \"type\": \"pubkey\"\n },\n {\n \"name\": \"signature\",\n \"type\": {\n \"defined\": {\n \"name\": \"Signature\"\n }\n }\n }\n ]\n }\n }\n ]\n}","export class SignatureNotFoundError extends Error {\n public readonly requestId?: string\n public readonly hash?: string\n\n constructor(requestId?: string, metadata?: { hash?: string }) {\n const message = requestId\n ? `Signature not found for request ID: ${requestId}`\n : 'Signature not found'\n\n super(message)\n this.name = 'SignatureNotFoundError'\n this.requestId = requestId\n this.hash = metadata?.hash\n }\n}\n\nexport class SignatureContractError extends Error {\n public readonly requestId?: string\n public readonly hash?: string\n public readonly originalError?: { hash: string }\n\n constructor(\n message: string,\n requestId?: string,\n metadata?: { hash?: string }\n ) {\n super(message)\n this.name = 'SignatureContractError'\n this.requestId = requestId\n this.hash = metadata?.hash\n }\n}\n\nexport class SigningError extends Error {\n public readonly requestId: string\n public readonly hash?: string\n public readonly originalError?: Error\n\n constructor(\n requestId: string,\n metadata?: { hash?: string },\n originalError?: Error\n ) {\n super(`Signing error for request ID: ${requestId}`)\n this.name = 'SigningError'\n this.requestId = requestId\n this.hash = metadata?.hash\n this.originalError = originalError\n }\n}\n\nexport class ResponseError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ResponseError'\n }\n}\n","import { encodeAbiParameters, parseAbiParameters, keccak256 } from 'viem'\n\nexport function generateRequestIdSolana({\n address,\n payload,\n path,\n keyVersion,\n algo,\n dest,\n params,\n}: {\n address: string\n payload: Uint8Array | number[]\n path: string\n keyVersion: number\n algo: string\n dest: string\n params: string\n}): string {\n const payloadHex: `0x${string}` = ('0x' + Buffer.from(payload as any).toString('hex')) as `0x${string}` \n\n const encoded = encodeAbiParameters(\n parseAbiParameters(\n 'string, bytes, string, uint32, uint256, string, string, string'\n ),\n [address, payloadHex, path, keyVersion, 0n, algo, dest, params]\n )\n\n return keccak256(encoded)\n}\n","import { AnchorProvider, Program, Wallet } from '@coral-xyz/anchor'\nimport {\n AccountMeta,\n PublicKey,\n Transaction,\n TransactionInstruction,\n} from '@solana/web3.js'\nimport BN from 'bn.js'\nimport { concat, createPublicClient, http, padHex, recoverAddress } from 'viem'\n\nimport { CHAINS, KDF_CHAIN_IDS } from '@constants'\nimport { ChainSignatureContract as AbstractChainSignatureContract } from '@contracts/ChainSignatureContract'\nimport type { SignArgs } from '@contracts/ChainSignatureContract'\nimport type { NajPublicKey, RSVSignature, UncompressedPubKeySEC1 } from '@types'\nimport { cryptography } from '@utils'\nimport { getRootPublicKey } from '@utils/publicKey'\nimport { najToUncompressedPubKeySEC1 } from '@utils/cryptography'\nimport { ChainSignaturesProject } from './types/chain_signatures_project'\nimport IDL from './types/chain_signatures_project.json'\n\nimport {\n SignatureNotFoundError,\n SignatureContractError,\n SigningError,\n} from './errors'\nimport type {\n RetryOptions,\n SignOptions,\n SignatureErrorData,\n} from '../evm/types'\nimport { generateRequestIdSolana } from './utils'\nimport { chainAdapters } from '../..'\nimport { SignatureErrorEvent, SignatureRespondedEvent } from './types/events'\n\nexport class ChainSignatureContract extends AbstractChainSignatureContract {\n private readonly provider: AnchorProvider\n private readonly program: Program<ChainSignaturesProject>\n private readonly programId: PublicKey\n private readonly rootPublicKey: NajPublicKey\n private readonly requesterAddress: string\n\n /**\n * Creates a new instance of the ChainSignatureContract for Solana chains.\n *\n * @param args - Configuration options for the contract\n * @param args.provider - An Anchor Provider for interacting with Solana\n * @param args.programId - The program ID as a string or PublicKey\n * @param args.rootPublicKey - Optional root public key. If not provided, it will be derived from the program ID\n * @param args.requesterAddress - Provider wallet address is always the fee payer but requester can be overridden\n */\n constructor(args: {\n provider: AnchorProvider\n programId: string | PublicKey\n rootPublicKey?: NajPublicKey\n requesterAddress?: string\n }) {\n super()\n this.provider = args.provider\n this.requesterAddress =\n args.requesterAddress ?? this.provider.wallet.publicKey.toString()\n\n this.programId =\n typeof args.programId === 'string'\n ? new PublicKey(args.programId)\n : args.programId\n\n this.program = new Program<ChainSignaturesProject>(\n { ...IDL, address: this.programId.toString() },\n this.provider\n )\n\n const rootPublicKey =\n args.rootPublicKey ||\n getRootPublicKey(this.programId.toString(), CHAINS.SOLANA)\n\n if (!rootPublicKey) {\n throw new Error(\n `Invalid public key, please provide a valid root public key or program ID`\n )\n }\n\n this.rootPublicKey = rootPublicKey\n }\n\n /**\n * Gets the connection from the provider\n */\n get connection() {\n return this.provider.connection\n }\n\n async getCurrentSignatureDeposit(): Promise<BN> {\n try {\n const programStatePDA = await this.getProgramStatePDA()\n\n const programState =\n await this.program.account.programState.fetch(programStatePDA)\n\n return new BN(programState.signatureDeposit.toString())\n } catch (error) {\n throw new Error(`Failed to get signature deposit: ${error}`)\n }\n }\n\n /**\n * Get the Program State PDA\n */\n async getProgramStatePDA(): Promise<PublicKey> {\n const [pda] = PublicKey.findProgramAddressSync(\n [Buffer.from('program-state')],\n this.programId\n )\n return pda\n }\n\n async getDerivedPublicKey(args: {\n path: string\n predecessor: string\n }): Promise<UncompressedPubKeySEC1> {\n const pubKey = cryptography.deriveChildPublicKey(\n await this.getPublicKey(),\n args.predecessor,\n args.path,\n KDF_CHAIN_IDS.SOLANA\n )\n\n return pubKey\n }\n\n async getPublicKey(): Promise<UncompressedPubKeySEC1> {\n return najToUncompressedPubKeySEC1(this.rootPublicKey)\n }\n\n async getSignRequestInstruction(\n args: SignArgs,\n options?: Pick<SignOptions, 'sign'> & {\n remainingAccounts?: Array<AccountMeta>\n }\n ): Promise<TransactionInstruction> {\n return this.program.methods\n .sign(\n Array.from(args.payload),\n args.key_version,\n args.path,\n options?.sign?.algo || '',\n options?.sign?.dest || '',\n options?.sign?.params || ''\n )\n .accounts({\n requester: this.requesterAddress,\n feePayer: this.provider.wallet.publicKey,\n })\n .remainingAccounts(options?.remainingAccounts ?? [])\n .instruction()\n }\n\n /**\n * Sends a transaction to the program to request a signature, then\n * polls for the signature result. If the signature is not found within the retry\n * parameters, it will throw an error.\n */\n async sign(\n args: SignArgs,\n options?: Partial<SignOptions> & {\n remainingAccounts?: Array<AccountMeta>\n }\n ): Promise<RSVSignature> {\n const algo = options?.sign?.algo ?? ''\n const dest = options?.sign?.dest ?? ''\n const params = options?.sign?.params ?? ''\n const delay = options?.retry?.delay ?? 5000\n const retryCount = options?.retry?.retryCount ?? 12\n\n const requestId = this.getRequestId(args, {\n algo,\n dest,\n params,\n })\n\n const eventPromise = this.listenForSignatureEvents({\n requestId,\n payload: args.payload,\n path: args.path,\n options: {\n delay,\n retryCount,\n },\n });\n\n const instruction = await this.getSignRequestInstruction(args, {\n sign: {\n algo,\n dest,\n params,\n },\n remainingAccounts: options?.remainingAccounts,\n });\n const transaction = new Transaction().add(instruction)\n transaction.feePayer = this.provider.wallet.publicKey\n const hash = await this.provider.sendAndConfirm(transaction)\n\n try {\n const pollResult = await eventPromise\n\n if (!pollResult) {\n throw new SignatureNotFoundError(requestId, { hash })\n }\n\n if ('error' in pollResult) {\n throw new SignatureContractError(pollResult.error, requestId, { hash })\n }\n\n return pollResult as RSVSignature\n } catch (error) {\n if (\n error instanceof SignatureNotFoundError ||\n error instanceof SignatureContractError\n ) {\n throw error\n } else {\n throw new SigningError(\n requestId,\n { hash },\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n /**\n * Listens for signature or error events matching the given requestId.\n * Sets up listeners for both event types and returns a promise that resolves when\n * either a valid signature or an error is received.\n */\n async listenForSignatureEvents({\n requestId,\n payload,\n path,\n options,\n }: {\n requestId: string\n payload: number[]\n path: string\n options?: RetryOptions\n }): Promise<RSVSignature | SignatureErrorData | undefined> {\n const delay = options?.delay ?? 5000\n const retryCount = options?.retryCount ?? 12\n const timeout = delay * retryCount\n\n return new Promise((resolve, reject) => {\n let resolved = false\n let signatureListener: number\n let errorListener: number\n const timeoutId = setTimeout(() => {\n if (!resolved) {\n this.program.removeEventListener(signatureListener)\n this.program.removeEventListener(errorListener)\n reject(new SignatureNotFoundError(requestId))\n }\n }, timeout)\n\n signatureListener = this.program.addEventListener(\n 'signatureRespondedEvent',\n (event: SignatureRespondedEvent) => {\n const eventRequestIdHex =\n '0x' + Buffer.from(event.requestId).toString('hex')\n if (eventRequestIdHex === requestId) {\n const signature = event.signature\n const bigRx = Buffer.from(signature.bigR.x).toString('hex')\n const s = Buffer.from(signature.s).toString('hex')\n const recoveryId = signature.recoveryId\n\n const rsvSignature: RSVSignature = {\n r: bigRx,\n s: s,\n v: recoveryId + 27,\n }\n\n // Verify the signature using ecrecover\n const sig = concat([\n padHex(`0x${rsvSignature.r}`, { size: 32 }),\n padHex(`0x${rsvSignature.s}`, { size: 32 }),\n `0x${rsvSignature.v.toString(16)}`,\n ])\n\n const verifySignature = async () => {\n try {\n const evm = new chainAdapters.evm.EVM({\n publicClient: createPublicClient({\n transport: http('https://dontcare.com'),\n }),\n contract: this,\n })\n\n const { address: expectedAddress } =\n await evm.deriveAddressAndPublicKey(\n this.requesterAddress,\n path\n )\n\n const recoveredAddress = await recoverAddress({\n hash: new Uint8Array(payload),\n signature: sig,\n })\n\n if (\n recoveredAddress.toLowerCase() ===\n expectedAddress.toLowerCase()\n ) {\n resolved = true\n clearTimeout(timeoutId)\n this.program.removeEventListener(signatureListener)\n this.program.removeEventListener(errorListener)\n resolve(rsvSignature)\n } else {\n console.warn('Signature verification failed, ignoring event')\n }\n } catch (e) {\n console.error('Error verifying signature:', e)\n }\n }\n\n verifySignature()\n }\n }\n )\n\n errorListener = this.program.addEventListener(\n 'signatureErrorEvent',\n (event: SignatureErrorEvent) => {\n const eventRequestIdHex =\n '0x' + Buffer.from(event.requestId).toString('hex')\n if (eventRequestIdHex === requestId) {\n resolved = true\n clearTimeout(timeoutId)\n this.program.removeEventListener(signatureListener)\n this.program.removeEventListener(errorListener)\n\n resolve({\n requestId: '0x' + Buffer.from(event.requestId).toString('hex'),\n error: event.error,\n })\n }\n }\n )\n })\n }\n\n /**\n * Generates the request ID for a signature request allowing to track the response.\n */\n getRequestId(\n args: SignArgs,\n options: SignOptions['sign'] = {\n algo: '',\n dest: '',\n params: '',\n }\n ): string {\n return generateRequestIdSolana({\n payload: args.payload,\n path: args.path,\n keyVersion: args.key_version,\n algo: options.algo || '',\n dest: options.dest || '',\n params: options.params || '',\n address: this.requesterAddress,\n })\n }\n}\n"]}
|