signet.js 0.0.12-beta.10 → 0.0.12-beta.11

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.
@@ -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/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/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/constants.ts","../../src/contracts/near/account.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/ChainSignaturesContract.ts","../../src/contracts/evm/utils.ts","../../src/contracts/solana/index.ts","../../src/contracts/solana/types/chain_signatures_project.json","../../src/contracts/solana/errors.ts","../../src/contracts/solana/ChainSignaturesContract.ts","../../src/contracts/solana/utils.ts"],"names":["constants_exports","__export","CHAINS","CONTRACT_ADDRESSES","ENVS","KDF_CHAIN_IDS","ROOT_PUBLIC_KEYS","utils_exports","cryptography_exports","compressPubKey","deriveChildPublicKey","najToUncompressedPubKeySEC1","toRSV","EC","elliptic","signature","uncompressedPubKeySEC1","slicedPubKey","x","y","najPublicKey","decodedKey","base58","rootUncompressedPubKeySEC1","predecessorId","path","chainId","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","ee","_Bitcoin","btcRpcAdapter","satoshis","btc","transactionId","data","tx","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","fixedRemainingAccounts","acc","instruction","Transaction","signers","blockhash","startTime","timeout","status","resolve","TransactionExpiredTimeoutError","afterSignature","lastCheckedSignature","i","SIGNATURE_RESPONDED_DISCRIMINATOR","SIGNATURE_ERROR_DISCRIMINATOR","log","dataMatch","eventData","bigRx","recoveryId","eventRequestIdHex","errorLength"],"mappings":"qgDAAAA,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,EAE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A,CAAAA,CAAW,CACnC,IAAMiE,CAAcJ,CAAAA,CAAAA,CAAU,YAAa,CAAA,EAAE,CACvCxO,CAAAA,CAAAA,CAAQwO,CACX,CAAA,QAAA,CAAS,EAAI,CAAA,EAAA,CAAKI,CAAW,CAAA,CAC7B,QAAS,CAAA,MAAM,CAElB,CAAA,OAAO,CACL,SAAA,CAAWD,CACX,CAAA,KAAA,CAAO3O,CACT,CACF,CACF,CACF,CACF,CAIJ,CAKA,YAAA,CACEwJ,CACAhB,CAAAA,CAAAA,CAA+B,CAC7B,IAAA,CAAM,EACN,CAAA,IAAA,CAAM,EACN,CAAA,MAAA,CAAQ,EACV,CAAA,CACQ,CACR,OAAOkE,EAAwB,CAAA,CAC7B,OAASlD,CAAAA,CAAAA,CAAK,OACd,CAAA,IAAA,CAAMA,CAAK,CAAA,IAAA,CACX,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,CHxfA,IAAMhC,EAAAA,CAAQ,CACZ,0BAAA,CAAAyF,EACA,CAAA,MAAA,CAAA3B,EACF,CAAA","file":"index.browser.js","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]: 'BtGZEs9ZJX3hAQuY5er8iyWrGsrPRZYupEtVSS129XKo',\n [ENVS.TESTNET]: 'JazJogTrTb6cCjPGKCBv19JvfqJqG5sxF5FiUKSZov1',\n [ENVS.MAINNET]: '',\n }\n}\n","export * as cryptography from './cryptography'\n","import { base58 } from '@scure/base'\nimport elliptic 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'\nconst { ec: EC } = elliptic\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 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","// 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 { 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.js'\nimport { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js'\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'\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 BN from 'bn.js'\n\nexport const NEAR_MAX_GAS = new BN('300000000000000')\nexport const DONT_CARE_ACCOUNT_ID = 'dontcare'\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 { 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/index.js'\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 { najToUncompressedPubKeySEC1 } from '@utils/cryptography'\nimport { getRootPublicKey } from '@utils/publicKey'\nimport BN from 'bn.js'\nimport {\n withRetry,\n type PublicClient,\n type WalletClient,\n type Hex,\n padHex,\n concat,\n recoverAddress,\n encodeFunctionData,\n} 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 { chainAdapters } from '../..'\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'\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' | 'transaction'> = {\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 ...options.transaction,\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 ('error' in pollResult) {\n throw new SignatureContractError(pollResult.error, requestId, receipt)\n }\n\n return pollResult\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 await 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: [request],\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 { 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 * 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 { type AnchorProvider, Program, Wallet } from '@coral-xyz/anchor'\nimport {\n type AccountMeta,\n PublicKey,\n type Signer,\n Transaction,\n type TransactionInstruction,\n TransactionExpiredTimeoutError,\n} from '@solana/web3.js'\nimport { najToUncompressedPubKeySEC1 } from '@utils/cryptography'\nimport { getRootPublicKey } from '@utils/publicKey'\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'\n\nimport { chainAdapters } from '../..'\nimport type {\n RetryOptions,\n SignOptions,\n SignatureErrorData,\n} from '../evm/types'\n\nimport {\n SignatureNotFoundError,\n SignatureContractError,\n SigningError,\n} from './errors'\nimport { type ChainSignaturesProject } from './types/chain_signatures_project'\nimport IDL from './types/chain_signatures_project.json'\nimport {\n type SignatureErrorEvent,\n type SignatureRespondedEvent,\n} from './types/events'\nimport { generateRequestIdSolana } from './utils'\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?: AccountMeta[]\n }\n ): Promise<TransactionInstruction> {\n const fixedRemainingAccounts: AccountMeta[] = [\n {\n pubkey: PublicKey.findProgramAddressSync(\n [Buffer.from('__event_authority')],\n this.program.programId\n )[0],\n isWritable: false,\n isSigner: false,\n },\n {\n pubkey: this.program.programId,\n isWritable: false,\n isSigner: false,\n },\n ]\n\n return await 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([\n ...fixedRemainingAccounts,\n ...(options?.remainingAccounts ?? []),\n ])\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?: AccountMeta[]\n remainingSigners?: Signer[]\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 missingSigners = options?.remainingAccounts\n ?.filter((acc) => acc.isSigner)\n ?.some(\n (acc) =>\n !options?.remainingSigners?.some((signer) =>\n signer.publicKey.equals(acc.pubkey)\n )\n )\n\n if (missingSigners) {\n throw new Error(\n 'All accounts marked as signers must have a corresponding signer'\n )\n }\n\n const requestId = this.getRequestId(args, {\n algo,\n dest,\n params,\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.sendAndConfirmWithoutWebSocket(\n transaction,\n options?.remainingSigners\n )\n\n try {\n const pollResult = await this.pollForRequestId({\n requestId,\n payload: args.payload,\n path: args.path,\n afterSignature: hash,\n options: {\n delay,\n retryCount,\n },\n })\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\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 private async sendAndConfirmWithoutWebSocket(\n transaction: Transaction,\n signers?: Array<Signer>\n ): Promise<string> {\n const { blockhash } =\n await this.provider.connection.getLatestBlockhash('confirmed')\n transaction.recentBlockhash = blockhash\n\n transaction = await this.provider.wallet.signTransaction(transaction)\n\n if (signers && signers.length > 0) {\n transaction.partialSign(...signers)\n }\n\n const signature = await this.provider.connection.sendRawTransaction(\n transaction.serialize(),\n {\n skipPreflight: false,\n preflightCommitment: 'processed',\n maxRetries: 3,\n }\n )\n\n const startTime = Date.now()\n const timeout = 30000 // 30 seconds, same as default sendAndConfirm\n\n while (Date.now() - startTime < timeout) {\n const status =\n await this.provider.connection.getSignatureStatus(signature)\n\n if (status.value?.err) {\n throw new Error(\n `Transaction failed: ${JSON.stringify(status.value.err)}`\n )\n }\n\n if (\n status.value?.confirmationStatus === 'confirmed' ||\n status.value?.confirmationStatus === 'finalized'\n ) {\n return signature\n }\n\n await new Promise((resolve) => setTimeout(resolve, 2000))\n }\n\n throw new TransactionExpiredTimeoutError(signature, timeout / 1000)\n }\n\n /**\n * Polls for signature or error events matching the given requestId starting from the solana transaction with signature afterSignature.\n * Returns a signature, error data, or undefined if nothing is found.\n */\n async pollForRequestId({\n requestId,\n payload,\n path,\n afterSignature,\n options,\n }: {\n requestId: string\n payload: number[]\n path: string\n afterSignature: string\n options?: RetryOptions\n }): Promise<RSVSignature | SignatureErrorData | undefined> {\n const delay = options?.delay ?? 5000\n const retryCount = options?.retryCount ?? 12\n\n let lastCheckedSignature = afterSignature\n\n for (let i = 0; i < retryCount; i++) {\n try {\n // Get all transactions since last check\n const signatures = await this.connection.getSignaturesForAddress(\n this.programId,\n {\n until: lastCheckedSignature,\n limit: 50,\n },\n 'confirmed'\n )\n\n if (signatures.length > 0) {\n lastCheckedSignature = signatures[signatures.length - 1].signature\n }\n\n for (const sig of signatures) {\n const tx = await this.connection.getParsedTransaction(sig.signature, {\n commitment: 'confirmed',\n maxSupportedTransactionVersion: 0,\n })\n\n if (tx?.meta?.logMessages) {\n const result = await this.parseLogsForEvents(\n tx.meta.logMessages,\n requestId,\n payload,\n path\n )\n\n if (result) {\n return result\n }\n }\n }\n } catch (error) {\n console.error('Error checking for events:', error)\n }\n\n if (i < retryCount - 1) {\n console.log(`Retrying get signature: ${i + 1}/${retryCount}`)\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n }\n\n return undefined\n }\n\n /**\n * Parses transaction logs for signature or error events.\n */\n private async parseLogsForEvents(\n logs: string[],\n requestId: string,\n payload: number[],\n path: string\n ): Promise<RSVSignature | SignatureErrorData | undefined> {\n const SIGNATURE_RESPONDED_DISCRIMINATOR = Buffer.from([\n 118, 146, 248, 151, 194, 93, 18, 86,\n ])\n const SIGNATURE_ERROR_DISCRIMINATOR = Buffer.from([\n 42, 28, 210, 105, 9, 196, 189, 51,\n ])\n\n for (const log of logs) {\n if (log.includes('Program data:')) {\n const dataMatch = log.match(/Program data: (.+)/)\n if (dataMatch) {\n const eventData = Buffer.from(dataMatch[1], 'base64')\n\n // Check if this is a SignatureRespondedEvent\n if (\n eventData.subarray(0, 8).equals(SIGNATURE_RESPONDED_DISCRIMINATOR)\n ) {\n const eventRequestId = eventData.subarray(8, 40)\n const eventRequestIdHex = '0x' + eventRequestId.toString('hex')\n\n if (eventRequestIdHex === requestId) {\n const bigRx = eventData.subarray(72, 104)\n const s = eventData.subarray(136, 168)\n const recoveryId = eventData[168]\n\n const rsvSignature: RSVSignature = {\n r: bigRx.toString('hex'),\n s: s.toString('hex'),\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 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(this.requesterAddress, path)\n\n const recoveredAddress = await recoverAddress({\n hash: new Uint8Array(payload),\n signature: sig,\n })\n\n if (\n recoveredAddress.toLowerCase() === expectedAddress.toLowerCase()\n ) {\n return rsvSignature\n } else {\n console.warn('Signature verification failed, ignoring event')\n }\n }\n }\n\n // Check if this is a SignatureErrorEvent\n if (eventData.subarray(0, 8).equals(SIGNATURE_ERROR_DISCRIMINATOR)) {\n const eventRequestId = eventData.subarray(8, 40)\n const eventRequestIdHex = '0x' + eventRequestId.toString('hex')\n\n if (eventRequestIdHex === requestId) {\n const errorLength = eventData.readUInt32LE(72)\n const error = eventData\n .subarray(76, 76 + errorLength)\n .toString('utf8')\n\n return {\n requestId: eventRequestIdHex,\n error: error,\n }\n }\n }\n }\n }\n }\n\n return undefined\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","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"]}
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/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/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/constants.ts","../../src/contracts/near/account.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/ChainSignaturesContract.ts","../../src/contracts/evm/utils.ts","../../src/contracts/solana/index.ts","../../src/contracts/solana/types/chain_signatures_project.json","../../src/contracts/solana/errors.ts","../../src/contracts/solana/ChainSignaturesContract.ts","../../src/contracts/solana/utils.ts"],"names":["constants_exports","__export","CHAINS","CONTRACT_ADDRESSES","ENVS","KDF_CHAIN_IDS","ROOT_PUBLIC_KEYS","utils_exports","cryptography_exports","compressPubKey","deriveChildPublicKey","najToUncompressedPubKeySEC1","toRSV","EC","elliptic","signature","uncompressedPubKeySEC1","slicedPubKey","x","y","najPublicKey","decodedKey","base58","rootUncompressedPubKeySEC1","predecessorId","path","chainId","ec","derivationPath","scalarHex","keccak256","jsSha3","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","ee","_Bitcoin","btcRpcAdapter","satoshis","btc","transactionId","data","tx","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","fixedRemainingAccounts","acc","instruction","Transaction","signers","blockhash","startTime","timeout","status","resolve","TransactionExpiredTimeoutError","afterSignature","lastCheckedSignature","i","SIGNATURE_RESPONDED_DISCRIMINATOR","SIGNATURE_ERROR_DISCRIMINATOR","log","dataMatch","eventData","bigRx","recoveryId","eventRequestIdHex","errorLength"],"mappings":"8/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,I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,CAAA,GAAIG,CAAsBhE,GAAAA,CAAAA,CAAW,CACnC,IAAMiE,CAAcJ,CAAAA,CAAAA,CAAU,YAAa,CAAA,EAAE,CACvCxO,CAAAA,CAAAA,CAAQwO,CACX,CAAA,QAAA,CAAS,EAAI,CAAA,EAAA,CAAKI,CAAW,CAAA,CAC7B,QAAS,CAAA,MAAM,CAElB,CAAA,OAAO,CACL,SAAA,CAAWD,CACX,CAAA,KAAA,CAAO3O,CACT,CACF,CACF,CACF,CACF,CAIJ,CAKA,YAAA,CACEwJ,CACAhB,CAAAA,CAAAA,CAA+B,CAC7B,IAAA,CAAM,EACN,CAAA,IAAA,CAAM,EACN,CAAA,MAAA,CAAQ,EACV,CAAA,CACQ,CACR,OAAOkE,EAAwB,CAAA,CAC7B,OAASlD,CAAAA,CAAAA,CAAK,OACd,CAAA,IAAA,CAAMA,CAAK,CAAA,IAAA,CACX,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,CHxfA,IAAMhC,EAAAA,CAAQ,CACZ,0BAAA,CAAAyF,EACA,CAAA,MAAA,CAAA3B,EACF,CAAA","file":"index.browser.js","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]: 'BtGZEs9ZJX3hAQuY5er8iyWrGsrPRZYupEtVSS129XKo',\n [ENVS.TESTNET]: 'JazJogTrTb6cCjPGKCBv19JvfqJqG5sxF5FiUKSZov1',\n [ENVS.MAINNET]: '',\n }\n}\n","export * as cryptography from './cryptography'\n","import { base58 } from '@scure/base'\nimport elliptic from 'elliptic'\nimport jsSha3 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'\nconst { ec: EC } = elliptic\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 = jsSha3.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 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","// 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 { 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.js'\nimport { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js'\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'\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 BN from 'bn.js'\n\nexport const NEAR_MAX_GAS = new BN('300000000000000')\nexport const DONT_CARE_ACCOUNT_ID = 'dontcare'\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 { 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/index.js'\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 { najToUncompressedPubKeySEC1 } from '@utils/cryptography'\nimport { getRootPublicKey } from '@utils/publicKey'\nimport BN from 'bn.js'\nimport {\n withRetry,\n type PublicClient,\n type WalletClient,\n type Hex,\n padHex,\n concat,\n recoverAddress,\n encodeFunctionData,\n} 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 { chainAdapters } from '../..'\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'\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' | 'transaction'> = {\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 ...options.transaction,\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 ('error' in pollResult) {\n throw new SignatureContractError(pollResult.error, requestId, receipt)\n }\n\n return pollResult\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 await 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: [request],\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 { 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 * 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 { type AnchorProvider, Program, Wallet } from '@coral-xyz/anchor'\nimport {\n type AccountMeta,\n PublicKey,\n type Signer,\n Transaction,\n type TransactionInstruction,\n TransactionExpiredTimeoutError,\n} from '@solana/web3.js'\nimport { najToUncompressedPubKeySEC1 } from '@utils/cryptography'\nimport { getRootPublicKey } from '@utils/publicKey'\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'\n\nimport { chainAdapters } from '../..'\nimport type {\n RetryOptions,\n SignOptions,\n SignatureErrorData,\n} from '../evm/types'\n\nimport {\n SignatureNotFoundError,\n SignatureContractError,\n SigningError,\n} from './errors'\nimport { type ChainSignaturesProject } from './types/chain_signatures_project'\nimport IDL from './types/chain_signatures_project.json'\nimport {\n type SignatureErrorEvent,\n type SignatureRespondedEvent,\n} from './types/events'\nimport { generateRequestIdSolana } from './utils'\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?: AccountMeta[]\n }\n ): Promise<TransactionInstruction> {\n const fixedRemainingAccounts: AccountMeta[] = [\n {\n pubkey: PublicKey.findProgramAddressSync(\n [Buffer.from('__event_authority')],\n this.program.programId\n )[0],\n isWritable: false,\n isSigner: false,\n },\n {\n pubkey: this.program.programId,\n isWritable: false,\n isSigner: false,\n },\n ]\n\n return await 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([\n ...fixedRemainingAccounts,\n ...(options?.remainingAccounts ?? []),\n ])\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?: AccountMeta[]\n remainingSigners?: Signer[]\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 missingSigners = options?.remainingAccounts\n ?.filter((acc) => acc.isSigner)\n ?.some(\n (acc) =>\n !options?.remainingSigners?.some((signer) =>\n signer.publicKey.equals(acc.pubkey)\n )\n )\n\n if (missingSigners) {\n throw new Error(\n 'All accounts marked as signers must have a corresponding signer'\n )\n }\n\n const requestId = this.getRequestId(args, {\n algo,\n dest,\n params,\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.sendAndConfirmWithoutWebSocket(\n transaction,\n options?.remainingSigners\n )\n\n try {\n const pollResult = await this.pollForRequestId({\n requestId,\n payload: args.payload,\n path: args.path,\n afterSignature: hash,\n options: {\n delay,\n retryCount,\n },\n })\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\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 private async sendAndConfirmWithoutWebSocket(\n transaction: Transaction,\n signers?: Array<Signer>\n ): Promise<string> {\n const { blockhash } =\n await this.provider.connection.getLatestBlockhash('confirmed')\n transaction.recentBlockhash = blockhash\n\n transaction = await this.provider.wallet.signTransaction(transaction)\n\n if (signers && signers.length > 0) {\n transaction.partialSign(...signers)\n }\n\n const signature = await this.provider.connection.sendRawTransaction(\n transaction.serialize(),\n {\n skipPreflight: false,\n preflightCommitment: 'processed',\n maxRetries: 3,\n }\n )\n\n const startTime = Date.now()\n const timeout = 30000 // 30 seconds, same as default sendAndConfirm\n\n while (Date.now() - startTime < timeout) {\n const status =\n await this.provider.connection.getSignatureStatus(signature)\n\n if (status.value?.err) {\n throw new Error(\n `Transaction failed: ${JSON.stringify(status.value.err)}`\n )\n }\n\n if (\n status.value?.confirmationStatus === 'confirmed' ||\n status.value?.confirmationStatus === 'finalized'\n ) {\n return signature\n }\n\n await new Promise((resolve) => setTimeout(resolve, 2000))\n }\n\n throw new TransactionExpiredTimeoutError(signature, timeout / 1000)\n }\n\n /**\n * Polls for signature or error events matching the given requestId starting from the solana transaction with signature afterSignature.\n * Returns a signature, error data, or undefined if nothing is found.\n */\n async pollForRequestId({\n requestId,\n payload,\n path,\n afterSignature,\n options,\n }: {\n requestId: string\n payload: number[]\n path: string\n afterSignature: string\n options?: RetryOptions\n }): Promise<RSVSignature | SignatureErrorData | undefined> {\n const delay = options?.delay ?? 5000\n const retryCount = options?.retryCount ?? 12\n\n let lastCheckedSignature = afterSignature\n\n for (let i = 0; i < retryCount; i++) {\n try {\n // Get all transactions since last check\n const signatures = await this.connection.getSignaturesForAddress(\n this.programId,\n {\n until: lastCheckedSignature,\n limit: 50,\n },\n 'confirmed'\n )\n\n if (signatures.length > 0) {\n lastCheckedSignature = signatures[signatures.length - 1].signature\n }\n\n for (const sig of signatures) {\n const tx = await this.connection.getParsedTransaction(sig.signature, {\n commitment: 'confirmed',\n maxSupportedTransactionVersion: 0,\n })\n\n if (tx?.meta?.logMessages) {\n const result = await this.parseLogsForEvents(\n tx.meta.logMessages,\n requestId,\n payload,\n path\n )\n\n if (result) {\n return result\n }\n }\n }\n } catch (error) {\n console.error('Error checking for events:', error)\n }\n\n if (i < retryCount - 1) {\n console.log(`Retrying get signature: ${i + 1}/${retryCount}`)\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n }\n\n return undefined\n }\n\n /**\n * Parses transaction logs for signature or error events.\n */\n private async parseLogsForEvents(\n logs: string[],\n requestId: string,\n payload: number[],\n path: string\n ): Promise<RSVSignature | SignatureErrorData | undefined> {\n const SIGNATURE_RESPONDED_DISCRIMINATOR = Buffer.from([\n 118, 146, 248, 151, 194, 93, 18, 86,\n ])\n const SIGNATURE_ERROR_DISCRIMINATOR = Buffer.from([\n 42, 28, 210, 105, 9, 196, 189, 51,\n ])\n\n for (const log of logs) {\n if (log.includes('Program data:')) {\n const dataMatch = log.match(/Program data: (.+)/)\n if (dataMatch) {\n const eventData = Buffer.from(dataMatch[1], 'base64')\n\n // Check if this is a SignatureRespondedEvent\n if (\n eventData.subarray(0, 8).equals(SIGNATURE_RESPONDED_DISCRIMINATOR)\n ) {\n const eventRequestId = eventData.subarray(8, 40)\n const eventRequestIdHex = '0x' + eventRequestId.toString('hex')\n\n if (eventRequestIdHex === requestId) {\n const bigRx = eventData.subarray(72, 104)\n const s = eventData.subarray(136, 168)\n const recoveryId = eventData[168]\n\n const rsvSignature: RSVSignature = {\n r: bigRx.toString('hex'),\n s: s.toString('hex'),\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 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(this.requesterAddress, path)\n\n const recoveredAddress = await recoverAddress({\n hash: new Uint8Array(payload),\n signature: sig,\n })\n\n if (\n recoveredAddress.toLowerCase() === expectedAddress.toLowerCase()\n ) {\n return rsvSignature\n } else {\n console.warn('Signature verification failed, ignoring event')\n }\n }\n }\n\n // Check if this is a SignatureErrorEvent\n if (eventData.subarray(0, 8).equals(SIGNATURE_ERROR_DISCRIMINATOR)) {\n const eventRequestId = eventData.subarray(8, 40)\n const eventRequestIdHex = '0x' + eventRequestId.toString('hex')\n\n if (eventRequestIdHex === requestId) {\n const errorLength = eventData.readUInt32LE(72)\n const error = eventData\n .subarray(76, 76 + errorLength)\n .toString('utf8')\n\n return {\n requestId: eventRequestIdHex,\n error: error,\n }\n }\n }\n }\n }\n }\n\n return undefined\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","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"]}