@ckb-ccc/core 1.16.0 → 1.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/address.advanced-C5UrS2uk.mjs +2 -0
  3. package/dist/address.advanced-C5UrS2uk.mjs.map +1 -0
  4. package/dist/advanced.d.mts +1 -1
  5. package/dist/advanced.mjs +1 -1
  6. package/dist/{advancedBarrel-4xTrm-An.d.mts → advancedBarrel-66JgvInl.d.mts} +2 -2
  7. package/dist/{advancedBarrel-4xTrm-An.d.mts.map → advancedBarrel-66JgvInl.d.mts.map} +1 -1
  8. package/dist/advancedBarrel.d.mts +1 -1
  9. package/dist/advancedBarrel.mjs +1 -1
  10. package/dist/{barrel-D3tMRxi5.mjs → barrel-yZm3ICzn.mjs} +2 -2
  11. package/dist/{barrel-D3tMRxi5.mjs.map → barrel-yZm3ICzn.mjs.map} +1 -1
  12. package/dist/barrel.d.mts +1 -1
  13. package/dist/barrel.mjs +1 -1
  14. package/dist/index.d.mts +1 -1
  15. package/dist/index.mjs +1 -1
  16. package/dist.commonjs/address.advanced-CQJ24Iei.js +2 -0
  17. package/dist.commonjs/address.advanced-CQJ24Iei.js.map +1 -0
  18. package/dist.commonjs/advanced.d.ts +1 -1
  19. package/dist.commonjs/advanced.js +1 -1
  20. package/dist.commonjs/{advancedBarrel-XD_hMVay.d.ts → advancedBarrel-CiJnF8me.d.ts} +2 -2
  21. package/dist.commonjs/{advancedBarrel-XD_hMVay.d.ts.map → advancedBarrel-CiJnF8me.d.ts.map} +1 -1
  22. package/dist.commonjs/advancedBarrel.d.ts +1 -1
  23. package/dist.commonjs/advancedBarrel.js +1 -1
  24. package/dist.commonjs/{barrel-D6tLiPED.js → barrel-CddEgDBp.js} +2 -2
  25. package/dist.commonjs/{barrel-D6tLiPED.js.map → barrel-CddEgDBp.js.map} +1 -1
  26. package/dist.commonjs/barrel.d.ts +1 -1
  27. package/dist.commonjs/barrel.js +1 -1
  28. package/dist.commonjs/index.d.ts +1 -1
  29. package/dist.commonjs/index.js +1 -1
  30. package/package.json +1 -1
  31. package/src/ckb/epoch.ts +9 -9
  32. package/src/ckb/script.ts +10 -2
  33. package/src/ckb/transaction.ts +45 -31
  34. package/src/molecule/codec.ts +19 -15
  35. package/dist/address.advanced-8N_Hcv6p.mjs +0 -2
  36. package/dist/address.advanced-8N_Hcv6p.mjs.map +0 -1
  37. package/dist.commonjs/address.advanced-CUIioHfv.js +0 -2
  38. package/dist.commonjs/address.advanced-CUIioHfv.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"barrel-D3tMRxi5.mjs","names":[],"sources":["../src/hasher/hasherKeecak256.ts","../src/molecule/barrel.ts","../src/client/cache/cache.ts","../src/client/cache/memory.ts","../src/client/client.ts","../src/jsonRpc/requestor.ts","../src/client/jsonRpc/client.ts","../src/client/clientPublicMainnet.ts","../src/client/clientPublicTestnet.ts","../src/ckb/hash.ts","../src/address/index.ts","../src/keystore/index.ts","../src/signer/btc/psbt.ts","../src/signer/btc/verify.ts","../src/signer/ckb/secp256k1Signing.ts","../src/signer/ckb/verifyJoyId.ts","../src/signer/doge/verify.ts","../src/signer/evm/verify.ts","../src/signer/nostr/verify.ts","../src/signer/signer/index.ts","../src/signer/btc/signerBtc.ts","../src/signer/btc/signerBtcPublicKeyReadonly.ts","../src/signer/ckb/signerCkbPublicKey.ts","../src/signer/ckb/signerCkbPrivateKey.ts","../src/signer/ckb/signerCkbScriptReadonly.ts","../src/signer/ckb/signerMultisigCkbReadonly.ts","../src/signer/ckb/signerMultisigCkbPrivateKey.ts","../src/signer/doge/signerDoge.ts","../src/signer/doge/signerDogeAddressReadonly.ts","../src/signer/doge/signerDogePrivateKey.ts","../src/signer/dummy/dummy.ts","../src/signer/dummy/alwaysError.ts","../src/signer/dummy/openLink.ts","../src/signer/evm/signerEvm.ts","../src/signer/evm/signerEvmAddressReadonly.ts","../src/signer/nostr/signerNostr.ts","../src/signer/nostr/signerNostrPublicKeyReadonly.ts","../src/signer/nostr/signerNostrPrivateKey.ts","../src/barrel.ts"],"sourcesContent":["import { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { BytesLike, bytesFrom } from \"../bytes/index.js\";\nimport { Hex, hexFrom } from \"../hex/index.js\";\nimport { Hasher } from \"./hasher.js\";\n\n/**\n * @public\n */\nexport class HasherKeecak256 implements Hasher {\n private readonly hasher: ReturnType<(typeof keccak_256)[\"create\"]>;\n\n /**\n * Creates an instance of Hasher.\n */\n\n constructor() {\n this.hasher = keccak_256.create();\n }\n\n /**\n * Updates the hash with the given data.\n *\n * @param data - The data to update the hash with.\n * @returns The current Hasher instance for chaining.\n *\n * @example\n * ```typescript\n * const hasher = new Hasher();\n * hasher.update(\"some data\").update(\"more data\");\n * const hash = hasher.digest();\n * ```\n */\n\n update(data: BytesLike): HasherKeecak256 {\n this.hasher.update(bytesFrom(data));\n return this;\n }\n\n /**\n * Finalizes the hash and returns the digest as a hexadecimal string.\n *\n * @returns The hexadecimal string representation of the hash.\n *\n * @example\n * ```typescript\n * const hasher = new Hasher();\n * hasher.update(\"some data\");\n * const hash = hasher.digest(); // Outputs something like \"0x...\"\n * ```\n */\n\n digest(): Hex {\n return hexFrom(this.hasher.digest());\n }\n}\n","export {\n /**\n * @deprecated Use ccc.Entity instead\n */\n Entity,\n /**\n * @deprecated Use ccc.codec instead\n */\n codec,\n} from \"../codec/entity.js\";\nexport * from \"./codec.js\";\nexport * from \"./predefined.js\";\n","import {\n Cell,\n CellLike,\n OutPointLike,\n Transaction,\n TransactionLike,\n} from \"../../ckb/index.js\";\nimport { HexLike } from \"../../hex/index.js\";\nimport { numFrom, NumLike } from \"../../num/index.js\";\nimport { ClientCollectableSearchKeyLike } from \"../clientTypes.advanced.js\";\nimport {\n ClientBlock,\n ClientBlockHeader,\n ClientBlockHeaderLike,\n ClientBlockLike,\n ClientTransactionResponse,\n ClientTransactionResponseLike,\n} from \"../clientTypes.js\";\nimport { DEFAULT_CONFIRMED_BLOCK_TIME } from \"./memory.advanced.js\";\n\n/**\n * @public\n * The ClientCache class is mainly designed for chained transactions.\n * Consumed & Created cells are \"marked\" so they can be correctly handled when composing transactions.\n * It also act as cache for rpc requests to reduce cost, but this is optional.\n */\nexport abstract class ClientCache {\n abstract markUsableNoCache(\n ...cellLikes: (CellLike | CellLike[])[]\n ): Promise<void>;\n async markUsable(...cellLikes: (CellLike | CellLike[])[]): Promise<void> {\n await this.recordCells(...cellLikes);\n return this.markUsableNoCache(...cellLikes);\n }\n abstract markUnusable(\n ...outPointLike: (OutPointLike | OutPointLike[])[]\n ): Promise<void>;\n async markTransactions(\n ...transactionLike: (TransactionLike | TransactionLike[])[]\n ): Promise<void> {\n await Promise.all([\n this.recordTransactionResponses(\n transactionLike.flat().map((transaction) => ({\n transaction: transaction,\n status: \"sent\",\n })),\n ),\n ...transactionLike.flat().map((transactionLike) => {\n const tx = Transaction.from(transactionLike);\n const txHash = tx.hash();\n\n return Promise.all([\n ...tx.inputs.map((i) => this.markUnusable(i.previousOutput)),\n ...tx.outputs.map((o, i) =>\n this.markUsable({\n cellOutput: o,\n outputData: tx.outputsData[i],\n outPoint: {\n txHash,\n index: i,\n },\n }),\n ),\n ]);\n }),\n ]);\n }\n abstract clear(): Promise<void>;\n abstract findCells(\n filter: ClientCollectableSearchKeyLike,\n ): AsyncGenerator<Cell>;\n abstract isUnusable(outPointLike: OutPointLike): Promise<boolean>;\n\n // ======\n // Following methods are for requests caching and optional.\n // ======\n\n /**\n * Record known cells\n * Implement this method to enable cells query caching\n * @param _cells\n */\n async recordCells(..._cells: (CellLike | CellLike[])[]): Promise<void> {}\n /**\n * Get a known cell by out point\n * Implement this method to enable cells query caching\n * @param _outPoint\n */\n async getCell(_outPoint: OutPointLike): Promise<Cell | undefined> {\n return;\n }\n\n /**\n * Record known transaction responses.\n * Implement this method to enable transactions query caching\n * @param _transactions\n */\n async recordTransactionResponses(\n ..._transactions: (\n ClientTransactionResponseLike | ClientTransactionResponseLike[]\n )[]\n ): Promise<void> {}\n /**\n * Get a known transaction response by hash\n * Implement this method to enable transactions query caching\n * @param _txHash\n */\n async getTransactionResponse(\n _txHash: HexLike,\n ): Promise<ClientTransactionResponse | undefined> {\n return;\n }\n /**\n * Record known transactions.\n * @param transactions\n */\n async recordTransactions(\n ...transactions: (TransactionLike | TransactionLike[])[]\n ): Promise<void> {\n return this.recordTransactionResponses(\n transactions.flat().map((transaction) => ({\n transaction,\n status: \"unknown\",\n })),\n );\n }\n /**\n * Get a known transaction by hash\n * @param txHash\n */\n async getTransaction(txHash: HexLike): Promise<Transaction | undefined> {\n return (await this.getTransactionResponse(txHash))?.transaction;\n }\n\n /**\n * Record known block headers.\n * Implement this method to enable block headers query caching\n * @param _headers\n */\n async recordHeaders(\n ..._headers: (ClientBlockHeaderLike | ClientBlockHeaderLike[])[]\n ): Promise<void> {}\n /**\n * Get a known block header by hash\n * Implement this method to enable block headers query caching\n * @param _hash\n */\n async getHeaderByHash(\n _hash: HexLike,\n ): Promise<ClientBlockHeader | undefined> {\n return;\n }\n /**\n * Get a known block header by number\n * Implement this method to enable block headers query caching\n * @param _number\n */\n async getHeaderByNumber(\n _number: NumLike,\n ): Promise<ClientBlockHeader | undefined> {\n return;\n }\n\n /**\n * Record known blocks.\n * Implement this method to enable blocks query caching\n * @param _blocks\n */\n async recordBlocks(\n ..._blocks: (ClientBlockLike | ClientBlockLike[])[]\n ): Promise<void> {}\n /**\n * Get a known block header by hash\n * Implement this method to enable block headers query caching\n * @param _hash\n */\n async getBlockByHash(_hash: HexLike): Promise<ClientBlock | undefined> {\n return;\n }\n /**\n * Get a known block header by number\n * Implement this method to enable block headers query caching\n * @param _number\n */\n async getBlockByNumber(_number: NumLike): Promise<ClientBlock | undefined> {\n return;\n }\n\n /**\n * Checks if a block header is considered confirmed.\n * The default implementation compares the header's timestamp against the current time\n * and a configured confirmation time. Override this method for custom confirmation logic.\n * @param header\n */\n hasHeaderConfirmed(header: ClientBlockHeader): boolean {\n return (\n numFrom(Date.now()) - header.timestamp >= DEFAULT_CONFIRMED_BLOCK_TIME\n );\n }\n}\n","import { Cell, CellLike, OutPoint, OutPointLike } from \"../../ckb/index.js\";\nimport { hexFrom, HexLike } from \"../../hex/index.js\";\nimport { Num, numFrom, NumLike } from \"../../num/index.js\";\nimport { ClientCollectableSearchKeyLike } from \"../clientTypes.advanced.js\";\nimport {\n ClientBlock,\n ClientBlockHeader,\n ClientBlockHeaderLike,\n ClientBlockLike,\n ClientTransactionResponse,\n ClientTransactionResponseLike,\n} from \"../clientTypes.js\";\nimport { ClientCache } from \"./cache.js\";\nimport {\n CellRecord,\n DEFAULT_CONFIRMED_BLOCK_TIME,\n filterCell,\n MapLru,\n} from \"./memory.advanced.js\";\n\nexport class ClientCacheMemory extends ClientCache {\n /**\n * OutPoint => [isLive, Cell | OutPoint]\n */\n private readonly cells: MapLru<string, CellRecord>;\n\n /**\n * TX Hash => Transaction Response\n */\n private readonly knownTransactions: MapLru<string, ClientTransactionResponse>;\n\n /**\n * Block Number => Block Hash\n */\n private readonly knownBlockHashes: MapLru<Num, string>;\n\n /**\n * Block Hash => Block Header / Full Block\n */\n private readonly knownBlocks: MapLru<\n string,\n Pick<ClientBlock, \"header\"> | ClientBlock\n >;\n\n private readonly confirmedBlockTime;\n\n /**\n * @param maxCells - Maximum number of cells to store in the cache. Defaults to 512.\n * @param maxTxs - Maximum number of transactions to store in the cache. Defaults to 256.\n * @param maxBlocks - Maximum number of blocks to store in the cache. Defaults to 128.\n * @param confirmedBlockTimeLike - Time in milliseconds after which a block is considered confirmed.\n * Defaults to DEFAULT_CONFIRMED_BLOCK_TIME (50 blocks * 10s).\n */\n constructor(\n private readonly maxCells = 512,\n private readonly maxTxs = 256,\n private readonly maxBlocks = 128,\n confirmedBlockTimeLike: NumLike = DEFAULT_CONFIRMED_BLOCK_TIME,\n ) {\n super();\n\n this.cells = new MapLru<string, CellRecord>(this.maxCells);\n this.knownTransactions = new MapLru<string, ClientTransactionResponse>(\n this.maxTxs,\n );\n this.knownBlockHashes = new MapLru<Num, string>(this.maxBlocks);\n this.knownBlocks = new MapLru<\n string,\n Pick<ClientBlock, \"header\"> | ClientBlock\n >(this.maxBlocks);\n\n this.confirmedBlockTime = numFrom(confirmedBlockTimeLike);\n }\n\n async markUsableNoCache(\n ...cellLikes: (CellLike | CellLike[])[]\n ): Promise<void> {\n cellLikes.flat().forEach((cellLike) => {\n const cell = Cell.from(cellLike).clone();\n const outPointStr = hexFrom(cell.outPoint.toBytes());\n\n this.cells.set(outPointStr, [true, cell]);\n });\n }\n\n async markUnusable(\n ...outPointLikes: (OutPointLike | OutPointLike[])[]\n ): Promise<void> {\n outPointLikes.flat().forEach((outPointLike) => {\n const outPoint = OutPoint.from(outPointLike);\n const outPointStr = hexFrom(outPoint.toBytes());\n\n const existed = this.cells.get(outPointStr);\n if (existed) {\n existed[0] = false;\n return;\n }\n this.cells.set(outPointStr, [false, { outPoint }]);\n });\n }\n\n async clear(): Promise<void> {\n this.cells.clear();\n this.knownTransactions.clear();\n }\n\n async *findCells(\n keyLike: ClientCollectableSearchKeyLike,\n ): AsyncGenerator<Cell> {\n for (const [key, [isLive, cell]] of this.cells.entries()) {\n if (!isLive) {\n continue;\n }\n if (!filterCell(keyLike, cell)) {\n continue;\n }\n\n this.cells.get(key);\n yield cell.clone();\n }\n }\n\n async isUnusable(outPointLike: OutPointLike): Promise<boolean> {\n const outPoint = OutPoint.from(outPointLike);\n\n return !(this.cells.get(hexFrom(outPoint.toBytes()))?.[0] ?? true);\n }\n\n async recordCells(...cells: (CellLike | CellLike[])[]): Promise<void> {\n cells.flat().map((cellLike) => {\n const cell = Cell.from(cellLike);\n const outPointStr = hexFrom(cell.outPoint.toBytes());\n\n if (this.cells.get(outPointStr)) {\n return;\n }\n this.cells.set(outPointStr, [undefined, cell]);\n });\n }\n async getCell(outPointLike: OutPointLike): Promise<Cell | undefined> {\n const outPoint = OutPoint.from(outPointLike);\n\n const cell = this.cells.get(hexFrom(outPoint.toBytes()))?.[1];\n if (cell && cell.cellOutput && cell.outputData) {\n return Cell.from((cell as Cell).clone());\n }\n }\n\n async recordTransactionResponses(\n ...transactions: (\n ClientTransactionResponseLike | ClientTransactionResponseLike[]\n )[]\n ): Promise<void> {\n transactions.flat().map((txLike) => {\n const tx = ClientTransactionResponse.from(txLike);\n this.knownTransactions.set(tx.transaction.hash(), tx);\n });\n }\n async getTransactionResponse(\n txHashLike: HexLike,\n ): Promise<ClientTransactionResponse | undefined> {\n const txHash = hexFrom(txHashLike);\n return this.knownTransactions.get(txHash)?.clone();\n }\n\n async recordHeaders(\n ...headers: (ClientBlockHeaderLike | ClientBlockHeaderLike[])[]\n ): Promise<void> {\n headers.flat().map((headerLike) => {\n const header = ClientBlockHeader.from(headerLike);\n\n this.knownBlockHashes.set(header.number, header.hash);\n\n const existed = this.knownBlocks.get(header.hash);\n if (existed) {\n return;\n }\n this.knownBlocks.set(header.hash, { header });\n });\n }\n async getHeaderByHash(\n hashLike: HexLike,\n ): Promise<ClientBlockHeader | undefined> {\n const hash = hexFrom(hashLike);\n const block = this.knownBlocks.get(hash);\n if (block) {\n this.knownBlockHashes.get(block.header.number); // For LRU\n }\n return block?.header;\n }\n async getHeaderByNumber(\n numberLike: NumLike,\n ): Promise<ClientBlockHeader | undefined> {\n const number = numFrom(numberLike);\n\n const hash = this.knownBlockHashes.get(number);\n if (!hash) {\n return;\n }\n return this.getHeaderByHash(hash);\n }\n\n async recordBlocks(\n ...blocks: (ClientBlockLike | ClientBlockLike[])[]\n ): Promise<void> {\n blocks.flat().map((blockLike) => {\n const block = ClientBlock.from(blockLike);\n\n this.knownBlockHashes.set(block.header.number, block.header.hash);\n this.knownBlocks.set(block.header.hash, block);\n });\n }\n async getBlockByHash(hashLike: HexLike): Promise<ClientBlock | undefined> {\n const hash = hexFrom(hashLike);\n const block = this.knownBlocks.get(hash);\n if (block) {\n this.knownBlockHashes.get(block.header.number); // For LRU\n if (\"transactions\" in block) {\n return block;\n }\n }\n return;\n }\n async getBlockByNumber(\n numberLike: NumLike,\n ): Promise<ClientBlock | undefined> {\n const number = numFrom(numberLike);\n\n const hash = this.knownBlockHashes.get(number);\n if (!hash) {\n return;\n }\n return this.getBlockByHash(hash);\n }\n\n hasHeaderConfirmed(header: ClientBlockHeader): boolean {\n return numFrom(Date.now()) - header.timestamp >= this.confirmedBlockTime;\n }\n}\n","import {\n Cell,\n CellDep,\n OutPoint,\n OutPointLike,\n ScriptLike,\n Transaction,\n TransactionLike,\n} from \"../ckb/index.js\";\nimport { Zero } from \"../fixedPoint/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../hex/index.js\";\nimport { Num, NumLike, numFrom, numMax, numMin } from \"../num/index.js\";\nimport { reduceAsync, sleep } from \"../utils/index.js\";\nimport { ClientCache } from \"./cache/index.js\";\nimport { ClientCacheMemory } from \"./cache/memory.js\";\nimport {\n ClientCollectableSearchKeyLike,\n DEFAULT_MAX_FEE_RATE,\n DEFAULT_MIN_FEE_RATE,\n} from \"./clientTypes.advanced.js\";\nimport {\n CellDepInfo,\n CellDepInfoLike,\n ClientBlock,\n ClientBlockHeader,\n ClientFindCellsResponse,\n ClientFindTransactionsGroupedResponse,\n ClientFindTransactionsResponse,\n ClientIndexerSearchKey,\n ClientIndexerSearchKeyLike,\n ClientIndexerSearchKeyTransactionLike,\n ClientTransactionResponse,\n ErrorClientMaxFeeRateExceeded,\n ErrorClientWaitTransactionTimeout,\n OutputsValidator,\n ScriptInfo,\n} from \"./clientTypes.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * @public\n */\nexport abstract class Client {\n public cache: ClientCache;\n\n constructor(config?: { cache?: ClientCache }) {\n this.cache = config?.cache ?? new ClientCacheMemory();\n }\n\n abstract get url(): string;\n abstract get addressPrefix(): string;\n\n /**\n * Get the deployment info for a well-known CKB script.\n * Returns the cell deps and type script info needed to use the script.\n *\n * @param script - The KnownScript enum value.\n * @returns Script info including cellDeps and type hash.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n *\n * // Get xUDT script deployment info\n * const xudtInfo = await client.getKnownScript(ccc.KnownScript.XUdt);\n * console.log(`xUDT cellDeps:`, xudtInfo.cellDeps);\n *\n * // Build an xUDT type script\n * const xudtType = await ccc.Script.fromKnownScript(\n * client,\n * ccc.KnownScript.XUdt,\n * \"0xOWNER_LOCK_HASH...\",\n * );\n * ```\n */\n abstract getKnownScript(script: KnownScript): Promise<ScriptInfo>;\n\n abstract getFeeRateStatistics(\n blockRange?: NumLike,\n ): Promise<{ mean: Num; median: Num }>;\n /**\n * Get the recommended transaction fee rate based on recent blocks.\n * Returns the median fee rate, clamped between min and max fee rates.\n *\n * @param blockRange - Number of recent blocks to analyze.\n * @param options - Optional max fee rate cap.\n * @returns The recommended fee rate in Shannons per KB.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const feeRate = await client.getFeeRate();\n * console.log(`Current fee rate: ${feeRate} Shannons/KB`);\n * ```\n */\n async getFeeRate(\n blockRange?: NumLike,\n options?: { maxFeeRate?: NumLike },\n ): Promise<Num> {\n const feeRate = numMax(\n (await this.getFeeRateStatistics(blockRange)).median,\n DEFAULT_MIN_FEE_RATE,\n );\n\n const maxFeeRate = numFrom(options?.maxFeeRate ?? DEFAULT_MAX_FEE_RATE);\n if (maxFeeRate === Zero) {\n return feeRate;\n }\n\n return numMin(feeRate, maxFeeRate);\n }\n\n /**\n * Get the latest block number (tip) of the chain.\n *\n * @returns The current tip block number.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const tipBlockNumber = await client.getTip();\n * console.log(`Current block height: ${tipBlockNumber}`);\n * ```\n */\n abstract getTip(): Promise<Num>;\n\n /**\n * Get the header of the latest block.\n *\n * @param verbosity - Verbosity level (0 for hex, 1 for object).\n * @returns The tip block header.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const header = await client.getTipHeader();\n * console.log(`Block #${header.number}, hash: ${header.hash}`);\n * ```\n */\n abstract getTipHeader(verbosity?: number | null): Promise<ClientBlockHeader>;\n abstract getBlockByNumberNoCache(\n blockNumber: NumLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined>;\n abstract getBlockByHashNoCache(\n blockHash: HexLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined>;\n abstract getHeaderByNumberNoCache(\n blockNumber: NumLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined>;\n abstract getHeaderByHashNoCache(\n blockHash: HexLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined>;\n async getBlockByNumber(\n blockNumber: NumLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined> {\n const block = await this.cache.getBlockByNumber(blockNumber);\n if (block) {\n return block;\n }\n\n const res = await this.getBlockByNumberNoCache(\n blockNumber,\n verbosity,\n withCycles,\n );\n if (res && this.cache.hasHeaderConfirmed(res.header)) {\n await this.cache.recordBlocks(res);\n }\n return res;\n }\n async getBlockByHash(\n blockHash: HexLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined> {\n const block = await this.cache.getBlockByHash(blockHash);\n if (block) {\n return block;\n }\n\n const res = await this.getBlockByHashNoCache(\n blockHash,\n verbosity,\n withCycles,\n );\n if (res && this.cache.hasHeaderConfirmed(res.header)) {\n await this.cache.recordBlocks(res);\n }\n return res;\n }\n async getHeaderByNumber(\n blockNumber: NumLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined> {\n const header = await this.cache.getHeaderByNumber(blockNumber);\n if (header) {\n return header;\n }\n\n const res = await this.getHeaderByNumberNoCache(blockNumber, verbosity);\n if (res && this.cache.hasHeaderConfirmed(res)) {\n await this.cache.recordHeaders(res);\n }\n return res;\n }\n async getHeaderByHash(\n blockHash: HexLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined> {\n const header = await this.cache.getHeaderByHash(blockHash);\n if (header) {\n return header;\n }\n\n const res = await this.getHeaderByHashNoCache(blockHash, verbosity);\n if (res && this.cache.hasHeaderConfirmed(res)) {\n await this.cache.recordHeaders(res);\n }\n return res;\n }\n\n abstract estimateCycles(transaction: TransactionLike): Promise<Num>;\n abstract sendTransactionDry(\n transaction: TransactionLike,\n validator?: OutputsValidator,\n ): Promise<Num>;\n\n abstract sendTransactionNoCache(\n transaction: TransactionLike,\n validator?: OutputsValidator,\n ): Promise<Hex>;\n abstract getTransactionNoCache(\n txHash: HexLike,\n ): Promise<ClientTransactionResponse | undefined>;\n\n /**\n * Get a cell by its out point.\n * The cell will be cached if it is found.\n *\n * @param outPointLike - The out point of the cell to get.\n * @returns The cell if it exists, otherwise undefined.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const cell = await client.getCell({\n * txHash: \"0xTX_HASH...\",\n * index: 0,\n * });\n * if (cell) {\n * console.log(`Capacity: ${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`);\n * console.log(`Lock: ${cell.cellOutput.lock.codeHash}`);\n * console.log(`Data: ${cell.outputData}`);\n * }\n * ```\n */\n async getCell(outPointLike: OutPointLike): Promise<Cell | undefined> {\n const outPoint = OutPoint.from(outPointLike);\n const cached = await this.cache.getCell(outPoint);\n\n if (cached) {\n return cached;\n }\n\n const transaction = await this.getTransaction(outPoint.txHash);\n if (!transaction) {\n return;\n }\n const output = transaction.transaction.getOutput(outPoint.index);\n if (!output) {\n return;\n }\n\n const cell = Cell.from({\n ...output,\n outPoint,\n });\n await this.cache.recordCells(cell);\n return cell;\n }\n\n async getCellWithHeader(\n outPointLike: OutPointLike,\n ): Promise<{ cell: Cell; header?: ClientBlockHeader } | undefined> {\n const outPoint = OutPoint.from(outPointLike);\n\n const res = await this.getTransactionWithHeader(outPoint.txHash);\n if (!res) {\n return;\n }\n const { transaction, header } = res;\n\n const output = transaction.transaction.getOutput(outPoint.index);\n if (!output) {\n return;\n }\n\n const cell = Cell.from({\n ...output,\n outPoint,\n });\n await this.cache.recordCells(cell);\n return { cell, header };\n }\n\n abstract getCellLiveNoCache(\n outPointLike: OutPointLike,\n withData?: boolean | null,\n includeTxPool?: boolean | null,\n ): Promise<Cell | undefined>;\n /**\n * Get a live (unspent) cell by its out point.\n * Unlike getCell(), this verifies the cell is still live on-chain.\n *\n * @param outPointLike - The out point of the cell.\n * @param withData - Whether to include cell data.\n * @param includeTxPool - Whether to include cells in the transaction pool.\n * @returns The live cell, or undefined if spent or not found.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const cell = await client.getCellLive(\n * { txHash: \"0xTX_HASH...\", index: 0 },\n * true, // include data\n * true, // include tx pool\n * );\n * if (cell) {\n * console.log(\"Cell is still live!\");\n * } else {\n * console.log(\"Cell has been spent or does not exist.\");\n * }\n * ```\n */\n async getCellLive(\n outPointLike: OutPointLike,\n withData?: boolean | null,\n includeTxPool?: boolean | null,\n ): Promise<Cell | undefined> {\n const cell = await this.getCellLiveNoCache(\n outPointLike,\n withData,\n includeTxPool,\n );\n if (withData && cell) {\n await this.cache.recordCells(cell);\n }\n return cell;\n }\n\n abstract findCellsPagedNoCache(\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindCellsResponse>;\n /**\n * Find cells with pagination support.\n * Returns one page of results at a time with a cursor for the next page.\n *\n * @param key - The indexer search key.\n * @param order - Sort order (\"asc\" or \"desc\").\n * @param limit - Maximum cells per page.\n * @param after - Cursor from previous page for pagination.\n * @returns A page of cells with a cursor for the next page.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // Get first page of cells\n * const page1 = await client.findCellsPaged({\n * script: lock,\n * scriptType: \"lock\",\n * }, \"asc\", 20);\n * console.log(`Found ${page1.cells.length} cells`);\n *\n * // Get next page\n * if (page1.cells.length === 20) {\n * const page2 = await client.findCellsPaged(\n * { script: lock, scriptType: \"lock\" },\n * \"asc\", 20, page1.lastCursor,\n * );\n * }\n * ```\n */\n async findCellsPaged(\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindCellsResponse> {\n const res = await this.findCellsPagedNoCache(key, order, limit, after);\n await this.cache.recordCells(res.cells);\n return res;\n }\n\n async *findCellsOnChain(\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n let last: string | undefined = undefined;\n\n while (true) {\n const { cells, lastCursor } = await this.findCellsPaged(\n key,\n order,\n limit,\n last,\n );\n for (const cell of cells) {\n yield cell;\n }\n if (cells.length === 0 || cells.length < limit) {\n return;\n }\n last = lastCursor;\n }\n }\n\n /**\n * Find cells by search key designed for collectable cells.\n * The result also includes cached cells, the order param only works for cells fetched from RPC.\n *\n * @param keyLike - The search key.\n * @returns A async generator for yielding cells.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // Find all cells owned by a lock script\n * for await (const cell of client.findCells({\n * script: lock,\n * scriptType: \"lock\",\n * scriptSearchMode: \"exact\",\n * withData: true,\n * })) {\n * console.log(`Cell: ${cell.outPoint.txHash}:${cell.outPoint.index}`);\n * console.log(`Capacity: ${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`);\n * }\n * ```\n */\n async *findCells(\n keyLike: ClientCollectableSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n const key = ClientIndexerSearchKey.from(keyLike);\n const foundedOutPoints = [];\n\n for await (const cell of this.cache.findCells(key)) {\n foundedOutPoints.push(cell.outPoint);\n yield cell;\n }\n\n for await (const cell of this.findCellsOnChain(key, order, limit)) {\n if (\n (await this.cache.isUnusable(cell.outPoint)) ||\n foundedOutPoints.some((founded) => founded.eq(cell.outPoint))\n ) {\n continue;\n }\n\n yield cell;\n }\n }\n\n /**\n * Find cells by lock script, optionally filtered by type script.\n *\n * @param lock - The lock script to search by.\n * @param type - Optional type script filter.\n * @param withData - Whether to include cell data (default: true).\n * @param order - Sort order by block number (\"asc\" or \"desc\").\n * @param limit - Page size for each RPC call (default: 10).\n * @returns An async generator yielding matching cells.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // Find all cells belonging to this address\n * for await (const cell of client.findCellsByLock(lock)) {\n * console.log(`${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`);\n * }\n *\n * // Find only xUDT cells belonging to this address\n * const xudtType = await ccc.Script.fromKnownScript(\n * client, ccc.KnownScript.XUdt, \"0xOWNER_LOCK_HASH...\",\n * );\n * for await (const cell of client.findCellsByLock(lock, xudtType)) {\n * console.log(`UDT cell found`);\n * }\n * ```\n */\n findCellsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n withData = true,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n return this.findCells(\n {\n script: lock,\n scriptType: \"lock\",\n scriptSearchMode: \"exact\",\n filter: {\n script: type,\n },\n withData,\n },\n order,\n limit,\n );\n }\n\n /**\n * Find cells by type script.\n *\n * @param type - The type script to search by.\n * @param withData - Whether to include cell data (default: true).\n * @param order - Sort order by block number.\n * @param limit - Page size for each RPC call (default: 10).\n * @returns An async generator yielding matching cells.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * // Find all xUDT cells of a specific token\n * const xudtType = await ccc.Script.fromKnownScript(\n * client, ccc.KnownScript.XUdt, \"0xOWNER_LOCK_HASH...\",\n * );\n * for await (const cell of client.findCellsByType(xudtType)) {\n * console.log(`Token cell: ${cell.outPoint.txHash}:${cell.outPoint.index}`);\n * }\n * ```\n */\n findCellsByType(\n type: ScriptLike,\n withData = true,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n return this.findCells(\n {\n script: type,\n scriptType: \"type\",\n scriptSearchMode: \"exact\",\n withData,\n },\n order,\n limit,\n );\n }\n\n async findSingletonCellByType(\n type: ScriptLike,\n withData = true,\n ): Promise<Cell | undefined> {\n for await (const cell of this.findCellsByType(\n type,\n withData,\n undefined,\n 1,\n )) {\n return cell;\n }\n }\n\n /**\n * Resolve cell dependency info into concrete CellDep objects.\n * If a CellDepInfo specifies a type script, the actual deployed cell is located on-chain.\n *\n * @param cellDepsInfoLike - One or more CellDepInfo or arrays of CellDepInfo.\n * @returns Resolved CellDep array ready to be added to a transaction.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const xudtInfo = await client.getKnownScript(ccc.KnownScript.XUdt);\n * const cellDeps = await client.getCellDeps(xudtInfo.cellDeps);\n * // cellDeps can be added to a transaction:\n * // tx.cellDeps.push(...cellDeps);\n * ```\n */\n async getCellDeps(\n ...cellDepsInfoLike: (CellDepInfoLike | CellDepInfoLike[])[]\n ): Promise<CellDep[]> {\n return Promise.all(\n cellDepsInfoLike.flat().map(async (infoLike) => {\n const { cellDep, type } = CellDepInfo.from(infoLike);\n if (type === undefined) {\n return cellDep;\n }\n const found = await this.findSingletonCellByType(type);\n if (!found) {\n return cellDep;\n }\n\n return CellDep.from({\n outPoint: found.outPoint,\n depType: cellDep.depType,\n });\n }),\n );\n }\n\n abstract findTransactionsPaged(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction: true;\n },\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindTransactionsGroupedResponse>;\n abstract findTransactionsPaged(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction?: false | null;\n },\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindTransactionsResponse>;\n abstract findTransactionsPaged(\n key: ClientIndexerSearchKeyTransactionLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<\n ClientFindTransactionsResponse | ClientFindTransactionsGroupedResponse\n >;\n\n findTransactions(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction: true;\n },\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n findTransactions(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction?: false | null;\n },\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n findTransactions(\n key: ClientIndexerSearchKeyTransactionLike,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n async *findTransactions(\n key: ClientIndexerSearchKeyTransactionLike,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n let last: string | undefined = undefined;\n\n while (true) {\n const {\n transactions,\n lastCursor,\n }:\n ClientFindTransactionsResponse | ClientFindTransactionsGroupedResponse =\n await this.findTransactionsPaged(key, order, limit, last);\n for (const tx of transactions) {\n yield tx;\n }\n if (transactions.length === 0 || transactions.length < limit) {\n return;\n }\n last = lastCursor;\n }\n }\n\n /**\n * Find transactions related to a lock script, optionally filtered by type script.\n *\n * @param lock - The lock script to search by.\n * @param type - Optional type script filter.\n * @param groupByTransaction - If true, group results by transaction.\n * @param order - Sort order by block number.\n * @param limit - Page size per RPC call.\n * @returns An async generator yielding transaction records.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // List all transactions related to an address (grouped)\n * for await (const txRecord of client.findTransactionsByLock(lock, null, true)) {\n * console.log(`TX: ${txRecord.txHash}, Block: ${txRecord.blockNumber}`);\n * }\n * ```\n */\n findTransactionsByLock(\n lock: ScriptLike,\n type: ScriptLike | undefined | null,\n groupByTransaction: true,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n findTransactionsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n groupByTransaction?: false | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n findTransactionsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n findTransactionsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n return this.findTransactions(\n {\n script: lock,\n scriptType: \"lock\",\n scriptSearchMode: \"exact\",\n filter: {\n script: type,\n },\n groupByTransaction,\n },\n order,\n limit,\n );\n }\n\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction: true,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction?: false | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n return this.findTransactions(\n {\n script: type,\n scriptType: \"type\",\n scriptSearchMode: \"exact\",\n groupByTransaction,\n },\n order,\n limit,\n );\n }\n\n abstract getCellsCapacity(key: ClientIndexerSearchKeyLike): Promise<Num>;\n\n /**\n * Get the total CKB balance of a single lock script.\n * Only counts cells with no type script and no data (pure CKB capacity cells).\n *\n * @param lock - The lock script to query balance for.\n * @returns The total capacity in Shannons as a bigint.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\n * \"ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsq...\",\n * client,\n * );\n * const balance = await client.getBalanceSingle(lock);\n * console.log(`Balance: ${ccc.fixedPointToString(balance)} CKB`);\n * ```\n */\n async getBalanceSingle(lock: ScriptLike): Promise<Num> {\n return this.getCellsCapacity({\n script: lock,\n scriptType: \"lock\",\n scriptSearchMode: \"exact\",\n filter: {\n scriptLenRange: [0, 1],\n outputDataLenRange: [0, 1],\n },\n });\n }\n\n /**\n * Get the total CKB balance across multiple lock scripts.\n * Sums the balance from each lock script.\n *\n * @param locks - An array of lock scripts to query.\n * @returns The combined total capacity in Shannons as a bigint.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const signer = new ccc.SignerCkbPrivateKey(client, \"0x...\");\n * await signer.connect();\n *\n * const locks = await signer.getRecommendedAddressObj()\n * .then(({ script }) => [script]);\n * const totalBalance = await client.getBalance(locks);\n * console.log(`Total: ${ccc.fixedPointToString(totalBalance)} CKB`);\n * ```\n */\n async getBalance(locks: ScriptLike[]): Promise<Num> {\n return reduceAsync(\n locks,\n async (acc, lock) => acc + (await this.getBalanceSingle(lock)),\n Zero,\n );\n }\n\n /**\n * Send a signed transaction to the CKB network.\n * Validates the fee rate against the maximum before sending.\n *\n * @param transaction - The transaction to send.\n * @param validator - Optional outputs validator (\"passthrough\" or \"well_known_scripts_only\").\n * @param options - Optional configuration including maxFeeRate.\n * @returns The transaction hash.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const signer = new ccc.SignerCkbPrivateKey(client, \"0x...\");\n * await signer.connect();\n *\n * const tx = ccc.Transaction.from({\n * outputs: [{ capacity: ccc.fixedPointFrom(100), lock: receiverLock }],\n * });\n * await tx.completeInputsByCapacity(signer);\n * await tx.completeFeeBy(signer);\n *\n * // Usually you call signer.sendTransaction(tx) which signs then sends.\n * // client.sendTransaction expects an already-signed transaction.\n * const txHash = await client.sendTransaction(tx);\n * ```\n */\n async sendTransaction(\n transaction: TransactionLike,\n validator?: OutputsValidator,\n options?: { maxFeeRate?: NumLike },\n ): Promise<Hex> {\n const tx = Transaction.from(transaction);\n\n const maxFeeRate = numFrom(options?.maxFeeRate ?? DEFAULT_MAX_FEE_RATE);\n const feeRate = await tx.getFeeRate(this);\n if (maxFeeRate > Zero && feeRate > maxFeeRate) {\n throw new ErrorClientMaxFeeRateExceeded(maxFeeRate, feeRate);\n }\n\n const txHash = await this.sendTransactionNoCache(tx, validator);\n\n await this.cache.markTransactions(tx);\n return txHash;\n }\n\n /**\n * Get a transaction by its hash, including its status and block info.\n *\n * @param txHashLike - The transaction hash to look up.\n * @returns The transaction response with status, or undefined if not found.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const txResponse = await client.getTransaction(\"0xTX_HASH...\");\n * if (txResponse) {\n * console.log(`Status: ${txResponse.status}`);\n * console.log(`Block: ${txResponse.blockNumber}`);\n * console.log(`Outputs: ${txResponse.transaction.outputs.length}`);\n * }\n * ```\n */\n async getTransaction(\n txHashLike: HexLike,\n ): Promise<ClientTransactionResponse | undefined> {\n const txHash = hexFrom(txHashLike);\n const res = await this.getTransactionNoCache(txHash);\n if (res) {\n await this.cache.recordTransactionResponses(res);\n return res;\n }\n\n return this.cache.getTransactionResponse(txHash);\n }\n\n /**\n * This method gets specified transaction with its block header (if existed).\n * This is mainly for caching because we need the header to test if we can safely trust the cached tx status.\n * @param txHashLike\n */\n async getTransactionWithHeader(\n txHashLike: HexLike,\n ): Promise<\n | { transaction: ClientTransactionResponse; header?: ClientBlockHeader }\n | undefined\n > {\n const txHash = hexFrom(txHashLike);\n const tx = await this.cache.getTransactionResponse(txHash);\n if (tx?.blockHash) {\n const header = await this.getHeaderByHash(tx.blockHash);\n if (header && this.cache.hasHeaderConfirmed(header)) {\n return {\n transaction: tx,\n header,\n };\n }\n }\n\n const res = await this.getTransactionNoCache(txHash);\n if (!res) {\n return;\n }\n\n await this.cache.recordTransactionResponses(res);\n return {\n transaction: res,\n header: res.blockHash\n ? await this.getHeaderByHash(res.blockHash)\n : undefined,\n };\n }\n\n /**\n * Wait for a transaction to be confirmed on-chain.\n * Polls the node until the transaction reaches the specified confirmation depth.\n *\n * @param txHash - The transaction hash to wait for.\n * @param confirmations - Number of block confirmations to wait for (default: 0 = committed).\n * @param timeout - Maximum wait time in milliseconds (default: 60000).\n * @param interval - Polling interval in milliseconds (default: 2000).\n * @returns The transaction response once confirmed, or throws on timeout.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * // Wait for transaction to be committed (0 confirmations)\n * const tx = await client.waitTransaction(\"0xTX_HASH...\");\n * console.log(`Confirmed in block: ${tx?.blockNumber}`);\n *\n * // Wait for 4 confirmations with 2 minute timeout\n * const confirmedTx = await client.waitTransaction(\n * \"0xTX_HASH...\",\n * 4, // confirmations\n * 120000, // timeout: 2 minutes\n * );\n * ```\n */\n async waitTransaction(\n txHash: HexLike,\n confirmations: number = 0,\n timeout: number = 60000,\n interval: number = 2000,\n ): Promise<ClientTransactionResponse | undefined> {\n const startTime = Date.now();\n let tx: ClientTransactionResponse | undefined;\n\n const getTx = async () => {\n const res = await this.getTransaction(txHash);\n if (\n !res ||\n res.blockNumber == null ||\n [\"sent\", \"pending\", \"proposed\"].includes(res.status)\n ) {\n return undefined;\n }\n\n tx = res;\n return res;\n };\n\n while (true) {\n if (!tx) {\n if (await getTx()) {\n continue;\n }\n } else if (confirmations === 0) {\n return tx;\n } else if (\n (await this.getTipHeader()).number - tx.blockNumber! >=\n confirmations\n ) {\n return tx;\n }\n\n if (Date.now() - startTime + interval >= timeout) {\n throw new ErrorClientWaitTransactionTimeout(timeout);\n }\n await sleep(interval);\n }\n }\n}\n","import {\n JsonRpcPayload,\n Transport,\n TransportFallback,\n transportFromUri,\n} from \"./transports/advanced.js\";\n\n/**\n * Applies a transformation function to a value if the transformer is provided.\n *\n * @param value - The value to be transformed.\n * @param transformer - An optional transformation function.\n * @returns The transformed value if a transformer is provided, otherwise the original value.\n *\n * @example\n * ```typescript\n * const result = transform(5, (x) => x * 2); // Outputs 10\n * const resultWithoutTransformer = transform(5); // Outputs 5\n * ```\n */\nfunction transform(value: unknown, transformer?: (i: unknown) => unknown) {\n if (transformer) {\n return transformer(value);\n }\n return value;\n}\n\nexport type RequestorJsonRpcConfig = {\n fallbacks?: string[];\n timeout?: number;\n maxConcurrent?: number;\n transport?: Transport;\n};\n\nexport class RequestorJsonRpc {\n public readonly maxConcurrent?: number;\n private concurrent = 0;\n private readonly pending: (() => void)[] = [];\n\n public readonly transport: Transport;\n\n private id = 0;\n\n /**\n * Creates an instance of ClientJsonRpc.\n *\n * @param url_ - The URL of the JSON-RPC server.\n * @param timeout - The timeout for requests in milliseconds\n */\n constructor(\n private readonly url_: string,\n config?: RequestorJsonRpcConfig,\n private readonly onError?: (err: unknown) => Promise<void> | void,\n ) {\n this.maxConcurrent = config?.maxConcurrent;\n this.transport =\n config?.transport ??\n new TransportFallback(\n Array.from(\n new Set([url_, ...(config?.fallbacks ?? [])]).values(),\n (url) => transportFromUri(url, config),\n ),\n );\n }\n\n /**\n * Returns the URL of the JSON-RPC server.\n *\n * @returns The URL of the JSON-RPC server.\n */\n\n get url(): string {\n return this.url_;\n }\n\n /**\n * request a JSON-RPC method.\n *\n * @param rpcMethod - The JSON-RPC method.\n * @param params - Params for the method.\n * @param inTransformers - An array of input transformers.\n * @param outTransformer - An output transformer function.\n * @returns Method response.\n */\n async request(\n rpcMethod: string,\n params: unknown[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inTransformers?: (((_: any) => unknown) | undefined)[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outTransformer?: (_: any) => unknown,\n ): Promise<unknown> {\n const payload = this.buildPayload(\n rpcMethod,\n inTransformers\n ? await Promise.all(\n params\n .concat(\n Array.from(\n new Array(Math.max(inTransformers.length - params.length, 0)),\n ),\n )\n .map((v, i) => transform(v, inTransformers[i])),\n )\n : params,\n );\n\n try {\n return await transform(\n await this.requestPayload(payload),\n outTransformer,\n );\n } catch (err: unknown) {\n if (!this.onError) {\n throw err;\n }\n await this.onError(err);\n }\n }\n\n async requestPayload(payload: JsonRpcPayload): Promise<unknown> {\n if (\n this.maxConcurrent !== undefined &&\n this.concurrent >= this.maxConcurrent\n ) {\n const pending = new Promise<void>((resolve) =>\n this.pending.push(resolve),\n );\n await pending;\n }\n\n this.concurrent += 1;\n const res = (await this.transport.request(payload)) as {\n id: number;\n error: unknown;\n result: unknown;\n };\n this.concurrent -= 1;\n this.pending.shift()?.();\n\n if (res.id !== payload.id) {\n throw new Error(`Id mismatched, got ${res.id}, expected ${payload.id}`);\n }\n if (res.error != null) {\n throw res.error as unknown;\n }\n return res.result;\n }\n\n /**\n * Builds a JSON-RPC payload for the given method and parameters.\n *\n * @param method - The JSON-RPC method name.\n * @param req - The parameters for the JSON-RPC method.\n * @returns The JSON-RPC payload.\n */\n\n buildPayload(method: string, req: unknown[]): JsonRpcPayload {\n return {\n id: this.id++,\n method,\n params: req,\n jsonrpc: \"2.0\",\n };\n }\n}\n","import {\n Cell,\n OutPoint,\n OutPointLike,\n TransactionLike,\n} from \"../../ckb/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport {\n RequestorJsonRpc,\n RequestorJsonRpcConfig,\n} from \"../../jsonRpc/requestor.js\";\nimport { Num, NumLike, numFrom, numToHex } from \"../../num/index.js\";\nimport { apply } from \"../../utils/index.js\";\nimport { ClientCache } from \"../cache/index.js\";\nimport { Client } from \"../client.js\";\nimport {\n ClientFindCellsResponse,\n ClientIndexerSearchKeyLike,\n ClientTransactionResponse,\n ErrorClientBase,\n ErrorClientBaseLike,\n ErrorClientDuplicatedTransaction,\n ErrorClientRBFRejected,\n ErrorClientResolveUnknown,\n ErrorClientVerification,\n OutputsValidator,\n} from \"../clientTypes.js\";\nimport {\n JsonRpcBlock,\n JsonRpcBlockHeader,\n JsonRpcCellOutput,\n JsonRpcTransformers,\n} from \"./advanced.js\";\n\nconst ERROR_PARSERS: [\n string,\n (error: ErrorClientBaseLike, match: RegExpMatchArray) => ErrorClientBase,\n][] = [\n [\n \"Resolve\\\\(Unknown\\\\(OutPoint\\\\((0x.*)\\\\)\\\\)\\\\)\",\n (error, match) =>\n new ErrorClientResolveUnknown(error, OutPoint.fromBytes(match[1])),\n ],\n [\n \"Verification\\\\(Error { kind: Script, inner: TransactionScriptError { source: (Inputs|Outputs)\\\\[([0-9]*)\\\\].(Lock|Type), cause: ValidationFailure: see error code (-?[0-9])* on page https://nervosnetwork\\\\.github\\\\.io/ckb-script-error-codes/by-(type|data)-hash/(.*)\\\\.html\",\n (error, match) =>\n new ErrorClientVerification(\n error,\n match[3] === \"Lock\"\n ? \"lock\"\n : match[1] === \"Inputs\"\n ? \"inputType\"\n : \"outputType\",\n match[2],\n Number(match[4]),\n match[5] === \"data\" ? \"data\" : \"type\",\n match[6],\n ),\n ],\n [\n \"Duplicated\\\\(Byte32\\\\((0x.*)\\\\)\\\\)\",\n (error, match) => new ErrorClientDuplicatedTransaction(error, match[1]),\n ],\n [\n 'RBFRejected\\\\(\"Tx\\'s current fee is ([0-9]*), expect it to >= ([0-9]*) to replace old txs\"\\\\)',\n (error, match) => new ErrorClientRBFRejected(error, match[1], match[2]),\n ],\n];\n\nexport type ClientJsonRpcConfig = RequestorJsonRpcConfig & {\n cache?: ClientCache;\n requestor?: RequestorJsonRpc;\n};\n\n/**\n * An abstract class implementing JSON-RPC client functionality for a specific URL and timeout.\n * Provides methods for sending transactions and building JSON-RPC payloads.\n */\nexport abstract class ClientJsonRpc extends Client {\n public readonly requestor: RequestorJsonRpc;\n\n /**\n * Creates an instance of ClientJsonRpc.\n *\n * @param url_ - The URL of the JSON-RPC server.\n * @param timeout - The timeout for requests in milliseconds\n */\n\n constructor(url_: string, config?: ClientJsonRpcConfig) {\n super(config);\n\n this.requestor =\n config?.requestor ??\n new RequestorJsonRpc(url_, config, (errAny) => {\n if (\n typeof errAny !== \"object\" ||\n errAny === null ||\n !(\"data\" in errAny) ||\n typeof errAny.data !== \"string\"\n ) {\n throw errAny;\n }\n const err = errAny as ErrorClientBaseLike;\n\n for (const [regexp, builder] of ERROR_PARSERS) {\n const match = err.data.match(regexp);\n if (match) {\n throw builder(err, match);\n }\n }\n\n throw new ErrorClientBase(err);\n });\n }\n\n /**\n * Returns the URL of the JSON-RPC server.\n *\n * @returns The URL of the JSON-RPC server.\n */\n get url(): string {\n return this.requestor.url;\n }\n\n /**\n * Get fee rate statistics\n *\n * @returns Fee rate statistics\n */\n\n getFeeRateStatistics = this.buildSender(\n \"get_fee_rate_statistics\",\n [(n: NumLike) => apply(numFrom, n)],\n ({ mean, median }: { mean: NumLike; median: NumLike }) => ({\n mean: numFrom(mean),\n median: numFrom(median),\n }),\n ) as Client[\"getFeeRateStatistics\"];\n\n /**\n * Get tip block number\n *\n * @returns Tip block number\n */\n\n getTip = this.buildSender(\n \"get_tip_block_number\",\n [],\n numFrom,\n ) as () => Promise<Num>;\n\n /**\n * Get tip block header\n *\n * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)\n * @returns BlockHeader\n */\n getTipHeader = this.buildSender(\n \"get_tip_header\",\n [],\n (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),\n ) as Client[\"getTipHeader\"];\n\n /**\n * Get block by block number\n *\n * @param blockNumber - The block number.\n * @param verbosity - result format which allows 0 and 2. (Optional, the default is 2.)\n * @param withCycles - whether the return cycles of block transactions. (Optional, default false.)\n * @returns Block\n */\n getBlockByNumberNoCache = this.buildSender(\n \"get_block_by_number\",\n [(v: NumLike) => numToHex(numFrom(v))],\n (b: JsonRpcBlock) => apply(JsonRpcTransformers.blockTo, b),\n ) as Client[\"getBlockByNumberNoCache\"];\n\n /**\n * Get block by block hash\n *\n * @param blockHash - The block hash.\n * @param verbosity - result format which allows 0 and 2. (Optional, the default is 2.)\n * @param withCycles - whether the return cycles of block transactions. (Optional, default false.)\n * @returns Block\n */\n getBlockByHashNoCache = this.buildSender(\n \"get_block\",\n [hexFrom],\n (b: JsonRpcBlock) => apply(JsonRpcTransformers.blockTo, b),\n ) as Client[\"getBlockByHashNoCache\"];\n\n /**\n * Get header by block number\n *\n * @param blockNumber - The block number.\n * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)\n * @returns BlockHeader\n */\n getHeaderByNumberNoCache = this.buildSender(\n \"get_header_by_number\",\n [(v: NumLike) => numToHex(numFrom(v))],\n (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),\n ) as Client[\"getHeaderByNumberNoCache\"];\n\n /**\n * Get header by block hash\n *\n * @param blockHash - The block hash.\n * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)\n * @returns BlockHeader\n */\n getHeaderByHashNoCache = this.buildSender(\n \"get_header\",\n [hexFrom],\n (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),\n ) as Client[\"getHeaderByHashNoCache\"];\n\n /**\n * Estimate cycles of a transaction.\n *\n * @param transaction - The transaction to estimate.\n * @returns Consumed cycles\n */\n estimateCycles = this.buildSender(\n \"estimate_cycles\",\n [JsonRpcTransformers.transactionFrom],\n ({ cycles }: { cycles: NumLike }) => numFrom(cycles),\n ) as Client[\"estimateCycles\"];\n\n /**\n * Test a transaction.\n *\n * @param transaction - The transaction to test.\n * @param validator - \"passthrough\": Disable validation. \"well_known_scripts_only\": Only accept well known scripts in the transaction.\n * @returns Consumed cycles\n */\n\n sendTransactionDry = this.buildSender(\n \"test_tx_pool_accept\",\n [JsonRpcTransformers.transactionFrom],\n ({ cycles }: { cycles: NumLike }) => numFrom(cycles),\n ) as Client[\"sendTransactionDry\"];\n\n /**\n * Send a transaction to node.\n *\n * @param transaction - The transaction to send.\n * @param validator - \"passthrough\": Disable validation. \"well_known_scripts_only\": Only accept well known scripts in the transaction.\n * @returns Transaction hash.\n */\n\n sendTransactionNoCache = this.buildSender(\n \"send_transaction\",\n [\n JsonRpcTransformers.transactionFrom,\n (validator?: OutputsValidator | null) => validator ?? undefined,\n ],\n hexFrom,\n ) as (\n transaction: TransactionLike,\n validator?: OutputsValidator | null,\n ) => Promise<Hex>;\n\n /**\n * Get a transaction from node.\n *\n * @param txHash - The hash of the transaction.\n * @returns The transaction with status.\n */\n\n getTransactionNoCache = this.buildSender(\n \"get_transaction\",\n [hexFrom],\n JsonRpcTransformers.transactionResponseTo,\n ) as (txHash: HexLike) => Promise<ClientTransactionResponse | undefined>;\n\n /**\n * Get a live cell from node.\n *\n * @param outPoint - The out point of the cell.\n * @param withData - Include data in the response.\n * @param includeTxPool - Include cells in the tx pool.\n * @returns The cell\n */\n getCellLiveNoCache(\n outPoint: OutPointLike,\n withData?: boolean | null,\n includeTxPool?: boolean | null,\n ) {\n return this.buildSender(\n \"get_live_cell\",\n [JsonRpcTransformers.outPointFrom],\n ({\n cell,\n }: {\n cell?: {\n output: JsonRpcCellOutput;\n data?: { content: HexLike; hash: HexLike };\n };\n }) =>\n apply(\n ({\n output,\n data,\n }: {\n output: JsonRpcCellOutput;\n data?: { content: HexLike; hash: HexLike };\n }) =>\n Cell.from({\n cellOutput: JsonRpcTransformers.cellOutputTo(output),\n outputData: data?.content ?? \"0x\",\n outPoint,\n }),\n cell,\n ),\n )(outPoint, withData ?? true, includeTxPool) as Promise<Cell | undefined>;\n }\n\n /**\n * find cells from node.\n *\n * @param key - The search key of cells.\n * @param order - The order of cells.\n * @param limit - The max return size of cells.\n * @param after - Pagination parameter.\n * @returns The found cells.\n */\n\n findCellsPagedNoCache = this.buildSender(\n \"get_cells\",\n [\n JsonRpcTransformers.indexerSearchKeyFrom,\n (order?: \"asc\" | \"desc\") => order ?? \"asc\",\n (limit?: NumLike) => numToHex(limit ?? 10),\n ],\n JsonRpcTransformers.findCellsResponseTo,\n ) as (\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ) => Promise<ClientFindCellsResponse>;\n\n /**\n * find transactions from node.\n *\n * @param key - The search key of transactions.\n * @param order - The order of transactions.\n * @param limit - The max return size of transactions.\n * @param after - Pagination parameter.\n * @returns The found transactions.\n */\n\n findTransactionsPaged = this.buildSender(\n \"get_transactions\",\n [\n JsonRpcTransformers.indexerSearchKeyTransactionFrom,\n (order?: \"asc\" | \"desc\") => order ?? \"asc\",\n (limit?: NumLike) => numToHex(limit ?? 10),\n ],\n JsonRpcTransformers.findTransactionsResponseTo,\n ) as Client[\"findTransactionsPaged\"];\n\n /**\n * get cells capacity from node.\n *\n * @param key - The search key of cells.\n * @returns The sum of cells capacity.\n */\n\n getCellsCapacity = this.buildSender(\n \"get_cells_capacity\",\n [JsonRpcTransformers.indexerSearchKeyFrom],\n ({ capacity }: { capacity: NumLike }) => numFrom(capacity),\n ) as (key: ClientIndexerSearchKeyLike) => Promise<Num>;\n\n /**\n * Builds a sender function for a JSON-RPC method.\n *\n * @param rpcMethod - The JSON-RPC method.\n * @param inTransformers - An array of input transformers.\n * @param outTransformer - An output transformer function.\n * @returns A function that sends a JSON-RPC request with the given method and transformed parameters.\n */\n\n buildSender(\n rpcMethod: Parameters<RequestorJsonRpc[\"request\"]>[0],\n inTransformers?: Parameters<RequestorJsonRpc[\"request\"]>[2],\n outTransformer?: Parameters<RequestorJsonRpc[\"request\"]>[3],\n ): (...req: unknown[]) => Promise<unknown> {\n return async (...req: unknown[]) => {\n return this.requestor.request(\n rpcMethod,\n req,\n inTransformers,\n outTransformer,\n );\n };\n }\n}\n","import WebSocket from \"isomorphic-ws\";\nimport { MAINNET_SCRIPTS } from \"./clientPublicMainnet.advanced.js\";\nimport { ScriptInfo, ScriptInfoLike } from \"./clientTypes.js\";\nimport { ClientJsonRpc, ClientJsonRpcConfig } from \"./jsonRpc/index.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * @public\n */\nexport class ClientPublicMainnet extends ClientJsonRpc {\n constructor(\n private readonly config?: ClientJsonRpcConfig & {\n url?: string;\n scripts?: Record<KnownScript, ScriptInfoLike | undefined>;\n },\n ) {\n const hasWebSocket = typeof WebSocket !== \"undefined\";\n super(\n config?.url ??\n (hasWebSocket\n ? \"wss://mainnet.ckb.dev/ws\"\n : \"https://mainnet.ckb.dev/\"),\n {\n ...config,\n fallbacks:\n config?.fallbacks ??\n (hasWebSocket\n ? [\n \"wss://mainnet.ckb.dev/ws\",\n \"https://mainnet.ckb.dev/\",\n \"https://mainnet.ckbapp.dev/\",\n ]\n : [\"https://mainnet.ckb.dev/\", \"https://mainnet.ckbapp.dev/\"]),\n },\n );\n }\n\n get scripts(): Record<KnownScript, ScriptInfoLike | undefined> {\n return this.config?.scripts ?? MAINNET_SCRIPTS;\n }\n\n get addressPrefix(): string {\n return \"ckb\";\n }\n\n async getKnownScript(script: KnownScript): Promise<ScriptInfo> {\n const found = this.scripts[script];\n if (!found) {\n throw new Error(\n `No script information was found for ${script} on ${this.addressPrefix}`,\n );\n }\n return ScriptInfo.from(found);\n }\n}\n","import WebSocket from \"isomorphic-ws\";\nimport { TESTNET_SCRIPTS } from \"./clientPublicTestnet.advanced.js\";\nimport { ScriptInfo, ScriptInfoLike } from \"./clientTypes.js\";\nimport { ClientJsonRpc, ClientJsonRpcConfig } from \"./jsonRpc/index.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * @public\n */\nexport class ClientPublicTestnet extends ClientJsonRpc {\n constructor(\n private readonly config?: ClientJsonRpcConfig & {\n url?: string;\n scripts?: Record<KnownScript, ScriptInfoLike | undefined>;\n },\n ) {\n const hasWebSocket = typeof WebSocket !== \"undefined\";\n super(\n config?.url ??\n (hasWebSocket\n ? \"wss://testnet.ckb.dev/ws\"\n : \"https://testnet.ckb.dev/\"),\n {\n ...config,\n fallbacks:\n config?.fallbacks ??\n (hasWebSocket\n ? [\n \"wss://testnet.ckb.dev/ws\",\n \"https://testnet.ckb.dev/\",\n \"https://testnet.ckbapp.dev/\",\n ]\n : [\"https://testnet.ckb.dev/\", \"https://testnet.ckbapp.dev/\"]),\n },\n );\n }\n\n get scripts(): Record<KnownScript, ScriptInfoLike | undefined> {\n return this.config?.scripts ?? TESTNET_SCRIPTS;\n }\n\n get addressPrefix(): string {\n return \"ckt\";\n }\n\n async getKnownScript(script: KnownScript): Promise<ScriptInfo> {\n const found = this.scripts[script];\n if (!found) {\n throw new Error(\n `No script information was found for ${script} on ${this.addressPrefix}`,\n );\n }\n return ScriptInfo.from(found);\n }\n}\n","import { hashCkb } from \"../hasher/hasherCkb.js\";\nimport { Hex } from \"../hex/index.js\";\nimport { NumLike, numLeToBytes } from \"../num/index.js\";\nimport { CellInput, CellInputLike } from \"./transaction.js\";\n\n/**\n * Computes the Type ID hash of the given data.\n * @public\n *\n * @param cellInputLike - The first cell input of the transaction.\n * @param outputIndex - The output index of the Type ID cell.\n * @returns The hexadecimal string representation of the hash.\n *\n * @example\n * ```typescript\n * const hash = hashTypeId(cellInput, outputIndex); // Outputs something like \"0x...\"\n * ```\n */\n\nexport function hashTypeId(\n cellInputLike: CellInputLike,\n outputIndex: NumLike,\n): Hex {\n return hashCkb(\n CellInput.from(cellInputLike).toBytes(),\n numLeToBytes(outputIndex, 8),\n );\n}\n","import { bech32m } from \"bech32\";\nimport { bytesConcat, bytesFrom } from \"../bytes/index.js\";\nimport { Script, ScriptLike, hashTypeToBytes } from \"../ckb/index.js\";\nimport { Client, KnownScript } from \"../client/index.js\";\nimport { HexLike } from \"../hex/index.js\";\nimport {\n ADDRESS_BECH32_LIMIT,\n AddressFormat,\n addressFromPayload,\n addressPayloadFromString,\n} from \"./address.advanced.js\";\n\n/**\n * @public\n */\nexport type AddressLike = {\n script: ScriptLike;\n prefix: string;\n};\n\n/**\n * Represents a ckb address with associated script and prefix.\n * @public\n */\nexport class Address {\n /**\n * Creates an instance of Address.\n *\n * @param script - The script associated with the address.\n * @param prefix - The address prefix.\n */\n constructor(\n public script: Script,\n public prefix: string,\n ) {}\n\n /**\n * Creates an Address instance from an AddressLike object.\n *\n * @param address - An AddressLike object or an instance of Address.\n * @returns An Address instance.\n */\n\n static from(address: AddressLike): Address {\n if (address instanceof Address) {\n return address;\n }\n\n return new Address(Script.from(address.script), address.prefix);\n }\n\n /**\n * Creates an Address instance from an address string.\n *\n * @param address - The address string to parse.\n * @param clients - A Client instance or a record of Client instances keyed by prefix.\n * @returns A promise that resolves to an Address instance.\n *\n * @throws Will throw an error if the address prefix is unknown or mismatched.\n */\n\n static async fromString(\n address: string,\n clients: Client | Record<string, Client>,\n ): Promise<Address> {\n const { prefix, format, payload } = addressPayloadFromString(address);\n\n const client = (clients as Record<string, Client>)[prefix] ?? clients;\n if (!client) {\n throw new Error(`Unknown address prefix ${prefix}`);\n }\n const expectedPrefix = client.addressPrefix;\n if (expectedPrefix !== prefix) {\n throw new Error(\n `Unknown address prefix ${prefix}, expected ${expectedPrefix}`,\n );\n }\n\n return Address.from(\n await addressFromPayload(prefix, format, payload, client),\n );\n }\n\n /**\n * Creates an Address instance from a script and client.\n *\n * @param script - The script-like object.\n * @param client - The client instance used to fetch the address prefix.\n * @returns A promise that resolves to an Address instance.\n */\n\n static fromScript(script: ScriptLike, client: Client): Address {\n return Address.from({ script, prefix: client.addressPrefix });\n }\n\n static async fromKnownScript(\n client: Client,\n script: KnownScript,\n args: HexLike,\n ): Promise<Address> {\n return Address.from({\n script: await Script.fromKnownScript(client, script, args),\n prefix: client.addressPrefix,\n });\n }\n\n /**\n * Converts the Address instance to a string.\n *\n * @returns The address as a string.\n */\n\n toString(): string {\n const data = bytesConcat(\n [AddressFormat.Full],\n bytesFrom(this.script.codeHash),\n hashTypeToBytes(this.script.hashType),\n bytesFrom(this.script.args),\n );\n\n return bech32m.encode(\n this.prefix,\n bech32m.toWords(data),\n ADDRESS_BECH32_LIMIT,\n );\n }\n}\n","import { ctr } from \"@noble/ciphers/aes.js\";\nimport { scryptAsync } from \"@noble/hashes/scrypt.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { randomBytes } from \"@noble/hashes/utils.js\";\nimport { Bytes, BytesLike, bytesConcat, bytesFrom } from \"../bytes/index.js\";\nimport { hexFrom } from \"../hex/index.js\";\n\n// The parameter r (\"blockSize\")\nconst DEFAULT_SCRYPT_PARAM_R = 8;\n// The parallelization parameter p\nconst DEFAULT_SCRYPT_PARAM_P = 1;\n// The CPU/Memory cost parameter N\nconst DEFAULT_SCRYPT_PARAM_N = 262144;\n\nfunction mac(derivedKey: Bytes, cipherText: Bytes) {\n return hexFrom(\n keccak_256(bytesConcat(derivedKey.slice(16, 32), cipherText)),\n ).slice(2);\n}\n\n/**\n * @public\n */\nexport async function keystoreEncrypt(\n privateKeyLike: BytesLike,\n chainCodeLike: BytesLike,\n password: string,\n): Promise<{\n id: string;\n crypto: {\n ciphertext: string;\n cipherparams: {\n iv: string;\n };\n cipher: string;\n kdf: string;\n kdfparams: {\n n: number;\n r: number;\n p: number;\n dklen: number;\n salt: string;\n };\n mac: string;\n };\n}> {\n const salt = randomBytes(32);\n const iv = randomBytes(16);\n const kdfparams = {\n dklen: 32,\n salt: hexFrom(salt).slice(2),\n n: DEFAULT_SCRYPT_PARAM_N,\n r: DEFAULT_SCRYPT_PARAM_R,\n p: DEFAULT_SCRYPT_PARAM_P,\n };\n const derivedKey = await scryptAsync(bytesFrom(password, \"utf8\"), salt, {\n N: kdfparams.n,\n r: kdfparams.r,\n p: kdfparams.p,\n dkLen: kdfparams.dklen,\n });\n const cipher = ctr(\n derivedKey.slice(0, 16),\n iv.map((v) => v),\n );\n const ciphertext = cipher.encrypt(\n bytesConcat(bytesFrom(privateKeyLike), bytesFrom(chainCodeLike)),\n );\n\n return {\n id: hexFrom(randomBytes(16)).slice(2),\n crypto: {\n ciphertext: hexFrom(ciphertext).slice(2),\n cipherparams: {\n iv: hexFrom(iv).slice(2),\n },\n cipher: \"aes-128-ctr\",\n kdf: \"scrypt\",\n kdfparams,\n mac: mac(derivedKey, ciphertext),\n },\n };\n}\n\n/**\n * @public\n */\nexport async function keystoreDecrypt(\n keystore: unknown,\n password: string,\n): Promise<{\n privateKey: Bytes;\n chainCode: Bytes;\n}> {\n if (\n typeof keystore !== \"object\" ||\n keystore === null ||\n !(\"crypto\" in keystore)\n ) {\n throw Error(\"Invalid keystore\");\n }\n const crypto = keystore.crypto;\n\n if (\n typeof crypto !== \"object\" ||\n crypto === null ||\n !(\"kdfparams\" in crypto) ||\n !(\"ciphertext\" in crypto) ||\n typeof crypto.ciphertext !== \"string\" ||\n !(\"mac\" in crypto) ||\n typeof crypto.mac !== \"string\" ||\n !(\"cipherparams\" in crypto) ||\n typeof crypto.cipherparams !== \"object\" ||\n crypto.cipherparams === null ||\n !(\"iv\" in crypto.cipherparams) ||\n typeof crypto.cipherparams.iv !== \"string\"\n ) {\n throw Error(\"Invalid crypto\");\n }\n const kdfparams = crypto.kdfparams;\n\n if (\n typeof kdfparams !== \"object\" ||\n kdfparams === null ||\n !(\"n\" in kdfparams) ||\n typeof kdfparams.n !== \"number\" ||\n !(\"r\" in kdfparams) ||\n typeof kdfparams.r !== \"number\" ||\n !(\"p\" in kdfparams) ||\n typeof kdfparams.p !== \"number\" ||\n !(\"dklen\" in kdfparams) ||\n typeof kdfparams.dklen !== \"number\" ||\n !(\"salt\" in kdfparams) ||\n typeof kdfparams.salt !== \"string\"\n ) {\n throw Error(\"Invalid kdfparams\");\n }\n\n const derivedKey = await scryptAsync(\n bytesFrom(password, \"utf8\"),\n bytesFrom(kdfparams.salt),\n {\n N: kdfparams.n,\n r: kdfparams.r,\n p: kdfparams.p,\n dkLen: kdfparams.dklen,\n },\n );\n const ciphertext = bytesFrom(crypto.ciphertext);\n if (mac(derivedKey, ciphertext) !== crypto.mac) {\n throw Error(\"Invalid password\");\n }\n const cipher = ctr(\n derivedKey.slice(0, 16),\n bytesFrom(crypto.cipherparams.iv),\n );\n const result = cipher.decrypt(ciphertext);\n return {\n privateKey: result.slice(0, 32),\n chainCode: result.slice(32),\n };\n}\n","import { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\n\n/**\n * Options for signing a PSBT (Partially Signed Bitcoin Transaction)\n */\nexport type SignPsbtOptionsLike = {\n /**\n * Whether to finalize the PSBT after signing.\n * Default is true.\n */\n autoFinalized?: boolean;\n /**\n * Array of inputs to sign\n */\n inputsToSign?: InputToSignLike[];\n};\n\nexport class SignPsbtOptions {\n constructor(\n public autoFinalized: boolean,\n public inputsToSign: InputToSign[],\n ) {}\n\n static from(options?: SignPsbtOptionsLike): SignPsbtOptions {\n if (options instanceof SignPsbtOptions) {\n return options;\n }\n return new SignPsbtOptions(\n options?.autoFinalized ?? true,\n options?.inputsToSign?.map((i) => InputToSign.from(i)) ?? [],\n );\n }\n}\n\n/**\n * Specification for an input to sign in a PSBT.\n * Must specify at least one of: address or pubkey.\n */\nexport type InputToSignLike = {\n /**\n * Which input to sign (index in the PSBT inputs array)\n */\n index: number;\n /**\n * (Optional) Sighash types to use for signing.\n */\n sighashTypes?: number[];\n /**\n * (Optional) When signing and unlocking Taproot addresses, the tweakSigner is used by default\n * for signature generation. Setting this to true allows for signing with the original private key.\n * Default value is false.\n */\n disableTweakSigner?: boolean;\n} & (\n | {\n /**\n * The address whose corresponding private key to use for signing.\n */\n address: string;\n /**\n * The public key whose corresponding private key to use for signing.\n */\n publicKey?: HexLike;\n }\n | {\n /**\n * The address whose corresponding private key to use for signing.\n */\n address?: string;\n /**\n * The public key whose corresponding private key to use for signing.\n */\n publicKey: HexLike;\n }\n);\n\nexport class InputToSign {\n constructor(\n public index: number,\n public sighashTypes?: number[],\n public disableTweakSigner?: boolean,\n public address?: string,\n public publicKey?: Hex,\n ) {}\n\n static from(input: InputToSignLike): InputToSign {\n if (input instanceof InputToSign) {\n return input;\n }\n return new InputToSign(\n input.index,\n input.sighashTypes,\n input.disableTweakSigner,\n input.address,\n input.publicKey ? hexFrom(input.publicKey) : undefined,\n );\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport bs58check from \"bs58check\";\nimport { Bytes, bytesConcat, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\nimport { numFrom, numLeToBytes, NumLike } from \"../../num/index.js\";\n\n/**\n * Encodes a number into a variable-length byte array according to the Bitcoin protocol.\n * This format is used for encoding lengths of data, such as script lengths.\n *\n * @param len - The number to encode. Can be a NumLike.\n * @returns The encoded length as a Bytes.\n * @public\n */\nexport function btcVarLengthBytesFrom(len: NumLike): Bytes {\n const num = numFrom(len);\n\n return num < 0xfd\n ? numLeToBytes(num, 1)\n : num <= 0xffff\n ? bytesConcat([0xfd], numLeToBytes(num, 2))\n : num <= 0xffffffff\n ? bytesConcat([0xfe], numLeToBytes(num, 4))\n : bytesConcat([0xff], numLeToBytes(num, 8));\n}\n\n/**\n * Computes the message hash for Bitcoin ECDSA signatures.\n * This function follows the Bitcoin message signing standard, which involves\n * prefixing the message with a magic string and its length, then double SHA256 hashing the result.\n *\n * @param message - The message to be hashed. Can be a string or BytesLike.\n * @param messagePrefix - Optional. A custom prefix to use instead of the default \"\\u0018Bitcoin Signed Message:\\n\".\n * @returns The Bitcoin hash of the prefixed message as Bytes.\n * @public\n */\nexport function messageHashBtcEcdsa(\n message: string | BytesLike,\n messagePrefix?: string | BytesLike,\n): Bytes {\n const prefix = messagePrefix ?? \"\\u0018Bitcoin Signed Message:\\n\";\n const rawPrefix: Bytes =\n typeof prefix === \"string\" ? bytesFrom(prefix, \"utf8\") : bytesFrom(prefix);\n const rawMsg: Bytes =\n typeof message === \"string\"\n ? bytesFrom(message, \"utf8\")\n : bytesFrom(message);\n\n return sha256(\n sha256(\n bytesConcat(rawPrefix, btcVarLengthBytesFrom(rawMsg.length), rawMsg),\n ),\n );\n}\n\n/**\n * @public\n */\nexport function btcEcdsaPublicKeyHash(publicKey: BytesLike): Bytes {\n return ripemd160(sha256(bytesFrom(publicKey)));\n}\n\n/**\n * @public\n */\nexport function btcP2pkhAddressFromPublicKey(\n publicKey: BytesLike,\n network: number,\n): string {\n return bs58check.encode(\n bytesConcat([network], btcEcdsaPublicKeyHash(publicKey)),\n );\n}\n\n/**\n * @public\n */\nexport function btcPublicKeyFromP2pkhAddress(address: string): Hex {\n return hexFrom(bs58check.decode(address).slice(1));\n}\n\n/**\n * @public\n */\nexport function verifyMessageBtcEcdsa(\n message: string | BytesLike,\n signature: string,\n publicKey: string,\n): boolean {\n const challenge =\n typeof message === \"string\" ? message : hexFrom(message).slice(2);\n\n const rawSign = bytesFrom(signature, \"base64\").slice(1);\n\n return secp256k1.verify(\n bytesFrom(rawSign),\n messageHashBtcEcdsa(challenge),\n bytesFrom(publicKey),\n { prehash: false },\n );\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { bytesConcat, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { hashCkb } from \"../../hasher/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\n\nexport const SECP256K1_SIGNATURE_LENGTH = 65;\n\n/**\n * Sign a message using Secp256k1.\n *\n * @param message - The message to sign.\n * @param privateKey - The private key.\n * @returns The signature.\n * @public\n */\nexport function signMessageSecp256k1(\n message: BytesLike,\n privateKey: BytesLike,\n): Hex {\n const signature = secp256k1.sign(bytesFrom(message), bytesFrom(privateKey), {\n format: \"recovered\",\n prehash: false,\n });\n return hexFrom(bytesConcat(signature.slice(1), signature.slice(0, 1)));\n}\n\n/**\n * Verify a message using Secp256k1.\n *\n * @param message - The message to verify.\n * @param signature - The signature.\n * @param publicKey - The public key.\n * @returns True if the signature is valid, false otherwise.\n * @public\n */\nexport function verifyMessageSecp256k1(\n message: BytesLike,\n signature: BytesLike,\n publicKey: BytesLike,\n): boolean {\n const signatureBytes = bytesFrom(signature);\n return secp256k1.verify(\n bytesConcat(signatureBytes.slice(64), signatureBytes.slice(0, 64)),\n bytesFrom(message),\n bytesFrom(publicKey),\n { format: \"recovered\", prehash: false },\n );\n}\n\n/**\n * Recover the public key from a Secp256k1 signature.\n *\n * @param message - The message.\n * @param signature - The signature.\n * @returns The recovered public key.\n * @public\n */\nexport function recoverMessageSecp256k1(\n message: BytesLike,\n signature: BytesLike,\n): Hex {\n const signatureBytes = bytesFrom(signature);\n return hexFrom(\n secp256k1.recoverPublicKey(\n bytesConcat(signatureBytes.slice(64), signatureBytes.slice(0, 64)),\n bytesFrom(message),\n { prehash: false },\n ),\n );\n}\n\n/**\n * @public\n */\nexport function messageHashCkbSecp256k1(message: string | BytesLike): Hex {\n const msg = typeof message === \"string\" ? message : hexFrom(message);\n const buffer = bytesFrom(`Nervos Message:${msg}`, \"utf8\");\n return hashCkb(buffer);\n}\n\n/**\n * @public\n */\nexport function verifyMessageCkbSecp256k1(\n message: string | BytesLike,\n signature: string,\n publicKey: string,\n): boolean {\n return verifyMessageSecp256k1(\n messageHashCkbSecp256k1(message),\n signature,\n publicKey,\n );\n}\n","import { verifySignature } from \"@joyid/ckb\";\nimport { BytesLike } from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\n\n/**\n * @public\n */\nexport function verifyMessageJoyId(\n message: string | BytesLike,\n signature: string,\n identity: string,\n): Promise<boolean> {\n const challenge =\n typeof message === \"string\" ? message : hexFrom(message).slice(2);\n const { publicKey, keyType } = JSON.parse(identity) as {\n publicKey: string;\n keyType: string;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return verifySignature({\n challenge,\n pubkey: publicKey,\n keyType,\n ...JSON.parse(signature),\n });\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { Bytes, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport {\n btcEcdsaPublicKeyHash,\n btcPublicKeyFromP2pkhAddress,\n messageHashBtcEcdsa,\n} from \"../btc/verify.js\";\n\n/**\n * Computes the message hash for Dogecoin ECDSA signatures.\n * This function follows the Dogecoin message signing standard, which involves\n * prefixing the message with a magic string and its length, then double SHA256 hashing the result.\n *\n * @param message - The message to be hashed. Can be a string or BytesLike.\n * @param messagePrefix - Optional. A custom prefix to use instead of the default \"\\x19Dogecoin Signed Message:\\n\".\n * @returns The Dogecoin hash of the prefixed message as Bytes.\n * @public\n */\nexport function messageHashDogeEcdsa(\n message: string | BytesLike,\n messagePrefix?: string | BytesLike,\n): Bytes {\n return messageHashBtcEcdsa(\n message,\n messagePrefix ?? \"\\x19Dogecoin Signed Message:\\n\",\n );\n}\n\n/**\n * @public\n */\nexport function verifyMessageDogeEcdsa(\n message: string | BytesLike,\n signature: string,\n address: string,\n): boolean {\n const challenge =\n typeof message === \"string\" ? message : hexFrom(message).slice(2);\n const signatureBytes = bytesFrom(signature, \"base64\");\n signatureBytes[0] -= 31;\n\n return (\n btcPublicKeyFromP2pkhAddress(address) ===\n hexFrom(\n btcEcdsaPublicKeyHash(\n secp256k1.recoverPublicKey(\n signatureBytes,\n messageHashDogeEcdsa(challenge),\n { prehash: false },\n ),\n ),\n )\n );\n}\n","import { verifyMessage } from \"ethers\";\nimport { BytesLike, bytesFrom } from \"../../bytes/index.js\";\n\n/**\n * @public\n */\nexport function verifyMessageEvmPersonal(\n message: string | BytesLike,\n signature: string,\n address: string,\n): boolean {\n return (\n address.toLowerCase() ===\n verifyMessage(\n typeof message === \"string\" ? message : bytesFrom(message),\n signature,\n ).toLowerCase()\n );\n}\n","import { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bech32 } from \"bech32\";\nimport { Bytes, BytesLike, bytesFrom } from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { NostrEvent } from \"./signerNostr.js\";\n\n/**\n * @public\n */\nexport function buildNostrEventFromMessage(\n message: string | BytesLike,\n): NostrEvent {\n if (typeof message === \"string\") {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const event = JSON.parse(message);\n if (\n typeof event === \"object\" &&\n typeof event.created_at === \"number\" &&\n typeof event.kind === \"number\" &&\n typeof event.content === \"string\" &&\n Array.isArray(event.tags) &&\n (event.tags as unknown[]).every(\n (tag) =>\n Array.isArray(tag) &&\n (tag as unknown[]).every((v) => typeof v === \"string\"),\n )\n ) {\n return event as NostrEvent;\n }\n } catch (_) {}\n }\n\n return {\n kind: 23335,\n created_at: 0,\n content: typeof message === \"string\" ? message : hexFrom(message),\n tags: [],\n };\n}\n\nexport function nostrEventHash(event: NostrEvent): Bytes {\n const serialized = JSON.stringify([\n 0,\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n ]);\n\n return sha256(bytesFrom(serialized, \"utf8\"));\n}\n\nexport function verifyMessageNostrEvent(\n message: string | BytesLike,\n signature: string,\n address: string,\n): boolean {\n const { words } = bech32.decode(address);\n const pubkey = hexFrom(bech32.fromWords(words)).slice(2);\n\n const event = buildNostrEventFromMessage(message);\n const eventHash = nostrEventHash({ ...event, pubkey });\n\n try {\n return schnorr.verify(bytesFrom(signature), eventHash, bytesFrom(pubkey));\n } catch (_) {\n return false;\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { ClientCollectableSearchKeyFilterLike } from \"../../advancedBarrel.js\";\nimport { BytesLike } from \"../../bytes/index.js\";\nimport { Cell, Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport {\n Client,\n ClientFindTransactionsGroupedResponse,\n ClientFindTransactionsResponse,\n ClientIndexerSearchKeyFilterLike,\n} from \"../../client/index.js\";\nimport { Hex } from \"../../hex/index.js\";\nimport { Num } from \"../../num/index.js\";\nimport { verifyMessageBtcEcdsa } from \"../btc/verify.js\";\nimport { verifyMessageCkbSecp256k1 } from \"../ckb/secp256k1Signing.js\";\nimport { verifyMessageJoyId } from \"../ckb/verifyJoyId.js\";\nimport { verifyMessageDogeEcdsa } from \"../doge/verify.js\";\nimport { verifyMessageEvmPersonal } from \"../evm/verify.js\";\nimport { verifyMessageNostrEvent } from \"../nostr/verify.js\";\n\n/**\n * @public\n */\nexport enum SignerSignType {\n Unknown = \"Unknown\",\n BtcEcdsa = \"BtcEcdsa\",\n EvmPersonal = \"EvmPersonal\",\n JoyId = \"JoyId\",\n NostrEvent = \"NostrEvent\",\n CkbSecp256k1 = \"CkbSecp256k1\",\n DogeEcdsa = \"DogeEcdsa\",\n}\n\n/**\n * An enumeration of signer display types in wallet.\n * @public\n */\nexport enum SignerType {\n EVM = \"EVM\",\n BTC = \"BTC\",\n CKB = \"CKB\",\n Nostr = \"Nostr\",\n Doge = \"Doge\",\n}\n\n/**\n * @public\n */\nexport type NetworkPreference = {\n addressPrefix: string;\n signerType: SignerType;\n /**\n * Wallet signers should check if the wallet is using preferred networks.\n * If not, try to switch to the first preferred network.\n * If non preferred, let users choose what they want.\n * BTC: // They made a mess...\n * btc\n * btcTestnet\n * btcTestnet4 // UTXO Global\n * btcSignet // OKX & UTXO Global\n * fractalBtc // UniSat\n */\n network: string;\n};\n\n/**\n * @public\n */\nexport class Signature {\n constructor(\n public signature: string,\n public identity: string,\n public signType: SignerSignType,\n ) {}\n}\n\n/**\n * An abstract class representing a generic signer.\n * This class provides methods to connect, get addresses, and sign transactions.\n * @public\n */\nexport abstract class Signer {\n constructor(protected client_: Client) {}\n\n abstract get type(): SignerType;\n abstract get signType(): SignerSignType;\n\n get client(): Client {\n return this.client_;\n }\n\n // Returns the preference if we need to switch network\n // undefined otherwise\n matchNetworkPreference(\n preferences: NetworkPreference[],\n currentNetwork: string | undefined,\n ): NetworkPreference | undefined {\n if (\n currentNetwork !== undefined &&\n preferences.some(\n ({ signerType, addressPrefix, network }) =>\n signerType === this.type &&\n addressPrefix === this.client.addressPrefix &&\n network === currentNetwork,\n )\n ) {\n return;\n }\n return preferences.find(\n ({ signerType, addressPrefix }) =>\n signerType === this.type && addressPrefix === this.client.addressPrefix,\n );\n }\n\n static async verifyMessage(\n message: string | BytesLike,\n signature: Signature,\n ): Promise<boolean> {\n switch (signature.signType) {\n case SignerSignType.EvmPersonal:\n return verifyMessageEvmPersonal(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.BtcEcdsa:\n return verifyMessageBtcEcdsa(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.JoyId:\n return verifyMessageJoyId(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.NostrEvent:\n return verifyMessageNostrEvent(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.CkbSecp256k1:\n return verifyMessageCkbSecp256k1(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.DogeEcdsa:\n return verifyMessageDogeEcdsa(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.Unknown:\n throw new Error(\"Unknown signer sign type\");\n }\n }\n\n /**\n * Connects to the signer.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n abstract connect(): Promise<void>;\n\n /**\n * Register a listener to be called when this signer is replaced.\n *\n * @returns A function for unregister\n */\n onReplaced(_: () => void): () => void {\n return () => {};\n }\n\n /**\n * Disconnects to the signer.\n *\n * @returns A promise that resolves when the signer is disconnected.\n */\n async disconnect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n abstract isConnected(): Promise<boolean>;\n\n /**\n * Gets the internal address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n abstract getInternalAddress(): Promise<string>;\n\n /**\n * Gets the identity for verifying signature, usually it's address\n *\n * @returns A promise that resolves to a string representing the identity\n */\n async getIdentity(): Promise<string> {\n return this.getInternalAddress();\n }\n\n /**\n * Gets an array of Address objects associated with the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n abstract getAddressObjs(): Promise<Address[]>;\n\n /**\n * Gets the recommended Address object for the signer.\n *\n * @param _preference - Optional preference parameter.\n * @returns A promise that resolves to the recommended Address object.\n */\n async getRecommendedAddressObj(_preference?: unknown): Promise<Address> {\n return (await this.getAddressObjs())[0];\n }\n\n /**\n * Gets the recommended address for the signer as a string.\n *\n * @param preference - Optional preference parameter.\n * @returns A promise that resolves to the recommended address as a string.\n */\n async getRecommendedAddress(preference?: unknown): Promise<string> {\n return (await this.getRecommendedAddressObj(preference)).toString();\n }\n\n /**\n * Gets an array of addresses associated with the signer as strings.\n *\n * @returns A promise that resolves to an array of addresses as strings.\n */\n async getAddresses(): Promise<string[]> {\n return this.getAddressObjs().then((addresses) =>\n addresses.map((address) => address.toString()),\n );\n }\n\n /**\n * Find cells of this signer\n *\n * @param filter - The filter for the search key.\n * @param withData - Whether to include cell data in the response.\n * @param order - The order of the returned cells, can be \"asc\" or \"desc\".\n * @param limit - The maximum number of cells for every querying chunk.\n * @returns A async generator that yields all matching cells\n */\n async *findCellsOnChain(\n filter: ClientIndexerSearchKeyFilterLike,\n withData?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<Cell> {\n const scripts = await this.getAddressObjs();\n for (const { script } of scripts) {\n for await (const cell of this.client.findCellsOnChain(\n {\n script,\n scriptType: \"lock\",\n filter,\n scriptSearchMode: \"exact\",\n withData,\n },\n order,\n limit,\n )) {\n yield cell;\n }\n }\n }\n\n /**\n * Find cells of this signer\n *\n * @returns A async generator that yields all matches cells\n */\n async *findCells(\n filter: ClientCollectableSearchKeyFilterLike,\n withData?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<Cell> {\n const scripts = await this.getAddressObjs();\n for (const { script } of scripts) {\n for await (const cell of this.client.findCells(\n {\n script,\n scriptType: \"lock\",\n filter,\n scriptSearchMode: \"exact\",\n withData,\n },\n order,\n limit,\n )) {\n yield cell;\n }\n }\n }\n\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction?: false | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction: true,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n async *findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n const scripts = await this.getAddressObjs();\n for (const { script } of scripts) {\n for await (const transaction of this.client.findTransactions(\n {\n script,\n scriptType: \"lock\",\n filter,\n scriptSearchMode: \"exact\",\n groupByTransaction,\n },\n order,\n limit,\n )) {\n yield transaction;\n }\n }\n }\n\n /**\n * Gets balance of all addresses\n *\n * @returns A promise that resolves to the balance\n */\n async getBalance(): Promise<Num> {\n return this.client.getBalance(\n (await this.getAddressObjs()).map(({ script }) => script),\n );\n }\n\n /**\n * Signs a message.\n *\n * @param message - The message to sign, as a string or BytesLike object.\n * @returns A promise that resolves to the signature info.\n * @throws Will throw an error if not implemented.\n */\n async signMessage(message: string | BytesLike): Promise<Signature> {\n return {\n signature: await this.signMessageRaw(message),\n identity: await this.getIdentity(),\n signType: this.signType,\n };\n }\n\n /**\n * Signs a message and returns signature only. This method is not implemented and should be overridden by subclasses.\n *\n * @param _ - The message to sign, as a string or BytesLike object.\n * @returns A promise that resolves to the signature as a string.\n * @throws Will throw an error if not implemented.\n */\n signMessageRaw(_: string | BytesLike): Promise<string> {\n throw Error(\"Signer.signMessageRaw not implemented\");\n }\n\n /**\n * Verify a signature.\n *\n * @param message - The original message.\n * @param signature - The signature to verify.\n * @returns A promise that resolves to the verification result.\n * @throws Will throw an error if not implemented.\n */\n async verifyMessage(\n message: string | BytesLike,\n signature: string | Signature,\n ): Promise<boolean> {\n if (typeof signature === \"string\") {\n return Signer.verifyMessage(message, {\n signType: this.signType,\n signature,\n identity: await this.getIdentity(),\n });\n }\n\n if (\n signature.identity !== (await this.getIdentity()) ||\n ![SignerSignType.Unknown, this.signType].includes(signature.signType)\n ) {\n return false;\n }\n\n return Signer.verifyMessage(message, signature);\n }\n\n /**\n * Sends a transaction after signing it.\n *\n * @param tx - The transaction to send, represented as a TransactionLike object.\n * @returns A promise that resolves to the transaction hash as a Hex string.\n */\n async sendTransaction(tx: TransactionLike): Promise<Hex> {\n return this.client.sendTransaction(await this.signTransaction(tx));\n }\n\n /**\n * Signs a transaction.\n *\n * @param tx - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to the signed Transaction object.\n */\n async signTransaction(tx: TransactionLike): Promise<Transaction> {\n const preparedTx = await this.prepareTransaction(tx);\n return this.signOnlyTransaction(preparedTx);\n }\n\n /**\n * Prepares a transaction before signing.\n * This method can be overridden by subclasses to perform any necessary steps,\n * such as adding cell dependencies or witnesses, before the transaction is signed.\n * The default implementation converts the {@link TransactionLike} object to a {@link Transaction} object\n * without modification.\n *\n * @remarks\n * Note that this default implementation does not add any cell dependencies or dummy witnesses.\n * This may lead to an underestimation of transaction size and fees if used with methods\n * like `Transaction.completeFee`. Subclasses for signers that are intended to sign\n * transactions should override this method to perform necessary preparations.\n *\n * @param tx - The transaction to prepare.\n * @returns A promise that resolves to the prepared {@link Transaction} object.\n */\n async prepareTransaction(tx: TransactionLike): Promise<Transaction> {\n return Transaction.from(tx);\n }\n\n /**\n * Signs a transaction without preparing information for it. This method is not implemented and should be overridden by subclasses.\n *\n * @param _ - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to the signed Transaction object.\n * @throws Will throw an error if not implemented.\n */\n signOnlyTransaction(_: TransactionLike): Promise<Transaction> {\n throw Error(\"Signer.signOnlyTransaction not implemented\");\n }\n}\n\n/**\n * An abstract class representing a multisig signer.\n * @public\n */\nexport abstract class SignerMultisig extends Signer {\n /**\n * Get the number of members in the multisig script.\n * @returns The number of members.\n */\n abstract getMemberCount(): Promise<number>;\n\n /**\n * Get the threshold of the multisig script.\n * @returns The threshold.\n */\n abstract getMemberThreshold(): Promise<number>;\n\n /**\n * Get the count of required member of the multisig script.\n * @returns The must match count.\n */\n abstract getMemberRequiredCount(): Promise<number>;\n\n /**\n * Get the number of valid signatures for matching multisig inputs in the transaction.\n *\n * @remarks\n * Returns `undefined` when the transaction has no inputs locked by any multisig address\n * supported by this signer. This method only evaluates matching multisig inputs and does\n * not indicate whether the transaction itself is expected to be signed by this multisig.\n *\n * @param _ - The transaction.\n * @returns The matched multisig signature count, or `undefined` when the transaction is unrelated to any multisig address supported by this signer.\n */\n abstract getSignaturesCount(_: TransactionLike): Promise<number | undefined>;\n\n /**\n * Check if related multisig inputs in the transaction need more signatures.\n *\n * @remarks\n * Returns `false` when the transaction has no inputs locked by any multisig address\n * supported by this signer.\n * A `false` result therefore means either the related multisig inputs are already fulfilled,\n * or the transaction is unrelated to all multisig addresses supported by this signer.\n *\n * @param txLike - The transaction to check.\n * @returns A promise that resolves to `true` when related multisig inputs still need signatures, and `false` otherwise.\n */\n abstract needMoreSignatures(_: TransactionLike): Promise<boolean>;\n\n /**\n * Aggregate transactions.\n * @param _ - The transactions to aggregate.\n * @returns The aggregated transaction.\n */\n abstract aggregateTransactions(_: TransactionLike[]): Promise<Transaction>;\n\n /**\n * Send a transaction.\n *\n * @remarks\n * This method rejects the transaction only when related multisig inputs still need signatures.\n * It does not verify that the transaction actually contains inputs locked by any multisig\n * address supported by this signer, so transactions unrelated to those multisig addresses\n * are not rejected by this check.\n *\n * @param tx - The transaction to send.\n * @returns The transaction hash.\n */\n async sendTransaction(tx: TransactionLike): Promise<Hex> {\n const signedTx = await this.signTransaction(tx);\n if (await this.needMoreSignatures(signedTx)) {\n const count = (await this.getSignaturesCount(signedTx)) ?? 0;\n const threshold = await this.getMemberThreshold();\n throw new SignerMultisigNotEnoughSignaturesError(count, threshold);\n }\n\n return this.client.sendTransaction(signedTx);\n }\n}\n\n/**\n * Thrown when a multisig transaction is sent before enough signatures are collected.\n *\n * @public\n */\nexport class SignerMultisigNotEnoughSignaturesError extends Error {\n readonly signaturesCount: number;\n readonly threshold: number;\n\n constructor(signaturesCount: number, threshold: number) {\n const message = `Not enough signatures: got ${signaturesCount}, need ${threshold}`;\n super(message);\n this.name = \"SignerMultisigNotEnoughSignaturesError\";\n this.signaturesCount = signaturesCount;\n this.threshold = threshold;\n }\n}\n\n/**\n * A class representing information about a signer, including its type and the signer instance.\n * @public\n */\nexport class SignerInfo {\n constructor(\n public name: string,\n public signer: Signer,\n ) {}\n}\n\n/**\n * Represents a wallet with a name, icon, and an array of signer information.\n * @public\n */\nexport type Wallet = {\n name: string;\n icon: string;\n};\n","import { Address } from \"../../address/index.js\";\nimport { bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { numToBytes } from \"../../num/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\nimport { SignPsbtOptionsLike } from \"./psbt.js\";\nimport { btcEcdsaPublicKeyHash } from \"./verify.js\";\n\n/**\n * An abstract class extending the Signer class for Bitcoin-like signing operations.\n * This class provides methods to get Bitcoin account, public key, and internal address,\n * as well as signing transactions.\n * @public\n */\nexport abstract class SignerBtc extends Signer {\n get type(): SignerType {\n return SignerType.BTC;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.BtcEcdsa;\n }\n\n /**\n * Sign and broadcast a PSBT.\n *\n * @param psbtHex - The hex string of PSBT to sign and broadcast.\n * @param options - Options for signing the PSBT.\n * @returns A promise that resolves to the transaction ID as a Hex string.\n */\n async signAndBroadcastPsbt(\n psbtHex: HexLike,\n options?: SignPsbtOptionsLike,\n ): Promise<Hex> {\n const signedPsbt = await this.signPsbt(psbtHex, options);\n return this.broadcastPsbt(signedPsbt, options);\n }\n\n /**\n * Gets the Bitcoin account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Bitcoin account.\n */\n abstract getBtcAccount(): Promise<string>;\n\n /**\n * Gets the Bitcoin public key associated with the signer.\n *\n * @returns A promise that resolves to a HexLike value representing the Bitcoin public key.\n */\n abstract getBtcPublicKey(): Promise<HexLike>;\n\n /**\n * Gets the internal address, which is the Bitcoin account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return this.getBtcAccount();\n }\n\n /**\n * Gets the identity, which is the Bitcoin public key in this case.\n *\n * @returns A promise that resolves to a string representing the identity\n */\n async getIdentity(): Promise<string> {\n return hexFrom(await this.getBtcPublicKey()).slice(2);\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const publicKey = await this.getBtcPublicKey();\n const hash = btcEcdsaPublicKeyHash(publicKey);\n\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x04, ...hash, 0x00]),\n ),\n ];\n }\n\n /**\n * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.OmniLock);\n await tx.prepareSighashAllWitness(script, 85, this.client);\n return tx;\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signature = bytesFrom(\n await this.signMessageRaw(\n `CKB (Bitcoin Layer) transaction: ${info.message}`,\n ),\n \"base64\",\n );\n signature[0] = 31 + ((signature[0] - 27) % 4);\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(\n bytesConcat(\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(4 * 4, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(signature.length, 4),\n signature,\n ),\n );\n\n tx.setWitnessArgsAt(info.position, witness);\n return tx;\n }\n\n /**\n * Signs a Partially Signed Bitcoin Transaction (PSBT).\n *\n * @param psbtHex - The hex string of PSBT to sign.\n * @param options - Options for signing the PSBT\n * @returns A promise that resolves to the signed PSBT as a Hex string.\n */\n abstract signPsbt(\n psbtHex: HexLike,\n options?: SignPsbtOptionsLike,\n ): Promise<Hex>;\n\n /**\n * Broadcasts a PSBT to the Bitcoin network.\n *\n * @param psbtHex - The hex string of the PSBT to broadcast.\n * @param options - Options for broadcasting the PSBT.\n * @returns A promise that resolves to the transaction ID as a Hex string.\n */\n abstract broadcastPsbt(\n psbtHex: HexLike,\n options?: SignPsbtOptionsLike,\n ): Promise<Hex>;\n}\n","import { Client } from \"../../client/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { SignPsbtOptionsLike } from \"./psbt.js\";\nimport { SignerBtc } from \"./signerBtc.js\";\n\n/**\n * A class extending SignerBtc that provides read-only access to a Bitcoin public key and account.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerBtcPublicKeyReadonly extends SignerBtc {\n private readonly publicKey: Hex;\n\n /**\n * Creates an instance of SignerBtcPublicKeyReadonly.\n *\n * @param client - The client instance used for communication.\n * @param account - The Bitcoin account associated with the signer.\n * @param publicKey - The public key associated with the signer.\n */\n constructor(\n client: Client,\n private readonly account: string,\n publicKey: HexLike,\n ) {\n super(client);\n\n this.publicKey = hexFrom(publicKey);\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the Bitcoin account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Bitcoin account.\n *\n * @example\n * ```typescript\n * const account = await signer.getBtcAccount(); // Outputs the Bitcoin account\n * ```\n */\n async getBtcAccount(): Promise<string> {\n return this.account;\n }\n\n /**\n * Gets the Bitcoin public key associated with the signer.\n *\n * @returns A promise that resolves to a Hex string representing the Bitcoin public key.\n *\n * @example\n * ```typescript\n * const publicKey = await signer.getBtcPublicKey(); // Outputs the Bitcoin public key\n * ```\n */\n async getBtcPublicKey(): Promise<Hex> {\n return this.publicKey;\n }\n\n async signPsbt(\n _psbtHex: HexLike,\n _options?: SignPsbtOptionsLike,\n ): Promise<Hex> {\n throw new Error(\"Read-only signer does not support signPsbt\");\n }\n\n async broadcastPsbt(\n _psbtHex: HexLike,\n _options?: SignPsbtOptionsLike,\n ): Promise<Hex> {\n throw new Error(\"Read-only signer does not support broadcastPsbt\");\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { bytesFrom } from \"../../bytes/index.js\";\nimport { Script, Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport { CellDepInfo, Client, KnownScript } from \"../../client/index.js\";\nimport { hashCkbShort } from \"../../hasher/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\nimport { SECP256K1_SIGNATURE_LENGTH } from \"./secp256k1Signing.js\";\n\n/**\n * @public\n */\nexport class SignerCkbPublicKey extends Signer {\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.CkbSecp256k1;\n }\n\n public readonly publicKey: Hex;\n\n constructor(client: Client, publicKey: HexLike) {\n super(client);\n this.publicKey = hexFrom(publicKey);\n\n if (bytesFrom(this.publicKey).length !== 33) {\n throw new Error(\"Public key must be 33 bytes!\");\n }\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n async getIdentity(): Promise<string> {\n return this.publicKey;\n }\n\n async getAddressObjSecp256k1(): Promise<Address> {\n return Address.fromKnownScript(\n this.client,\n KnownScript.Secp256k1Blake160,\n hashCkbShort(this.publicKey),\n );\n }\n\n async getRecommendedAddressObj(_preference?: unknown): Promise<Address> {\n return this.getAddressObjSecp256k1();\n }\n\n async getAddressObjs(): Promise<Address[]> {\n const secp256k1 = await this.getAddressObjSecp256k1();\n\n const addresses: Address[] = [];\n let count = 0;\n for await (const cell of this.client.findCells({\n script: await Script.fromKnownScript(\n this.client,\n KnownScript.AnyoneCanPay,\n secp256k1.script.args,\n ),\n scriptType: \"lock\",\n scriptSearchMode: \"prefix\",\n withData: false,\n })) {\n if (count >= 10) {\n break;\n }\n count += 1;\n\n if (addresses.some(({ script }) => script.eq(cell.cellOutput.lock))) {\n continue;\n }\n\n addresses.push(\n Address.from({\n prefix: this.client.addressPrefix,\n script: cell.cellOutput.lock,\n }),\n );\n }\n\n return [secp256k1, ...addresses];\n }\n\n async getRelatedScripts(\n txLike: TransactionLike,\n ): Promise<{ script: Script; cellDeps: CellDepInfo[] }[]> {\n const tx = Transaction.from(txLike);\n\n const secp256k1 = await this.getAddressObjSecp256k1();\n const acp = await Script.fromKnownScript(\n this.client,\n KnownScript.AnyoneCanPay,\n secp256k1.script.args,\n );\n\n const scripts: { script: Script; cellDeps: CellDepInfo[] }[] = [];\n for (const input of tx.inputs) {\n const {\n cellOutput: { lock },\n } = await input.getCell(this.client);\n\n if (scripts.some(({ script }) => script.eq(lock))) {\n continue;\n }\n\n if (lock.eq(secp256k1.script)) {\n scripts.push({\n script: lock,\n cellDeps: (\n await this.client.getKnownScript(KnownScript.Secp256k1Blake160)\n ).cellDeps,\n });\n } else if (\n lock.codeHash === acp.codeHash &&\n lock.hashType === acp.hashType &&\n lock.args.startsWith(acp.args)\n ) {\n scripts.push({\n script: lock,\n cellDeps: (await this.client.getKnownScript(KnownScript.AnyoneCanPay))\n .cellDeps,\n });\n }\n }\n\n return scripts;\n }\n\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n\n await Promise.all(\n (await this.getRelatedScripts(tx)).map(async ({ script, cellDeps }) => {\n await tx.prepareSighashAllWitness(\n script,\n SECP256K1_SIGNATURE_LENGTH,\n this.client,\n );\n await tx.addCellDepInfos(this.client, cellDeps);\n }),\n );\n return tx;\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport {\n messageHashCkbSecp256k1,\n signMessageSecp256k1,\n} from \"./secp256k1Signing.js\";\nimport { SignerCkbPublicKey } from \"./signerCkbPublicKey.js\";\n\n/**\n * @public\n */\nexport class SignerCkbPrivateKey extends SignerCkbPublicKey {\n public readonly privateKey: Hex;\n\n constructor(client: Client, privateKey: HexLike) {\n const pk = hexFrom(privateKey);\n if (bytesFrom(pk).length !== 32) {\n throw new Error(\"Private key must be 32 bytes!\");\n }\n\n super(client, secp256k1.getPublicKey(bytesFrom(pk), true));\n this.privateKey = pk;\n }\n\n async _signMessage(message: HexLike): Promise<Hex> {\n return signMessageSecp256k1(message, this.privateKey);\n }\n\n async signMessageRaw(message: string | BytesLike): Promise<Hex> {\n return this._signMessage(messageHashCkbSecp256k1(message));\n }\n\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n\n for (const { script } of await this.getRelatedScripts(tx)) {\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signature = await this._signMessage(info.message);\n\n const witness =\n tx.getWitnessArgsAt(info.position) ?? WitnessArgs.from({});\n witness.lock = signature;\n tx.setWitnessArgsAt(info.position, witness);\n }\n\n return tx;\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Script, ScriptLike } from \"../../ckb/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * A read-only signer for a CKB script. It can be used to get addresses,\n * but not to sign transactions. This is useful when you want to watch an address\n * without having the private key.\n *\n * @public\n */\nexport class SignerCkbScriptReadonly extends Signer {\n /**\n * The type of the signer.\n */\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n /**\n * The sign type of the signer.\n * As this is a read-only signer, the sign type is {@link SignerSignType.Unknown}.\n */\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n /**\n * The scripts associated with the signer.\n */\n public readonly scripts: Script[];\n\n /**\n * Creates an instance of SignerCkbScriptReadonly.\n *\n * @param client - The client instance used for communication.\n * @param scripts - The scripts associated with the signer. Can be a single script, an array of scripts, or multiple script arguments.\n */\n constructor(client: Client, ...scripts: (ScriptLike | ScriptLike[])[]) {\n super(client);\n\n this.scripts = scripts.flat().map(Script.from);\n if (this.scripts.length === 0) {\n throw new Error(\"SignerCkbScriptReadonly requires at least one script.\");\n }\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the internal address for the script.\n *\n * @returns A promise that resolves to a string representing the internal address.\n *\n * @example\n * ```typescript\n * const internalAddress = await signer.getInternalAddress(); // Outputs the internal address\n * ```\n */\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n /**\n * Gets an array of Address objects representing the script address.\n *\n * @returns A promise that resolves to an array of Address objects.\n *\n * @example\n * ```typescript\n * const addressObjs = await signer.getAddressObjs(); // Outputs the array of Address objects\n * ```\n */\n async getAddressObjs(): Promise<Address[]> {\n return this.scripts.map((script) =>\n Address.fromScript(script, this.client),\n );\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Bytes, bytesConcat, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport {\n Script,\n ScriptLike,\n Since,\n SinceLike,\n Transaction,\n TransactionLike,\n WitnessArgs,\n WitnessArgsLike,\n} from \"../../ckb/index.js\";\nimport {\n CellDepInfo,\n CellDepInfoLike,\n Client,\n KnownScript,\n ScriptInfo,\n ScriptInfoLike,\n} from \"../../client/index.js\";\nimport { codec, Entity } from \"../../codec/index.js\";\nimport { HASH_CKB_SHORT_LENGTH, hashCkbShort } from \"../../hasher/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport { numFrom, NumLike, numToBytes } from \"../../num/index.js\";\nimport { apply, reduceAsync } from \"../../utils/index.js\";\nimport { SignerMultisig, SignerSignType, SignerType } from \"../signer/index.js\";\nimport {\n recoverMessageSecp256k1,\n SECP256K1_SIGNATURE_LENGTH,\n} from \"./secp256k1Signing.js\";\n\nexport type MultisigCkbWitnessLike = (\n | {\n publicKeyHashes: HexLike[];\n publicKeys?: undefined | null;\n }\n | {\n publicKeyHashes?: undefined | null;\n publicKeys: HexLike[];\n }\n) & {\n threshold: NumLike;\n mustMatch?: NumLike | null;\n signatures?: HexLike[] | null;\n};\n\n/**\n * A class representing multisig information, holding information ingredients and containing utilities.\n * @public\n */\n@codec({\n encode: (encodable: MultisigCkbWitness) => {\n const { publicKeyHashes, threshold, mustMatch, signatures } =\n MultisigCkbWitness.from(encodable);\n\n if (\n signatures.some((s) => s.length !== SECP256K1_SIGNATURE_LENGTH * 2 + 2)\n ) {\n throw Error(\"MultisigCkbWitness: invalid signature length\");\n }\n if (\n publicKeyHashes.some((s) => s.length !== HASH_CKB_SHORT_LENGTH * 2 + 2)\n ) {\n throw Error(\"MultisigCkbWitness: invalid public key hash length\");\n }\n\n return bytesConcat(\n \"0x00\",\n numToBytes(mustMatch ?? 0),\n numToBytes(threshold),\n numToBytes(publicKeyHashes.length),\n ...publicKeyHashes,\n ...signatures,\n );\n },\n decode: (raw: Bytes) => {\n if (raw.length < 4) {\n throw Error(\"MultisigCkbWitness: data length too short\");\n }\n\n const [\n _reserved,\n mustMatch,\n threshold,\n publicKeyHashesLength,\n ...rawKeyAndSignatures\n ] = raw;\n\n if (\n rawKeyAndSignatures.length <\n publicKeyHashesLength * HASH_CKB_SHORT_LENGTH\n ) {\n throw Error(\"MultisigCkbWitness: invalid public key hashes length\");\n }\n\n const signatures = rawKeyAndSignatures.slice(\n publicKeyHashesLength * HASH_CKB_SHORT_LENGTH,\n );\n\n return MultisigCkbWitness.from({\n publicKeyHashes: Array.from(new Array(publicKeyHashesLength), (_, i) =>\n hexFrom(\n rawKeyAndSignatures.slice(\n i * HASH_CKB_SHORT_LENGTH,\n (i + 1) * HASH_CKB_SHORT_LENGTH,\n ),\n ),\n ),\n threshold: numFrom(threshold),\n mustMatch: numFrom(mustMatch),\n signatures: Array.from(\n new Array(Math.floor(signatures.length / SECP256K1_SIGNATURE_LENGTH)),\n (_, i) =>\n hexFrom(\n signatures.slice(\n i * SECP256K1_SIGNATURE_LENGTH,\n (i + 1) * SECP256K1_SIGNATURE_LENGTH,\n ),\n ),\n ),\n });\n },\n})\nexport class MultisigCkbWitness extends Entity.Base<\n MultisigCkbWitnessLike,\n MultisigCkbWitness\n>() {\n /**\n * @param publicKeyHashes - The public key hashes.\n * @param threshold - The threshold.\n * @param mustMatch - The number of signatures that must match.\n * @param signatures - The signatures.\n */\n constructor(\n public publicKeyHashes: Hex[],\n public threshold: number,\n public mustMatch: number,\n public signatures: Hex[],\n ) {\n super();\n\n const keysLength = publicKeyHashes.length;\n\n if (threshold <= 0 || threshold > keysLength) {\n throw new Error(\n \"threshold should be in range from 1 to public keys length\",\n );\n }\n if (mustMatch < 0 || mustMatch > Math.min(keysLength, threshold)) {\n throw new Error(\n \"mustMatch should be in range from 0 to min(public keys length, threshold)\",\n );\n }\n if (keysLength > 255) {\n throw new Error(\"public keys length should be less than 256\");\n }\n }\n\n /**\n * Create a MultisigCkbWitness from a MultisigCkbWitnessLike.\n *\n * @param witness - The witness like object.\n * @returns The MultisigCkbWitness.\n */\n static from(witness: MultisigCkbWitnessLike): MultisigCkbWitness {\n const publicKeyHashes = (() => {\n if (witness.publicKeyHashes) {\n return witness.publicKeyHashes;\n }\n return witness.publicKeys.map((k) => hashCkbShort(k));\n })();\n\n return new MultisigCkbWitness(\n publicKeyHashes.map(hexFrom),\n Number(numFrom(witness.threshold)),\n Number(numFrom(witness.mustMatch ?? 0)),\n witness.signatures?.map(hexFrom) ?? [],\n );\n }\n\n /**\n * Get the threshold of flexible signatures.\n */\n get flexibleThreshold() {\n return this.threshold - this.mustMatch;\n }\n\n /**\n * Get the script args of the multisig script.\n *\n * @param since - The since value.\n * @returns The script args.\n */\n scriptArgs(since?: SinceLike | null): Bytes {\n const hash = hashCkbShort(\n MultisigCkbWitness.from({ ...this, signatures: [] }).toBytes(),\n );\n\n if (since != null) {\n return bytesConcat(hash, Since.from(since).toBytes());\n }\n\n return bytesFrom(hash);\n }\n\n /**\n * Check if the multisig info is equal to another.\n *\n * @param otherLike - The other multisig info.\n * @returns True if the multisig info is equal, false otherwise.\n */\n eqInfo(otherLike: MultisigCkbWitnessLike): boolean {\n const other = MultisigCkbWitness.from(otherLike);\n return (\n this.publicKeyHashes.length === other.publicKeyHashes.length &&\n this.publicKeyHashes.every((h, i) => h === other.publicKeyHashes[i]) &&\n this.threshold === other.threshold &&\n this.mustMatch === other.mustMatch\n );\n }\n\n /**\n * Generate valid public key hashes and their signatures from the witness.\n * This method filters out invalid signatures, duplicate signatures, and signatures not in the multisig script.\n *\n * @param message - The message signed.\n * @returns A generator of public key hashes, signatures, and whether the signature is required.\n */\n *generatePublicKeyHashesFromSignatures(message: BytesLike): Generator<{\n pubkeyHash: Hex;\n signature: Hex;\n isRequired: boolean;\n }> {\n const publicKeyHashesFromSignature = new Set<Hex>();\n\n for (const signature of this.signatures.filter(\n (sig) => sig !== SignerMultisigCkbReadonly.EmptySignature,\n )) {\n const pubkey = (() => {\n try {\n return recoverMessageSecp256k1(message, signature);\n } catch (_) {\n // Ignore invalid signature\n return;\n }\n })();\n if (pubkey === undefined) {\n continue;\n }\n\n const pubkeyHash = hashCkbShort(pubkey);\n if (publicKeyHashesFromSignature.has(pubkeyHash)) {\n continue;\n }\n\n const index = this.publicKeyHashes.indexOf(pubkeyHash);\n if (index === -1) {\n continue;\n }\n publicKeyHashesFromSignature.add(pubkeyHash);\n const isRequired = index < this.mustMatch;\n\n yield {\n pubkeyHash,\n signature,\n isRequired,\n };\n }\n }\n\n /**\n * Calculate the number of matched signatures in the witness.\n *\n * @param message - The message signed.\n * @returns The number of required and flexible signatures.\n */\n calcMatchedSignaturesCount(message: BytesLike): {\n required: number;\n flexible: number;\n } {\n let required = 0;\n let flexible = 0;\n\n for (const { isRequired } of this.generatePublicKeyHashesFromSignatures(\n message,\n )) {\n if (isRequired) {\n required += 1;\n } else {\n flexible += 1;\n }\n }\n\n return { required, flexible };\n }\n}\n\n/**\n * A class extending Signer that provides access to a CKB multisig script.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerMultisigCkbReadonly extends SignerMultisig {\n static EmptySignature = hexFrom(\"00\".repeat(SECP256K1_SIGNATURE_LENGTH));\n\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n public readonly multisigInfo: MultisigCkbWitness;\n\n public readonly since?: Since;\n public readonly scriptInfos: Promise<\n {\n script: Script;\n cellDeps: CellDepInfo[];\n }[]\n >;\n\n /**\n * Creates an instance of SignerMultisigCkbReadonly.\n *\n * @param client - The client instance.\n * @param multisigInfoLike - The multisig information.\n * @param options - The options.\n */\n constructor(\n client: Client,\n multisigInfoLike: MultisigCkbWitnessLike,\n options?: {\n since?: SinceLike | null;\n scriptInfos?: (KnownScript | ScriptInfoLike)[] | null;\n } | null,\n ) {\n super(client);\n\n this.multisigInfo = MultisigCkbWitness.from(multisigInfoLike);\n this.since = apply(Since.from, options?.since);\n\n const args = this.multisigInfo.scriptArgs(this.since);\n this.scriptInfos = Promise.all(\n (\n options?.scriptInfos ?? [\n KnownScript.Secp256k1MultisigV2,\n KnownScript.Secp256k1MultisigV2Beta,\n KnownScript.Secp256k1Multisig,\n ]\n ).map(async (v) => {\n if (typeof v !== \"string\") {\n return ScriptInfo.from(v);\n }\n\n try {\n return await client.getKnownScript(v);\n } catch (_) {\n return undefined;\n }\n }),\n ).then((infos) =>\n infos\n .filter((s) => s !== undefined)\n .map((i) => ({\n script: Script.from({ ...i, args }),\n cellDeps: i.cellDeps,\n })),\n );\n }\n\n /**\n * Get the number of members in the multisig script.\n *\n * @returns The number of members.\n */\n async getMemberCount() {\n return this.multisigInfo.publicKeyHashes.length;\n }\n\n /**\n * Get the threshold of the multisig script.\n *\n * @returns The threshold.\n */\n async getMemberThreshold() {\n return this.multisigInfo.threshold;\n }\n\n /**\n * Get the count of required member of the multisig script.\n *\n * @returns The must match count.\n */\n async getMemberRequiredCount() {\n return this.multisigInfo.mustMatch;\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n async getAddressObjs(): Promise<Address[]> {\n return (await this.scriptInfos).map(({ script }) =>\n Address.fromScript(script, this.client),\n );\n }\n\n /**\n * Decode the witness args at a specific index.\n *\n * @param txLike - The transaction.\n * @param index - The index of the witness args.\n * @returns The decoded MultisigCkbWitness.\n */\n decodeWitnessArgsAt(\n txLike: TransactionLike,\n index: number,\n ): MultisigCkbWitness | undefined {\n const tx = Transaction.from(txLike);\n\n return this.decodeWitnessArgs(tx.getWitnessArgsAt(index));\n }\n\n /**\n * Decode the witness args.\n *\n * @param witnessLike - The witness args like object.\n * @returns The decoded MultisigCkbWitness.\n */\n decodeWitnessArgs(\n witnessLike?: WitnessArgsLike | null,\n ): MultisigCkbWitness | undefined {\n if (!witnessLike) {\n return;\n }\n const witness = WitnessArgs.from(witnessLike);\n\n if (witness.lock == null) {\n return;\n }\n\n try {\n const decoded = MultisigCkbWitness.decode(witness.lock);\n if (decoded.eqInfo(this.multisigInfo)) {\n return decoded;\n }\n } catch (_) {\n // Returns undefined for invalid data\n }\n }\n\n /**\n * Prepare the witness args at a specific index.\n *\n * @param txLike - The transaction.\n * @param index - The index of the witness args.\n * @param transformer - The transformer function.\n * @returns The prepared transaction.\n */\n async prepareWitnessArgsAt(\n txLike: TransactionLike,\n index: number,\n transformer?:\n | ((\n witness: MultisigCkbWitness,\n witnessArgs: WitnessArgs,\n ) =>\n | MultisigCkbWitnessLike\n | undefined\n | null\n | void\n | Promise<MultisigCkbWitnessLike | undefined | null | void>)\n | null,\n ): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n\n const witnessArgs = tx.getWitnessArgsAt(index) ?? WitnessArgs.from({});\n const multisigWitness =\n this.decodeWitnessArgs(witnessArgs) ?? this.multisigInfo.clone();\n\n const transformed = MultisigCkbWitness.from(\n (await transformer?.(multisigWitness, witnessArgs)) ?? multisigWitness,\n );\n\n transformed.signatures = transformed.signatures.slice(\n 0,\n this.multisigInfo.threshold,\n );\n transformed.signatures.push(\n ...Array.from(\n new Array(this.multisigInfo.threshold - transformed.signatures.length),\n () => SignerMultisigCkbReadonly.EmptySignature,\n ),\n );\n\n witnessArgs.lock = transformed.toHex();\n tx.setWitnessArgsAt(index, witnessArgs);\n\n return tx;\n }\n\n /**\n * Prepare multisig witness, if the existence of multisig witness is detected, nothing happens\n *\n * @param txLike - The transaction to prepare.\n * @param scriptLike - The script to prepare.\n * @returns A promise that resolves to the prepared transaction\n */\n async prepareTransactionOneScript(\n txLike: TransactionLike,\n script: ScriptLike,\n cellDeps: CellDepInfoLike[],\n ) {\n const tx = Transaction.from(txLike);\n const position = await tx.findInputIndexByLock(script, this.client);\n if (position === undefined) {\n return tx;\n }\n\n await tx.addCellDepInfos(this.client, cellDeps);\n return this.prepareWitnessArgsAt(tx, position);\n }\n\n /**\n * Prepare transaction for multisig witness and adding related cell deps\n *\n * @param txLike - The transaction to prepare.\n * @returns A promise that resolves to the prepared transaction\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n return await reduceAsync(\n await this.scriptInfos,\n (tx, { script, cellDeps }) =>\n this.prepareTransactionOneScript(tx, script, cellDeps),\n Transaction.from(txLike),\n );\n }\n\n /**\n * Get the number of valid signatures for matching multisig inputs in the transaction.\n *\n * @remarks\n * Returns `undefined` when the transaction has no inputs locked by any multisig address\n * supported by this signer. This method only counts signatures for matching multisig inputs\n * and does not imply that the transaction should be signed by this multisig.\n *\n * @param txLike - The transaction.\n * @returns The matched multisig signature count, or `undefined` when the transaction is unrelated to any multisig address supported by this signer.\n */\n async getSignaturesCount(\n txLike: TransactionLike,\n ): Promise<number | undefined> {\n const tx = Transaction.from(txLike);\n let minSignaturesCount = undefined;\n\n for (const { script } of await this.scriptInfos) {\n const info = await this.getSignInfo(tx, script);\n if (info === undefined) {\n continue;\n }\n\n const multisigWitness = this.decodeWitnessArgsAt(tx, info.position);\n if (!multisigWitness) {\n minSignaturesCount = 0;\n continue;\n }\n\n const { required, flexible } = multisigWitness.calcMatchedSignaturesCount(\n info.message,\n );\n\n minSignaturesCount = Math.min(\n minSignaturesCount ?? 256,\n required + Math.min(flexible, this.multisigInfo.flexibleThreshold),\n );\n }\n\n return minSignaturesCount;\n }\n\n /**\n * Check if related multisig inputs in the transaction need more signatures.\n *\n * @remarks\n * Returns `false` when the transaction has no inputs locked by any multisig address\n * supported by this signer.\n * A `false` result therefore means either the related multisig inputs are already fulfilled,\n * or the transaction is unrelated to all multisig addresses supported by this signer.\n *\n * @param txLike - The transaction to check.\n * @returns A promise that resolves to `true` when related multisig inputs still need signatures, and `false` otherwise.\n */\n async needMoreSignatures(txLike: TransactionLike): Promise<boolean> {\n const count = await this.getSignaturesCount(txLike);\n if (count == null) {\n return false;\n }\n return count < (await this.getMemberThreshold());\n }\n\n /**\n * Get the sign info for a script.\n *\n * @param txLike - The transaction.\n * @param script - The script.\n * @returns The sign info.\n */\n async getSignInfo(\n txLike: TransactionLike,\n script: ScriptLike,\n ): Promise<{ message: Hex; position: number } | undefined> {\n const tx = Transaction.from(txLike);\n\n const position = await tx.findInputIndexByLock(script, this.client);\n if (position == null) {\n return;\n }\n\n // === Replace the witness with a dummy one ===\n const witness = tx.getWitnessArgsAt(position) ?? WitnessArgs.from({});\n witness.lock = MultisigCkbWitness.from({\n ...this.multisigInfo,\n signatures: Array.from(\n new Array(this.multisigInfo.threshold),\n () => SignerMultisigCkbReadonly.EmptySignature,\n ),\n }).toHex();\n\n const clonedTx = tx.clone();\n clonedTx.setWitnessArgsAt(position, witness);\n // === Replace the witness with a dummy one ===\n\n return clonedTx.getSignHashInfo(script, this.client);\n }\n\n /**\n * Aggregate transactions.\n *\n * @param txs - The transactions to aggregate.\n * @returns The aggregated transaction.\n */\n async aggregateTransactions(txs: TransactionLike[]): Promise<Transaction> {\n if (txs.length === 0) {\n throw Error(\"No transaction to aggregate\");\n }\n\n let res = Transaction.from(txs[0]);\n\n for (const { script } of await this.scriptInfos) {\n const info = await this.getSignInfo(res, script);\n if (info === undefined) {\n continue;\n }\n\n const signatures = new Map<Hex, Hex>();\n let requiredCount = 0;\n for (const txLike of txs) {\n const tx = Transaction.from(txLike);\n const multisigWitness = this.decodeWitnessArgsAt(tx, info.position);\n\n if (!multisigWitness) {\n continue;\n }\n\n for (const {\n pubkeyHash,\n signature,\n isRequired,\n } of multisigWitness.generatePublicKeyHashesFromSignatures(\n info.message,\n )) {\n if (signatures.has(pubkeyHash)) {\n continue;\n }\n\n if (isRequired) {\n // A required public key\n requiredCount += 1;\n } else if (\n signatures.size - requiredCount >=\n this.multisigInfo.flexibleThreshold\n ) {\n // Not a required public key, and we have too many optional public key\n continue;\n }\n\n signatures.set(pubkeyHash, signature);\n if (signatures.size >= this.multisigInfo.threshold) {\n break;\n }\n }\n\n if (signatures.size >= this.multisigInfo.threshold) {\n break;\n }\n }\n\n res = await this.prepareWitnessArgsAt(res, info.position, (witness) => {\n witness.signatures = Array.from(signatures.values());\n });\n }\n\n return res;\n }\n}\n","import { SinceLike, Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport { Client, KnownScript, ScriptInfoLike } from \"../../client/index.js\";\nimport { hashCkbShort } from \"../../hasher/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport { signMessageSecp256k1 } from \"./secp256k1Signing.js\";\nimport { SignerCkbPrivateKey } from \"./signerCkbPrivateKey.js\";\nimport {\n MultisigCkbWitnessLike,\n SignerMultisigCkbReadonly,\n} from \"./signerMultisigCkbReadonly.js\";\n\n/**\n * A class extending Signer that provides access to a CKB multisig script and supports signing operations.\n * @public\n */\nexport class SignerMultisigCkbPrivateKey extends SignerMultisigCkbReadonly {\n private readonly privateKey: Hex;\n private readonly signer: SignerCkbPrivateKey;\n\n /**\n * Creates an instance of SignerMultisigCkbPrivateKey.\n *\n * @param client - The client instance.\n * @param privateKey - The private key.\n * @param multisigInfo - The multisig information.\n * @param options - The options.\n */\n constructor(\n client: Client,\n privateKey: HexLike,\n multisigInfo: MultisigCkbWitnessLike,\n options?: {\n since?: SinceLike | null;\n scriptInfos?: (KnownScript | ScriptInfoLike)[] | null;\n } | null,\n ) {\n super(client, multisigInfo, options);\n\n this.privateKey = hexFrom(privateKey);\n this.signer = new SignerCkbPrivateKey(client, this.privateKey);\n }\n\n /**\n * Sign a transaction only (without preparing).\n *\n * @param txLike - The transaction to sign.\n * @returns The signed transaction.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n let tx = Transaction.from(txLike);\n\n const thisPubkeyHash = hashCkbShort(this.signer.publicKey);\n\n const index = this.multisigInfo.publicKeyHashes.indexOf(thisPubkeyHash);\n if (index === -1) {\n return tx;\n }\n const isSelfRequired = index < this.multisigInfo.mustMatch;\n\n for (const { script } of await this.scriptInfos) {\n const info = await this.getSignInfo(tx, script);\n if (!info) {\n continue;\n }\n\n // === Find a position for the signature ===\n tx = await this.prepareWitnessArgsAt(\n tx,\n info.position,\n async (witness) => {\n // We re-evaluate the signatures to filter invalid / excessive signatures\n const signatures: Hex[] = [];\n let requiredCount = 0;\n let isSignNeeded = true;\n\n for (const {\n pubkeyHash,\n signature,\n isRequired,\n } of witness.generatePublicKeyHashesFromSignatures(info.message)) {\n if (pubkeyHash === thisPubkeyHash) {\n if (!isSignNeeded) {\n // Has signed and added to the signatures list already. We will not add it again.\n continue;\n }\n isSignNeeded = false;\n }\n\n if (isRequired) {\n requiredCount += 1;\n } else if (\n signatures.length - requiredCount >=\n this.multisigInfo.flexibleThreshold\n ) {\n // Too many flexible signatures\n continue;\n }\n\n signatures.push(signature);\n if (signatures.length >= this.multisigInfo.threshold) {\n // We have got enough signatures\n isSignNeeded = false;\n break;\n }\n }\n\n if (\n isSignNeeded &&\n (isSelfRequired ||\n signatures.length - requiredCount <\n this.multisigInfo.flexibleThreshold)\n ) {\n // Add the signature from this signer only when\n // 1. The signature is needed\n // 2. It's required or...\n // 3. We haven't got enough flexible signatures\n signatures.push(\n signMessageSecp256k1(info.message, this.privateKey),\n );\n }\n witness.signatures = signatures;\n return witness;\n },\n );\n }\n\n return tx;\n }\n}\n","import bs58check from \"bs58check\";\nimport { Address } from \"../../address/index.js\";\nimport { bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { numToBytes } from \"../../num/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * An abstract class extending the Signer class for Dogecoin-like signing operations.\n * This class provides methods to get Doge account, public key, and internal address,\n * as well as signing transactions.\n * @public\n */\nexport abstract class SignerDoge extends Signer {\n get type(): SignerType {\n return SignerType.Doge;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.DogeEcdsa;\n }\n\n /**\n * Gets the Doge address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Doge account.\n */\n abstract getDogeAddress(): Promise<string>;\n\n /**\n * Gets the internal address, which is the Doge account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return this.getDogeAddress();\n }\n\n /**\n * Gets the identity, which is the Doge address in this case.\n *\n * @returns A promise that resolves to a string representing the identity\n */\n async getIdentity(): Promise<string> {\n return this.getDogeAddress();\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const hash = bs58check.decode(await this.getDogeAddress()).slice(1);\n\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x05, ...hash, 0x00]),\n ),\n ];\n }\n\n /**\n * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.OmniLock);\n await tx.prepareSighashAllWitness(script, 85, this.client);\n return tx;\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signature = bytesFrom(\n await this.signMessageRaw(info.message.slice(2)),\n \"base64\",\n );\n signature[0] = 31 + ((signature[0] - 27) % 4);\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(\n bytesConcat(\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(4 * 4, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(signature.length, 4),\n signature,\n ),\n );\n\n tx.setWitnessArgsAt(info.position, witness);\n return tx;\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { SignerDoge } from \"./signerDoge.js\";\n\n/**\n * A class extending SignerDoge that provides read-only access to a Doge address.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerDogeAddressReadonly extends SignerDoge {\n /**\n * Creates an instance of SignerDogeAddressReadonly.\n *\n * @param client - The client instance used for communication.\n * @param address - The Doge address with the signer.\n */\n constructor(\n client: Client,\n private readonly address: string,\n ) {\n super(client);\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the Doge address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Doge address.\n *\n * @example\n * ```typescript\n * const account = await signer.getDogeAddress(); // Outputs the Doge address\n * ```\n */\n async getDogeAddress(): Promise<string> {\n return this.address;\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport {\n Bytes,\n bytesConcat,\n bytesFrom,\n BytesLike,\n bytesTo,\n} from \"../../bytes/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\nimport { btcP2pkhAddressFromPublicKey } from \"../btc/verify.js\";\nimport { SignerDoge } from \"./signerDoge.js\";\nimport { messageHashDogeEcdsa } from \"./verify.js\";\n\n/**\n * A class extending SignerDoge that provides access to a Doge address.\n * @public\n */\nexport class SignerDogePrivateKey extends SignerDoge {\n private readonly privateKey: Bytes;\n\n /**\n * Creates an instance of SignerDogePrivateKey\n *\n * @param client - The client instance used for communication.\n * @param privateKey - The Doge private key with the signer.\n */\n constructor(\n client: Client,\n privateKey: BytesLike,\n public readonly dogeNetwork = 0x1e,\n ) {\n super(client);\n this.privateKey = bytesFrom(privateKey);\n if (this.privateKey.length !== 32) {\n throw new Error(\"Private key must be 32 bytes!\");\n }\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is always connected.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getDogePublicKey(): Promise<Hex> {\n return hexFrom(secp256k1.getPublicKey(this.privateKey, true));\n }\n\n /**\n * Gets the Doge address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Doge address.\n *\n * @example\n * ```typescript\n * const account = await signer.getDogeAddress(); // Outputs the Doge address\n * ```\n */\n async getDogeAddress(): Promise<string> {\n return btcP2pkhAddressFromPublicKey(\n await this.getDogePublicKey(),\n this.dogeNetwork,\n );\n }\n\n /**\n * Signs a message and returns signature only.\n *\n * @param msg - The message to sign, as a string or BytesLike object.\n * @returns A promise that resolves to the signature as a string.\n * @throws Will throw an error if not implemented.\n */\n async signMessageRaw(msg: string | BytesLike): Promise<string> {\n const challenge = typeof msg === \"string\" ? msg : hexFrom(msg).slice(2);\n\n const signature = secp256k1.sign(\n messageHashDogeEcdsa(challenge),\n this.privateKey,\n {\n format: \"recovered\",\n prehash: false,\n },\n );\n return bytesTo(\n bytesConcat([31 + Number(signature[0])], signature.slice(1)),\n \"base64\",\n );\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * @public\n */\nexport abstract class SignerDummy extends Signer {\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n constructor(\n client: Client,\n public readonly type: SignerType,\n ) {\n super(client);\n }\n\n async isConnected(): Promise<boolean> {\n return false;\n }\n\n async getInternalAddress(): Promise<string> {\n throw new Error(\"Can't get address from SignerDummy\");\n }\n\n async getAddressObjs(): Promise<Address[]> {\n throw new Error(\"Can't get addresses from SignerDummy\");\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { SignerType } from \"../signer/index.js\";\nimport { SignerDummy } from \"./dummy.js\";\n\n/**\n * @public\n */\nexport class SignerAlwaysError extends SignerDummy {\n constructor(\n client: Client,\n type: SignerType,\n private readonly message: string,\n ) {\n super(client, type);\n }\n\n async connect(): Promise<void> {\n throw new Error(this.message);\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { SignerType } from \"../signer/index.js\";\nimport { SignerDummy } from \"./dummy.js\";\n\n/**\n * @public\n */\nexport class SignerOpenLink extends SignerDummy {\n constructor(\n client: Client,\n type: SignerType,\n private readonly link: string,\n ) {\n super(client, type);\n }\n\n async connect(): Promise<void> {\n window.open(this.link, \"_blank\")?.focus();\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Bytes, BytesLike, bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport {\n Script,\n Transaction,\n TransactionLike,\n WitnessArgs,\n} from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { Hasher, HasherKeecak256 } from \"../../hasher/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { numToBytes } from \"../../num/index.js\";\nimport { reduceAsync } from \"../../utils/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * An abstract class extending Signer for Ethereum Virtual Machine (EVM) based signing operations.\n * This class provides methods to get EVM account, internal address, and signing transactions.\n * @public\n */\nexport abstract class SignerEvm extends Signer {\n get type(): SignerType {\n return SignerType.EVM;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.EvmPersonal;\n }\n\n /**\n * Gets the EVM account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the EVM account.\n */\n abstract getEvmAccount(): Promise<Hex>;\n\n /**\n * Gets the internal address, which is the EVM account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return this.getEvmAccount();\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const account = await this.getEvmAccount();\n const addresses = await Promise.all([\n this._getOmniLockAddresses(account),\n this._getPWLockAddresses(account),\n ]);\n\n return addresses.flat();\n }\n\n _getOmniLockAddresses(account: HexLike): Promise<Address[]> {\n return Promise.all([\n this._getOmniLockEvmAddressObj(account),\n this._getOmniLockOldEvmAddressObj(account),\n ]);\n }\n\n async _getPWLockAddresses(account: HexLike): Promise<Address[]> {\n const addr = await this._getPWLockEvmAddressObj(account);\n if (!addr) {\n return [];\n }\n return [addr];\n }\n\n async _getOmniLockEvmAddressObj(account: HexLike): Promise<Address> {\n return Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x12, ...bytesFrom(account), 0x00]),\n );\n }\n\n async _getOmniLockOldEvmAddressObj(account: HexLike): Promise<Address> {\n return Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x1, ...bytesFrom(account), 0x00]),\n );\n }\n\n async _getPWLockEvmAddressObj(\n account: HexLike,\n ): Promise<Address | undefined> {\n try {\n return Address.fromKnownScript(\n this.client,\n KnownScript.PWLock,\n hexFrom(bytesFrom(account)),\n );\n } catch {}\n return;\n }\n\n /**\n * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n if (\n (await tx.findInputIndexByLockId(\n await this.client.getKnownScript(KnownScript.OmniLock),\n this.client,\n )) !== undefined\n ) {\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.OmniLock);\n }\n if (\n (await tx.findInputIndexByLockId(\n await this.client.getKnownScript(KnownScript.PWLock),\n this.client,\n )) !== undefined\n ) {\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.PWLock);\n }\n\n const account = await this.getEvmAccount();\n const omniLockAddresses = await this._getOmniLockAddresses(account);\n const pwLockAddresses = await this._getPWLockAddresses(account);\n\n const omniTx = reduceAsync(\n omniLockAddresses,\n (tx: Transaction, { script }) =>\n tx.prepareSighashAllWitness(script, 85, this.client),\n tx,\n );\n\n return reduceAsync(\n pwLockAddresses,\n (tx: Transaction, { script }) =>\n tx.prepareSighashAllWitness(script, 65, this.client),\n omniTx,\n );\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n let tx = Transaction.from(txLike);\n\n const account = await this.getEvmAccount();\n const { script: evmScript } = await this._getOmniLockEvmAddressObj(account);\n const { script: oldEvmScript } =\n await this._getOmniLockOldEvmAddressObj(account);\n\n tx = await this._signOmniLockScriptForTransaction(\n tx,\n evmScript,\n (hash) => `CKB transaction: ${hash}`,\n );\n tx = await this._signOmniLockScriptForTransaction(\n tx,\n oldEvmScript,\n (hash) => bytesFrom(hash),\n );\n\n const pwAddress = await this._getPWLockEvmAddressObj(account);\n if (pwAddress) {\n tx = await this._signPWLockScriptForTransaction(\n tx,\n pwAddress.script,\n (hash) => bytesFrom(hash),\n );\n }\n\n return tx;\n }\n\n async _signOmniLockScriptForTransaction(\n tx: Transaction,\n script: Script,\n messageTransformer: (hash: string) => BytesLike,\n ): Promise<Transaction> {\n const info = await this._signPersonalEvmForTransaction(\n tx,\n script,\n messageTransformer,\n );\n if (!info) {\n return tx;\n }\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(\n bytesConcat(\n numToBytes(5 * 4 + info.signature.length, 4),\n numToBytes(4 * 4, 4),\n numToBytes(5 * 4 + info.signature.length, 4),\n numToBytes(5 * 4 + info.signature.length, 4),\n numToBytes(info.signature.length, 4),\n info.signature,\n ),\n );\n\n tx.setWitnessArgsAt(info.position, witness);\n\n return tx;\n }\n\n async _signPWLockScriptForTransaction(\n tx: Transaction,\n script: Script,\n messageTransformer: (hash: string) => BytesLike,\n ): Promise<Transaction> {\n const info = await this._signPersonalEvmForTransaction(\n tx,\n script,\n messageTransformer,\n new HasherKeecak256(),\n );\n if (!info) {\n return tx;\n }\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(info.signature);\n tx.setWitnessArgsAt(info.position, witness);\n\n return tx;\n }\n\n async _signPersonalEvmForTransaction(\n tx: Transaction,\n script: Script,\n messageTransformer: (hash: string) => BytesLike,\n hasher?: Hasher,\n ): Promise<{ signature: Bytes; position: number } | undefined> {\n const info = await tx.getSignHashInfo(script, this.client, hasher);\n if (!info) {\n return;\n }\n\n const signature = bytesFrom(\n await this.signMessageRaw(messageTransformer(info.message)),\n );\n if (signature[signature.length - 1] >= 27) {\n signature[signature.length - 1] -= 27;\n }\n\n return { signature, position: info.position };\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { SignerEvm } from \"./signerEvm.js\";\n\n/**\n * A class extending SignerEvm that provides read-only access to an EVM address.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerEvmAddressReadonly extends SignerEvm {\n private readonly address: Hex;\n\n /**\n * Creates an instance of SignerEvmAddressReadonly.\n *\n * @param client - The client instance used for communication.\n * @param address - The EVM address associated with the signer.\n */\n constructor(client: Client, address: HexLike) {\n super(client);\n\n this.address = hexFrom(address);\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n *\n * @example\n * ```typescript\n * await signer.connect();\n * ```\n */\n\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the EVM account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the EVM account.\n *\n * @example\n * ```typescript\n * const account = await signer.getEvmAccount(); // Outputs the EVM account\n * ```\n */\n async getEvmAccount(): Promise<Hex> {\n return this.address;\n }\n}\n","import { bech32 } from \"bech32\";\nimport { Address } from \"../../address/index.js\";\nimport { BytesLike, bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { hashCkb } from \"../../hasher/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\nimport { buildNostrEventFromMessage } from \"./verify.js\";\n\n/**\n * @public\n */\nexport interface NostrEvent {\n id?: string;\n pubkey?: string;\n sig?: string;\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n}\n\n/**\n * @public\n */\nexport abstract class SignerNostr extends Signer {\n static CKB_SIG_HASH_ALL_TAG = \"ckb_sighash_all\";\n static CKB_UNLOCK_EVENT_KIND = 23334;\n static CKB_UNLOCK_EVENT_CONTENT =\n \"Signing a CKB transaction\\n\\nIMPORTANT: Please verify the integrity and authenticity of connected Nostr client before signing this message\\n\";\n\n get type(): SignerType {\n return SignerType.Nostr;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.NostrEvent;\n }\n\n /**\n * Gets the Nostr public key associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Nostr public key.\n */\n abstract getNostrPublicKey(): Promise<Hex>;\n\n /**\n * Sign a nostr event.\n *\n * @returns A promise that resolves to the signed event.\n */\n async signNostrEvent(_event: NostrEvent): Promise<Required<NostrEvent>> {\n throw Error(\"SignerNostr.signNostrEvent not implemented\");\n }\n\n /**\n * Sign a message.\n *\n * @returns A promise that resolves to the signature.\n */\n async signMessageRaw(message: string | BytesLike): Promise<Hex> {\n return hexFrom(\n (await this.signNostrEvent(buildNostrEventFromMessage(message))).sig,\n );\n }\n\n /**\n * Gets the internal address, which is the EVM account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return bech32.encode(\n \"npub\",\n bech32.toWords(bytesFrom(await this.getNostrPublicKey())),\n );\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const publicKey = await this.getNostrPublicKey();\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.NostrLock,\n hexFrom(bytesConcat([0x00], hashCkb(publicKey).slice(0, 42))),\n ),\n ];\n }\n\n /**\n * prepare a transaction before signing.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.NostrLock);\n await tx.prepareSighashAllWitness(script, 572, this.client);\n return tx;\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signedEvent = bytesFrom(\n JSON.stringify(\n await this.signNostrEvent({\n pubkey: (await this.getNostrPublicKey()).slice(2),\n tags: [[SignerNostr.CKB_SIG_HASH_ALL_TAG, info.message.slice(2)]],\n created_at: Math.floor(Date.now() / 1000),\n kind: SignerNostr.CKB_UNLOCK_EVENT_KIND,\n content: SignerNostr.CKB_UNLOCK_EVENT_CONTENT,\n }),\n ),\n \"utf8\",\n );\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(signedEvent);\n tx.setWitnessArgsAt(info.position, witness);\n\n return tx;\n }\n}\n","import { bech32 } from \"bech32\";\nimport { Client } from \"../../client/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport { SignerNostr } from \"./signerNostr.js\";\n\n/**\n * Signer from Nostr public key\n * Support npub and hex format\n */\nexport class SignerNostrPublicKeyReadonly extends SignerNostr {\n public readonly publicKey: Hex;\n\n constructor(client: Client, publicKey: HexLike) {\n super(client);\n\n if (typeof publicKey === \"string\" && publicKey.startsWith(\"npub\")) {\n const { words } = bech32.decode(publicKey);\n this.publicKey = hexFrom(bech32.fromWords(words));\n } else {\n this.publicKey = hexFrom(publicKey);\n }\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getNostrPublicKey(): Promise<Hex> {\n return this.publicKey;\n }\n}\n","import { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { bech32 } from \"bech32\";\nimport { Bytes, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { NostrEvent } from \"./signerNostr.js\";\nimport { SignerNostrPublicKeyReadonly } from \"./signerNostrPublicKeyReadonly.js\";\nimport { nostrEventHash } from \"./verify.js\";\n\n/**\n * Signer from Nostr private key\n * Support nsec and hex format\n */\nexport class SignerNostrPrivateKey extends SignerNostrPublicKeyReadonly {\n private readonly privateKey: Bytes;\n\n constructor(client: Client, privateKeyLike: BytesLike) {\n const privateKey = (() => {\n if (\n typeof privateKeyLike === \"string\" &&\n privateKeyLike.startsWith(\"nsec\")\n ) {\n const { words } = bech32.decode(privateKeyLike);\n return bytesFrom(bech32.fromWords(words));\n }\n\n return bytesFrom(privateKeyLike);\n })();\n\n super(client, schnorr.getPublicKey(privateKey));\n\n this.privateKey = privateKey;\n }\n\n async signNostrEvent(event: NostrEvent): Promise<Required<NostrEvent>> {\n const pubkey = (await this.getNostrPublicKey()).slice(2);\n const eventHash = nostrEventHash({ ...event, pubkey });\n const signature = schnorr.sign(eventHash, this.privateKey);\n\n return {\n ...event,\n id: hexFrom(eventHash).slice(2),\n pubkey,\n sig: hexFrom(signature).slice(2),\n };\n }\n}\n","export * from \"./address/index.js\";\nexport * from \"./bytes/index.js\";\nexport * from \"./ckb/index.js\";\nexport * from \"./client/index.js\";\nexport * from \"./codec/index.js\";\nexport * from \"./fixedPoint/index.js\";\nexport * from \"./hasher/index.js\";\nexport * from \"./hex/index.js\";\nexport * from \"./jsonRpc/index.js\";\nexport * from \"./keystore/index.js\";\nexport * from \"./molecule/index.js\";\nexport * from \"./num/index.js\";\nexport * from \"./signer/index.js\";\nexport * from \"./utils/index.js\";\n"],"mappings":"0kEAQA,IAAa,GAAb,KAA+C,CAO7C,aAAc,CACZ,KAAK,OAAS,GAAW,OAAO,CAClC,CAgBA,OAAO,EAAkC,CAEvC,OADA,KAAK,OAAO,OAAO,EAAU,CAAI,CAAC,EAC3B,IACT,CAeA,QAAc,CACZ,OAAO,EAAQ,KAAK,OAAO,OAAO,CAAC,CACrC,CACF,wlCE5BsB,GAAtB,KAAkC,CAIhC,MAAM,WAAW,GAAG,EAAqD,CAEvE,OADA,MAAM,KAAK,YAAY,GAAG,CAAS,EAC5B,KAAK,kBAAkB,GAAG,CAAS,CAC5C,CAIA,MAAM,iBACJ,GAAG,EACY,CACf,MAAM,QAAQ,IAAI,CAChB,KAAK,2BACH,EAAgB,KAAK,CAAC,CAAC,IAAK,IAAiB,CAC9B,cACb,OAAQ,MACV,EAAE,CACJ,EACA,GAAG,EAAgB,KAAK,CAAC,CAAC,IAAK,GAAoB,CACjD,IAAM,EA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GACE,OAAO,GAAmB,UAC1B,EAAe,WAAW,MAAM,EAChC,CACA,GAAM,CAAE,SAAU,EAAO,OAAO,CAAc,EAC9C,OAAO,EAAU,EAAO,UAAU,CAAK,CAAC,CAC1C,CAEA,OAAO,EAAU,CAAc,CACjC,EAAA,CAAG,EAEH,MAAM,EAAQ,EAAQ,aAAa,CAAU,CAAC,EAE9C,KAAK,WAAa,CACpB,CAEA,MAAM,eAAe,EAAkD,CACrE,IAAM,GAAU,MAAM,KAAK,kBAAkB,EAAA,CAAG,MAAM,CAAC,EACjD,EAAY,EAAe,CAAE,GAAG,EAAO,QAAO,CAAC,EAC/C,EAAY,EAAQ,KAAK,EAAW,KAAK,UAAU,EAEzD,MAAO,CACL,GAAG,EACH,GAAI,EAAQ,CAAS,CAAC,CAAC,MAAM,CAAC,EAC9B,SACA,IAAK,EAAQ,CAAS,CAAC,CAAC,MAAM,CAAC,CACjC,CACF,CACF"}
1
+ {"version":3,"file":"barrel-yZm3ICzn.mjs","names":[],"sources":["../src/hasher/hasherKeecak256.ts","../src/molecule/barrel.ts","../src/client/cache/cache.ts","../src/client/cache/memory.ts","../src/client/client.ts","../src/jsonRpc/requestor.ts","../src/client/jsonRpc/client.ts","../src/client/clientPublicMainnet.ts","../src/client/clientPublicTestnet.ts","../src/ckb/hash.ts","../src/address/index.ts","../src/keystore/index.ts","../src/signer/btc/psbt.ts","../src/signer/btc/verify.ts","../src/signer/ckb/secp256k1Signing.ts","../src/signer/ckb/verifyJoyId.ts","../src/signer/doge/verify.ts","../src/signer/evm/verify.ts","../src/signer/nostr/verify.ts","../src/signer/signer/index.ts","../src/signer/btc/signerBtc.ts","../src/signer/btc/signerBtcPublicKeyReadonly.ts","../src/signer/ckb/signerCkbPublicKey.ts","../src/signer/ckb/signerCkbPrivateKey.ts","../src/signer/ckb/signerCkbScriptReadonly.ts","../src/signer/ckb/signerMultisigCkbReadonly.ts","../src/signer/ckb/signerMultisigCkbPrivateKey.ts","../src/signer/doge/signerDoge.ts","../src/signer/doge/signerDogeAddressReadonly.ts","../src/signer/doge/signerDogePrivateKey.ts","../src/signer/dummy/dummy.ts","../src/signer/dummy/alwaysError.ts","../src/signer/dummy/openLink.ts","../src/signer/evm/signerEvm.ts","../src/signer/evm/signerEvmAddressReadonly.ts","../src/signer/nostr/signerNostr.ts","../src/signer/nostr/signerNostrPublicKeyReadonly.ts","../src/signer/nostr/signerNostrPrivateKey.ts","../src/barrel.ts"],"sourcesContent":["import { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { BytesLike, bytesFrom } from \"../bytes/index.js\";\nimport { Hex, hexFrom } from \"../hex/index.js\";\nimport { Hasher } from \"./hasher.js\";\n\n/**\n * @public\n */\nexport class HasherKeecak256 implements Hasher {\n private readonly hasher: ReturnType<(typeof keccak_256)[\"create\"]>;\n\n /**\n * Creates an instance of Hasher.\n */\n\n constructor() {\n this.hasher = keccak_256.create();\n }\n\n /**\n * Updates the hash with the given data.\n *\n * @param data - The data to update the hash with.\n * @returns The current Hasher instance for chaining.\n *\n * @example\n * ```typescript\n * const hasher = new Hasher();\n * hasher.update(\"some data\").update(\"more data\");\n * const hash = hasher.digest();\n * ```\n */\n\n update(data: BytesLike): HasherKeecak256 {\n this.hasher.update(bytesFrom(data));\n return this;\n }\n\n /**\n * Finalizes the hash and returns the digest as a hexadecimal string.\n *\n * @returns The hexadecimal string representation of the hash.\n *\n * @example\n * ```typescript\n * const hasher = new Hasher();\n * hasher.update(\"some data\");\n * const hash = hasher.digest(); // Outputs something like \"0x...\"\n * ```\n */\n\n digest(): Hex {\n return hexFrom(this.hasher.digest());\n }\n}\n","export {\n /**\n * @deprecated Use ccc.Entity instead\n */\n Entity,\n /**\n * @deprecated Use ccc.codec instead\n */\n codec,\n} from \"../codec/entity.js\";\nexport * from \"./codec.js\";\nexport * from \"./predefined.js\";\n","import {\n Cell,\n CellLike,\n OutPointLike,\n Transaction,\n TransactionLike,\n} from \"../../ckb/index.js\";\nimport { HexLike } from \"../../hex/index.js\";\nimport { numFrom, NumLike } from \"../../num/index.js\";\nimport { ClientCollectableSearchKeyLike } from \"../clientTypes.advanced.js\";\nimport {\n ClientBlock,\n ClientBlockHeader,\n ClientBlockHeaderLike,\n ClientBlockLike,\n ClientTransactionResponse,\n ClientTransactionResponseLike,\n} from \"../clientTypes.js\";\nimport { DEFAULT_CONFIRMED_BLOCK_TIME } from \"./memory.advanced.js\";\n\n/**\n * @public\n * The ClientCache class is mainly designed for chained transactions.\n * Consumed & Created cells are \"marked\" so they can be correctly handled when composing transactions.\n * It also act as cache for rpc requests to reduce cost, but this is optional.\n */\nexport abstract class ClientCache {\n abstract markUsableNoCache(\n ...cellLikes: (CellLike | CellLike[])[]\n ): Promise<void>;\n async markUsable(...cellLikes: (CellLike | CellLike[])[]): Promise<void> {\n await this.recordCells(...cellLikes);\n return this.markUsableNoCache(...cellLikes);\n }\n abstract markUnusable(\n ...outPointLike: (OutPointLike | OutPointLike[])[]\n ): Promise<void>;\n async markTransactions(\n ...transactionLike: (TransactionLike | TransactionLike[])[]\n ): Promise<void> {\n await Promise.all([\n this.recordTransactionResponses(\n transactionLike.flat().map((transaction) => ({\n transaction: transaction,\n status: \"sent\",\n })),\n ),\n ...transactionLike.flat().map((transactionLike) => {\n const tx = Transaction.from(transactionLike);\n const txHash = tx.hash();\n\n return Promise.all([\n ...tx.inputs.map((i) => this.markUnusable(i.previousOutput)),\n ...tx.outputs.map((o, i) =>\n this.markUsable({\n cellOutput: o,\n outputData: tx.outputsData[i],\n outPoint: {\n txHash,\n index: i,\n },\n }),\n ),\n ]);\n }),\n ]);\n }\n abstract clear(): Promise<void>;\n abstract findCells(\n filter: ClientCollectableSearchKeyLike,\n ): AsyncGenerator<Cell>;\n abstract isUnusable(outPointLike: OutPointLike): Promise<boolean>;\n\n // ======\n // Following methods are for requests caching and optional.\n // ======\n\n /**\n * Record known cells\n * Implement this method to enable cells query caching\n * @param _cells\n */\n async recordCells(..._cells: (CellLike | CellLike[])[]): Promise<void> {}\n /**\n * Get a known cell by out point\n * Implement this method to enable cells query caching\n * @param _outPoint\n */\n async getCell(_outPoint: OutPointLike): Promise<Cell | undefined> {\n return;\n }\n\n /**\n * Record known transaction responses.\n * Implement this method to enable transactions query caching\n * @param _transactions\n */\n async recordTransactionResponses(\n ..._transactions: (\n ClientTransactionResponseLike | ClientTransactionResponseLike[]\n )[]\n ): Promise<void> {}\n /**\n * Get a known transaction response by hash\n * Implement this method to enable transactions query caching\n * @param _txHash\n */\n async getTransactionResponse(\n _txHash: HexLike,\n ): Promise<ClientTransactionResponse | undefined> {\n return;\n }\n /**\n * Record known transactions.\n * @param transactions\n */\n async recordTransactions(\n ...transactions: (TransactionLike | TransactionLike[])[]\n ): Promise<void> {\n return this.recordTransactionResponses(\n transactions.flat().map((transaction) => ({\n transaction,\n status: \"unknown\",\n })),\n );\n }\n /**\n * Get a known transaction by hash\n * @param txHash\n */\n async getTransaction(txHash: HexLike): Promise<Transaction | undefined> {\n return (await this.getTransactionResponse(txHash))?.transaction;\n }\n\n /**\n * Record known block headers.\n * Implement this method to enable block headers query caching\n * @param _headers\n */\n async recordHeaders(\n ..._headers: (ClientBlockHeaderLike | ClientBlockHeaderLike[])[]\n ): Promise<void> {}\n /**\n * Get a known block header by hash\n * Implement this method to enable block headers query caching\n * @param _hash\n */\n async getHeaderByHash(\n _hash: HexLike,\n ): Promise<ClientBlockHeader | undefined> {\n return;\n }\n /**\n * Get a known block header by number\n * Implement this method to enable block headers query caching\n * @param _number\n */\n async getHeaderByNumber(\n _number: NumLike,\n ): Promise<ClientBlockHeader | undefined> {\n return;\n }\n\n /**\n * Record known blocks.\n * Implement this method to enable blocks query caching\n * @param _blocks\n */\n async recordBlocks(\n ..._blocks: (ClientBlockLike | ClientBlockLike[])[]\n ): Promise<void> {}\n /**\n * Get a known block header by hash\n * Implement this method to enable block headers query caching\n * @param _hash\n */\n async getBlockByHash(_hash: HexLike): Promise<ClientBlock | undefined> {\n return;\n }\n /**\n * Get a known block header by number\n * Implement this method to enable block headers query caching\n * @param _number\n */\n async getBlockByNumber(_number: NumLike): Promise<ClientBlock | undefined> {\n return;\n }\n\n /**\n * Checks if a block header is considered confirmed.\n * The default implementation compares the header's timestamp against the current time\n * and a configured confirmation time. Override this method for custom confirmation logic.\n * @param header\n */\n hasHeaderConfirmed(header: ClientBlockHeader): boolean {\n return (\n numFrom(Date.now()) - header.timestamp >= DEFAULT_CONFIRMED_BLOCK_TIME\n );\n }\n}\n","import { Cell, CellLike, OutPoint, OutPointLike } from \"../../ckb/index.js\";\nimport { hexFrom, HexLike } from \"../../hex/index.js\";\nimport { Num, numFrom, NumLike } from \"../../num/index.js\";\nimport { ClientCollectableSearchKeyLike } from \"../clientTypes.advanced.js\";\nimport {\n ClientBlock,\n ClientBlockHeader,\n ClientBlockHeaderLike,\n ClientBlockLike,\n ClientTransactionResponse,\n ClientTransactionResponseLike,\n} from \"../clientTypes.js\";\nimport { ClientCache } from \"./cache.js\";\nimport {\n CellRecord,\n DEFAULT_CONFIRMED_BLOCK_TIME,\n filterCell,\n MapLru,\n} from \"./memory.advanced.js\";\n\nexport class ClientCacheMemory extends ClientCache {\n /**\n * OutPoint => [isLive, Cell | OutPoint]\n */\n private readonly cells: MapLru<string, CellRecord>;\n\n /**\n * TX Hash => Transaction Response\n */\n private readonly knownTransactions: MapLru<string, ClientTransactionResponse>;\n\n /**\n * Block Number => Block Hash\n */\n private readonly knownBlockHashes: MapLru<Num, string>;\n\n /**\n * Block Hash => Block Header / Full Block\n */\n private readonly knownBlocks: MapLru<\n string,\n Pick<ClientBlock, \"header\"> | ClientBlock\n >;\n\n private readonly confirmedBlockTime;\n\n /**\n * @param maxCells - Maximum number of cells to store in the cache. Defaults to 512.\n * @param maxTxs - Maximum number of transactions to store in the cache. Defaults to 256.\n * @param maxBlocks - Maximum number of blocks to store in the cache. Defaults to 128.\n * @param confirmedBlockTimeLike - Time in milliseconds after which a block is considered confirmed.\n * Defaults to DEFAULT_CONFIRMED_BLOCK_TIME (50 blocks * 10s).\n */\n constructor(\n private readonly maxCells = 512,\n private readonly maxTxs = 256,\n private readonly maxBlocks = 128,\n confirmedBlockTimeLike: NumLike = DEFAULT_CONFIRMED_BLOCK_TIME,\n ) {\n super();\n\n this.cells = new MapLru<string, CellRecord>(this.maxCells);\n this.knownTransactions = new MapLru<string, ClientTransactionResponse>(\n this.maxTxs,\n );\n this.knownBlockHashes = new MapLru<Num, string>(this.maxBlocks);\n this.knownBlocks = new MapLru<\n string,\n Pick<ClientBlock, \"header\"> | ClientBlock\n >(this.maxBlocks);\n\n this.confirmedBlockTime = numFrom(confirmedBlockTimeLike);\n }\n\n async markUsableNoCache(\n ...cellLikes: (CellLike | CellLike[])[]\n ): Promise<void> {\n cellLikes.flat().forEach((cellLike) => {\n const cell = Cell.from(cellLike).clone();\n const outPointStr = hexFrom(cell.outPoint.toBytes());\n\n this.cells.set(outPointStr, [true, cell]);\n });\n }\n\n async markUnusable(\n ...outPointLikes: (OutPointLike | OutPointLike[])[]\n ): Promise<void> {\n outPointLikes.flat().forEach((outPointLike) => {\n const outPoint = OutPoint.from(outPointLike);\n const outPointStr = hexFrom(outPoint.toBytes());\n\n const existed = this.cells.get(outPointStr);\n if (existed) {\n existed[0] = false;\n return;\n }\n this.cells.set(outPointStr, [false, { outPoint }]);\n });\n }\n\n async clear(): Promise<void> {\n this.cells.clear();\n this.knownTransactions.clear();\n }\n\n async *findCells(\n keyLike: ClientCollectableSearchKeyLike,\n ): AsyncGenerator<Cell> {\n for (const [key, [isLive, cell]] of this.cells.entries()) {\n if (!isLive) {\n continue;\n }\n if (!filterCell(keyLike, cell)) {\n continue;\n }\n\n this.cells.get(key);\n yield cell.clone();\n }\n }\n\n async isUnusable(outPointLike: OutPointLike): Promise<boolean> {\n const outPoint = OutPoint.from(outPointLike);\n\n return !(this.cells.get(hexFrom(outPoint.toBytes()))?.[0] ?? true);\n }\n\n async recordCells(...cells: (CellLike | CellLike[])[]): Promise<void> {\n cells.flat().map((cellLike) => {\n const cell = Cell.from(cellLike);\n const outPointStr = hexFrom(cell.outPoint.toBytes());\n\n if (this.cells.get(outPointStr)) {\n return;\n }\n this.cells.set(outPointStr, [undefined, cell]);\n });\n }\n async getCell(outPointLike: OutPointLike): Promise<Cell | undefined> {\n const outPoint = OutPoint.from(outPointLike);\n\n const cell = this.cells.get(hexFrom(outPoint.toBytes()))?.[1];\n if (cell && cell.cellOutput && cell.outputData) {\n return Cell.from((cell as Cell).clone());\n }\n }\n\n async recordTransactionResponses(\n ...transactions: (\n ClientTransactionResponseLike | ClientTransactionResponseLike[]\n )[]\n ): Promise<void> {\n transactions.flat().map((txLike) => {\n const tx = ClientTransactionResponse.from(txLike);\n this.knownTransactions.set(tx.transaction.hash(), tx);\n });\n }\n async getTransactionResponse(\n txHashLike: HexLike,\n ): Promise<ClientTransactionResponse | undefined> {\n const txHash = hexFrom(txHashLike);\n return this.knownTransactions.get(txHash)?.clone();\n }\n\n async recordHeaders(\n ...headers: (ClientBlockHeaderLike | ClientBlockHeaderLike[])[]\n ): Promise<void> {\n headers.flat().map((headerLike) => {\n const header = ClientBlockHeader.from(headerLike);\n\n this.knownBlockHashes.set(header.number, header.hash);\n\n const existed = this.knownBlocks.get(header.hash);\n if (existed) {\n return;\n }\n this.knownBlocks.set(header.hash, { header });\n });\n }\n async getHeaderByHash(\n hashLike: HexLike,\n ): Promise<ClientBlockHeader | undefined> {\n const hash = hexFrom(hashLike);\n const block = this.knownBlocks.get(hash);\n if (block) {\n this.knownBlockHashes.get(block.header.number); // For LRU\n }\n return block?.header;\n }\n async getHeaderByNumber(\n numberLike: NumLike,\n ): Promise<ClientBlockHeader | undefined> {\n const number = numFrom(numberLike);\n\n const hash = this.knownBlockHashes.get(number);\n if (!hash) {\n return;\n }\n return this.getHeaderByHash(hash);\n }\n\n async recordBlocks(\n ...blocks: (ClientBlockLike | ClientBlockLike[])[]\n ): Promise<void> {\n blocks.flat().map((blockLike) => {\n const block = ClientBlock.from(blockLike);\n\n this.knownBlockHashes.set(block.header.number, block.header.hash);\n this.knownBlocks.set(block.header.hash, block);\n });\n }\n async getBlockByHash(hashLike: HexLike): Promise<ClientBlock | undefined> {\n const hash = hexFrom(hashLike);\n const block = this.knownBlocks.get(hash);\n if (block) {\n this.knownBlockHashes.get(block.header.number); // For LRU\n if (\"transactions\" in block) {\n return block;\n }\n }\n return;\n }\n async getBlockByNumber(\n numberLike: NumLike,\n ): Promise<ClientBlock | undefined> {\n const number = numFrom(numberLike);\n\n const hash = this.knownBlockHashes.get(number);\n if (!hash) {\n return;\n }\n return this.getBlockByHash(hash);\n }\n\n hasHeaderConfirmed(header: ClientBlockHeader): boolean {\n return numFrom(Date.now()) - header.timestamp >= this.confirmedBlockTime;\n }\n}\n","import {\n Cell,\n CellDep,\n OutPoint,\n OutPointLike,\n ScriptLike,\n Transaction,\n TransactionLike,\n} from \"../ckb/index.js\";\nimport { Zero } from \"../fixedPoint/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../hex/index.js\";\nimport { Num, NumLike, numFrom, numMax, numMin } from \"../num/index.js\";\nimport { reduceAsync, sleep } from \"../utils/index.js\";\nimport { ClientCache } from \"./cache/index.js\";\nimport { ClientCacheMemory } from \"./cache/memory.js\";\nimport {\n ClientCollectableSearchKeyLike,\n DEFAULT_MAX_FEE_RATE,\n DEFAULT_MIN_FEE_RATE,\n} from \"./clientTypes.advanced.js\";\nimport {\n CellDepInfo,\n CellDepInfoLike,\n ClientBlock,\n ClientBlockHeader,\n ClientFindCellsResponse,\n ClientFindTransactionsGroupedResponse,\n ClientFindTransactionsResponse,\n ClientIndexerSearchKey,\n ClientIndexerSearchKeyLike,\n ClientIndexerSearchKeyTransactionLike,\n ClientTransactionResponse,\n ErrorClientMaxFeeRateExceeded,\n ErrorClientWaitTransactionTimeout,\n OutputsValidator,\n ScriptInfo,\n} from \"./clientTypes.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * @public\n */\nexport abstract class Client {\n public cache: ClientCache;\n\n constructor(config?: { cache?: ClientCache }) {\n this.cache = config?.cache ?? new ClientCacheMemory();\n }\n\n abstract get url(): string;\n abstract get addressPrefix(): string;\n\n /**\n * Get the deployment info for a well-known CKB script.\n * Returns the cell deps and type script info needed to use the script.\n *\n * @param script - The KnownScript enum value.\n * @returns Script info including cellDeps and type hash.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n *\n * // Get xUDT script deployment info\n * const xudtInfo = await client.getKnownScript(ccc.KnownScript.XUdt);\n * console.log(`xUDT cellDeps:`, xudtInfo.cellDeps);\n *\n * // Build an xUDT type script\n * const xudtType = await ccc.Script.fromKnownScript(\n * client,\n * ccc.KnownScript.XUdt,\n * \"0xOWNER_LOCK_HASH...\",\n * );\n * ```\n */\n abstract getKnownScript(script: KnownScript): Promise<ScriptInfo>;\n\n abstract getFeeRateStatistics(\n blockRange?: NumLike,\n ): Promise<{ mean: Num; median: Num }>;\n /**\n * Get the recommended transaction fee rate based on recent blocks.\n * Returns the median fee rate, clamped between min and max fee rates.\n *\n * @param blockRange - Number of recent blocks to analyze.\n * @param options - Optional max fee rate cap.\n * @returns The recommended fee rate in Shannons per KB.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const feeRate = await client.getFeeRate();\n * console.log(`Current fee rate: ${feeRate} Shannons/KB`);\n * ```\n */\n async getFeeRate(\n blockRange?: NumLike,\n options?: { maxFeeRate?: NumLike },\n ): Promise<Num> {\n const feeRate = numMax(\n (await this.getFeeRateStatistics(blockRange)).median,\n DEFAULT_MIN_FEE_RATE,\n );\n\n const maxFeeRate = numFrom(options?.maxFeeRate ?? DEFAULT_MAX_FEE_RATE);\n if (maxFeeRate === Zero) {\n return feeRate;\n }\n\n return numMin(feeRate, maxFeeRate);\n }\n\n /**\n * Get the latest block number (tip) of the chain.\n *\n * @returns The current tip block number.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const tipBlockNumber = await client.getTip();\n * console.log(`Current block height: ${tipBlockNumber}`);\n * ```\n */\n abstract getTip(): Promise<Num>;\n\n /**\n * Get the header of the latest block.\n *\n * @param verbosity - Verbosity level (0 for hex, 1 for object).\n * @returns The tip block header.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const header = await client.getTipHeader();\n * console.log(`Block #${header.number}, hash: ${header.hash}`);\n * ```\n */\n abstract getTipHeader(verbosity?: number | null): Promise<ClientBlockHeader>;\n abstract getBlockByNumberNoCache(\n blockNumber: NumLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined>;\n abstract getBlockByHashNoCache(\n blockHash: HexLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined>;\n abstract getHeaderByNumberNoCache(\n blockNumber: NumLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined>;\n abstract getHeaderByHashNoCache(\n blockHash: HexLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined>;\n async getBlockByNumber(\n blockNumber: NumLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined> {\n const block = await this.cache.getBlockByNumber(blockNumber);\n if (block) {\n return block;\n }\n\n const res = await this.getBlockByNumberNoCache(\n blockNumber,\n verbosity,\n withCycles,\n );\n if (res && this.cache.hasHeaderConfirmed(res.header)) {\n await this.cache.recordBlocks(res);\n }\n return res;\n }\n async getBlockByHash(\n blockHash: HexLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined> {\n const block = await this.cache.getBlockByHash(blockHash);\n if (block) {\n return block;\n }\n\n const res = await this.getBlockByHashNoCache(\n blockHash,\n verbosity,\n withCycles,\n );\n if (res && this.cache.hasHeaderConfirmed(res.header)) {\n await this.cache.recordBlocks(res);\n }\n return res;\n }\n async getHeaderByNumber(\n blockNumber: NumLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined> {\n const header = await this.cache.getHeaderByNumber(blockNumber);\n if (header) {\n return header;\n }\n\n const res = await this.getHeaderByNumberNoCache(blockNumber, verbosity);\n if (res && this.cache.hasHeaderConfirmed(res)) {\n await this.cache.recordHeaders(res);\n }\n return res;\n }\n async getHeaderByHash(\n blockHash: HexLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined> {\n const header = await this.cache.getHeaderByHash(blockHash);\n if (header) {\n return header;\n }\n\n const res = await this.getHeaderByHashNoCache(blockHash, verbosity);\n if (res && this.cache.hasHeaderConfirmed(res)) {\n await this.cache.recordHeaders(res);\n }\n return res;\n }\n\n abstract estimateCycles(transaction: TransactionLike): Promise<Num>;\n abstract sendTransactionDry(\n transaction: TransactionLike,\n validator?: OutputsValidator,\n ): Promise<Num>;\n\n abstract sendTransactionNoCache(\n transaction: TransactionLike,\n validator?: OutputsValidator,\n ): Promise<Hex>;\n abstract getTransactionNoCache(\n txHash: HexLike,\n ): Promise<ClientTransactionResponse | undefined>;\n\n /**\n * Get a cell by its out point.\n * The cell will be cached if it is found.\n *\n * @param outPointLike - The out point of the cell to get.\n * @returns The cell if it exists, otherwise undefined.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const cell = await client.getCell({\n * txHash: \"0xTX_HASH...\",\n * index: 0,\n * });\n * if (cell) {\n * console.log(`Capacity: ${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`);\n * console.log(`Lock: ${cell.cellOutput.lock.codeHash}`);\n * console.log(`Data: ${cell.outputData}`);\n * }\n * ```\n */\n async getCell(outPointLike: OutPointLike): Promise<Cell | undefined> {\n const outPoint = OutPoint.from(outPointLike);\n const cached = await this.cache.getCell(outPoint);\n\n if (cached) {\n return cached;\n }\n\n const transaction = await this.getTransaction(outPoint.txHash);\n if (!transaction) {\n return;\n }\n const output = transaction.transaction.getOutput(outPoint.index);\n if (!output) {\n return;\n }\n\n const cell = Cell.from({\n ...output,\n outPoint,\n });\n await this.cache.recordCells(cell);\n return cell;\n }\n\n async getCellWithHeader(\n outPointLike: OutPointLike,\n ): Promise<{ cell: Cell; header?: ClientBlockHeader } | undefined> {\n const outPoint = OutPoint.from(outPointLike);\n\n const res = await this.getTransactionWithHeader(outPoint.txHash);\n if (!res) {\n return;\n }\n const { transaction, header } = res;\n\n const output = transaction.transaction.getOutput(outPoint.index);\n if (!output) {\n return;\n }\n\n const cell = Cell.from({\n ...output,\n outPoint,\n });\n await this.cache.recordCells(cell);\n return { cell, header };\n }\n\n abstract getCellLiveNoCache(\n outPointLike: OutPointLike,\n withData?: boolean | null,\n includeTxPool?: boolean | null,\n ): Promise<Cell | undefined>;\n /**\n * Get a live (unspent) cell by its out point.\n * Unlike getCell(), this verifies the cell is still live on-chain.\n *\n * @param outPointLike - The out point of the cell.\n * @param withData - Whether to include cell data.\n * @param includeTxPool - Whether to include cells in the transaction pool.\n * @returns The live cell, or undefined if spent or not found.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const cell = await client.getCellLive(\n * { txHash: \"0xTX_HASH...\", index: 0 },\n * true, // include data\n * true, // include tx pool\n * );\n * if (cell) {\n * console.log(\"Cell is still live!\");\n * } else {\n * console.log(\"Cell has been spent or does not exist.\");\n * }\n * ```\n */\n async getCellLive(\n outPointLike: OutPointLike,\n withData?: boolean | null,\n includeTxPool?: boolean | null,\n ): Promise<Cell | undefined> {\n const cell = await this.getCellLiveNoCache(\n outPointLike,\n withData,\n includeTxPool,\n );\n if (withData && cell) {\n await this.cache.recordCells(cell);\n }\n return cell;\n }\n\n abstract findCellsPagedNoCache(\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindCellsResponse>;\n /**\n * Find cells with pagination support.\n * Returns one page of results at a time with a cursor for the next page.\n *\n * @param key - The indexer search key.\n * @param order - Sort order (\"asc\" or \"desc\").\n * @param limit - Maximum cells per page.\n * @param after - Cursor from previous page for pagination.\n * @returns A page of cells with a cursor for the next page.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // Get first page of cells\n * const page1 = await client.findCellsPaged({\n * script: lock,\n * scriptType: \"lock\",\n * }, \"asc\", 20);\n * console.log(`Found ${page1.cells.length} cells`);\n *\n * // Get next page\n * if (page1.cells.length === 20) {\n * const page2 = await client.findCellsPaged(\n * { script: lock, scriptType: \"lock\" },\n * \"asc\", 20, page1.lastCursor,\n * );\n * }\n * ```\n */\n async findCellsPaged(\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindCellsResponse> {\n const res = await this.findCellsPagedNoCache(key, order, limit, after);\n await this.cache.recordCells(res.cells);\n return res;\n }\n\n async *findCellsOnChain(\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n let last: string | undefined = undefined;\n\n while (true) {\n const { cells, lastCursor } = await this.findCellsPaged(\n key,\n order,\n limit,\n last,\n );\n for (const cell of cells) {\n yield cell;\n }\n if (cells.length === 0 || cells.length < limit) {\n return;\n }\n last = lastCursor;\n }\n }\n\n /**\n * Find cells by search key designed for collectable cells.\n * The result also includes cached cells, the order param only works for cells fetched from RPC.\n *\n * @param keyLike - The search key.\n * @returns A async generator for yielding cells.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // Find all cells owned by a lock script\n * for await (const cell of client.findCells({\n * script: lock,\n * scriptType: \"lock\",\n * scriptSearchMode: \"exact\",\n * withData: true,\n * })) {\n * console.log(`Cell: ${cell.outPoint.txHash}:${cell.outPoint.index}`);\n * console.log(`Capacity: ${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`);\n * }\n * ```\n */\n async *findCells(\n keyLike: ClientCollectableSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n const key = ClientIndexerSearchKey.from(keyLike);\n const foundedOutPoints = [];\n\n for await (const cell of this.cache.findCells(key)) {\n foundedOutPoints.push(cell.outPoint);\n yield cell;\n }\n\n for await (const cell of this.findCellsOnChain(key, order, limit)) {\n if (\n (await this.cache.isUnusable(cell.outPoint)) ||\n foundedOutPoints.some((founded) => founded.eq(cell.outPoint))\n ) {\n continue;\n }\n\n yield cell;\n }\n }\n\n /**\n * Find cells by lock script, optionally filtered by type script.\n *\n * @param lock - The lock script to search by.\n * @param type - Optional type script filter.\n * @param withData - Whether to include cell data (default: true).\n * @param order - Sort order by block number (\"asc\" or \"desc\").\n * @param limit - Page size for each RPC call (default: 10).\n * @returns An async generator yielding matching cells.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // Find all cells belonging to this address\n * for await (const cell of client.findCellsByLock(lock)) {\n * console.log(`${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`);\n * }\n *\n * // Find only xUDT cells belonging to this address\n * const xudtType = await ccc.Script.fromKnownScript(\n * client, ccc.KnownScript.XUdt, \"0xOWNER_LOCK_HASH...\",\n * );\n * for await (const cell of client.findCellsByLock(lock, xudtType)) {\n * console.log(`UDT cell found`);\n * }\n * ```\n */\n findCellsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n withData = true,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n return this.findCells(\n {\n script: lock,\n scriptType: \"lock\",\n scriptSearchMode: \"exact\",\n filter: {\n script: type,\n },\n withData,\n },\n order,\n limit,\n );\n }\n\n /**\n * Find cells by type script.\n *\n * @param type - The type script to search by.\n * @param withData - Whether to include cell data (default: true).\n * @param order - Sort order by block number.\n * @param limit - Page size for each RPC call (default: 10).\n * @returns An async generator yielding matching cells.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * // Find all xUDT cells of a specific token\n * const xudtType = await ccc.Script.fromKnownScript(\n * client, ccc.KnownScript.XUdt, \"0xOWNER_LOCK_HASH...\",\n * );\n * for await (const cell of client.findCellsByType(xudtType)) {\n * console.log(`Token cell: ${cell.outPoint.txHash}:${cell.outPoint.index}`);\n * }\n * ```\n */\n findCellsByType(\n type: ScriptLike,\n withData = true,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n return this.findCells(\n {\n script: type,\n scriptType: \"type\",\n scriptSearchMode: \"exact\",\n withData,\n },\n order,\n limit,\n );\n }\n\n async findSingletonCellByType(\n type: ScriptLike,\n withData = true,\n ): Promise<Cell | undefined> {\n for await (const cell of this.findCellsByType(\n type,\n withData,\n undefined,\n 1,\n )) {\n return cell;\n }\n }\n\n /**\n * Resolve cell dependency info into concrete CellDep objects.\n * If a CellDepInfo specifies a type script, the actual deployed cell is located on-chain.\n *\n * @param cellDepsInfoLike - One or more CellDepInfo or arrays of CellDepInfo.\n * @returns Resolved CellDep array ready to be added to a transaction.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const xudtInfo = await client.getKnownScript(ccc.KnownScript.XUdt);\n * const cellDeps = await client.getCellDeps(xudtInfo.cellDeps);\n * // cellDeps can be added to a transaction:\n * // tx.cellDeps.push(...cellDeps);\n * ```\n */\n async getCellDeps(\n ...cellDepsInfoLike: (CellDepInfoLike | CellDepInfoLike[])[]\n ): Promise<CellDep[]> {\n return Promise.all(\n cellDepsInfoLike.flat().map(async (infoLike) => {\n const { cellDep, type } = CellDepInfo.from(infoLike);\n if (type === undefined) {\n return cellDep;\n }\n const found = await this.findSingletonCellByType(type);\n if (!found) {\n return cellDep;\n }\n\n return CellDep.from({\n outPoint: found.outPoint,\n depType: cellDep.depType,\n });\n }),\n );\n }\n\n abstract findTransactionsPaged(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction: true;\n },\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindTransactionsGroupedResponse>;\n abstract findTransactionsPaged(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction?: false | null;\n },\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindTransactionsResponse>;\n abstract findTransactionsPaged(\n key: ClientIndexerSearchKeyTransactionLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<\n ClientFindTransactionsResponse | ClientFindTransactionsGroupedResponse\n >;\n\n findTransactions(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction: true;\n },\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n findTransactions(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction?: false | null;\n },\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n findTransactions(\n key: ClientIndexerSearchKeyTransactionLike,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n async *findTransactions(\n key: ClientIndexerSearchKeyTransactionLike,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n let last: string | undefined = undefined;\n\n while (true) {\n const {\n transactions,\n lastCursor,\n }:\n ClientFindTransactionsResponse | ClientFindTransactionsGroupedResponse =\n await this.findTransactionsPaged(key, order, limit, last);\n for (const tx of transactions) {\n yield tx;\n }\n if (transactions.length === 0 || transactions.length < limit) {\n return;\n }\n last = lastCursor;\n }\n }\n\n /**\n * Find transactions related to a lock script, optionally filtered by type script.\n *\n * @param lock - The lock script to search by.\n * @param type - Optional type script filter.\n * @param groupByTransaction - If true, group results by transaction.\n * @param order - Sort order by block number.\n * @param limit - Page size per RPC call.\n * @returns An async generator yielding transaction records.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // List all transactions related to an address (grouped)\n * for await (const txRecord of client.findTransactionsByLock(lock, null, true)) {\n * console.log(`TX: ${txRecord.txHash}, Block: ${txRecord.blockNumber}`);\n * }\n * ```\n */\n findTransactionsByLock(\n lock: ScriptLike,\n type: ScriptLike | undefined | null,\n groupByTransaction: true,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n findTransactionsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n groupByTransaction?: false | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n findTransactionsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n findTransactionsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n return this.findTransactions(\n {\n script: lock,\n scriptType: \"lock\",\n scriptSearchMode: \"exact\",\n filter: {\n script: type,\n },\n groupByTransaction,\n },\n order,\n limit,\n );\n }\n\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction: true,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction?: false | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n return this.findTransactions(\n {\n script: type,\n scriptType: \"type\",\n scriptSearchMode: \"exact\",\n groupByTransaction,\n },\n order,\n limit,\n );\n }\n\n abstract getCellsCapacity(key: ClientIndexerSearchKeyLike): Promise<Num>;\n\n /**\n * Get the total CKB balance of a single lock script.\n * Only counts cells with no type script and no data (pure CKB capacity cells).\n *\n * @param lock - The lock script to query balance for.\n * @returns The total capacity in Shannons as a bigint.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const { script: lock } = await ccc.Address.fromString(\n * \"ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsq...\",\n * client,\n * );\n * const balance = await client.getBalanceSingle(lock);\n * console.log(`Balance: ${ccc.fixedPointToString(balance)} CKB`);\n * ```\n */\n async getBalanceSingle(lock: ScriptLike): Promise<Num> {\n return this.getCellsCapacity({\n script: lock,\n scriptType: \"lock\",\n scriptSearchMode: \"exact\",\n filter: {\n scriptLenRange: [0, 1],\n outputDataLenRange: [0, 1],\n },\n });\n }\n\n /**\n * Get the total CKB balance across multiple lock scripts.\n * Sums the balance from each lock script.\n *\n * @param locks - An array of lock scripts to query.\n * @returns The combined total capacity in Shannons as a bigint.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const signer = new ccc.SignerCkbPrivateKey(client, \"0x...\");\n * await signer.connect();\n *\n * const locks = await signer.getRecommendedAddressObj()\n * .then(({ script }) => [script]);\n * const totalBalance = await client.getBalance(locks);\n * console.log(`Total: ${ccc.fixedPointToString(totalBalance)} CKB`);\n * ```\n */\n async getBalance(locks: ScriptLike[]): Promise<Num> {\n return reduceAsync(\n locks,\n async (acc, lock) => acc + (await this.getBalanceSingle(lock)),\n Zero,\n );\n }\n\n /**\n * Send a signed transaction to the CKB network.\n * Validates the fee rate against the maximum before sending.\n *\n * @param transaction - The transaction to send.\n * @param validator - Optional outputs validator (\"passthrough\" or \"well_known_scripts_only\").\n * @param options - Optional configuration including maxFeeRate.\n * @returns The transaction hash.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const signer = new ccc.SignerCkbPrivateKey(client, \"0x...\");\n * await signer.connect();\n *\n * const tx = ccc.Transaction.from({\n * outputs: [{ capacity: ccc.fixedPointFrom(100), lock: receiverLock }],\n * });\n * await tx.completeInputsByCapacity(signer);\n * await tx.completeFeeBy(signer);\n *\n * // Usually you call signer.sendTransaction(tx) which signs then sends.\n * // client.sendTransaction expects an already-signed transaction.\n * const txHash = await client.sendTransaction(tx);\n * ```\n */\n async sendTransaction(\n transaction: TransactionLike,\n validator?: OutputsValidator,\n options?: { maxFeeRate?: NumLike },\n ): Promise<Hex> {\n const tx = Transaction.from(transaction);\n\n const maxFeeRate = numFrom(options?.maxFeeRate ?? DEFAULT_MAX_FEE_RATE);\n const feeRate = await tx.getFeeRate(this);\n if (maxFeeRate > Zero && feeRate > maxFeeRate) {\n throw new ErrorClientMaxFeeRateExceeded(maxFeeRate, feeRate);\n }\n\n const txHash = await this.sendTransactionNoCache(tx, validator);\n\n await this.cache.markTransactions(tx);\n return txHash;\n }\n\n /**\n * Get a transaction by its hash, including its status and block info.\n *\n * @param txHashLike - The transaction hash to look up.\n * @returns The transaction response with status, or undefined if not found.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * const txResponse = await client.getTransaction(\"0xTX_HASH...\");\n * if (txResponse) {\n * console.log(`Status: ${txResponse.status}`);\n * console.log(`Block: ${txResponse.blockNumber}`);\n * console.log(`Outputs: ${txResponse.transaction.outputs.length}`);\n * }\n * ```\n */\n async getTransaction(\n txHashLike: HexLike,\n ): Promise<ClientTransactionResponse | undefined> {\n const txHash = hexFrom(txHashLike);\n const res = await this.getTransactionNoCache(txHash);\n if (res) {\n await this.cache.recordTransactionResponses(res);\n return res;\n }\n\n return this.cache.getTransactionResponse(txHash);\n }\n\n /**\n * This method gets specified transaction with its block header (if existed).\n * This is mainly for caching because we need the header to test if we can safely trust the cached tx status.\n * @param txHashLike\n */\n async getTransactionWithHeader(\n txHashLike: HexLike,\n ): Promise<\n | { transaction: ClientTransactionResponse; header?: ClientBlockHeader }\n | undefined\n > {\n const txHash = hexFrom(txHashLike);\n const tx = await this.cache.getTransactionResponse(txHash);\n if (tx?.blockHash) {\n const header = await this.getHeaderByHash(tx.blockHash);\n if (header && this.cache.hasHeaderConfirmed(header)) {\n return {\n transaction: tx,\n header,\n };\n }\n }\n\n const res = await this.getTransactionNoCache(txHash);\n if (!res) {\n return;\n }\n\n await this.cache.recordTransactionResponses(res);\n return {\n transaction: res,\n header: res.blockHash\n ? await this.getHeaderByHash(res.blockHash)\n : undefined,\n };\n }\n\n /**\n * Wait for a transaction to be confirmed on-chain.\n * Polls the node until the transaction reaches the specified confirmation depth.\n *\n * @param txHash - The transaction hash to wait for.\n * @param confirmations - Number of block confirmations to wait for (default: 0 = committed).\n * @param timeout - Maximum wait time in milliseconds (default: 60000).\n * @param interval - Polling interval in milliseconds (default: 2000).\n * @returns The transaction response once confirmed, or throws on timeout.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const client = new ccc.ClientPublicTestnet();\n * // Wait for transaction to be committed (0 confirmations)\n * const tx = await client.waitTransaction(\"0xTX_HASH...\");\n * console.log(`Confirmed in block: ${tx?.blockNumber}`);\n *\n * // Wait for 4 confirmations with 2 minute timeout\n * const confirmedTx = await client.waitTransaction(\n * \"0xTX_HASH...\",\n * 4, // confirmations\n * 120000, // timeout: 2 minutes\n * );\n * ```\n */\n async waitTransaction(\n txHash: HexLike,\n confirmations: number = 0,\n timeout: number = 60000,\n interval: number = 2000,\n ): Promise<ClientTransactionResponse | undefined> {\n const startTime = Date.now();\n let tx: ClientTransactionResponse | undefined;\n\n const getTx = async () => {\n const res = await this.getTransaction(txHash);\n if (\n !res ||\n res.blockNumber == null ||\n [\"sent\", \"pending\", \"proposed\"].includes(res.status)\n ) {\n return undefined;\n }\n\n tx = res;\n return res;\n };\n\n while (true) {\n if (!tx) {\n if (await getTx()) {\n continue;\n }\n } else if (confirmations === 0) {\n return tx;\n } else if (\n (await this.getTipHeader()).number - tx.blockNumber! >=\n confirmations\n ) {\n return tx;\n }\n\n if (Date.now() - startTime + interval >= timeout) {\n throw new ErrorClientWaitTransactionTimeout(timeout);\n }\n await sleep(interval);\n }\n }\n}\n","import {\n JsonRpcPayload,\n Transport,\n TransportFallback,\n transportFromUri,\n} from \"./transports/advanced.js\";\n\n/**\n * Applies a transformation function to a value if the transformer is provided.\n *\n * @param value - The value to be transformed.\n * @param transformer - An optional transformation function.\n * @returns The transformed value if a transformer is provided, otherwise the original value.\n *\n * @example\n * ```typescript\n * const result = transform(5, (x) => x * 2); // Outputs 10\n * const resultWithoutTransformer = transform(5); // Outputs 5\n * ```\n */\nfunction transform(value: unknown, transformer?: (i: unknown) => unknown) {\n if (transformer) {\n return transformer(value);\n }\n return value;\n}\n\nexport type RequestorJsonRpcConfig = {\n fallbacks?: string[];\n timeout?: number;\n maxConcurrent?: number;\n transport?: Transport;\n};\n\nexport class RequestorJsonRpc {\n public readonly maxConcurrent?: number;\n private concurrent = 0;\n private readonly pending: (() => void)[] = [];\n\n public readonly transport: Transport;\n\n private id = 0;\n\n /**\n * Creates an instance of ClientJsonRpc.\n *\n * @param url_ - The URL of the JSON-RPC server.\n * @param timeout - The timeout for requests in milliseconds\n */\n constructor(\n private readonly url_: string,\n config?: RequestorJsonRpcConfig,\n private readonly onError?: (err: unknown) => Promise<void> | void,\n ) {\n this.maxConcurrent = config?.maxConcurrent;\n this.transport =\n config?.transport ??\n new TransportFallback(\n Array.from(\n new Set([url_, ...(config?.fallbacks ?? [])]).values(),\n (url) => transportFromUri(url, config),\n ),\n );\n }\n\n /**\n * Returns the URL of the JSON-RPC server.\n *\n * @returns The URL of the JSON-RPC server.\n */\n\n get url(): string {\n return this.url_;\n }\n\n /**\n * request a JSON-RPC method.\n *\n * @param rpcMethod - The JSON-RPC method.\n * @param params - Params for the method.\n * @param inTransformers - An array of input transformers.\n * @param outTransformer - An output transformer function.\n * @returns Method response.\n */\n async request(\n rpcMethod: string,\n params: unknown[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inTransformers?: (((_: any) => unknown) | undefined)[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outTransformer?: (_: any) => unknown,\n ): Promise<unknown> {\n const payload = this.buildPayload(\n rpcMethod,\n inTransformers\n ? await Promise.all(\n params\n .concat(\n Array.from(\n new Array(Math.max(inTransformers.length - params.length, 0)),\n ),\n )\n .map((v, i) => transform(v, inTransformers[i])),\n )\n : params,\n );\n\n try {\n return await transform(\n await this.requestPayload(payload),\n outTransformer,\n );\n } catch (err: unknown) {\n if (!this.onError) {\n throw err;\n }\n await this.onError(err);\n }\n }\n\n async requestPayload(payload: JsonRpcPayload): Promise<unknown> {\n if (\n this.maxConcurrent !== undefined &&\n this.concurrent >= this.maxConcurrent\n ) {\n const pending = new Promise<void>((resolve) =>\n this.pending.push(resolve),\n );\n await pending;\n }\n\n this.concurrent += 1;\n const res = (await this.transport.request(payload)) as {\n id: number;\n error: unknown;\n result: unknown;\n };\n this.concurrent -= 1;\n this.pending.shift()?.();\n\n if (res.id !== payload.id) {\n throw new Error(`Id mismatched, got ${res.id}, expected ${payload.id}`);\n }\n if (res.error != null) {\n throw res.error as unknown;\n }\n return res.result;\n }\n\n /**\n * Builds a JSON-RPC payload for the given method and parameters.\n *\n * @param method - The JSON-RPC method name.\n * @param req - The parameters for the JSON-RPC method.\n * @returns The JSON-RPC payload.\n */\n\n buildPayload(method: string, req: unknown[]): JsonRpcPayload {\n return {\n id: this.id++,\n method,\n params: req,\n jsonrpc: \"2.0\",\n };\n }\n}\n","import {\n Cell,\n OutPoint,\n OutPointLike,\n TransactionLike,\n} from \"../../ckb/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport {\n RequestorJsonRpc,\n RequestorJsonRpcConfig,\n} from \"../../jsonRpc/requestor.js\";\nimport { Num, NumLike, numFrom, numToHex } from \"../../num/index.js\";\nimport { apply } from \"../../utils/index.js\";\nimport { ClientCache } from \"../cache/index.js\";\nimport { Client } from \"../client.js\";\nimport {\n ClientFindCellsResponse,\n ClientIndexerSearchKeyLike,\n ClientTransactionResponse,\n ErrorClientBase,\n ErrorClientBaseLike,\n ErrorClientDuplicatedTransaction,\n ErrorClientRBFRejected,\n ErrorClientResolveUnknown,\n ErrorClientVerification,\n OutputsValidator,\n} from \"../clientTypes.js\";\nimport {\n JsonRpcBlock,\n JsonRpcBlockHeader,\n JsonRpcCellOutput,\n JsonRpcTransformers,\n} from \"./advanced.js\";\n\nconst ERROR_PARSERS: [\n string,\n (error: ErrorClientBaseLike, match: RegExpMatchArray) => ErrorClientBase,\n][] = [\n [\n \"Resolve\\\\(Unknown\\\\(OutPoint\\\\((0x.*)\\\\)\\\\)\\\\)\",\n (error, match) =>\n new ErrorClientResolveUnknown(error, OutPoint.fromBytes(match[1])),\n ],\n [\n \"Verification\\\\(Error { kind: Script, inner: TransactionScriptError { source: (Inputs|Outputs)\\\\[([0-9]*)\\\\].(Lock|Type), cause: ValidationFailure: see error code (-?[0-9])* on page https://nervosnetwork\\\\.github\\\\.io/ckb-script-error-codes/by-(type|data)-hash/(.*)\\\\.html\",\n (error, match) =>\n new ErrorClientVerification(\n error,\n match[3] === \"Lock\"\n ? \"lock\"\n : match[1] === \"Inputs\"\n ? \"inputType\"\n : \"outputType\",\n match[2],\n Number(match[4]),\n match[5] === \"data\" ? \"data\" : \"type\",\n match[6],\n ),\n ],\n [\n \"Duplicated\\\\(Byte32\\\\((0x.*)\\\\)\\\\)\",\n (error, match) => new ErrorClientDuplicatedTransaction(error, match[1]),\n ],\n [\n 'RBFRejected\\\\(\"Tx\\'s current fee is ([0-9]*), expect it to >= ([0-9]*) to replace old txs\"\\\\)',\n (error, match) => new ErrorClientRBFRejected(error, match[1], match[2]),\n ],\n];\n\nexport type ClientJsonRpcConfig = RequestorJsonRpcConfig & {\n cache?: ClientCache;\n requestor?: RequestorJsonRpc;\n};\n\n/**\n * An abstract class implementing JSON-RPC client functionality for a specific URL and timeout.\n * Provides methods for sending transactions and building JSON-RPC payloads.\n */\nexport abstract class ClientJsonRpc extends Client {\n public readonly requestor: RequestorJsonRpc;\n\n /**\n * Creates an instance of ClientJsonRpc.\n *\n * @param url_ - The URL of the JSON-RPC server.\n * @param timeout - The timeout for requests in milliseconds\n */\n\n constructor(url_: string, config?: ClientJsonRpcConfig) {\n super(config);\n\n this.requestor =\n config?.requestor ??\n new RequestorJsonRpc(url_, config, (errAny) => {\n if (\n typeof errAny !== \"object\" ||\n errAny === null ||\n !(\"data\" in errAny) ||\n typeof errAny.data !== \"string\"\n ) {\n throw errAny;\n }\n const err = errAny as ErrorClientBaseLike;\n\n for (const [regexp, builder] of ERROR_PARSERS) {\n const match = err.data.match(regexp);\n if (match) {\n throw builder(err, match);\n }\n }\n\n throw new ErrorClientBase(err);\n });\n }\n\n /**\n * Returns the URL of the JSON-RPC server.\n *\n * @returns The URL of the JSON-RPC server.\n */\n get url(): string {\n return this.requestor.url;\n }\n\n /**\n * Get fee rate statistics\n *\n * @returns Fee rate statistics\n */\n\n getFeeRateStatistics = this.buildSender(\n \"get_fee_rate_statistics\",\n [(n: NumLike) => apply(numFrom, n)],\n ({ mean, median }: { mean: NumLike; median: NumLike }) => ({\n mean: numFrom(mean),\n median: numFrom(median),\n }),\n ) as Client[\"getFeeRateStatistics\"];\n\n /**\n * Get tip block number\n *\n * @returns Tip block number\n */\n\n getTip = this.buildSender(\n \"get_tip_block_number\",\n [],\n numFrom,\n ) as () => Promise<Num>;\n\n /**\n * Get tip block header\n *\n * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)\n * @returns BlockHeader\n */\n getTipHeader = this.buildSender(\n \"get_tip_header\",\n [],\n (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),\n ) as Client[\"getTipHeader\"];\n\n /**\n * Get block by block number\n *\n * @param blockNumber - The block number.\n * @param verbosity - result format which allows 0 and 2. (Optional, the default is 2.)\n * @param withCycles - whether the return cycles of block transactions. (Optional, default false.)\n * @returns Block\n */\n getBlockByNumberNoCache = this.buildSender(\n \"get_block_by_number\",\n [(v: NumLike) => numToHex(numFrom(v))],\n (b: JsonRpcBlock) => apply(JsonRpcTransformers.blockTo, b),\n ) as Client[\"getBlockByNumberNoCache\"];\n\n /**\n * Get block by block hash\n *\n * @param blockHash - The block hash.\n * @param verbosity - result format which allows 0 and 2. (Optional, the default is 2.)\n * @param withCycles - whether the return cycles of block transactions. (Optional, default false.)\n * @returns Block\n */\n getBlockByHashNoCache = this.buildSender(\n \"get_block\",\n [hexFrom],\n (b: JsonRpcBlock) => apply(JsonRpcTransformers.blockTo, b),\n ) as Client[\"getBlockByHashNoCache\"];\n\n /**\n * Get header by block number\n *\n * @param blockNumber - The block number.\n * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)\n * @returns BlockHeader\n */\n getHeaderByNumberNoCache = this.buildSender(\n \"get_header_by_number\",\n [(v: NumLike) => numToHex(numFrom(v))],\n (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),\n ) as Client[\"getHeaderByNumberNoCache\"];\n\n /**\n * Get header by block hash\n *\n * @param blockHash - The block hash.\n * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)\n * @returns BlockHeader\n */\n getHeaderByHashNoCache = this.buildSender(\n \"get_header\",\n [hexFrom],\n (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),\n ) as Client[\"getHeaderByHashNoCache\"];\n\n /**\n * Estimate cycles of a transaction.\n *\n * @param transaction - The transaction to estimate.\n * @returns Consumed cycles\n */\n estimateCycles = this.buildSender(\n \"estimate_cycles\",\n [JsonRpcTransformers.transactionFrom],\n ({ cycles }: { cycles: NumLike }) => numFrom(cycles),\n ) as Client[\"estimateCycles\"];\n\n /**\n * Test a transaction.\n *\n * @param transaction - The transaction to test.\n * @param validator - \"passthrough\": Disable validation. \"well_known_scripts_only\": Only accept well known scripts in the transaction.\n * @returns Consumed cycles\n */\n\n sendTransactionDry = this.buildSender(\n \"test_tx_pool_accept\",\n [JsonRpcTransformers.transactionFrom],\n ({ cycles }: { cycles: NumLike }) => numFrom(cycles),\n ) as Client[\"sendTransactionDry\"];\n\n /**\n * Send a transaction to node.\n *\n * @param transaction - The transaction to send.\n * @param validator - \"passthrough\": Disable validation. \"well_known_scripts_only\": Only accept well known scripts in the transaction.\n * @returns Transaction hash.\n */\n\n sendTransactionNoCache = this.buildSender(\n \"send_transaction\",\n [\n JsonRpcTransformers.transactionFrom,\n (validator?: OutputsValidator | null) => validator ?? undefined,\n ],\n hexFrom,\n ) as (\n transaction: TransactionLike,\n validator?: OutputsValidator | null,\n ) => Promise<Hex>;\n\n /**\n * Get a transaction from node.\n *\n * @param txHash - The hash of the transaction.\n * @returns The transaction with status.\n */\n\n getTransactionNoCache = this.buildSender(\n \"get_transaction\",\n [hexFrom],\n JsonRpcTransformers.transactionResponseTo,\n ) as (txHash: HexLike) => Promise<ClientTransactionResponse | undefined>;\n\n /**\n * Get a live cell from node.\n *\n * @param outPoint - The out point of the cell.\n * @param withData - Include data in the response.\n * @param includeTxPool - Include cells in the tx pool.\n * @returns The cell\n */\n getCellLiveNoCache(\n outPoint: OutPointLike,\n withData?: boolean | null,\n includeTxPool?: boolean | null,\n ) {\n return this.buildSender(\n \"get_live_cell\",\n [JsonRpcTransformers.outPointFrom],\n ({\n cell,\n }: {\n cell?: {\n output: JsonRpcCellOutput;\n data?: { content: HexLike; hash: HexLike };\n };\n }) =>\n apply(\n ({\n output,\n data,\n }: {\n output: JsonRpcCellOutput;\n data?: { content: HexLike; hash: HexLike };\n }) =>\n Cell.from({\n cellOutput: JsonRpcTransformers.cellOutputTo(output),\n outputData: data?.content ?? \"0x\",\n outPoint,\n }),\n cell,\n ),\n )(outPoint, withData ?? true, includeTxPool) as Promise<Cell | undefined>;\n }\n\n /**\n * find cells from node.\n *\n * @param key - The search key of cells.\n * @param order - The order of cells.\n * @param limit - The max return size of cells.\n * @param after - Pagination parameter.\n * @returns The found cells.\n */\n\n findCellsPagedNoCache = this.buildSender(\n \"get_cells\",\n [\n JsonRpcTransformers.indexerSearchKeyFrom,\n (order?: \"asc\" | \"desc\") => order ?? \"asc\",\n (limit?: NumLike) => numToHex(limit ?? 10),\n ],\n JsonRpcTransformers.findCellsResponseTo,\n ) as (\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ) => Promise<ClientFindCellsResponse>;\n\n /**\n * find transactions from node.\n *\n * @param key - The search key of transactions.\n * @param order - The order of transactions.\n * @param limit - The max return size of transactions.\n * @param after - Pagination parameter.\n * @returns The found transactions.\n */\n\n findTransactionsPaged = this.buildSender(\n \"get_transactions\",\n [\n JsonRpcTransformers.indexerSearchKeyTransactionFrom,\n (order?: \"asc\" | \"desc\") => order ?? \"asc\",\n (limit?: NumLike) => numToHex(limit ?? 10),\n ],\n JsonRpcTransformers.findTransactionsResponseTo,\n ) as Client[\"findTransactionsPaged\"];\n\n /**\n * get cells capacity from node.\n *\n * @param key - The search key of cells.\n * @returns The sum of cells capacity.\n */\n\n getCellsCapacity = this.buildSender(\n \"get_cells_capacity\",\n [JsonRpcTransformers.indexerSearchKeyFrom],\n ({ capacity }: { capacity: NumLike }) => numFrom(capacity),\n ) as (key: ClientIndexerSearchKeyLike) => Promise<Num>;\n\n /**\n * Builds a sender function for a JSON-RPC method.\n *\n * @param rpcMethod - The JSON-RPC method.\n * @param inTransformers - An array of input transformers.\n * @param outTransformer - An output transformer function.\n * @returns A function that sends a JSON-RPC request with the given method and transformed parameters.\n */\n\n buildSender(\n rpcMethod: Parameters<RequestorJsonRpc[\"request\"]>[0],\n inTransformers?: Parameters<RequestorJsonRpc[\"request\"]>[2],\n outTransformer?: Parameters<RequestorJsonRpc[\"request\"]>[3],\n ): (...req: unknown[]) => Promise<unknown> {\n return async (...req: unknown[]) => {\n return this.requestor.request(\n rpcMethod,\n req,\n inTransformers,\n outTransformer,\n );\n };\n }\n}\n","import WebSocket from \"isomorphic-ws\";\nimport { MAINNET_SCRIPTS } from \"./clientPublicMainnet.advanced.js\";\nimport { ScriptInfo, ScriptInfoLike } from \"./clientTypes.js\";\nimport { ClientJsonRpc, ClientJsonRpcConfig } from \"./jsonRpc/index.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * @public\n */\nexport class ClientPublicMainnet extends ClientJsonRpc {\n constructor(\n private readonly config?: ClientJsonRpcConfig & {\n url?: string;\n scripts?: Record<KnownScript, ScriptInfoLike | undefined>;\n },\n ) {\n const hasWebSocket = typeof WebSocket !== \"undefined\";\n super(\n config?.url ??\n (hasWebSocket\n ? \"wss://mainnet.ckb.dev/ws\"\n : \"https://mainnet.ckb.dev/\"),\n {\n ...config,\n fallbacks:\n config?.fallbacks ??\n (hasWebSocket\n ? [\n \"wss://mainnet.ckb.dev/ws\",\n \"https://mainnet.ckb.dev/\",\n \"https://mainnet.ckbapp.dev/\",\n ]\n : [\"https://mainnet.ckb.dev/\", \"https://mainnet.ckbapp.dev/\"]),\n },\n );\n }\n\n get scripts(): Record<KnownScript, ScriptInfoLike | undefined> {\n return this.config?.scripts ?? MAINNET_SCRIPTS;\n }\n\n get addressPrefix(): string {\n return \"ckb\";\n }\n\n async getKnownScript(script: KnownScript): Promise<ScriptInfo> {\n const found = this.scripts[script];\n if (!found) {\n throw new Error(\n `No script information was found for ${script} on ${this.addressPrefix}`,\n );\n }\n return ScriptInfo.from(found);\n }\n}\n","import WebSocket from \"isomorphic-ws\";\nimport { TESTNET_SCRIPTS } from \"./clientPublicTestnet.advanced.js\";\nimport { ScriptInfo, ScriptInfoLike } from \"./clientTypes.js\";\nimport { ClientJsonRpc, ClientJsonRpcConfig } from \"./jsonRpc/index.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * @public\n */\nexport class ClientPublicTestnet extends ClientJsonRpc {\n constructor(\n private readonly config?: ClientJsonRpcConfig & {\n url?: string;\n scripts?: Record<KnownScript, ScriptInfoLike | undefined>;\n },\n ) {\n const hasWebSocket = typeof WebSocket !== \"undefined\";\n super(\n config?.url ??\n (hasWebSocket\n ? \"wss://testnet.ckb.dev/ws\"\n : \"https://testnet.ckb.dev/\"),\n {\n ...config,\n fallbacks:\n config?.fallbacks ??\n (hasWebSocket\n ? [\n \"wss://testnet.ckb.dev/ws\",\n \"https://testnet.ckb.dev/\",\n \"https://testnet.ckbapp.dev/\",\n ]\n : [\"https://testnet.ckb.dev/\", \"https://testnet.ckbapp.dev/\"]),\n },\n );\n }\n\n get scripts(): Record<KnownScript, ScriptInfoLike | undefined> {\n return this.config?.scripts ?? TESTNET_SCRIPTS;\n }\n\n get addressPrefix(): string {\n return \"ckt\";\n }\n\n async getKnownScript(script: KnownScript): Promise<ScriptInfo> {\n const found = this.scripts[script];\n if (!found) {\n throw new Error(\n `No script information was found for ${script} on ${this.addressPrefix}`,\n );\n }\n return ScriptInfo.from(found);\n }\n}\n","import { hashCkb } from \"../hasher/hasherCkb.js\";\nimport { Hex } from \"../hex/index.js\";\nimport { NumLike, numLeToBytes } from \"../num/index.js\";\nimport { CellInput, CellInputLike } from \"./transaction.js\";\n\n/**\n * Computes the Type ID hash of the given data.\n * @public\n *\n * @param cellInputLike - The first cell input of the transaction.\n * @param outputIndex - The output index of the Type ID cell.\n * @returns The hexadecimal string representation of the hash.\n *\n * @example\n * ```typescript\n * const hash = hashTypeId(cellInput, outputIndex); // Outputs something like \"0x...\"\n * ```\n */\n\nexport function hashTypeId(\n cellInputLike: CellInputLike,\n outputIndex: NumLike,\n): Hex {\n return hashCkb(\n CellInput.from(cellInputLike).toBytes(),\n numLeToBytes(outputIndex, 8),\n );\n}\n","import { bech32m } from \"bech32\";\nimport { bytesConcat, bytesFrom } from \"../bytes/index.js\";\nimport { Script, ScriptLike, hashTypeToBytes } from \"../ckb/index.js\";\nimport { Client, KnownScript } from \"../client/index.js\";\nimport { HexLike } from \"../hex/index.js\";\nimport {\n ADDRESS_BECH32_LIMIT,\n AddressFormat,\n addressFromPayload,\n addressPayloadFromString,\n} from \"./address.advanced.js\";\n\n/**\n * @public\n */\nexport type AddressLike = {\n script: ScriptLike;\n prefix: string;\n};\n\n/**\n * Represents a ckb address with associated script and prefix.\n * @public\n */\nexport class Address {\n /**\n * Creates an instance of Address.\n *\n * @param script - The script associated with the address.\n * @param prefix - The address prefix.\n */\n constructor(\n public script: Script,\n public prefix: string,\n ) {}\n\n /**\n * Creates an Address instance from an AddressLike object.\n *\n * @param address - An AddressLike object or an instance of Address.\n * @returns An Address instance.\n */\n\n static from(address: AddressLike): Address {\n if (address instanceof Address) {\n return address;\n }\n\n return new Address(Script.from(address.script), address.prefix);\n }\n\n /**\n * Creates an Address instance from an address string.\n *\n * @param address - The address string to parse.\n * @param clients - A Client instance or a record of Client instances keyed by prefix.\n * @returns A promise that resolves to an Address instance.\n *\n * @throws Will throw an error if the address prefix is unknown or mismatched.\n */\n\n static async fromString(\n address: string,\n clients: Client | Record<string, Client>,\n ): Promise<Address> {\n const { prefix, format, payload } = addressPayloadFromString(address);\n\n const client = (clients as Record<string, Client>)[prefix] ?? clients;\n if (!client) {\n throw new Error(`Unknown address prefix ${prefix}`);\n }\n const expectedPrefix = client.addressPrefix;\n if (expectedPrefix !== prefix) {\n throw new Error(\n `Unknown address prefix ${prefix}, expected ${expectedPrefix}`,\n );\n }\n\n return Address.from(\n await addressFromPayload(prefix, format, payload, client),\n );\n }\n\n /**\n * Creates an Address instance from a script and client.\n *\n * @param script - The script-like object.\n * @param client - The client instance used to fetch the address prefix.\n * @returns A promise that resolves to an Address instance.\n */\n\n static fromScript(script: ScriptLike, client: Client): Address {\n return Address.from({ script, prefix: client.addressPrefix });\n }\n\n static async fromKnownScript(\n client: Client,\n script: KnownScript,\n args: HexLike,\n ): Promise<Address> {\n return Address.from({\n script: await Script.fromKnownScript(client, script, args),\n prefix: client.addressPrefix,\n });\n }\n\n /**\n * Converts the Address instance to a string.\n *\n * @returns The address as a string.\n */\n\n toString(): string {\n const data = bytesConcat(\n [AddressFormat.Full],\n bytesFrom(this.script.codeHash),\n hashTypeToBytes(this.script.hashType),\n bytesFrom(this.script.args),\n );\n\n return bech32m.encode(\n this.prefix,\n bech32m.toWords(data),\n ADDRESS_BECH32_LIMIT,\n );\n }\n}\n","import { ctr } from \"@noble/ciphers/aes.js\";\nimport { scryptAsync } from \"@noble/hashes/scrypt.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { randomBytes } from \"@noble/hashes/utils.js\";\nimport { Bytes, BytesLike, bytesConcat, bytesFrom } from \"../bytes/index.js\";\nimport { hexFrom } from \"../hex/index.js\";\n\n// The parameter r (\"blockSize\")\nconst DEFAULT_SCRYPT_PARAM_R = 8;\n// The parallelization parameter p\nconst DEFAULT_SCRYPT_PARAM_P = 1;\n// The CPU/Memory cost parameter N\nconst DEFAULT_SCRYPT_PARAM_N = 262144;\n\nfunction mac(derivedKey: Bytes, cipherText: Bytes) {\n return hexFrom(\n keccak_256(bytesConcat(derivedKey.slice(16, 32), cipherText)),\n ).slice(2);\n}\n\n/**\n * @public\n */\nexport async function keystoreEncrypt(\n privateKeyLike: BytesLike,\n chainCodeLike: BytesLike,\n password: string,\n): Promise<{\n id: string;\n crypto: {\n ciphertext: string;\n cipherparams: {\n iv: string;\n };\n cipher: string;\n kdf: string;\n kdfparams: {\n n: number;\n r: number;\n p: number;\n dklen: number;\n salt: string;\n };\n mac: string;\n };\n}> {\n const salt = randomBytes(32);\n const iv = randomBytes(16);\n const kdfparams = {\n dklen: 32,\n salt: hexFrom(salt).slice(2),\n n: DEFAULT_SCRYPT_PARAM_N,\n r: DEFAULT_SCRYPT_PARAM_R,\n p: DEFAULT_SCRYPT_PARAM_P,\n };\n const derivedKey = await scryptAsync(bytesFrom(password, \"utf8\"), salt, {\n N: kdfparams.n,\n r: kdfparams.r,\n p: kdfparams.p,\n dkLen: kdfparams.dklen,\n });\n const cipher = ctr(\n derivedKey.slice(0, 16),\n iv.map((v) => v),\n );\n const ciphertext = cipher.encrypt(\n bytesConcat(bytesFrom(privateKeyLike), bytesFrom(chainCodeLike)),\n );\n\n return {\n id: hexFrom(randomBytes(16)).slice(2),\n crypto: {\n ciphertext: hexFrom(ciphertext).slice(2),\n cipherparams: {\n iv: hexFrom(iv).slice(2),\n },\n cipher: \"aes-128-ctr\",\n kdf: \"scrypt\",\n kdfparams,\n mac: mac(derivedKey, ciphertext),\n },\n };\n}\n\n/**\n * @public\n */\nexport async function keystoreDecrypt(\n keystore: unknown,\n password: string,\n): Promise<{\n privateKey: Bytes;\n chainCode: Bytes;\n}> {\n if (\n typeof keystore !== \"object\" ||\n keystore === null ||\n !(\"crypto\" in keystore)\n ) {\n throw Error(\"Invalid keystore\");\n }\n const crypto = keystore.crypto;\n\n if (\n typeof crypto !== \"object\" ||\n crypto === null ||\n !(\"kdfparams\" in crypto) ||\n !(\"ciphertext\" in crypto) ||\n typeof crypto.ciphertext !== \"string\" ||\n !(\"mac\" in crypto) ||\n typeof crypto.mac !== \"string\" ||\n !(\"cipherparams\" in crypto) ||\n typeof crypto.cipherparams !== \"object\" ||\n crypto.cipherparams === null ||\n !(\"iv\" in crypto.cipherparams) ||\n typeof crypto.cipherparams.iv !== \"string\"\n ) {\n throw Error(\"Invalid crypto\");\n }\n const kdfparams = crypto.kdfparams;\n\n if (\n typeof kdfparams !== \"object\" ||\n kdfparams === null ||\n !(\"n\" in kdfparams) ||\n typeof kdfparams.n !== \"number\" ||\n !(\"r\" in kdfparams) ||\n typeof kdfparams.r !== \"number\" ||\n !(\"p\" in kdfparams) ||\n typeof kdfparams.p !== \"number\" ||\n !(\"dklen\" in kdfparams) ||\n typeof kdfparams.dklen !== \"number\" ||\n !(\"salt\" in kdfparams) ||\n typeof kdfparams.salt !== \"string\"\n ) {\n throw Error(\"Invalid kdfparams\");\n }\n\n const derivedKey = await scryptAsync(\n bytesFrom(password, \"utf8\"),\n bytesFrom(kdfparams.salt),\n {\n N: kdfparams.n,\n r: kdfparams.r,\n p: kdfparams.p,\n dkLen: kdfparams.dklen,\n },\n );\n const ciphertext = bytesFrom(crypto.ciphertext);\n if (mac(derivedKey, ciphertext) !== crypto.mac) {\n throw Error(\"Invalid password\");\n }\n const cipher = ctr(\n derivedKey.slice(0, 16),\n bytesFrom(crypto.cipherparams.iv),\n );\n const result = cipher.decrypt(ciphertext);\n return {\n privateKey: result.slice(0, 32),\n chainCode: result.slice(32),\n };\n}\n","import { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\n\n/**\n * Options for signing a PSBT (Partially Signed Bitcoin Transaction)\n */\nexport type SignPsbtOptionsLike = {\n /**\n * Whether to finalize the PSBT after signing.\n * Default is true.\n */\n autoFinalized?: boolean;\n /**\n * Array of inputs to sign\n */\n inputsToSign?: InputToSignLike[];\n};\n\nexport class SignPsbtOptions {\n constructor(\n public autoFinalized: boolean,\n public inputsToSign: InputToSign[],\n ) {}\n\n static from(options?: SignPsbtOptionsLike): SignPsbtOptions {\n if (options instanceof SignPsbtOptions) {\n return options;\n }\n return new SignPsbtOptions(\n options?.autoFinalized ?? true,\n options?.inputsToSign?.map((i) => InputToSign.from(i)) ?? [],\n );\n }\n}\n\n/**\n * Specification for an input to sign in a PSBT.\n * Must specify at least one of: address or pubkey.\n */\nexport type InputToSignLike = {\n /**\n * Which input to sign (index in the PSBT inputs array)\n */\n index: number;\n /**\n * (Optional) Sighash types to use for signing.\n */\n sighashTypes?: number[];\n /**\n * (Optional) When signing and unlocking Taproot addresses, the tweakSigner is used by default\n * for signature generation. Setting this to true allows for signing with the original private key.\n * Default value is false.\n */\n disableTweakSigner?: boolean;\n} & (\n | {\n /**\n * The address whose corresponding private key to use for signing.\n */\n address: string;\n /**\n * The public key whose corresponding private key to use for signing.\n */\n publicKey?: HexLike;\n }\n | {\n /**\n * The address whose corresponding private key to use for signing.\n */\n address?: string;\n /**\n * The public key whose corresponding private key to use for signing.\n */\n publicKey: HexLike;\n }\n);\n\nexport class InputToSign {\n constructor(\n public index: number,\n public sighashTypes?: number[],\n public disableTweakSigner?: boolean,\n public address?: string,\n public publicKey?: Hex,\n ) {}\n\n static from(input: InputToSignLike): InputToSign {\n if (input instanceof InputToSign) {\n return input;\n }\n return new InputToSign(\n input.index,\n input.sighashTypes,\n input.disableTweakSigner,\n input.address,\n input.publicKey ? hexFrom(input.publicKey) : undefined,\n );\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport bs58check from \"bs58check\";\nimport { Bytes, bytesConcat, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\nimport { numFrom, numLeToBytes, NumLike } from \"../../num/index.js\";\n\n/**\n * Encodes a number into a variable-length byte array according to the Bitcoin protocol.\n * This format is used for encoding lengths of data, such as script lengths.\n *\n * @param len - The number to encode. Can be a NumLike.\n * @returns The encoded length as a Bytes.\n * @public\n */\nexport function btcVarLengthBytesFrom(len: NumLike): Bytes {\n const num = numFrom(len);\n\n return num < 0xfd\n ? numLeToBytes(num, 1)\n : num <= 0xffff\n ? bytesConcat([0xfd], numLeToBytes(num, 2))\n : num <= 0xffffffff\n ? bytesConcat([0xfe], numLeToBytes(num, 4))\n : bytesConcat([0xff], numLeToBytes(num, 8));\n}\n\n/**\n * Computes the message hash for Bitcoin ECDSA signatures.\n * This function follows the Bitcoin message signing standard, which involves\n * prefixing the message with a magic string and its length, then double SHA256 hashing the result.\n *\n * @param message - The message to be hashed. Can be a string or BytesLike.\n * @param messagePrefix - Optional. A custom prefix to use instead of the default \"\\u0018Bitcoin Signed Message:\\n\".\n * @returns The Bitcoin hash of the prefixed message as Bytes.\n * @public\n */\nexport function messageHashBtcEcdsa(\n message: string | BytesLike,\n messagePrefix?: string | BytesLike,\n): Bytes {\n const prefix = messagePrefix ?? \"\\u0018Bitcoin Signed Message:\\n\";\n const rawPrefix: Bytes =\n typeof prefix === \"string\" ? bytesFrom(prefix, \"utf8\") : bytesFrom(prefix);\n const rawMsg: Bytes =\n typeof message === \"string\"\n ? bytesFrom(message, \"utf8\")\n : bytesFrom(message);\n\n return sha256(\n sha256(\n bytesConcat(rawPrefix, btcVarLengthBytesFrom(rawMsg.length), rawMsg),\n ),\n );\n}\n\n/**\n * @public\n */\nexport function btcEcdsaPublicKeyHash(publicKey: BytesLike): Bytes {\n return ripemd160(sha256(bytesFrom(publicKey)));\n}\n\n/**\n * @public\n */\nexport function btcP2pkhAddressFromPublicKey(\n publicKey: BytesLike,\n network: number,\n): string {\n return bs58check.encode(\n bytesConcat([network], btcEcdsaPublicKeyHash(publicKey)),\n );\n}\n\n/**\n * @public\n */\nexport function btcPublicKeyFromP2pkhAddress(address: string): Hex {\n return hexFrom(bs58check.decode(address).slice(1));\n}\n\n/**\n * @public\n */\nexport function verifyMessageBtcEcdsa(\n message: string | BytesLike,\n signature: string,\n publicKey: string,\n): boolean {\n const challenge =\n typeof message === \"string\" ? message : hexFrom(message).slice(2);\n\n const rawSign = bytesFrom(signature, \"base64\").slice(1);\n\n return secp256k1.verify(\n bytesFrom(rawSign),\n messageHashBtcEcdsa(challenge),\n bytesFrom(publicKey),\n { prehash: false },\n );\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { bytesConcat, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { hashCkb } from \"../../hasher/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\n\nexport const SECP256K1_SIGNATURE_LENGTH = 65;\n\n/**\n * Sign a message using Secp256k1.\n *\n * @param message - The message to sign.\n * @param privateKey - The private key.\n * @returns The signature.\n * @public\n */\nexport function signMessageSecp256k1(\n message: BytesLike,\n privateKey: BytesLike,\n): Hex {\n const signature = secp256k1.sign(bytesFrom(message), bytesFrom(privateKey), {\n format: \"recovered\",\n prehash: false,\n });\n return hexFrom(bytesConcat(signature.slice(1), signature.slice(0, 1)));\n}\n\n/**\n * Verify a message using Secp256k1.\n *\n * @param message - The message to verify.\n * @param signature - The signature.\n * @param publicKey - The public key.\n * @returns True if the signature is valid, false otherwise.\n * @public\n */\nexport function verifyMessageSecp256k1(\n message: BytesLike,\n signature: BytesLike,\n publicKey: BytesLike,\n): boolean {\n const signatureBytes = bytesFrom(signature);\n return secp256k1.verify(\n bytesConcat(signatureBytes.slice(64), signatureBytes.slice(0, 64)),\n bytesFrom(message),\n bytesFrom(publicKey),\n { format: \"recovered\", prehash: false },\n );\n}\n\n/**\n * Recover the public key from a Secp256k1 signature.\n *\n * @param message - The message.\n * @param signature - The signature.\n * @returns The recovered public key.\n * @public\n */\nexport function recoverMessageSecp256k1(\n message: BytesLike,\n signature: BytesLike,\n): Hex {\n const signatureBytes = bytesFrom(signature);\n return hexFrom(\n secp256k1.recoverPublicKey(\n bytesConcat(signatureBytes.slice(64), signatureBytes.slice(0, 64)),\n bytesFrom(message),\n { prehash: false },\n ),\n );\n}\n\n/**\n * @public\n */\nexport function messageHashCkbSecp256k1(message: string | BytesLike): Hex {\n const msg = typeof message === \"string\" ? message : hexFrom(message);\n const buffer = bytesFrom(`Nervos Message:${msg}`, \"utf8\");\n return hashCkb(buffer);\n}\n\n/**\n * @public\n */\nexport function verifyMessageCkbSecp256k1(\n message: string | BytesLike,\n signature: string,\n publicKey: string,\n): boolean {\n return verifyMessageSecp256k1(\n messageHashCkbSecp256k1(message),\n signature,\n publicKey,\n );\n}\n","import { verifySignature } from \"@joyid/ckb\";\nimport { BytesLike } from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\n\n/**\n * @public\n */\nexport function verifyMessageJoyId(\n message: string | BytesLike,\n signature: string,\n identity: string,\n): Promise<boolean> {\n const challenge =\n typeof message === \"string\" ? message : hexFrom(message).slice(2);\n const { publicKey, keyType } = JSON.parse(identity) as {\n publicKey: string;\n keyType: string;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return verifySignature({\n challenge,\n pubkey: publicKey,\n keyType,\n ...JSON.parse(signature),\n });\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { Bytes, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport {\n btcEcdsaPublicKeyHash,\n btcPublicKeyFromP2pkhAddress,\n messageHashBtcEcdsa,\n} from \"../btc/verify.js\";\n\n/**\n * Computes the message hash for Dogecoin ECDSA signatures.\n * This function follows the Dogecoin message signing standard, which involves\n * prefixing the message with a magic string and its length, then double SHA256 hashing the result.\n *\n * @param message - The message to be hashed. Can be a string or BytesLike.\n * @param messagePrefix - Optional. A custom prefix to use instead of the default \"\\x19Dogecoin Signed Message:\\n\".\n * @returns The Dogecoin hash of the prefixed message as Bytes.\n * @public\n */\nexport function messageHashDogeEcdsa(\n message: string | BytesLike,\n messagePrefix?: string | BytesLike,\n): Bytes {\n return messageHashBtcEcdsa(\n message,\n messagePrefix ?? \"\\x19Dogecoin Signed Message:\\n\",\n );\n}\n\n/**\n * @public\n */\nexport function verifyMessageDogeEcdsa(\n message: string | BytesLike,\n signature: string,\n address: string,\n): boolean {\n const challenge =\n typeof message === \"string\" ? message : hexFrom(message).slice(2);\n const signatureBytes = bytesFrom(signature, \"base64\");\n signatureBytes[0] -= 31;\n\n return (\n btcPublicKeyFromP2pkhAddress(address) ===\n hexFrom(\n btcEcdsaPublicKeyHash(\n secp256k1.recoverPublicKey(\n signatureBytes,\n messageHashDogeEcdsa(challenge),\n { prehash: false },\n ),\n ),\n )\n );\n}\n","import { verifyMessage } from \"ethers\";\nimport { BytesLike, bytesFrom } from \"../../bytes/index.js\";\n\n/**\n * @public\n */\nexport function verifyMessageEvmPersonal(\n message: string | BytesLike,\n signature: string,\n address: string,\n): boolean {\n return (\n address.toLowerCase() ===\n verifyMessage(\n typeof message === \"string\" ? message : bytesFrom(message),\n signature,\n ).toLowerCase()\n );\n}\n","import { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bech32 } from \"bech32\";\nimport { Bytes, BytesLike, bytesFrom } from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { NostrEvent } from \"./signerNostr.js\";\n\n/**\n * @public\n */\nexport function buildNostrEventFromMessage(\n message: string | BytesLike,\n): NostrEvent {\n if (typeof message === \"string\") {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const event = JSON.parse(message);\n if (\n typeof event === \"object\" &&\n typeof event.created_at === \"number\" &&\n typeof event.kind === \"number\" &&\n typeof event.content === \"string\" &&\n Array.isArray(event.tags) &&\n (event.tags as unknown[]).every(\n (tag) =>\n Array.isArray(tag) &&\n (tag as unknown[]).every((v) => typeof v === \"string\"),\n )\n ) {\n return event as NostrEvent;\n }\n } catch (_) {}\n }\n\n return {\n kind: 23335,\n created_at: 0,\n content: typeof message === \"string\" ? message : hexFrom(message),\n tags: [],\n };\n}\n\nexport function nostrEventHash(event: NostrEvent): Bytes {\n const serialized = JSON.stringify([\n 0,\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n ]);\n\n return sha256(bytesFrom(serialized, \"utf8\"));\n}\n\nexport function verifyMessageNostrEvent(\n message: string | BytesLike,\n signature: string,\n address: string,\n): boolean {\n const { words } = bech32.decode(address);\n const pubkey = hexFrom(bech32.fromWords(words)).slice(2);\n\n const event = buildNostrEventFromMessage(message);\n const eventHash = nostrEventHash({ ...event, pubkey });\n\n try {\n return schnorr.verify(bytesFrom(signature), eventHash, bytesFrom(pubkey));\n } catch (_) {\n return false;\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { ClientCollectableSearchKeyFilterLike } from \"../../advancedBarrel.js\";\nimport { BytesLike } from \"../../bytes/index.js\";\nimport { Cell, Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport {\n Client,\n ClientFindTransactionsGroupedResponse,\n ClientFindTransactionsResponse,\n ClientIndexerSearchKeyFilterLike,\n} from \"../../client/index.js\";\nimport { Hex } from \"../../hex/index.js\";\nimport { Num } from \"../../num/index.js\";\nimport { verifyMessageBtcEcdsa } from \"../btc/verify.js\";\nimport { verifyMessageCkbSecp256k1 } from \"../ckb/secp256k1Signing.js\";\nimport { verifyMessageJoyId } from \"../ckb/verifyJoyId.js\";\nimport { verifyMessageDogeEcdsa } from \"../doge/verify.js\";\nimport { verifyMessageEvmPersonal } from \"../evm/verify.js\";\nimport { verifyMessageNostrEvent } from \"../nostr/verify.js\";\n\n/**\n * @public\n */\nexport enum SignerSignType {\n Unknown = \"Unknown\",\n BtcEcdsa = \"BtcEcdsa\",\n EvmPersonal = \"EvmPersonal\",\n JoyId = \"JoyId\",\n NostrEvent = \"NostrEvent\",\n CkbSecp256k1 = \"CkbSecp256k1\",\n DogeEcdsa = \"DogeEcdsa\",\n}\n\n/**\n * An enumeration of signer display types in wallet.\n * @public\n */\nexport enum SignerType {\n EVM = \"EVM\",\n BTC = \"BTC\",\n CKB = \"CKB\",\n Nostr = \"Nostr\",\n Doge = \"Doge\",\n}\n\n/**\n * @public\n */\nexport type NetworkPreference = {\n addressPrefix: string;\n signerType: SignerType;\n /**\n * Wallet signers should check if the wallet is using preferred networks.\n * If not, try to switch to the first preferred network.\n * If non preferred, let users choose what they want.\n * BTC: // They made a mess...\n * btc\n * btcTestnet\n * btcTestnet4 // UTXO Global\n * btcSignet // OKX & UTXO Global\n * fractalBtc // UniSat\n */\n network: string;\n};\n\n/**\n * @public\n */\nexport class Signature {\n constructor(\n public signature: string,\n public identity: string,\n public signType: SignerSignType,\n ) {}\n}\n\n/**\n * An abstract class representing a generic signer.\n * This class provides methods to connect, get addresses, and sign transactions.\n * @public\n */\nexport abstract class Signer {\n constructor(protected client_: Client) {}\n\n abstract get type(): SignerType;\n abstract get signType(): SignerSignType;\n\n get client(): Client {\n return this.client_;\n }\n\n // Returns the preference if we need to switch network\n // undefined otherwise\n matchNetworkPreference(\n preferences: NetworkPreference[],\n currentNetwork: string | undefined,\n ): NetworkPreference | undefined {\n if (\n currentNetwork !== undefined &&\n preferences.some(\n ({ signerType, addressPrefix, network }) =>\n signerType === this.type &&\n addressPrefix === this.client.addressPrefix &&\n network === currentNetwork,\n )\n ) {\n return;\n }\n return preferences.find(\n ({ signerType, addressPrefix }) =>\n signerType === this.type && addressPrefix === this.client.addressPrefix,\n );\n }\n\n static async verifyMessage(\n message: string | BytesLike,\n signature: Signature,\n ): Promise<boolean> {\n switch (signature.signType) {\n case SignerSignType.EvmPersonal:\n return verifyMessageEvmPersonal(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.BtcEcdsa:\n return verifyMessageBtcEcdsa(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.JoyId:\n return verifyMessageJoyId(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.NostrEvent:\n return verifyMessageNostrEvent(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.CkbSecp256k1:\n return verifyMessageCkbSecp256k1(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.DogeEcdsa:\n return verifyMessageDogeEcdsa(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.Unknown:\n throw new Error(\"Unknown signer sign type\");\n }\n }\n\n /**\n * Connects to the signer.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n abstract connect(): Promise<void>;\n\n /**\n * Register a listener to be called when this signer is replaced.\n *\n * @returns A function for unregister\n */\n onReplaced(_: () => void): () => void {\n return () => {};\n }\n\n /**\n * Disconnects to the signer.\n *\n * @returns A promise that resolves when the signer is disconnected.\n */\n async disconnect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n abstract isConnected(): Promise<boolean>;\n\n /**\n * Gets the internal address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n abstract getInternalAddress(): Promise<string>;\n\n /**\n * Gets the identity for verifying signature, usually it's address\n *\n * @returns A promise that resolves to a string representing the identity\n */\n async getIdentity(): Promise<string> {\n return this.getInternalAddress();\n }\n\n /**\n * Gets an array of Address objects associated with the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n abstract getAddressObjs(): Promise<Address[]>;\n\n /**\n * Gets the recommended Address object for the signer.\n *\n * @param _preference - Optional preference parameter.\n * @returns A promise that resolves to the recommended Address object.\n */\n async getRecommendedAddressObj(_preference?: unknown): Promise<Address> {\n return (await this.getAddressObjs())[0];\n }\n\n /**\n * Gets the recommended address for the signer as a string.\n *\n * @param preference - Optional preference parameter.\n * @returns A promise that resolves to the recommended address as a string.\n */\n async getRecommendedAddress(preference?: unknown): Promise<string> {\n return (await this.getRecommendedAddressObj(preference)).toString();\n }\n\n /**\n * Gets an array of addresses associated with the signer as strings.\n *\n * @returns A promise that resolves to an array of addresses as strings.\n */\n async getAddresses(): Promise<string[]> {\n return this.getAddressObjs().then((addresses) =>\n addresses.map((address) => address.toString()),\n );\n }\n\n /**\n * Find cells of this signer\n *\n * @param filter - The filter for the search key.\n * @param withData - Whether to include cell data in the response.\n * @param order - The order of the returned cells, can be \"asc\" or \"desc\".\n * @param limit - The maximum number of cells for every querying chunk.\n * @returns A async generator that yields all matching cells\n */\n async *findCellsOnChain(\n filter: ClientIndexerSearchKeyFilterLike,\n withData?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<Cell> {\n const scripts = await this.getAddressObjs();\n for (const { script } of scripts) {\n for await (const cell of this.client.findCellsOnChain(\n {\n script,\n scriptType: \"lock\",\n filter,\n scriptSearchMode: \"exact\",\n withData,\n },\n order,\n limit,\n )) {\n yield cell;\n }\n }\n }\n\n /**\n * Find cells of this signer\n *\n * @returns A async generator that yields all matches cells\n */\n async *findCells(\n filter: ClientCollectableSearchKeyFilterLike,\n withData?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<Cell> {\n const scripts = await this.getAddressObjs();\n for (const { script } of scripts) {\n for await (const cell of this.client.findCells(\n {\n script,\n scriptType: \"lock\",\n filter,\n scriptSearchMode: \"exact\",\n withData,\n },\n order,\n limit,\n )) {\n yield cell;\n }\n }\n }\n\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction?: false | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction: true,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n async *findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n const scripts = await this.getAddressObjs();\n for (const { script } of scripts) {\n for await (const transaction of this.client.findTransactions(\n {\n script,\n scriptType: \"lock\",\n filter,\n scriptSearchMode: \"exact\",\n groupByTransaction,\n },\n order,\n limit,\n )) {\n yield transaction;\n }\n }\n }\n\n /**\n * Gets balance of all addresses\n *\n * @returns A promise that resolves to the balance\n */\n async getBalance(): Promise<Num> {\n return this.client.getBalance(\n (await this.getAddressObjs()).map(({ script }) => script),\n );\n }\n\n /**\n * Signs a message.\n *\n * @param message - The message to sign, as a string or BytesLike object.\n * @returns A promise that resolves to the signature info.\n * @throws Will throw an error if not implemented.\n */\n async signMessage(message: string | BytesLike): Promise<Signature> {\n return {\n signature: await this.signMessageRaw(message),\n identity: await this.getIdentity(),\n signType: this.signType,\n };\n }\n\n /**\n * Signs a message and returns signature only. This method is not implemented and should be overridden by subclasses.\n *\n * @param _ - The message to sign, as a string or BytesLike object.\n * @returns A promise that resolves to the signature as a string.\n * @throws Will throw an error if not implemented.\n */\n signMessageRaw(_: string | BytesLike): Promise<string> {\n throw Error(\"Signer.signMessageRaw not implemented\");\n }\n\n /**\n * Verify a signature.\n *\n * @param message - The original message.\n * @param signature - The signature to verify.\n * @returns A promise that resolves to the verification result.\n * @throws Will throw an error if not implemented.\n */\n async verifyMessage(\n message: string | BytesLike,\n signature: string | Signature,\n ): Promise<boolean> {\n if (typeof signature === \"string\") {\n return Signer.verifyMessage(message, {\n signType: this.signType,\n signature,\n identity: await this.getIdentity(),\n });\n }\n\n if (\n signature.identity !== (await this.getIdentity()) ||\n ![SignerSignType.Unknown, this.signType].includes(signature.signType)\n ) {\n return false;\n }\n\n return Signer.verifyMessage(message, signature);\n }\n\n /**\n * Sends a transaction after signing it.\n *\n * @param tx - The transaction to send, represented as a TransactionLike object.\n * @returns A promise that resolves to the transaction hash as a Hex string.\n */\n async sendTransaction(tx: TransactionLike): Promise<Hex> {\n return this.client.sendTransaction(await this.signTransaction(tx));\n }\n\n /**\n * Signs a transaction.\n *\n * @param tx - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to the signed Transaction object.\n */\n async signTransaction(tx: TransactionLike): Promise<Transaction> {\n const preparedTx = await this.prepareTransaction(tx);\n return this.signOnlyTransaction(preparedTx);\n }\n\n /**\n * Prepares a transaction before signing.\n * This method can be overridden by subclasses to perform any necessary steps,\n * such as adding cell dependencies or witnesses, before the transaction is signed.\n * The default implementation converts the {@link TransactionLike} object to a {@link Transaction} object\n * without modification.\n *\n * @remarks\n * Note that this default implementation does not add any cell dependencies or dummy witnesses.\n * This may lead to an underestimation of transaction size and fees if used with methods\n * like `Transaction.completeFee`. Subclasses for signers that are intended to sign\n * transactions should override this method to perform necessary preparations.\n *\n * @param tx - The transaction to prepare.\n * @returns A promise that resolves to the prepared {@link Transaction} object.\n */\n async prepareTransaction(tx: TransactionLike): Promise<Transaction> {\n return Transaction.from(tx);\n }\n\n /**\n * Signs a transaction without preparing information for it. This method is not implemented and should be overridden by subclasses.\n *\n * @param _ - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to the signed Transaction object.\n * @throws Will throw an error if not implemented.\n */\n signOnlyTransaction(_: TransactionLike): Promise<Transaction> {\n throw Error(\"Signer.signOnlyTransaction not implemented\");\n }\n}\n\n/**\n * An abstract class representing a multisig signer.\n * @public\n */\nexport abstract class SignerMultisig extends Signer {\n /**\n * Get the number of members in the multisig script.\n * @returns The number of members.\n */\n abstract getMemberCount(): Promise<number>;\n\n /**\n * Get the threshold of the multisig script.\n * @returns The threshold.\n */\n abstract getMemberThreshold(): Promise<number>;\n\n /**\n * Get the count of required member of the multisig script.\n * @returns The must match count.\n */\n abstract getMemberRequiredCount(): Promise<number>;\n\n /**\n * Get the number of valid signatures for matching multisig inputs in the transaction.\n *\n * @remarks\n * Returns `undefined` when the transaction has no inputs locked by any multisig address\n * supported by this signer. This method only evaluates matching multisig inputs and does\n * not indicate whether the transaction itself is expected to be signed by this multisig.\n *\n * @param _ - The transaction.\n * @returns The matched multisig signature count, or `undefined` when the transaction is unrelated to any multisig address supported by this signer.\n */\n abstract getSignaturesCount(_: TransactionLike): Promise<number | undefined>;\n\n /**\n * Check if related multisig inputs in the transaction need more signatures.\n *\n * @remarks\n * Returns `false` when the transaction has no inputs locked by any multisig address\n * supported by this signer.\n * A `false` result therefore means either the related multisig inputs are already fulfilled,\n * or the transaction is unrelated to all multisig addresses supported by this signer.\n *\n * @param txLike - The transaction to check.\n * @returns A promise that resolves to `true` when related multisig inputs still need signatures, and `false` otherwise.\n */\n abstract needMoreSignatures(_: TransactionLike): Promise<boolean>;\n\n /**\n * Aggregate transactions.\n * @param _ - The transactions to aggregate.\n * @returns The aggregated transaction.\n */\n abstract aggregateTransactions(_: TransactionLike[]): Promise<Transaction>;\n\n /**\n * Send a transaction.\n *\n * @remarks\n * This method rejects the transaction only when related multisig inputs still need signatures.\n * It does not verify that the transaction actually contains inputs locked by any multisig\n * address supported by this signer, so transactions unrelated to those multisig addresses\n * are not rejected by this check.\n *\n * @param tx - The transaction to send.\n * @returns The transaction hash.\n */\n async sendTransaction(tx: TransactionLike): Promise<Hex> {\n const signedTx = await this.signTransaction(tx);\n if (await this.needMoreSignatures(signedTx)) {\n const count = (await this.getSignaturesCount(signedTx)) ?? 0;\n const threshold = await this.getMemberThreshold();\n throw new SignerMultisigNotEnoughSignaturesError(count, threshold);\n }\n\n return this.client.sendTransaction(signedTx);\n }\n}\n\n/**\n * Thrown when a multisig transaction is sent before enough signatures are collected.\n *\n * @public\n */\nexport class SignerMultisigNotEnoughSignaturesError extends Error {\n readonly signaturesCount: number;\n readonly threshold: number;\n\n constructor(signaturesCount: number, threshold: number) {\n const message = `Not enough signatures: got ${signaturesCount}, need ${threshold}`;\n super(message);\n this.name = \"SignerMultisigNotEnoughSignaturesError\";\n this.signaturesCount = signaturesCount;\n this.threshold = threshold;\n }\n}\n\n/**\n * A class representing information about a signer, including its type and the signer instance.\n * @public\n */\nexport class SignerInfo {\n constructor(\n public name: string,\n public signer: Signer,\n ) {}\n}\n\n/**\n * Represents a wallet with a name, icon, and an array of signer information.\n * @public\n */\nexport type Wallet = {\n name: string;\n icon: string;\n};\n","import { Address } from \"../../address/index.js\";\nimport { bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { numToBytes } from \"../../num/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\nimport { SignPsbtOptionsLike } from \"./psbt.js\";\nimport { btcEcdsaPublicKeyHash } from \"./verify.js\";\n\n/**\n * An abstract class extending the Signer class for Bitcoin-like signing operations.\n * This class provides methods to get Bitcoin account, public key, and internal address,\n * as well as signing transactions.\n * @public\n */\nexport abstract class SignerBtc extends Signer {\n get type(): SignerType {\n return SignerType.BTC;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.BtcEcdsa;\n }\n\n /**\n * Sign and broadcast a PSBT.\n *\n * @param psbtHex - The hex string of PSBT to sign and broadcast.\n * @param options - Options for signing the PSBT.\n * @returns A promise that resolves to the transaction ID as a Hex string.\n */\n async signAndBroadcastPsbt(\n psbtHex: HexLike,\n options?: SignPsbtOptionsLike,\n ): Promise<Hex> {\n const signedPsbt = await this.signPsbt(psbtHex, options);\n return this.broadcastPsbt(signedPsbt, options);\n }\n\n /**\n * Gets the Bitcoin account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Bitcoin account.\n */\n abstract getBtcAccount(): Promise<string>;\n\n /**\n * Gets the Bitcoin public key associated with the signer.\n *\n * @returns A promise that resolves to a HexLike value representing the Bitcoin public key.\n */\n abstract getBtcPublicKey(): Promise<HexLike>;\n\n /**\n * Gets the internal address, which is the Bitcoin account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return this.getBtcAccount();\n }\n\n /**\n * Gets the identity, which is the Bitcoin public key in this case.\n *\n * @returns A promise that resolves to a string representing the identity\n */\n async getIdentity(): Promise<string> {\n return hexFrom(await this.getBtcPublicKey()).slice(2);\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const publicKey = await this.getBtcPublicKey();\n const hash = btcEcdsaPublicKeyHash(publicKey);\n\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x04, ...hash, 0x00]),\n ),\n ];\n }\n\n /**\n * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.OmniLock);\n await tx.prepareSighashAllWitness(script, 85, this.client);\n return tx;\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signature = bytesFrom(\n await this.signMessageRaw(\n `CKB (Bitcoin Layer) transaction: ${info.message}`,\n ),\n \"base64\",\n );\n signature[0] = 31 + ((signature[0] - 27) % 4);\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(\n bytesConcat(\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(4 * 4, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(signature.length, 4),\n signature,\n ),\n );\n\n tx.setWitnessArgsAt(info.position, witness);\n return tx;\n }\n\n /**\n * Signs a Partially Signed Bitcoin Transaction (PSBT).\n *\n * @param psbtHex - The hex string of PSBT to sign.\n * @param options - Options for signing the PSBT\n * @returns A promise that resolves to the signed PSBT as a Hex string.\n */\n abstract signPsbt(\n psbtHex: HexLike,\n options?: SignPsbtOptionsLike,\n ): Promise<Hex>;\n\n /**\n * Broadcasts a PSBT to the Bitcoin network.\n *\n * @param psbtHex - The hex string of the PSBT to broadcast.\n * @param options - Options for broadcasting the PSBT.\n * @returns A promise that resolves to the transaction ID as a Hex string.\n */\n abstract broadcastPsbt(\n psbtHex: HexLike,\n options?: SignPsbtOptionsLike,\n ): Promise<Hex>;\n}\n","import { Client } from \"../../client/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { SignPsbtOptionsLike } from \"./psbt.js\";\nimport { SignerBtc } from \"./signerBtc.js\";\n\n/**\n * A class extending SignerBtc that provides read-only access to a Bitcoin public key and account.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerBtcPublicKeyReadonly extends SignerBtc {\n private readonly publicKey: Hex;\n\n /**\n * Creates an instance of SignerBtcPublicKeyReadonly.\n *\n * @param client - The client instance used for communication.\n * @param account - The Bitcoin account associated with the signer.\n * @param publicKey - The public key associated with the signer.\n */\n constructor(\n client: Client,\n private readonly account: string,\n publicKey: HexLike,\n ) {\n super(client);\n\n this.publicKey = hexFrom(publicKey);\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the Bitcoin account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Bitcoin account.\n *\n * @example\n * ```typescript\n * const account = await signer.getBtcAccount(); // Outputs the Bitcoin account\n * ```\n */\n async getBtcAccount(): Promise<string> {\n return this.account;\n }\n\n /**\n * Gets the Bitcoin public key associated with the signer.\n *\n * @returns A promise that resolves to a Hex string representing the Bitcoin public key.\n *\n * @example\n * ```typescript\n * const publicKey = await signer.getBtcPublicKey(); // Outputs the Bitcoin public key\n * ```\n */\n async getBtcPublicKey(): Promise<Hex> {\n return this.publicKey;\n }\n\n async signPsbt(\n _psbtHex: HexLike,\n _options?: SignPsbtOptionsLike,\n ): Promise<Hex> {\n throw new Error(\"Read-only signer does not support signPsbt\");\n }\n\n async broadcastPsbt(\n _psbtHex: HexLike,\n _options?: SignPsbtOptionsLike,\n ): Promise<Hex> {\n throw new Error(\"Read-only signer does not support broadcastPsbt\");\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { bytesFrom } from \"../../bytes/index.js\";\nimport { Script, Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport { CellDepInfo, Client, KnownScript } from \"../../client/index.js\";\nimport { hashCkbShort } from \"../../hasher/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\nimport { SECP256K1_SIGNATURE_LENGTH } from \"./secp256k1Signing.js\";\n\n/**\n * @public\n */\nexport class SignerCkbPublicKey extends Signer {\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.CkbSecp256k1;\n }\n\n public readonly publicKey: Hex;\n\n constructor(client: Client, publicKey: HexLike) {\n super(client);\n this.publicKey = hexFrom(publicKey);\n\n if (bytesFrom(this.publicKey).length !== 33) {\n throw new Error(\"Public key must be 33 bytes!\");\n }\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n async getIdentity(): Promise<string> {\n return this.publicKey;\n }\n\n async getAddressObjSecp256k1(): Promise<Address> {\n return Address.fromKnownScript(\n this.client,\n KnownScript.Secp256k1Blake160,\n hashCkbShort(this.publicKey),\n );\n }\n\n async getRecommendedAddressObj(_preference?: unknown): Promise<Address> {\n return this.getAddressObjSecp256k1();\n }\n\n async getAddressObjs(): Promise<Address[]> {\n const secp256k1 = await this.getAddressObjSecp256k1();\n\n const addresses: Address[] = [];\n let count = 0;\n for await (const cell of this.client.findCells({\n script: await Script.fromKnownScript(\n this.client,\n KnownScript.AnyoneCanPay,\n secp256k1.script.args,\n ),\n scriptType: \"lock\",\n scriptSearchMode: \"prefix\",\n withData: false,\n })) {\n if (count >= 10) {\n break;\n }\n count += 1;\n\n if (addresses.some(({ script }) => script.eq(cell.cellOutput.lock))) {\n continue;\n }\n\n addresses.push(\n Address.from({\n prefix: this.client.addressPrefix,\n script: cell.cellOutput.lock,\n }),\n );\n }\n\n return [secp256k1, ...addresses];\n }\n\n async getRelatedScripts(\n txLike: TransactionLike,\n ): Promise<{ script: Script; cellDeps: CellDepInfo[] }[]> {\n const tx = Transaction.from(txLike);\n\n const secp256k1 = await this.getAddressObjSecp256k1();\n const acp = await Script.fromKnownScript(\n this.client,\n KnownScript.AnyoneCanPay,\n secp256k1.script.args,\n );\n\n const scripts: { script: Script; cellDeps: CellDepInfo[] }[] = [];\n for (const input of tx.inputs) {\n const {\n cellOutput: { lock },\n } = await input.getCell(this.client);\n\n if (scripts.some(({ script }) => script.eq(lock))) {\n continue;\n }\n\n if (lock.eq(secp256k1.script)) {\n scripts.push({\n script: lock,\n cellDeps: (\n await this.client.getKnownScript(KnownScript.Secp256k1Blake160)\n ).cellDeps,\n });\n } else if (\n lock.codeHash === acp.codeHash &&\n lock.hashType === acp.hashType &&\n lock.args.startsWith(acp.args)\n ) {\n scripts.push({\n script: lock,\n cellDeps: (await this.client.getKnownScript(KnownScript.AnyoneCanPay))\n .cellDeps,\n });\n }\n }\n\n return scripts;\n }\n\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n\n await Promise.all(\n (await this.getRelatedScripts(tx)).map(async ({ script, cellDeps }) => {\n await tx.prepareSighashAllWitness(\n script,\n SECP256K1_SIGNATURE_LENGTH,\n this.client,\n );\n await tx.addCellDepInfos(this.client, cellDeps);\n }),\n );\n return tx;\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport {\n messageHashCkbSecp256k1,\n signMessageSecp256k1,\n} from \"./secp256k1Signing.js\";\nimport { SignerCkbPublicKey } from \"./signerCkbPublicKey.js\";\n\n/**\n * @public\n */\nexport class SignerCkbPrivateKey extends SignerCkbPublicKey {\n public readonly privateKey: Hex;\n\n constructor(client: Client, privateKey: HexLike) {\n const pk = hexFrom(privateKey);\n if (bytesFrom(pk).length !== 32) {\n throw new Error(\"Private key must be 32 bytes!\");\n }\n\n super(client, secp256k1.getPublicKey(bytesFrom(pk), true));\n this.privateKey = pk;\n }\n\n async _signMessage(message: HexLike): Promise<Hex> {\n return signMessageSecp256k1(message, this.privateKey);\n }\n\n async signMessageRaw(message: string | BytesLike): Promise<Hex> {\n return this._signMessage(messageHashCkbSecp256k1(message));\n }\n\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n\n for (const { script } of await this.getRelatedScripts(tx)) {\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signature = await this._signMessage(info.message);\n\n const witness =\n tx.getWitnessArgsAt(info.position) ?? WitnessArgs.from({});\n witness.lock = signature;\n tx.setWitnessArgsAt(info.position, witness);\n }\n\n return tx;\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Script, ScriptLike } from \"../../ckb/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * A read-only signer for a CKB script. It can be used to get addresses,\n * but not to sign transactions. This is useful when you want to watch an address\n * without having the private key.\n *\n * @public\n */\nexport class SignerCkbScriptReadonly extends Signer {\n /**\n * The type of the signer.\n */\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n /**\n * The sign type of the signer.\n * As this is a read-only signer, the sign type is {@link SignerSignType.Unknown}.\n */\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n /**\n * The scripts associated with the signer.\n */\n public readonly scripts: Script[];\n\n /**\n * Creates an instance of SignerCkbScriptReadonly.\n *\n * @param client - The client instance used for communication.\n * @param scripts - The scripts associated with the signer. Can be a single script, an array of scripts, or multiple script arguments.\n */\n constructor(client: Client, ...scripts: (ScriptLike | ScriptLike[])[]) {\n super(client);\n\n this.scripts = scripts.flat().map(Script.from);\n if (this.scripts.length === 0) {\n throw new Error(\"SignerCkbScriptReadonly requires at least one script.\");\n }\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the internal address for the script.\n *\n * @returns A promise that resolves to a string representing the internal address.\n *\n * @example\n * ```typescript\n * const internalAddress = await signer.getInternalAddress(); // Outputs the internal address\n * ```\n */\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n /**\n * Gets an array of Address objects representing the script address.\n *\n * @returns A promise that resolves to an array of Address objects.\n *\n * @example\n * ```typescript\n * const addressObjs = await signer.getAddressObjs(); // Outputs the array of Address objects\n * ```\n */\n async getAddressObjs(): Promise<Address[]> {\n return this.scripts.map((script) =>\n Address.fromScript(script, this.client),\n );\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Bytes, bytesConcat, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport {\n Script,\n ScriptLike,\n Since,\n SinceLike,\n Transaction,\n TransactionLike,\n WitnessArgs,\n WitnessArgsLike,\n} from \"../../ckb/index.js\";\nimport {\n CellDepInfo,\n CellDepInfoLike,\n Client,\n KnownScript,\n ScriptInfo,\n ScriptInfoLike,\n} from \"../../client/index.js\";\nimport { codec, Entity } from \"../../codec/index.js\";\nimport { HASH_CKB_SHORT_LENGTH, hashCkbShort } from \"../../hasher/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport { numFrom, NumLike, numToBytes } from \"../../num/index.js\";\nimport { apply, reduceAsync } from \"../../utils/index.js\";\nimport { SignerMultisig, SignerSignType, SignerType } from \"../signer/index.js\";\nimport {\n recoverMessageSecp256k1,\n SECP256K1_SIGNATURE_LENGTH,\n} from \"./secp256k1Signing.js\";\n\nexport type MultisigCkbWitnessLike = (\n | {\n publicKeyHashes: HexLike[];\n publicKeys?: undefined | null;\n }\n | {\n publicKeyHashes?: undefined | null;\n publicKeys: HexLike[];\n }\n) & {\n threshold: NumLike;\n mustMatch?: NumLike | null;\n signatures?: HexLike[] | null;\n};\n\n/**\n * A class representing multisig information, holding information ingredients and containing utilities.\n * @public\n */\n@codec({\n encode: (encodable: MultisigCkbWitness) => {\n const { publicKeyHashes, threshold, mustMatch, signatures } =\n MultisigCkbWitness.from(encodable);\n\n if (\n signatures.some((s) => s.length !== SECP256K1_SIGNATURE_LENGTH * 2 + 2)\n ) {\n throw Error(\"MultisigCkbWitness: invalid signature length\");\n }\n if (\n publicKeyHashes.some((s) => s.length !== HASH_CKB_SHORT_LENGTH * 2 + 2)\n ) {\n throw Error(\"MultisigCkbWitness: invalid public key hash length\");\n }\n\n return bytesConcat(\n \"0x00\",\n numToBytes(mustMatch ?? 0),\n numToBytes(threshold),\n numToBytes(publicKeyHashes.length),\n ...publicKeyHashes,\n ...signatures,\n );\n },\n decode: (raw: Bytes) => {\n if (raw.length < 4) {\n throw Error(\"MultisigCkbWitness: data length too short\");\n }\n\n const [\n _reserved,\n mustMatch,\n threshold,\n publicKeyHashesLength,\n ...rawKeyAndSignatures\n ] = raw;\n\n if (\n rawKeyAndSignatures.length <\n publicKeyHashesLength * HASH_CKB_SHORT_LENGTH\n ) {\n throw Error(\"MultisigCkbWitness: invalid public key hashes length\");\n }\n\n const signatures = rawKeyAndSignatures.slice(\n publicKeyHashesLength * HASH_CKB_SHORT_LENGTH,\n );\n\n return MultisigCkbWitness.from({\n publicKeyHashes: Array.from(new Array(publicKeyHashesLength), (_, i) =>\n hexFrom(\n rawKeyAndSignatures.slice(\n i * HASH_CKB_SHORT_LENGTH,\n (i + 1) * HASH_CKB_SHORT_LENGTH,\n ),\n ),\n ),\n threshold: numFrom(threshold),\n mustMatch: numFrom(mustMatch),\n signatures: Array.from(\n new Array(Math.floor(signatures.length / SECP256K1_SIGNATURE_LENGTH)),\n (_, i) =>\n hexFrom(\n signatures.slice(\n i * SECP256K1_SIGNATURE_LENGTH,\n (i + 1) * SECP256K1_SIGNATURE_LENGTH,\n ),\n ),\n ),\n });\n },\n})\nexport class MultisigCkbWitness extends Entity.Base<\n MultisigCkbWitnessLike,\n MultisigCkbWitness\n>() {\n /**\n * @param publicKeyHashes - The public key hashes.\n * @param threshold - The threshold.\n * @param mustMatch - The number of signatures that must match.\n * @param signatures - The signatures.\n */\n constructor(\n public publicKeyHashes: Hex[],\n public threshold: number,\n public mustMatch: number,\n public signatures: Hex[],\n ) {\n super();\n\n const keysLength = publicKeyHashes.length;\n\n if (threshold <= 0 || threshold > keysLength) {\n throw new Error(\n \"threshold should be in range from 1 to public keys length\",\n );\n }\n if (mustMatch < 0 || mustMatch > Math.min(keysLength, threshold)) {\n throw new Error(\n \"mustMatch should be in range from 0 to min(public keys length, threshold)\",\n );\n }\n if (keysLength > 255) {\n throw new Error(\"public keys length should be less than 256\");\n }\n }\n\n /**\n * Create a MultisigCkbWitness from a MultisigCkbWitnessLike.\n *\n * @param witness - The witness like object.\n * @returns The MultisigCkbWitness.\n */\n static from(witness: MultisigCkbWitnessLike): MultisigCkbWitness {\n const publicKeyHashes = (() => {\n if (witness.publicKeyHashes) {\n return witness.publicKeyHashes;\n }\n return witness.publicKeys.map((k) => hashCkbShort(k));\n })();\n\n return new MultisigCkbWitness(\n publicKeyHashes.map(hexFrom),\n Number(numFrom(witness.threshold)),\n Number(numFrom(witness.mustMatch ?? 0)),\n witness.signatures?.map(hexFrom) ?? [],\n );\n }\n\n /**\n * Get the threshold of flexible signatures.\n */\n get flexibleThreshold() {\n return this.threshold - this.mustMatch;\n }\n\n /**\n * Get the script args of the multisig script.\n *\n * @param since - The since value.\n * @returns The script args.\n */\n scriptArgs(since?: SinceLike | null): Bytes {\n const hash = hashCkbShort(\n MultisigCkbWitness.from({ ...this, signatures: [] }).toBytes(),\n );\n\n if (since != null) {\n return bytesConcat(hash, Since.from(since).toBytes());\n }\n\n return bytesFrom(hash);\n }\n\n /**\n * Check if the multisig info is equal to another.\n *\n * @param otherLike - The other multisig info.\n * @returns True if the multisig info is equal, false otherwise.\n */\n eqInfo(otherLike: MultisigCkbWitnessLike): boolean {\n const other = MultisigCkbWitness.from(otherLike);\n return (\n this.publicKeyHashes.length === other.publicKeyHashes.length &&\n this.publicKeyHashes.every((h, i) => h === other.publicKeyHashes[i]) &&\n this.threshold === other.threshold &&\n this.mustMatch === other.mustMatch\n );\n }\n\n /**\n * Generate valid public key hashes and their signatures from the witness.\n * This method filters out invalid signatures, duplicate signatures, and signatures not in the multisig script.\n *\n * @param message - The message signed.\n * @returns A generator of public key hashes, signatures, and whether the signature is required.\n */\n *generatePublicKeyHashesFromSignatures(message: BytesLike): Generator<{\n pubkeyHash: Hex;\n signature: Hex;\n isRequired: boolean;\n }> {\n const publicKeyHashesFromSignature = new Set<Hex>();\n\n for (const signature of this.signatures.filter(\n (sig) => sig !== SignerMultisigCkbReadonly.EmptySignature,\n )) {\n const pubkey = (() => {\n try {\n return recoverMessageSecp256k1(message, signature);\n } catch (_) {\n // Ignore invalid signature\n return;\n }\n })();\n if (pubkey === undefined) {\n continue;\n }\n\n const pubkeyHash = hashCkbShort(pubkey);\n if (publicKeyHashesFromSignature.has(pubkeyHash)) {\n continue;\n }\n\n const index = this.publicKeyHashes.indexOf(pubkeyHash);\n if (index === -1) {\n continue;\n }\n publicKeyHashesFromSignature.add(pubkeyHash);\n const isRequired = index < this.mustMatch;\n\n yield {\n pubkeyHash,\n signature,\n isRequired,\n };\n }\n }\n\n /**\n * Calculate the number of matched signatures in the witness.\n *\n * @param message - The message signed.\n * @returns The number of required and flexible signatures.\n */\n calcMatchedSignaturesCount(message: BytesLike): {\n required: number;\n flexible: number;\n } {\n let required = 0;\n let flexible = 0;\n\n for (const { isRequired } of this.generatePublicKeyHashesFromSignatures(\n message,\n )) {\n if (isRequired) {\n required += 1;\n } else {\n flexible += 1;\n }\n }\n\n return { required, flexible };\n }\n}\n\n/**\n * A class extending Signer that provides access to a CKB multisig script.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerMultisigCkbReadonly extends SignerMultisig {\n static EmptySignature = hexFrom(\"00\".repeat(SECP256K1_SIGNATURE_LENGTH));\n\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n public readonly multisigInfo: MultisigCkbWitness;\n\n public readonly since?: Since;\n public readonly scriptInfos: Promise<\n {\n script: Script;\n cellDeps: CellDepInfo[];\n }[]\n >;\n\n /**\n * Creates an instance of SignerMultisigCkbReadonly.\n *\n * @param client - The client instance.\n * @param multisigInfoLike - The multisig information.\n * @param options - The options.\n */\n constructor(\n client: Client,\n multisigInfoLike: MultisigCkbWitnessLike,\n options?: {\n since?: SinceLike | null;\n scriptInfos?: (KnownScript | ScriptInfoLike)[] | null;\n } | null,\n ) {\n super(client);\n\n this.multisigInfo = MultisigCkbWitness.from(multisigInfoLike);\n this.since = apply(Since.from, options?.since);\n\n const args = this.multisigInfo.scriptArgs(this.since);\n this.scriptInfos = Promise.all(\n (\n options?.scriptInfos ?? [\n KnownScript.Secp256k1MultisigV2,\n KnownScript.Secp256k1MultisigV2Beta,\n KnownScript.Secp256k1Multisig,\n ]\n ).map(async (v) => {\n if (typeof v !== \"string\") {\n return ScriptInfo.from(v);\n }\n\n try {\n return await client.getKnownScript(v);\n } catch (_) {\n return undefined;\n }\n }),\n ).then((infos) =>\n infos\n .filter((s) => s !== undefined)\n .map((i) => ({\n script: Script.from({ ...i, args }),\n cellDeps: i.cellDeps,\n })),\n );\n }\n\n /**\n * Get the number of members in the multisig script.\n *\n * @returns The number of members.\n */\n async getMemberCount() {\n return this.multisigInfo.publicKeyHashes.length;\n }\n\n /**\n * Get the threshold of the multisig script.\n *\n * @returns The threshold.\n */\n async getMemberThreshold() {\n return this.multisigInfo.threshold;\n }\n\n /**\n * Get the count of required member of the multisig script.\n *\n * @returns The must match count.\n */\n async getMemberRequiredCount() {\n return this.multisigInfo.mustMatch;\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n async getAddressObjs(): Promise<Address[]> {\n return (await this.scriptInfos).map(({ script }) =>\n Address.fromScript(script, this.client),\n );\n }\n\n /**\n * Decode the witness args at a specific index.\n *\n * @param txLike - The transaction.\n * @param index - The index of the witness args.\n * @returns The decoded MultisigCkbWitness.\n */\n decodeWitnessArgsAt(\n txLike: TransactionLike,\n index: number,\n ): MultisigCkbWitness | undefined {\n const tx = Transaction.from(txLike);\n\n return this.decodeWitnessArgs(tx.getWitnessArgsAt(index));\n }\n\n /**\n * Decode the witness args.\n *\n * @param witnessLike - The witness args like object.\n * @returns The decoded MultisigCkbWitness.\n */\n decodeWitnessArgs(\n witnessLike?: WitnessArgsLike | null,\n ): MultisigCkbWitness | undefined {\n if (!witnessLike) {\n return;\n }\n const witness = WitnessArgs.from(witnessLike);\n\n if (witness.lock == null) {\n return;\n }\n\n try {\n const decoded = MultisigCkbWitness.decode(witness.lock);\n if (decoded.eqInfo(this.multisigInfo)) {\n return decoded;\n }\n } catch (_) {\n // Returns undefined for invalid data\n }\n }\n\n /**\n * Prepare the witness args at a specific index.\n *\n * @param txLike - The transaction.\n * @param index - The index of the witness args.\n * @param transformer - The transformer function.\n * @returns The prepared transaction.\n */\n async prepareWitnessArgsAt(\n txLike: TransactionLike,\n index: number,\n transformer?:\n | ((\n witness: MultisigCkbWitness,\n witnessArgs: WitnessArgs,\n ) =>\n | MultisigCkbWitnessLike\n | undefined\n | null\n | void\n | Promise<MultisigCkbWitnessLike | undefined | null | void>)\n | null,\n ): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n\n const witnessArgs = tx.getWitnessArgsAt(index) ?? WitnessArgs.from({});\n const multisigWitness =\n this.decodeWitnessArgs(witnessArgs) ?? this.multisigInfo.clone();\n\n const transformed = MultisigCkbWitness.from(\n (await transformer?.(multisigWitness, witnessArgs)) ?? multisigWitness,\n );\n\n transformed.signatures = transformed.signatures.slice(\n 0,\n this.multisigInfo.threshold,\n );\n transformed.signatures.push(\n ...Array.from(\n new Array(this.multisigInfo.threshold - transformed.signatures.length),\n () => SignerMultisigCkbReadonly.EmptySignature,\n ),\n );\n\n witnessArgs.lock = transformed.toHex();\n tx.setWitnessArgsAt(index, witnessArgs);\n\n return tx;\n }\n\n /**\n * Prepare multisig witness, if the existence of multisig witness is detected, nothing happens\n *\n * @param txLike - The transaction to prepare.\n * @param scriptLike - The script to prepare.\n * @returns A promise that resolves to the prepared transaction\n */\n async prepareTransactionOneScript(\n txLike: TransactionLike,\n script: ScriptLike,\n cellDeps: CellDepInfoLike[],\n ) {\n const tx = Transaction.from(txLike);\n const position = await tx.findInputIndexByLock(script, this.client);\n if (position === undefined) {\n return tx;\n }\n\n await tx.addCellDepInfos(this.client, cellDeps);\n return this.prepareWitnessArgsAt(tx, position);\n }\n\n /**\n * Prepare transaction for multisig witness and adding related cell deps\n *\n * @param txLike - The transaction to prepare.\n * @returns A promise that resolves to the prepared transaction\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n return await reduceAsync(\n await this.scriptInfos,\n (tx, { script, cellDeps }) =>\n this.prepareTransactionOneScript(tx, script, cellDeps),\n Transaction.from(txLike),\n );\n }\n\n /**\n * Get the number of valid signatures for matching multisig inputs in the transaction.\n *\n * @remarks\n * Returns `undefined` when the transaction has no inputs locked by any multisig address\n * supported by this signer. This method only counts signatures for matching multisig inputs\n * and does not imply that the transaction should be signed by this multisig.\n *\n * @param txLike - The transaction.\n * @returns The matched multisig signature count, or `undefined` when the transaction is unrelated to any multisig address supported by this signer.\n */\n async getSignaturesCount(\n txLike: TransactionLike,\n ): Promise<number | undefined> {\n const tx = Transaction.from(txLike);\n let minSignaturesCount = undefined;\n\n for (const { script } of await this.scriptInfos) {\n const info = await this.getSignInfo(tx, script);\n if (info === undefined) {\n continue;\n }\n\n const multisigWitness = this.decodeWitnessArgsAt(tx, info.position);\n if (!multisigWitness) {\n minSignaturesCount = 0;\n continue;\n }\n\n const { required, flexible } = multisigWitness.calcMatchedSignaturesCount(\n info.message,\n );\n\n minSignaturesCount = Math.min(\n minSignaturesCount ?? 256,\n required + Math.min(flexible, this.multisigInfo.flexibleThreshold),\n );\n }\n\n return minSignaturesCount;\n }\n\n /**\n * Check if related multisig inputs in the transaction need more signatures.\n *\n * @remarks\n * Returns `false` when the transaction has no inputs locked by any multisig address\n * supported by this signer.\n * A `false` result therefore means either the related multisig inputs are already fulfilled,\n * or the transaction is unrelated to all multisig addresses supported by this signer.\n *\n * @param txLike - The transaction to check.\n * @returns A promise that resolves to `true` when related multisig inputs still need signatures, and `false` otherwise.\n */\n async needMoreSignatures(txLike: TransactionLike): Promise<boolean> {\n const count = await this.getSignaturesCount(txLike);\n if (count == null) {\n return false;\n }\n return count < (await this.getMemberThreshold());\n }\n\n /**\n * Get the sign info for a script.\n *\n * @param txLike - The transaction.\n * @param script - The script.\n * @returns The sign info.\n */\n async getSignInfo(\n txLike: TransactionLike,\n script: ScriptLike,\n ): Promise<{ message: Hex; position: number } | undefined> {\n const tx = Transaction.from(txLike);\n\n const position = await tx.findInputIndexByLock(script, this.client);\n if (position == null) {\n return;\n }\n\n // === Replace the witness with a dummy one ===\n const witness = tx.getWitnessArgsAt(position) ?? WitnessArgs.from({});\n witness.lock = MultisigCkbWitness.from({\n ...this.multisigInfo,\n signatures: Array.from(\n new Array(this.multisigInfo.threshold),\n () => SignerMultisigCkbReadonly.EmptySignature,\n ),\n }).toHex();\n\n const clonedTx = tx.clone();\n clonedTx.setWitnessArgsAt(position, witness);\n // === Replace the witness with a dummy one ===\n\n return clonedTx.getSignHashInfo(script, this.client);\n }\n\n /**\n * Aggregate transactions.\n *\n * @param txs - The transactions to aggregate.\n * @returns The aggregated transaction.\n */\n async aggregateTransactions(txs: TransactionLike[]): Promise<Transaction> {\n if (txs.length === 0) {\n throw Error(\"No transaction to aggregate\");\n }\n\n let res = Transaction.from(txs[0]);\n\n for (const { script } of await this.scriptInfos) {\n const info = await this.getSignInfo(res, script);\n if (info === undefined) {\n continue;\n }\n\n const signatures = new Map<Hex, Hex>();\n let requiredCount = 0;\n for (const txLike of txs) {\n const tx = Transaction.from(txLike);\n const multisigWitness = this.decodeWitnessArgsAt(tx, info.position);\n\n if (!multisigWitness) {\n continue;\n }\n\n for (const {\n pubkeyHash,\n signature,\n isRequired,\n } of multisigWitness.generatePublicKeyHashesFromSignatures(\n info.message,\n )) {\n if (signatures.has(pubkeyHash)) {\n continue;\n }\n\n if (isRequired) {\n // A required public key\n requiredCount += 1;\n } else if (\n signatures.size - requiredCount >=\n this.multisigInfo.flexibleThreshold\n ) {\n // Not a required public key, and we have too many optional public key\n continue;\n }\n\n signatures.set(pubkeyHash, signature);\n if (signatures.size >= this.multisigInfo.threshold) {\n break;\n }\n }\n\n if (signatures.size >= this.multisigInfo.threshold) {\n break;\n }\n }\n\n res = await this.prepareWitnessArgsAt(res, info.position, (witness) => {\n witness.signatures = Array.from(signatures.values());\n });\n }\n\n return res;\n }\n}\n","import { SinceLike, Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport { Client, KnownScript, ScriptInfoLike } from \"../../client/index.js\";\nimport { hashCkbShort } from \"../../hasher/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport { signMessageSecp256k1 } from \"./secp256k1Signing.js\";\nimport { SignerCkbPrivateKey } from \"./signerCkbPrivateKey.js\";\nimport {\n MultisigCkbWitnessLike,\n SignerMultisigCkbReadonly,\n} from \"./signerMultisigCkbReadonly.js\";\n\n/**\n * A class extending Signer that provides access to a CKB multisig script and supports signing operations.\n * @public\n */\nexport class SignerMultisigCkbPrivateKey extends SignerMultisigCkbReadonly {\n private readonly privateKey: Hex;\n private readonly signer: SignerCkbPrivateKey;\n\n /**\n * Creates an instance of SignerMultisigCkbPrivateKey.\n *\n * @param client - The client instance.\n * @param privateKey - The private key.\n * @param multisigInfo - The multisig information.\n * @param options - The options.\n */\n constructor(\n client: Client,\n privateKey: HexLike,\n multisigInfo: MultisigCkbWitnessLike,\n options?: {\n since?: SinceLike | null;\n scriptInfos?: (KnownScript | ScriptInfoLike)[] | null;\n } | null,\n ) {\n super(client, multisigInfo, options);\n\n this.privateKey = hexFrom(privateKey);\n this.signer = new SignerCkbPrivateKey(client, this.privateKey);\n }\n\n /**\n * Sign a transaction only (without preparing).\n *\n * @param txLike - The transaction to sign.\n * @returns The signed transaction.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n let tx = Transaction.from(txLike);\n\n const thisPubkeyHash = hashCkbShort(this.signer.publicKey);\n\n const index = this.multisigInfo.publicKeyHashes.indexOf(thisPubkeyHash);\n if (index === -1) {\n return tx;\n }\n const isSelfRequired = index < this.multisigInfo.mustMatch;\n\n for (const { script } of await this.scriptInfos) {\n const info = await this.getSignInfo(tx, script);\n if (!info) {\n continue;\n }\n\n // === Find a position for the signature ===\n tx = await this.prepareWitnessArgsAt(\n tx,\n info.position,\n async (witness) => {\n // We re-evaluate the signatures to filter invalid / excessive signatures\n const signatures: Hex[] = [];\n let requiredCount = 0;\n let isSignNeeded = true;\n\n for (const {\n pubkeyHash,\n signature,\n isRequired,\n } of witness.generatePublicKeyHashesFromSignatures(info.message)) {\n if (pubkeyHash === thisPubkeyHash) {\n if (!isSignNeeded) {\n // Has signed and added to the signatures list already. We will not add it again.\n continue;\n }\n isSignNeeded = false;\n }\n\n if (isRequired) {\n requiredCount += 1;\n } else if (\n signatures.length - requiredCount >=\n this.multisigInfo.flexibleThreshold\n ) {\n // Too many flexible signatures\n continue;\n }\n\n signatures.push(signature);\n if (signatures.length >= this.multisigInfo.threshold) {\n // We have got enough signatures\n isSignNeeded = false;\n break;\n }\n }\n\n if (\n isSignNeeded &&\n (isSelfRequired ||\n signatures.length - requiredCount <\n this.multisigInfo.flexibleThreshold)\n ) {\n // Add the signature from this signer only when\n // 1. The signature is needed\n // 2. It's required or...\n // 3. We haven't got enough flexible signatures\n signatures.push(\n signMessageSecp256k1(info.message, this.privateKey),\n );\n }\n witness.signatures = signatures;\n return witness;\n },\n );\n }\n\n return tx;\n }\n}\n","import bs58check from \"bs58check\";\nimport { Address } from \"../../address/index.js\";\nimport { bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { numToBytes } from \"../../num/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * An abstract class extending the Signer class for Dogecoin-like signing operations.\n * This class provides methods to get Doge account, public key, and internal address,\n * as well as signing transactions.\n * @public\n */\nexport abstract class SignerDoge extends Signer {\n get type(): SignerType {\n return SignerType.Doge;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.DogeEcdsa;\n }\n\n /**\n * Gets the Doge address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Doge account.\n */\n abstract getDogeAddress(): Promise<string>;\n\n /**\n * Gets the internal address, which is the Doge account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return this.getDogeAddress();\n }\n\n /**\n * Gets the identity, which is the Doge address in this case.\n *\n * @returns A promise that resolves to a string representing the identity\n */\n async getIdentity(): Promise<string> {\n return this.getDogeAddress();\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const hash = bs58check.decode(await this.getDogeAddress()).slice(1);\n\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x05, ...hash, 0x00]),\n ),\n ];\n }\n\n /**\n * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.OmniLock);\n await tx.prepareSighashAllWitness(script, 85, this.client);\n return tx;\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signature = bytesFrom(\n await this.signMessageRaw(info.message.slice(2)),\n \"base64\",\n );\n signature[0] = 31 + ((signature[0] - 27) % 4);\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(\n bytesConcat(\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(4 * 4, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(signature.length, 4),\n signature,\n ),\n );\n\n tx.setWitnessArgsAt(info.position, witness);\n return tx;\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { SignerDoge } from \"./signerDoge.js\";\n\n/**\n * A class extending SignerDoge that provides read-only access to a Doge address.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerDogeAddressReadonly extends SignerDoge {\n /**\n * Creates an instance of SignerDogeAddressReadonly.\n *\n * @param client - The client instance used for communication.\n * @param address - The Doge address with the signer.\n */\n constructor(\n client: Client,\n private readonly address: string,\n ) {\n super(client);\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the Doge address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Doge address.\n *\n * @example\n * ```typescript\n * const account = await signer.getDogeAddress(); // Outputs the Doge address\n * ```\n */\n async getDogeAddress(): Promise<string> {\n return this.address;\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport {\n Bytes,\n bytesConcat,\n bytesFrom,\n BytesLike,\n bytesTo,\n} from \"../../bytes/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\nimport { btcP2pkhAddressFromPublicKey } from \"../btc/verify.js\";\nimport { SignerDoge } from \"./signerDoge.js\";\nimport { messageHashDogeEcdsa } from \"./verify.js\";\n\n/**\n * A class extending SignerDoge that provides access to a Doge address.\n * @public\n */\nexport class SignerDogePrivateKey extends SignerDoge {\n private readonly privateKey: Bytes;\n\n /**\n * Creates an instance of SignerDogePrivateKey\n *\n * @param client - The client instance used for communication.\n * @param privateKey - The Doge private key with the signer.\n */\n constructor(\n client: Client,\n privateKey: BytesLike,\n public readonly dogeNetwork = 0x1e,\n ) {\n super(client);\n this.privateKey = bytesFrom(privateKey);\n if (this.privateKey.length !== 32) {\n throw new Error(\"Private key must be 32 bytes!\");\n }\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is always connected.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getDogePublicKey(): Promise<Hex> {\n return hexFrom(secp256k1.getPublicKey(this.privateKey, true));\n }\n\n /**\n * Gets the Doge address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Doge address.\n *\n * @example\n * ```typescript\n * const account = await signer.getDogeAddress(); // Outputs the Doge address\n * ```\n */\n async getDogeAddress(): Promise<string> {\n return btcP2pkhAddressFromPublicKey(\n await this.getDogePublicKey(),\n this.dogeNetwork,\n );\n }\n\n /**\n * Signs a message and returns signature only.\n *\n * @param msg - The message to sign, as a string or BytesLike object.\n * @returns A promise that resolves to the signature as a string.\n * @throws Will throw an error if not implemented.\n */\n async signMessageRaw(msg: string | BytesLike): Promise<string> {\n const challenge = typeof msg === \"string\" ? msg : hexFrom(msg).slice(2);\n\n const signature = secp256k1.sign(\n messageHashDogeEcdsa(challenge),\n this.privateKey,\n {\n format: \"recovered\",\n prehash: false,\n },\n );\n return bytesTo(\n bytesConcat([31 + Number(signature[0])], signature.slice(1)),\n \"base64\",\n );\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * @public\n */\nexport abstract class SignerDummy extends Signer {\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n constructor(\n client: Client,\n public readonly type: SignerType,\n ) {\n super(client);\n }\n\n async isConnected(): Promise<boolean> {\n return false;\n }\n\n async getInternalAddress(): Promise<string> {\n throw new Error(\"Can't get address from SignerDummy\");\n }\n\n async getAddressObjs(): Promise<Address[]> {\n throw new Error(\"Can't get addresses from SignerDummy\");\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { SignerType } from \"../signer/index.js\";\nimport { SignerDummy } from \"./dummy.js\";\n\n/**\n * @public\n */\nexport class SignerAlwaysError extends SignerDummy {\n constructor(\n client: Client,\n type: SignerType,\n private readonly message: string,\n ) {\n super(client, type);\n }\n\n async connect(): Promise<void> {\n throw new Error(this.message);\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { SignerType } from \"../signer/index.js\";\nimport { SignerDummy } from \"./dummy.js\";\n\n/**\n * @public\n */\nexport class SignerOpenLink extends SignerDummy {\n constructor(\n client: Client,\n type: SignerType,\n private readonly link: string,\n ) {\n super(client, type);\n }\n\n async connect(): Promise<void> {\n window.open(this.link, \"_blank\")?.focus();\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Bytes, BytesLike, bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport {\n Script,\n Transaction,\n TransactionLike,\n WitnessArgs,\n} from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { Hasher, HasherKeecak256 } from \"../../hasher/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { numToBytes } from \"../../num/index.js\";\nimport { reduceAsync } from \"../../utils/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * An abstract class extending Signer for Ethereum Virtual Machine (EVM) based signing operations.\n * This class provides methods to get EVM account, internal address, and signing transactions.\n * @public\n */\nexport abstract class SignerEvm extends Signer {\n get type(): SignerType {\n return SignerType.EVM;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.EvmPersonal;\n }\n\n /**\n * Gets the EVM account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the EVM account.\n */\n abstract getEvmAccount(): Promise<Hex>;\n\n /**\n * Gets the internal address, which is the EVM account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return this.getEvmAccount();\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const account = await this.getEvmAccount();\n const addresses = await Promise.all([\n this._getOmniLockAddresses(account),\n this._getPWLockAddresses(account),\n ]);\n\n return addresses.flat();\n }\n\n _getOmniLockAddresses(account: HexLike): Promise<Address[]> {\n return Promise.all([\n this._getOmniLockEvmAddressObj(account),\n this._getOmniLockOldEvmAddressObj(account),\n ]);\n }\n\n async _getPWLockAddresses(account: HexLike): Promise<Address[]> {\n const addr = await this._getPWLockEvmAddressObj(account);\n if (!addr) {\n return [];\n }\n return [addr];\n }\n\n async _getOmniLockEvmAddressObj(account: HexLike): Promise<Address> {\n return Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x12, ...bytesFrom(account), 0x00]),\n );\n }\n\n async _getOmniLockOldEvmAddressObj(account: HexLike): Promise<Address> {\n return Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x1, ...bytesFrom(account), 0x00]),\n );\n }\n\n async _getPWLockEvmAddressObj(\n account: HexLike,\n ): Promise<Address | undefined> {\n try {\n return Address.fromKnownScript(\n this.client,\n KnownScript.PWLock,\n hexFrom(bytesFrom(account)),\n );\n } catch {}\n return;\n }\n\n /**\n * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n if (\n (await tx.findInputIndexByLockId(\n await this.client.getKnownScript(KnownScript.OmniLock),\n this.client,\n )) !== undefined\n ) {\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.OmniLock);\n }\n if (\n (await tx.findInputIndexByLockId(\n await this.client.getKnownScript(KnownScript.PWLock),\n this.client,\n )) !== undefined\n ) {\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.PWLock);\n }\n\n const account = await this.getEvmAccount();\n const omniLockAddresses = await this._getOmniLockAddresses(account);\n const pwLockAddresses = await this._getPWLockAddresses(account);\n\n const omniTx = reduceAsync(\n omniLockAddresses,\n (tx: Transaction, { script }) =>\n tx.prepareSighashAllWitness(script, 85, this.client),\n tx,\n );\n\n return reduceAsync(\n pwLockAddresses,\n (tx: Transaction, { script }) =>\n tx.prepareSighashAllWitness(script, 65, this.client),\n omniTx,\n );\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n let tx = Transaction.from(txLike);\n\n const account = await this.getEvmAccount();\n const { script: evmScript } = await this._getOmniLockEvmAddressObj(account);\n const { script: oldEvmScript } =\n await this._getOmniLockOldEvmAddressObj(account);\n\n tx = await this._signOmniLockScriptForTransaction(\n tx,\n evmScript,\n (hash) => `CKB transaction: ${hash}`,\n );\n tx = await this._signOmniLockScriptForTransaction(\n tx,\n oldEvmScript,\n (hash) => bytesFrom(hash),\n );\n\n const pwAddress = await this._getPWLockEvmAddressObj(account);\n if (pwAddress) {\n tx = await this._signPWLockScriptForTransaction(\n tx,\n pwAddress.script,\n (hash) => bytesFrom(hash),\n );\n }\n\n return tx;\n }\n\n async _signOmniLockScriptForTransaction(\n tx: Transaction,\n script: Script,\n messageTransformer: (hash: string) => BytesLike,\n ): Promise<Transaction> {\n const info = await this._signPersonalEvmForTransaction(\n tx,\n script,\n messageTransformer,\n );\n if (!info) {\n return tx;\n }\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(\n bytesConcat(\n numToBytes(5 * 4 + info.signature.length, 4),\n numToBytes(4 * 4, 4),\n numToBytes(5 * 4 + info.signature.length, 4),\n numToBytes(5 * 4 + info.signature.length, 4),\n numToBytes(info.signature.length, 4),\n info.signature,\n ),\n );\n\n tx.setWitnessArgsAt(info.position, witness);\n\n return tx;\n }\n\n async _signPWLockScriptForTransaction(\n tx: Transaction,\n script: Script,\n messageTransformer: (hash: string) => BytesLike,\n ): Promise<Transaction> {\n const info = await this._signPersonalEvmForTransaction(\n tx,\n script,\n messageTransformer,\n new HasherKeecak256(),\n );\n if (!info) {\n return tx;\n }\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(info.signature);\n tx.setWitnessArgsAt(info.position, witness);\n\n return tx;\n }\n\n async _signPersonalEvmForTransaction(\n tx: Transaction,\n script: Script,\n messageTransformer: (hash: string) => BytesLike,\n hasher?: Hasher,\n ): Promise<{ signature: Bytes; position: number } | undefined> {\n const info = await tx.getSignHashInfo(script, this.client, hasher);\n if (!info) {\n return;\n }\n\n const signature = bytesFrom(\n await this.signMessageRaw(messageTransformer(info.message)),\n );\n if (signature[signature.length - 1] >= 27) {\n signature[signature.length - 1] -= 27;\n }\n\n return { signature, position: info.position };\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { SignerEvm } from \"./signerEvm.js\";\n\n/**\n * A class extending SignerEvm that provides read-only access to an EVM address.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerEvmAddressReadonly extends SignerEvm {\n private readonly address: Hex;\n\n /**\n * Creates an instance of SignerEvmAddressReadonly.\n *\n * @param client - The client instance used for communication.\n * @param address - The EVM address associated with the signer.\n */\n constructor(client: Client, address: HexLike) {\n super(client);\n\n this.address = hexFrom(address);\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n *\n * @example\n * ```typescript\n * await signer.connect();\n * ```\n */\n\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the EVM account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the EVM account.\n *\n * @example\n * ```typescript\n * const account = await signer.getEvmAccount(); // Outputs the EVM account\n * ```\n */\n async getEvmAccount(): Promise<Hex> {\n return this.address;\n }\n}\n","import { bech32 } from \"bech32\";\nimport { Address } from \"../../address/index.js\";\nimport { BytesLike, bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { hashCkb } from \"../../hasher/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\nimport { buildNostrEventFromMessage } from \"./verify.js\";\n\n/**\n * @public\n */\nexport interface NostrEvent {\n id?: string;\n pubkey?: string;\n sig?: string;\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n}\n\n/**\n * @public\n */\nexport abstract class SignerNostr extends Signer {\n static CKB_SIG_HASH_ALL_TAG = \"ckb_sighash_all\";\n static CKB_UNLOCK_EVENT_KIND = 23334;\n static CKB_UNLOCK_EVENT_CONTENT =\n \"Signing a CKB transaction\\n\\nIMPORTANT: Please verify the integrity and authenticity of connected Nostr client before signing this message\\n\";\n\n get type(): SignerType {\n return SignerType.Nostr;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.NostrEvent;\n }\n\n /**\n * Gets the Nostr public key associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Nostr public key.\n */\n abstract getNostrPublicKey(): Promise<Hex>;\n\n /**\n * Sign a nostr event.\n *\n * @returns A promise that resolves to the signed event.\n */\n async signNostrEvent(_event: NostrEvent): Promise<Required<NostrEvent>> {\n throw Error(\"SignerNostr.signNostrEvent not implemented\");\n }\n\n /**\n * Sign a message.\n *\n * @returns A promise that resolves to the signature.\n */\n async signMessageRaw(message: string | BytesLike): Promise<Hex> {\n return hexFrom(\n (await this.signNostrEvent(buildNostrEventFromMessage(message))).sig,\n );\n }\n\n /**\n * Gets the internal address, which is the EVM account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return bech32.encode(\n \"npub\",\n bech32.toWords(bytesFrom(await this.getNostrPublicKey())),\n );\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const publicKey = await this.getNostrPublicKey();\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.NostrLock,\n hexFrom(bytesConcat([0x00], hashCkb(publicKey).slice(0, 42))),\n ),\n ];\n }\n\n /**\n * prepare a transaction before signing.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.NostrLock);\n await tx.prepareSighashAllWitness(script, 572, this.client);\n return tx;\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signedEvent = bytesFrom(\n JSON.stringify(\n await this.signNostrEvent({\n pubkey: (await this.getNostrPublicKey()).slice(2),\n tags: [[SignerNostr.CKB_SIG_HASH_ALL_TAG, info.message.slice(2)]],\n created_at: Math.floor(Date.now() / 1000),\n kind: SignerNostr.CKB_UNLOCK_EVENT_KIND,\n content: SignerNostr.CKB_UNLOCK_EVENT_CONTENT,\n }),\n ),\n \"utf8\",\n );\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(signedEvent);\n tx.setWitnessArgsAt(info.position, witness);\n\n return tx;\n }\n}\n","import { bech32 } from \"bech32\";\nimport { Client } from \"../../client/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport { SignerNostr } from \"./signerNostr.js\";\n\n/**\n * Signer from Nostr public key\n * Support npub and hex format\n */\nexport class SignerNostrPublicKeyReadonly extends SignerNostr {\n public readonly publicKey: Hex;\n\n constructor(client: Client, publicKey: HexLike) {\n super(client);\n\n if (typeof publicKey === \"string\" && publicKey.startsWith(\"npub\")) {\n const { words } = bech32.decode(publicKey);\n this.publicKey = hexFrom(bech32.fromWords(words));\n } else {\n this.publicKey = hexFrom(publicKey);\n }\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getNostrPublicKey(): Promise<Hex> {\n return this.publicKey;\n }\n}\n","import { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { bech32 } from \"bech32\";\nimport { Bytes, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { NostrEvent } from \"./signerNostr.js\";\nimport { SignerNostrPublicKeyReadonly } from \"./signerNostrPublicKeyReadonly.js\";\nimport { nostrEventHash } from \"./verify.js\";\n\n/**\n * Signer from Nostr private key\n * Support nsec and hex format\n */\nexport class SignerNostrPrivateKey extends SignerNostrPublicKeyReadonly {\n private readonly privateKey: Bytes;\n\n constructor(client: Client, privateKeyLike: BytesLike) {\n const privateKey = (() => {\n if (\n typeof privateKeyLike === \"string\" &&\n privateKeyLike.startsWith(\"nsec\")\n ) {\n const { words } = bech32.decode(privateKeyLike);\n return bytesFrom(bech32.fromWords(words));\n }\n\n return bytesFrom(privateKeyLike);\n })();\n\n super(client, schnorr.getPublicKey(privateKey));\n\n this.privateKey = privateKey;\n }\n\n async signNostrEvent(event: NostrEvent): Promise<Required<NostrEvent>> {\n const pubkey = (await this.getNostrPublicKey()).slice(2);\n const eventHash = nostrEventHash({ ...event, pubkey });\n const signature = schnorr.sign(eventHash, this.privateKey);\n\n return {\n ...event,\n id: hexFrom(eventHash).slice(2),\n pubkey,\n sig: hexFrom(signature).slice(2),\n };\n }\n}\n","export * from \"./address/index.js\";\nexport * from \"./bytes/index.js\";\nexport * from \"./ckb/index.js\";\nexport * from \"./client/index.js\";\nexport * from \"./codec/index.js\";\nexport * from \"./fixedPoint/index.js\";\nexport * from \"./hasher/index.js\";\nexport * from \"./hex/index.js\";\nexport * from \"./jsonRpc/index.js\";\nexport * from \"./keystore/index.js\";\nexport * from \"./molecule/index.js\";\nexport * from \"./num/index.js\";\nexport * from \"./signer/index.js\";\nexport * from \"./utils/index.js\";\n"],"mappings":"0kEAQA,IAAa,GAAb,KAA+C,CAO7C,aAAc,CACZ,KAAK,OAAS,GAAW,OAAO,CAClC,CAgBA,OAAO,EAAkC,CAEvC,OADA,KAAK,OAAO,OAAO,EAAU,CAAI,CAAC,EAC3B,IACT,CAeA,QAAc,CACZ,OAAO,EAAQ,KAAK,OAAO,OAAO,CAAC,CACrC,CACF,wlCE5BsB,GAAtB,KAAkC,CAIhC,MAAM,WAAW,GAAG,EAAqD,CAEvE,OADA,MAAM,KAAK,YAAY,GAAG,CAAS,EAC5B,KAAK,kBAAkB,GAAG,CAAS,CAC5C,CAIA,MAAM,iBACJ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