{"version":3,"file":"barrel-DWr0OZgc.mjs","names":["__exportAll","CodecUint8","BytesVec","Since","CodecByte32","bytesConcat","retry","ErrorTransactionInsufficientCapacity","CodecUint16LE","BoolVec","CellInput","struct","hashCkbShort","epochFromHex","DepTypeCodec","CodecBool","hexFrom","gcd","CellOutputVec","vector","bytesLenUnsafe","apply","depTypeFrom","CodecUint128","Owner","HashTypeCodec","CodecUint32BE","Byte4Opt","CodecUint256BE","Byte16Vec","depTypeFromBytes","CodecUint128BE","OwnerMoved","ScriptVec","CodecUint512BE","Byte8Vec","Script","CodecUint32LE","Byte4Vec","depTypeToBytes","CodecUint128LE","abortSignalAny","WitnessArgs","CodecByte8","bytesEq","stringify","calcDaoClaimEpoch","CodecBytes","bytesFrom","waitForAvailability","OutPoint","CodecByte","Codec","isWebview","calcDaoProfit","CodecRaw","bytesTo","OwnerUnique","CodecUint64LE","BytesOpt","isDaoOutputLimitExceeded","CodecUint16","abortSignalToPromise","CellDepVec","option","hashCkb","epochFrom","CellOutput","union","bytesLen","__decorate","CodecUint256LE","Byte32Opt","ErrorTransactionInsufficientCoin","CodecUint256","Byte16Opt","CodecUint32","Byte32Vec","hashTypeFromBytes","CodecUint64","ByteVec","hashTypeFrom","CodecUint512LE","ByteOpt","hashTypeToBytes","CodecUint64BE","Bytes","array","Entity","ScriptInfo","addressPayloadFromString","Uint16Opt","numFrom","ClientBlockUncle","CellAny","fixedItemVec","jsonRpcTransportFromUri","Uint256Vec","numLeToBytes","ClientIndexerSearchKeyTransaction","MAINNET_SCRIPTS","Uint512Opt","numToBytes","ErrorClientDuplicatedTransaction","String","codecPadding","DEFAULT_CONFIRMED_BLOCK_TIME","Uint512Vec","numToHex","ErrorClientMaxFeeRateExceeded","Uint8Vec","fixedPointToString","ErrorClientWaitTransactionTimeout","Uint8Opt","fixedPointFrom","ErrorClientVerification","addressFromPayload","Uint128Vec","numBeToBytes","ClientBlockHeader","Transaction","CodecByte4","bytesConcatTo","sleep","RawTransaction","CodecByte16","Bytes$1","reduceAsync","JsonRpcTransportWebSocket","Uint32Opt","numMax","ClientTransactionResponse","filterCell","Uint64Vec","Zero","ErrorClientResolveUnknown","ADDRESS_BECH32_LIMIT","StringVec","codecUintNumber","CellDepInfo","TESTNET_SCRIPTS","Uint16Vec","numFromBytes","ClientIndexerSearchKey","MapLru","Uint64Opt","One","ErrorClientRBFRejected","ScriptOpt","CodecUint512","Byte8Opt","Uint128Opt","numBeFromBytes","ClientBlock","JsonRpcTransformers","Uint256Opt","numLeFromBytes","ClientIndexerSearchKeyFilter","SignerJsonRpcTransformers","StringOpt","codecUint","KnownScript","JsonRpcTransportHttp","Uint32Vec","numMin","ErrorClientBase","byteVec","codec","DEFAULT_MAX_FEE_RATE","CellInputVec","table","epochToHex","CellDep","fixedUnion","HasherCkb","Epoch","Cell","dynItemVec","DEFAULT_MIN_FEE_RATE","udtBalanceFrom","CodecUint16BE","BoolOpt","WebSocket","bs58check","HasherKeecak256","keccak_256","data","barrel_exports$1","OwnerAggregated","value_","owners","values","owner","moved","results","errors","result","OwnerRefCount","state","value","disposer","Proxy","inner","localKeys","Base","ProxyClass","innerValue","allLocalKeys","forwardedFunctions","prototype","property","constructor","metadataKeys","isLocalProperty","target","isLocal","receiver","cached","args","BasePrototype","BaseClass","hashTypeId","cellInputLike","outputIndex","ClientCache","cellLikes","transactionLike","transactions","txHash","tx","index","input","_cells","_transactions","_headers","_blocks","header","ClientCacheMemory","maxCells","maxTxs","maxBlocks","confirmedBlockTimeLike","cell","cellLike","outPointStr","outPointLikes","outPoint","outPointLike","existed","key","isLive","keyLike","cells","txLike","txHashLike","headers","headerLike","hash","hashLike","block","number","numberLike","blocks","blockLike","Client","config","found","script","feeRate","blockRange","maxFeeRate","options","blockNumber","res","verbosity","withCycles","blockHash","transaction","output","withData","includeTxPool","order","limit","after","last","lastCursor","foundedOutPoints","founded","lock","type","cellDepsInfoLike","infoLike","cellDep","locks","acc","validator","startTime","getTx","confirmations","interval","timeout","JsonRpcTransportFallback","transports","startI","lastErr","tried","i","err","JsonRpcError","error","openTransports","transportOwners","urls","url","transform","transformer","RequestorJsonRpc","url_","onError","fallbacks","payload","rpcMethod","inTransformers","params","v","outTransformer","resolvePending","pending","resolve","cause","req","ERROR_PARSERS","match","handleJsonRpcError","errAny","regexp","builder","ClientJsonRpc","n","b","cycles","capacity","requestor","ClientPublicMainnet","defaultUrls","resolved","requestorConfig","ClientPublicTestnet","Address","prefix","address","parsed","client","clients","resolver","expectedPrefix","format","bech32m","mac","derivedKey","cipherText","keystoreEncrypt","salt","randomBytes","iv","kdfparams","scryptAsync","password","ciphertext","ctr","privateKeyLike","chainCodeLike","keystoreDecrypt","keystore","crypto","SignPsbtOptions","autoFinalized","inputsToSign","InputToSign","sighashTypes","disableTweakSigner","publicKey","btcVarLengthBytesFrom","num","len","messageHashBtcEcdsa","messagePrefix","rawPrefix","rawMsg","message","sha256","btcEcdsaPublicKeyHash","ripemd160","btcP2pkhAddressFromPublicKey","network","btcPublicKeyFromP2pkhAddress","verifyMessageBtcEcdsa","challenge","rawSign","signature","secp256k1","SECP256K1_SIGNATURE_LENGTH","signMessageSecp256k1","privateKey","verifyMessageSecp256k1","signatureBytes","recoverMessageSecp256k1","messageHashCkbSecp256k1","msg","buffer","verifyMessageCkbSecp256k1","verifyBinaryPasskeySignature","signedMessage","clientData","signatureBase","p256","verifySessionKeySignature","verifyMessageJoyId","identity","keyType","signed","isPasskey","verifySignature","SigningAlg","messageHashDogeEcdsa","verifyMessageDogeEcdsa","verifyMessageEvmPersonal","verifyMessage","buildNostrEventFromMessage","event","tag","nostrEventHash","serialized","verifyMessageNostrEvent","bech32","pubkey","words","eventHash","schnorr","SignerSignType","\"Unknown\"","\"BtcEcdsa\"","\"EvmPersonal\"","\"JoyId\"","\"NostrEvent\"","\"CkbSecp256k1\"","\"DogeEcdsa\"","SignerType","\"EVM\"","\"BTC\"","\"CKB\"","\"Nostr\"","\"Doge\"","Signature","signType","Signer","client_","preferences","signerType","addressPrefix","currentNetwork","preference","addresses","scripts","preparedTx","SignerMultisig","signedTx","SignerMultisigNotEnoughSignaturesError","signaturesCount","threshold","SignerInfo","name","signer","SignerBtc","signedPsbt","psbtHex","info","witness","SignerBtcPublicKeyReadonly","account","SignerCkbAlwaysSuccess","SignerCkbPublicKey","count","acp","cellDeps","SignerCkbPrivateKey","pk","SignerCkbScriptReadonly","_MultisigCkbWitness","sinceSatisfiesConstraint","inputSince","inputSinceLike","since","MultisigCkbWitness","publicKeyHashes","mustMatch","signatures","keysLength","k","other","otherLike","h","publicKeyHashesFromSignature","sig","SignerMultisigCkbReadonly","pubkeyHash","required","flexible","isRequired","encodable","s","raw","_reserved","publicKeyHashesLength","rawKeyAndSignatures","multisigInfoLike","infos","witnessLike","decoded","witnessArgs","multisigWitness","transformed","scriptLike","position","cellOutput","minSignaturesCount","clonedTx","txs","requiredCount","SignerMultisigCkbPrivateKey","multisigInfo","thisPubkeyHash","isSelfRequired","isSignNeeded","SignerDoge","SignerDogeAddressReadonly","SignerDogePrivateKey","dogeNetwork","SignerDummy","SignerAlwaysError","SignerOpenLink","link","SignerEvm","addr","omniLockAddresses","pwLockAddresses","omniTx","evmScript","oldEvmScript","pwAddress","messageTransformer","hasher","SignerEvmAddressReadonly","signerJsonRpcNetworkIdFromAddressPrefix","GET_RESULT_PENDING_RESULT","SignerJsonRpcErrorCode","\"MethodNotFound\"","\"InvalidParams\"","\"ServerError\"","\"InvalidState\"","\"NetworkMismatch\"","\"UserRejected\"","\"InvalidSession\"","\"DuplicateRequestId\"","SignerJsonRpcProviderSession","signal","metadata","requireParams","parseRequestMetadata","targetRequestId","requireRequestId","requestId","isGetInfo","sessionId","entry","paramCount","handler","buildSignerInfo","networkId","actualNetworkId","parsedMessage","parseMessageParam","parseTransactionParam","parsedTransaction","session","confirmed","request","completion","expire","oldestRetrieved","controller","rebuildPseudoInput","previousOutput","GET_RESULT_RETRY_DELAYS","REQUEST_RETRY_DELAYS","SignerJsonRpc","disconnectHandler","connecting","listener","requestsController","listeners","method","reject","getResultStartedAt","requestError","remaining","next","SignerNostr","signedEvent","SignerNostrPublicKeyReadonly","SignerNostrPrivateKey","barrel_exports"],"sources":["../src/hasher/hasherKeecak256.ts","../src/molecule/barrel.ts","../src/utils/owner/aggregated.ts","../src/utils/owner/refCount.ts","../src/utils/proxy.ts","../src/ckb/hash.ts","../src/client/cache/cache.ts","../src/client/cache/memory.ts","../src/client/client.ts","../src/jsonRpc/transports/fallback.ts","../src/jsonRpc/transports/transport.ts","../src/jsonRpc/requestor.ts","../src/client/jsonRpc/client.ts","../src/client/clientPublicMainnet.ts","../src/client/clientPublicTestnet.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/signerCkbAlwaysSuccess.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/jsonRpc/network.ts","../src/signer/jsonRpc/handler.ts","../src/signer/jsonRpc/signer.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 { Owner, OwnerMoved } from \"./owner.js\";\n\n// TypeScript has no existential type for heterogeneous Owner values.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Owners = readonly Owner<any>[];\n\ntype OwnerValues<T extends Owners> = {\n  [K in keyof T]: T[K] extends Owner<infer U> ? U : never;\n};\n\n/**\n * An Owner that aggregates multiple ownership claims.\n *\n * Disposing it attempts to release every claim and aggregates any failures.\n *\n * @public\n */\nexport class OwnerAggregated<T extends readonly unknown[]> extends Owner<T> {\n  private constructor(\n    protected readonly value_: T,\n    private readonly owners: readonly OwnerMoved<unknown>[],\n  ) {\n    super();\n  }\n\n  /** Moves multiple ownership claims into one Owner. */\n  static from<const TOwners extends Owners>(\n    owners: TOwners,\n  ): OwnerAggregated<OwnerValues<TOwners>> {\n    if (new Set(owners).size !== owners.length) {\n      throw new Error(\"Cannot aggregate the same Owner more than once\");\n    }\n\n    // Validate every source before moving any of them.\n    const values = owners.map(\n      (owner): unknown => owner.value,\n    ) as OwnerValues<TOwners>;\n    const moved = owners.map((owner) => this.moveFrom(owner));\n    return new OwnerAggregated(values, moved);\n  }\n\n  protected async release(): Promise<void> {\n    const results = await Promise.allSettled(\n      this.owners.map((owner) => owner.dispose()),\n    );\n    const errors: unknown[] = [];\n    for (const result of results) {\n      if (result.status === \"rejected\") {\n        errors.push(result.reason as unknown);\n      }\n    }\n    if (errors.length !== 0) {\n      throw new AggregateError(errors, \"Failed to dispose aggregated Owners\");\n    }\n  }\n}\n","import { Owner, OwnerMoved } from \"./owner.js\";\n\ntype OwnerRefCountState<T> = {\n  owner: OwnerMoved<T>;\n  referenceCount: number;\n};\n\n/**\n * A reference-counted Owner for a shared value.\n *\n * The source ownership is disposed after the final OwnerRefCount is disposed.\n * Each clone owns one reference and can be disposed independently.\n *\n * @example\n * ```ts\n * const controller = new AbortController();\n * const first = OwnerRefCount.new(\n *   controller,\n *   (controller) => controller.abort(),\n * );\n * const second = first.clone();\n *\n * await first.dispose();\n * console.log(controller.signal.aborted); // false\n *\n * await second.dispose();\n * console.log(controller.signal.aborted); // true\n * ```\n *\n * @public\n */\nexport class OwnerRefCount<T> extends Owner<T> {\n  private constructor(private readonly state: OwnerRefCountState<T>) {\n    super();\n  }\n\n  protected get value_(): T {\n    return this.state.owner.value;\n  }\n\n  /** Creates the first reference-counted Owner for a value. */\n  static new<T>(\n    value: T,\n    disposer: (value: T) => PromiseLike<void> | void,\n  ): OwnerRefCount<T> {\n    return new OwnerRefCount({\n      owner: new OwnerMoved(value, disposer),\n      referenceCount: 1,\n    });\n  }\n\n  /**\n   * Moves an ownership claim into a new reference-counted Owner.\n   *\n   * @throws If the source Owner has already been moved or disposed.\n   */\n  static from<T>(owner: Owner<T>): OwnerRefCount<T> {\n    return new OwnerRefCount({\n      owner: this.moveFrom(owner),\n      referenceCount: 1,\n    });\n  }\n\n  /** Creates another Owner for the same shared value. */\n  clone(): OwnerRefCount<T> {\n    // Assert that this Owner is still active before adding a reference.\n    void this.value;\n    this.state.referenceCount += 1;\n    return new OwnerRefCount(this.state);\n  }\n\n  protected release(): Promise<void> | void {\n    this.state.referenceCount -= 1;\n    if (this.state.referenceCount === 0) {\n      return this.state.owner.dispose();\n    }\n  }\n}\n","import type { AbstractConstructor, Constructor } from \"./constructor.js\";\n\n/**\n * Utilities for creating composition wrappers.\n *\n * @example\n * ```ts\n * class Wrapper extends Proxy.Base(Client) {\n *   static readonly [Proxy.localKeys] = [\"feeRate\"];\n *   public feeRate = 1000;\n *\n *   request(): void {\n *     this[Proxy.inner].request();\n *   }\n * }\n *\n * const wrapper = new Wrapper(client);\n * ```\n *\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace Proxy {\n  /** The property key for accessing the immediately wrapped object. */\n  export const inner = \"@ckb-ccc/core.Proxy.inner\";\n\n  /**\n   * The static metadata key for instance fields that belong to the wrapper.\n   * Every wrapper instance field must be listed here. Prototype members are\n   * detected automatically.\n   */\n  export const localKeys: unique symbol = Symbol.for(\n    \"@ckb-ccc/core.Proxy.localKeys\",\n  );\n\n  /**\n   * Creates a wrapper base that delegates non-local members to an inner instance.\n   * Its constructor accepts the inner instance and does not invoke `BaseClass`.\n   *\n   * @remarks\n   * Wrapping an abstract class may require suppressing TS2655 because its abstract\n   * members are implemented by runtime delegation.\n   *\n   * @param BaseClass - The class represented by the wrapper.\n   */\n  export function Base<BaseClass extends AbstractConstructor<object>>(\n    BaseClass: BaseClass,\n  ): Omit<BaseClass, \"prototype\"> &\n    Constructor<\n      InstanceType<BaseClass> & {\n        readonly [inner]: InstanceType<BaseClass>;\n      },\n      [InstanceType<BaseClass>]\n    > {\n    type T = InstanceType<BaseClass>;\n\n    class ProxyClass {\n      public readonly [inner]: T;\n\n      constructor(innerValue: T) {\n        this[inner] = innerValue;\n\n        const allLocalKeys = new Set<PropertyKey>([inner]);\n        const forwardedFunctions = new Map<\n          PropertyKey,\n          { value: unknown; wrapper: (...args: unknown[]) => unknown }\n        >();\n\n        // Members introduced between the concrete subclass and ProxyClass belong\n        // to the wrapper. Stop before ProxyClass so members inherited from Base\n        // continue to be forwarded to inner.\n        for (\n          let prototype: object | null = new.target.prototype;\n          prototype !== null && prototype !== ProxyClass.prototype;\n          prototype = Reflect.getPrototypeOf(prototype)\n        ) {\n          // Every member defined directly on this prototype belongs to the wrapper.\n          for (const property of Reflect.ownKeys(prototype)) {\n            allLocalKeys.add(property);\n          }\n\n          // Resolve the class that owns this prototype and merge the local keys\n          // declared in its static metadata.\n          const constructor = Object.getOwnPropertyDescriptor(\n            prototype,\n            \"constructor\",\n          )?.value as unknown;\n\n          try {\n            const metadataKeys = Object.getOwnPropertyDescriptor(\n              constructor,\n              localKeys,\n            )?.value as readonly PropertyKey[] | undefined;\n            for (const property of metadataKeys ?? []) {\n              allLocalKeys.add(property);\n            }\n          } catch {}\n        }\n\n        const isLocalProperty = (\n          target: object,\n          property: PropertyKey,\n        ): boolean =>\n          allLocalKeys.has(property) ||\n          Reflect.getOwnPropertyDescriptor(target, property) !== undefined;\n\n        return new globalThis.Proxy(this, {\n          deleteProperty: (target, property) => {\n            return Reflect.deleteProperty(\n              isLocalProperty(target, property) ? target : innerValue,\n              property,\n            );\n          },\n          get: (target, property, receiver) => {\n            const isLocal = isLocalProperty(target, property);\n            const value = Reflect.get(\n              isLocal ? target : innerValue,\n              property,\n              isLocal ? receiver : innerValue,\n            ) as unknown;\n            if (isLocal || typeof value !== \"function\") {\n              return value;\n            }\n\n            let cached = forwardedFunctions.get(property);\n            if (cached?.value !== value) {\n              cached = {\n                value,\n                wrapper: (...args: unknown[]): unknown =>\n                  Reflect.apply(value, innerValue, args) as unknown,\n              };\n              forwardedFunctions.set(property, cached);\n            }\n            return cached.wrapper;\n          },\n          has: (target, property) => {\n            return Reflect.has(\n              isLocalProperty(target, property) ? target : innerValue,\n              property,\n            );\n          },\n          set: (target, property, value, receiver) => {\n            const isLocal = isLocalProperty(target, property);\n            return Reflect.set(\n              isLocal ? target : innerValue,\n              property,\n              value,\n              isLocal ? receiver : innerValue,\n            );\n          },\n        });\n      }\n    }\n\n    // Preserve the runtime instance and static inheritance relationships without\n    // constructing a second BaseClass instance as the proxy target.\n    const BasePrototype = (BaseClass as unknown as { prototype: object })\n      .prototype;\n    Object.setPrototypeOf(ProxyClass.prototype, BasePrototype);\n    Object.setPrototypeOf(ProxyClass, BaseClass);\n\n    return ProxyClass as unknown as Omit<BaseClass, \"prototype\"> &\n      Constructor<T & { readonly [inner]: T }, [T]>;\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 {\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    const transactions = transactionLike.flat().map(Transaction.from);\n\n    await this.recordTransactionResponses(\n      transactions.map((transaction) => ({\n        transaction,\n        status: \"sent\",\n      })),\n    );\n\n    await Promise.all(\n      transactions.flatMap((tx) => {\n        const txHash = tx.hash();\n        return tx.outputs.map((cellOutput, index) =>\n          this.markUsable({\n            cellOutput,\n            outputData: tx.outputsData[index],\n            outPoint: {\n              txHash,\n              index,\n            },\n          }),\n        );\n      }),\n    );\n\n    await Promise.all(\n      transactions.flatMap((tx) =>\n        tx.inputs.map((input) => this.markUnusable(input.previousOutput)),\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  type ScriptInfoLike,\n} from \"./clientTypes.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * Resolves address representations that `Address.fromString` cannot parse,\n * such as human-readable names, to scripts.\n *\n * @public\n */\nexport interface AddressResolver {\n  /** Whether this resolver handles the representation. */\n  shouldResolve(address: string): boolean;\n  /** The script it points to, or `undefined` if it is not found. */\n  resolve(address: string, client: Client): Promise<ScriptLike | undefined>;\n}\n\nexport type ClientConfig = {\n  cache?: ClientCache;\n  scripts?: Partial<Record<KnownScript, ScriptInfoLike>>;\n  addressResolver?: AddressResolver;\n};\n\n/**\n * @public\n */\nexport abstract class Client {\n  public cache: ClientCache;\n  private readonly scripts: Partial<Record<KnownScript, ScriptInfoLike>>;\n  public readonly addressResolver?: AddressResolver;\n\n  constructor(config?: ClientConfig) {\n    this.cache = config?.cache ?? new ClientCacheMemory();\n    this.scripts = config?.scripts ?? {};\n    this.addressResolver = config?.addressResolver;\n  }\n\n  /**\n   * The legacy primary URL associated with this Client.\n   *\n   * @deprecated A Client may use multiple endpoints or a Transport without a\n   * URL, so this value does not reliably identify its connection.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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  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  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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 - Deprecated; this parameter has no effect.\n   * @returns The tip block header.\n   *\n   * @example\n   * ```typescript\n   * import { ccc } from \"@ckb-ccc/core\";\n   *\n   * const clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\n   * const header = await client.getTipHeader();\n   * console.log(`Block #${header.number}, hash: ${header.hash}`);\n   * ```\n   */\n  abstract getTipHeader(\n    /** @deprecated This parameter has no effect and will be removed. */\n    verbosity?: number | null,\n  ): Promise<ClientBlockHeader>;\n  abstract getBlockByNumberNoCache(\n    blockNumber: NumLike,\n    /** @deprecated This parameter has no effect and will be removed. */\n    verbosity?: number | null,\n    /**\n     * @deprecated This parameter has no effect and will be removed.\n     */\n    withCycles?: boolean | null,\n  ): Promise<ClientBlock | undefined>;\n  abstract getBlockByHashNoCache(\n    blockHash: HexLike,\n    /** @deprecated This parameter has no effect and will be removed. */\n    verbosity?: number | null,\n    /**\n     * @deprecated This parameter has no effect and will be removed.\n     */\n    withCycles?: boolean | null,\n  ): Promise<ClientBlock | undefined>;\n  abstract getHeaderByNumberNoCache(\n    blockNumber: NumLike,\n    /** @deprecated This parameter has no effect and will be removed. */\n    verbosity?: number | null,\n  ): Promise<ClientBlockHeader | undefined>;\n  abstract getHeaderByHashNoCache(\n    blockHash: HexLike,\n    /** @deprecated This parameter has no effect and will be removed. */\n    verbosity?: number | null,\n  ): Promise<ClientBlockHeader | undefined>;\n  async getBlockByNumber(\n    blockNumber: NumLike,\n    /** @deprecated This parameter has no effect and will be removed. */\n    verbosity?: number | null,\n    /**\n     * @deprecated This parameter has no effect and will be removed.\n     */\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    /** @deprecated This parameter has no effect and will be removed. */\n    verbosity?: number | null,\n    /**\n     * @deprecated This parameter has no effect and will be removed.\n     */\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    /** @deprecated This parameter has no effect and will be removed. */\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    /** @deprecated This parameter has no effect and will be removed. */\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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    if (key.withData !== false) {\n      await this.cache.recordCells(res.cells);\n    }\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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   *\n   * If a CellDepInfo specifies a type script, the live cell carrying it is looked up\n   * on-chain and, when found, its outpoint is used instead of the configured one. When\n   * the lookup finds nothing, the configured outpoint is used as written. A CellDepInfo\n   * without a type script is always used as written.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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 clientOwner = ccc.ClientPublicTestnet.open();\n   * const client = clientOwner.value;\n   * // Call `await clientOwner.dispose()` when the client is no longer needed.\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  JsonRpcResponse,\n  JsonRpcTransport,\n  JsonRpcTransportRequestOptions,\n} from \"./transport.js\";\n\nexport class JsonRpcTransportFallback implements JsonRpcTransport {\n  // Current transport index\n  private i = 0;\n\n  constructor(private readonly transports: JsonRpcTransport[]) {}\n\n  async request(\n    data: JsonRpcPayload,\n    options?: JsonRpcTransportRequestOptions,\n  ): Promise<JsonRpcResponse> {\n    const startI = this.i;\n    let lastErr: unknown = new Error(\n      \"JsonRpcTransportFallback requires at least one transport\",\n    );\n\n    for (let tried = 0; tried < this.transports.length; tried += 1) {\n      const i = (startI + tried) % this.transports.length;\n\n      try {\n        const res = await this.transports[i].request(data, options);\n\n        this.i = i;\n        return res;\n      } catch (err) {\n        lastErr = err;\n      }\n    }\n\n    throw lastErr;\n  }\n}\n","export type JsonRpcId = string | number;\n\nexport type JsonRpcPayload = {\n  id: JsonRpcId;\n  jsonrpc: \"2.0\";\n  method: string;\n  params: unknown[] | Record<string, unknown>;\n};\n\nexport type JsonRpcErrorLike<Data = unknown> = {\n  code: number;\n  message: string;\n  data?: Data;\n};\n\nexport class JsonRpcError<Data = unknown> extends Error {\n  readonly code: number;\n  readonly data?: Data;\n\n  constructor(error: JsonRpcErrorLike<Data>) {\n    super(error.message);\n    this.name = \"JsonRpcError\";\n    this.code = error.code;\n    this.data = error.data;\n  }\n}\n\nexport type JsonRpcResponse<Result = unknown, ErrorData = unknown> = {\n  id: JsonRpcId;\n  jsonrpc: \"2.0\";\n} & (\n  | { result: Result; error?: never }\n  | { result?: never; error: JsonRpcErrorLike<ErrorData> }\n);\n\nexport type JsonRpcTransportRequestOptions = {\n  /** Cancels this individual request without disposing the transport. */\n  signal?: AbortSignal;\n  /** Overrides the transport's default timeout for this request. */\n  timeout?: number;\n};\n\nexport interface JsonRpcTransport {\n  /**\n   * Sends a JSON-RPC request to the server.\n   *\n   * @param payload - The JSON-RPC payload to send.\n   * @returns The JSON-RPC response.\n   */\n  request(\n    payload: JsonRpcPayload,\n    options?: JsonRpcTransportRequestOptions,\n  ): Promise<JsonRpcResponse>;\n}\n","import { abortSignalToPromise } from \"../utils/abortSignal.js\";\nimport { OwnerAggregated } from \"../utils/owner/aggregated.js\";\nimport { Owner } from \"../utils/owner/owner.js\";\nimport { jsonRpcTransportFromUri } from \"./transports/factory.js\";\nimport { JsonRpcTransportFallback } from \"./transports/fallback.js\";\nimport {\n  JsonRpcError,\n  JsonRpcPayload,\n  JsonRpcResponse,\n  JsonRpcTransport,\n  JsonRpcTransportRequestOptions,\n} from \"./transports/index.js\";\n\nfunction openTransports(\n  urls: readonly [string, ...string[]],\n  config?: { timeout?: number },\n): Owner<JsonRpcTransportFallback> {\n  const transportOwners = Array.from(new Set(urls), (url) =>\n    jsonRpcTransportFromUri(url, config),\n  );\n  return OwnerAggregated.from(transportOwners).map(\n    (transports) => new JsonRpcTransportFallback([...transports]),\n  );\n}\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\n/**\n * @deprecated Used only by the legacy positional constructor. Use the static\n * {@link RequestorJsonRpc.new} or {@link RequestorJsonRpc.open} methods.\n */\nexport type RequestorJsonRpcConfig = {\n  fallbacks?: string[];\n  timeout?: number;\n  maxConcurrent?: number;\n  transport?: JsonRpcTransport;\n};\n\nexport class RequestorJsonRpc {\n  public readonly maxConcurrent?: number;\n  private concurrent = 0;\n  private readonly pending: (() => void)[] = [];\n\n  public readonly transport: JsonRpcTransport;\n\n  private id = 0;\n\n  /**\n   * Creates a Requestor using legacy positional arguments.\n   *\n   * @param url_ - The URL of the JSON-RPC server.\n   * @param timeout - The timeout for requests in milliseconds\n   * @deprecated Use {@link RequestorJsonRpc.new} with a borrowed Transport or\n   * {@link RequestorJsonRpc.open} when creating Transports.\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    if (config?.transport) {\n      this.transport = config.transport;\n    } else {\n      this.transport = openTransports(\n        [url_, ...(config?.fallbacks ?? [])],\n        config,\n      ).value;\n    }\n  }\n\n  /**\n   * Creates a Requestor that borrows an existing Transport.\n   * The caller manages the transport's lifecycle.\n   *\n   * Do not share a WebSocket transport across requestors: request IDs can collide,\n   * mixing up responses or leaving requests unresolved. Reuse one requestor, or\n   * create separate transports with {@link RequestorJsonRpc.open}.\n   */\n  static new({\n    transport,\n    maxConcurrent,\n    onError,\n  }: {\n    transport: JsonRpcTransport;\n    maxConcurrent?: number;\n    onError?: (err: unknown) => Promise<void> | void;\n  }): RequestorJsonRpc {\n    return new RequestorJsonRpc(\"\", { transport, maxConcurrent }, onError);\n  }\n\n  /** Opens a Requestor with ownership of its default transports. */\n  static open({\n    urls: [url, ...fallbacks],\n    onError,\n    ...config\n  }: {\n    urls: readonly [string, ...string[]];\n    timeout?: number;\n    maxConcurrent?: number;\n    onError?: (err: unknown) => Promise<void> | void;\n  }): Owner<RequestorJsonRpc> {\n    const transportOwner = openTransports([url, ...fallbacks], config);\n    return transportOwner.map((transport) =>\n      RequestorJsonRpc.new({\n        transport,\n        ...config,\n        onError,\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   * @deprecated URL belongs to Transport construction and is unavailable for\n   * Requestors created with {@link RequestorJsonRpc.new}.\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    options?: JsonRpcTransportRequestOptions,\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, options),\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(\n    payload: JsonRpcPayload,\n    options?: JsonRpcTransportRequestOptions,\n  ): Promise<unknown> {\n    if (\n      this.maxConcurrent !== undefined &&\n      this.concurrent >= this.maxConcurrent\n    ) {\n      options?.signal?.throwIfAborted();\n      let resolvePending: (() => void) | undefined;\n      const pending = new Promise<void>((resolve) => {\n        resolvePending = resolve;\n        this.pending.push(resolve);\n      });\n      try {\n        await (options?.signal\n          ? Promise.race([pending, abortSignalToPromise(options.signal)])\n          : pending);\n      } catch (cause) {\n        const index = resolvePending\n          ? this.pending.indexOf(resolvePending)\n          : -1;\n        if (index !== -1) {\n          this.pending.splice(index, 1);\n        } else {\n          this.pending.shift()?.();\n        }\n        throw cause;\n      }\n    }\n\n    const res: JsonRpcResponse = await (async () => {\n      this.concurrent += 1;\n      try {\n        return await this.transport.request(payload, options);\n      } finally {\n        this.concurrent -= 1;\n        this.pending.shift()?.();\n      }\n    })();\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 new JsonRpcError(res.error);\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 { Owner, apply } from \"../../utils/index.js\";\nimport type { ClientConfig } from \"../client.js\";\nimport { Client } from \"../client.js\";\nimport { DEFAULT_MIN_FEE_RATE } from \"../clientTypes.advanced.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\nfunction handleJsonRpcError(errAny: unknown): never {\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\nexport type ClientJsonRpcConfig = RequestorJsonRpcConfig &\n  ClientConfig & {\n    /**\n     * @deprecated Requestor injection is supported only by legacy constructors.\n     * Use a borrowed Transport with `Client.new` or let `Client.open` create one.\n     */\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   * @deprecated Use the concrete Client's `new` or `open` method.\n   */\n\n  constructor(\n    private readonly url_: string,\n    config?: ClientJsonRpcConfig,\n  ) {\n    super(config);\n\n    const requestor = config?.requestor;\n    if (requestor) {\n      this.requestor = requestor;\n    } else if (config?.transport) {\n      this.requestor = RequestorJsonRpc.new({\n        transport: config.transport,\n        maxConcurrent: config.maxConcurrent,\n        onError: handleJsonRpcError,\n      });\n    } else {\n      // Legacy constructor intentionally discards ownership.\n      this.requestor = RequestorJsonRpc.open({\n        urls: [url_, ...(config?.fallbacks ?? [])],\n        timeout: config?.timeout,\n        maxConcurrent: config?.maxConcurrent,\n        onError: handleJsonRpcError,\n      }).value;\n    }\n  }\n\n  /** Creates a Requestor that borrows an existing Transport. */\n  protected static newRequestor(\n    config: Omit<Parameters<typeof RequestorJsonRpc.new>[0], \"onError\">,\n  ): RequestorJsonRpc {\n    return RequestorJsonRpc.new({\n      ...config,\n      onError: handleJsonRpcError,\n    });\n  }\n\n  /** Opens a Requestor with ownership of its default Transport. */\n  protected static openRequestor(\n    config: Omit<Parameters<typeof RequestorJsonRpc.open>[0], \"onError\">,\n  ): Owner<RequestorJsonRpc> {\n    return RequestorJsonRpc.open({\n      ...config,\n      onError: handleJsonRpcError,\n    });\n  }\n\n  /**\n   * Returns the legacy primary URL of the JSON-RPC server.\n   *\n   * @returns The URL of the JSON-RPC server.\n   * @deprecated A Client may use multiple endpoints or a Transport without a\n   * URL, so this value does not reliably identify its connection.\n   */\n  get url(): string {\n    return this.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(numToHex, n)],\n    // TODO: This is a temporary workaround for the fact that the node may return null for fee rate statistics.\n    // We should change the method signature to return null instead of falling back to the default value,\n    // but this would be a breaking change.\n    (res: { mean: NumLike; median: NumLike } | null) => ({\n      mean: numFrom(res?.mean ?? DEFAULT_MIN_FEE_RATE),\n      median: numFrom(res?.median ?? DEFAULT_MIN_FEE_RATE),\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 - Deprecated; this parameter has no effect.\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 - Deprecated; this parameter has no effect.\n   * @param withCycles - Deprecated; this parameter has no effect.\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 - Deprecated; this parameter has no effect.\n   * @param withCycles - Deprecated; this parameter has no effect.\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 - Deprecated; this parameter has no effect.\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 - Deprecated; this parameter has no effect.\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 { RequestorJsonRpc } from \"../jsonRpc/requestor.js\";\nimport type { ClientConfig } from \"./client.js\";\nimport { MAINNET_SCRIPTS } from \"./clientPublicMainnet.advanced.js\";\nimport { ClientJsonRpc, type ClientJsonRpcConfig } from \"./jsonRpc/client.js\";\n\n/**\n * @public\n */\nexport class ClientPublicMainnet extends ClientJsonRpc {\n  private static defaultUrls(): readonly [string, ...string[]] {\n    return typeof WebSocket !== \"undefined\"\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  private static resolveConfig(\n    config?: ClientJsonRpcConfig & {\n      /** @deprecated URL belongs to Transport construction. */\n      url?: string;\n    },\n  ): ClientJsonRpcConfig & { url: string; fallbacks: string[] } {\n    const defaultUrls = this.defaultUrls();\n    return {\n      ...config,\n      url: config?.url ?? defaultUrls[0],\n      fallbacks: config?.fallbacks ?? [...defaultUrls],\n      scripts: config?.scripts ?? MAINNET_SCRIPTS,\n    };\n  }\n\n  /**\n   * @deprecated Use {@link ClientPublicMainnet.new} with a borrowed Transport or\n   * {@link ClientPublicMainnet.open} when creating Transports.\n   */\n  constructor(\n    config?: ClientJsonRpcConfig & {\n      /** @deprecated URL belongs to Transport construction. */\n      url?: string;\n    },\n  ) {\n    const resolved = ClientPublicMainnet.resolveConfig(config);\n    super(resolved.url, resolved);\n  }\n\n  /**\n   * Creates a Client that borrows an existing Transport.\n   *\n   * For WebSocket, reuse one client instead of sharing a transport across clients.\n   * See {@link RequestorJsonRpc.new} for details.\n   */\n  static new(\n    config: Omit<Parameters<typeof RequestorJsonRpc.new>[0], \"onError\"> &\n      ClientConfig,\n  ): ClientPublicMainnet {\n    const { cache, scripts, addressResolver, ...requestorConfig } = config;\n    const requestor = this.newRequestor(requestorConfig);\n    return new ClientPublicMainnet({\n      cache,\n      scripts,\n      addressResolver,\n      requestor,\n    });\n  }\n\n  /** Opens a Client with explicit ownership of its default dependencies. */\n  static open(\n    config?: Omit<\n      Parameters<typeof RequestorJsonRpc.open>[0],\n      \"onError\" | \"urls\"\n    > &\n      ClientConfig & {\n        urls?: Parameters<typeof RequestorJsonRpc.open>[0][\"urls\"];\n      },\n  ) {\n    const {\n      cache,\n      scripts,\n      addressResolver,\n      urls = this.defaultUrls(),\n      ...requestorConfig\n    } = config ?? {};\n    return this.openRequestor({\n      ...requestorConfig,\n      urls,\n    }).map(\n      (requestor) =>\n        new ClientPublicMainnet({\n          cache,\n          scripts,\n          addressResolver,\n          requestor,\n          url: urls[0],\n          fallbacks: [...urls.slice(1)],\n        }),\n    );\n  }\n\n  get addressPrefix(): string {\n    return \"ckb\";\n  }\n}\n","import WebSocket from \"isomorphic-ws\";\nimport { RequestorJsonRpc } from \"../jsonRpc/requestor.js\";\nimport type { ClientConfig } from \"./client.js\";\nimport { TESTNET_SCRIPTS } from \"./clientPublicTestnet.advanced.js\";\nimport { ClientJsonRpc, type ClientJsonRpcConfig } from \"./jsonRpc/client.js\";\n\n/**\n * @public\n */\nexport class ClientPublicTestnet extends ClientJsonRpc {\n  private static defaultUrls(): readonly [string, ...string[]] {\n    return typeof WebSocket !== \"undefined\"\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  private static resolveConfig(\n    config?: ClientJsonRpcConfig & {\n      /** @deprecated URL belongs to Transport construction. */\n      url?: string;\n    },\n  ): ClientJsonRpcConfig & { url: string; fallbacks: string[] } {\n    const defaultUrls = this.defaultUrls();\n    return {\n      ...config,\n      url: config?.url ?? defaultUrls[0],\n      fallbacks: config?.fallbacks ?? [...defaultUrls],\n      scripts: config?.scripts ?? TESTNET_SCRIPTS,\n    };\n  }\n\n  /**\n   * @deprecated Use {@link ClientPublicTestnet.new} with a borrowed Transport or\n   * {@link ClientPublicTestnet.open} when creating Transports.\n   */\n  constructor(\n    config?: ClientJsonRpcConfig & {\n      /** @deprecated URL belongs to Transport construction. */\n      url?: string;\n    },\n  ) {\n    const resolved = ClientPublicTestnet.resolveConfig(config);\n    super(resolved.url, resolved);\n  }\n\n  /**\n   * Creates a Client that borrows an existing Transport.\n   *\n   * For WebSocket, reuse one client instead of sharing a transport across clients.\n   * See {@link RequestorJsonRpc.new} for details.\n   */\n  static new(\n    config: Omit<Parameters<typeof RequestorJsonRpc.new>[0], \"onError\"> &\n      ClientConfig,\n  ): ClientPublicTestnet {\n    const { cache, scripts, addressResolver, ...requestorConfig } = config;\n    const requestor = this.newRequestor(requestorConfig);\n    return new ClientPublicTestnet({\n      cache,\n      scripts,\n      addressResolver,\n      requestor,\n    });\n  }\n\n  /** Opens a Client with explicit ownership of its default dependencies. */\n  static open(\n    config?: Omit<\n      Parameters<typeof RequestorJsonRpc.open>[0],\n      \"onError\" | \"urls\"\n    > &\n      ClientConfig & {\n        urls?: Parameters<typeof RequestorJsonRpc.open>[0][\"urls\"];\n      },\n  ) {\n    const {\n      cache,\n      scripts,\n      addressResolver,\n      urls = this.defaultUrls(),\n      ...requestorConfig\n    } = config ?? {};\n    return this.openRequestor({\n      ...requestorConfig,\n      urls,\n    }).map(\n      (requestor) =>\n        new ClientPublicTestnet({\n          cache,\n          scripts,\n          addressResolver,\n          requestor,\n          url: urls[0],\n          fallbacks: [...urls.slice(1)],\n        }),\n    );\n  }\n\n  get addressPrefix(): string {\n    return \"ckt\";\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. If it does not parse, a\n   * single Client's `addressResolver` may resolve it.\n   * @param client - The Client instance used to parse or resolve the address.\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   * or if the resolver handles the address but does not find it.\n   */\n\n  static async fromString(address: string, client: Client): Promise<Address>;\n\n  /**\n   * @deprecated Pass a single Client instead. Callers supporting multiple\n   * prefixes should try each Client themselves.\n   */\n  static async fromString(\n    address: string,\n    clients: Record<string, Client>,\n  ): Promise<Address>;\n\n  static async fromString(\n    address: string,\n    clients: Client | Record<string, Client>,\n  ): Promise<Address> {\n    let parsed: ReturnType<typeof addressPayloadFromString>;\n    try {\n      parsed = addressPayloadFromString(address);\n    } catch (error) {\n      const client = clients as Client;\n      const resolver = client.addressResolver;\n      if (!resolver?.shouldResolve(address)) {\n        throw error;\n      }\n      const script = await resolver.resolve(address, client);\n      if (!script) {\n        throw new Error(`Address ${address} not found`, { cause: error });\n      }\n      return Address.fromScript(script, client);\n    }\n    const { prefix, format, payload } = parsed;\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.subarray(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.subarray(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.subarray(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 attempt to finalize the signed inputs 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(\n    options?: SignPsbtOptionsLike | SignPsbtOptions,\n  ): 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).subarray(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\").subarray(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.subarray(1), signature.subarray(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.subarray(64), signatureBytes.subarray(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.subarray(64), signatureBytes.subarray(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 {\n  SigningAlg,\n  verifySessionKeySignature,\n  verifySignature,\n} from \"@joyid/ckb\";\nimport { p256 } from \"@noble/curves/nist.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport {\n  BytesLike,\n  bytesConcat,\n  bytesFrom,\n  bytesTo,\n} from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\n\nasync function verifyBinaryPasskeySignature(\n  message: BytesLike,\n  signature: string,\n  signedMessage: string,\n  publicKey: string,\n): Promise<boolean> {\n  try {\n    const payload = bytesFrom(signedMessage, \"base64url\");\n    const clientData = payload.subarray(37);\n    const { challenge } = JSON.parse(bytesTo(clientData, \"utf8\")) as {\n      challenge: unknown;\n    };\n    if (challenge !== bytesTo(message, \"base64url\")) {\n      return false;\n    }\n    // Verify the original bytes: rewriting clientData would invalidate its signature.\n    const signatureBase = bytesConcat(\n      payload.subarray(0, 37),\n      sha256(clientData),\n    );\n    if (publicKey.length === 128) {\n      return p256.verify(\n        bytesFrom(signature, \"base64url\"),\n        signatureBase,\n        bytesConcat([4], bytesFrom(publicKey)),\n        { format: \"der\", prehash: true, lowS: false },\n      );\n    }\n    // The SDK's raw RSA/SHA-256 verifier also handles the passkey signature base.\n    return verifySessionKeySignature(\n      bytesTo(signatureBase, \"base64url\"),\n      signature,\n      publicKey,\n    );\n  } catch {\n    return false;\n  }\n}\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: unknown;\n  };\n  if (\n    keyType !== \"main_key\" &&\n    keyType !== \"sub_key\" &&\n    keyType !== \"main_session_key\" &&\n    keyType !== \"sub_session_key\"\n  ) {\n    return Promise.resolve(false);\n  }\n  // Only what the JoyID signer writes: the key and the challenge come from the caller\n  const { signature: signed, message: signedMessage } = JSON.parse(\n    signature,\n  ) as { signature: string; message: string };\n  const isPasskey = keyType === \"main_key\" || keyType === \"sub_key\";\n  // @joyid/ckb 1.1.4's native verifier only binds UTF-8 text challenges.\n  if (isPasskey && typeof message !== \"string\") {\n    return verifyBinaryPasskeySignature(\n      message,\n      signed,\n      signedMessage,\n      publicKey,\n    );\n  }\n\n  return verifySignature({\n    challenge,\n    pubkey: publicKey,\n    keyType,\n    // A P-256 public key is 64 bytes, an RSA one 260\n    alg: publicKey.length === 128 ? SigningAlg.ES256 : SigningAlg.RS256,\n    signature: signed,\n    // Bind session verification to the caller's challenge rather than the\n    // message supplied in the signature response.\n    message: isPasskey\n      ? signedMessage\n      : bytesTo(bytesFrom(challenge, \"utf8\"), \"base64url\"),\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 * @deprecated Wallet integrations now expose one signer per selectable network.\n * This compatibility type will be removed in the next major release.\n */\nexport type NetworkPreference = {\n  addressPrefix: string;\n  signerType: SignerType;\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  /**\n   * @deprecated Wallet integrations now use fixed-network signers.\n   */\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.setWitnessArgs(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 { Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport { Client, KnownScript } from \"../../client/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * A signer for the well-known always-success lock script.\n *\n * The always-success script does not require a signature, so signing a\n * transaction only needs to add its cell dependency.\n *\n * @public\n */\nexport class SignerCkbAlwaysSuccess extends Signer {\n  get type(): SignerType {\n    return SignerType.CKB;\n  }\n\n  get signType(): SignerSignType {\n    return SignerSignType.Unknown;\n  }\n\n  /**\n   * Creates an instance of SignerCkbAlwaysSuccess.\n   *\n   * @param client - The client instance used for communication and resolving\n   * the always-success deployment.\n   */\n  constructor(client: Client) {\n    super(client);\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  /**\n   * Gets the address of the always-success lock script.\n   */\n  async getAddressObjs(): Promise<Address[]> {\n    return [\n      await Address.fromKnownScript(\n        this.client,\n        KnownScript.AlwaysSuccess,\n        \"0x\",\n      ),\n    ];\n  }\n\n  /**\n   * Adds the always-success cell dependency to a transaction.\n   */\n  async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n    const tx = Transaction.from(txLike);\n    await tx.addCellDepsOfKnownScripts(this.client, KnownScript.AlwaysSuccess);\n    return tx;\n  }\n\n  /**\n   * The always-success script requires no signature.\n   */\n  async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n    return Transaction.from(txLike);\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 = tx.getWitnessArgs(info.position) ?? WitnessArgs.from({});\n      witness.lock = signature;\n      tx.setWitnessArgs(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  Epoch,\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\nfunction sinceSatisfiesConstraint(inputSinceLike: NumLike, since: Since) {\n  const inputSince = Since.from(inputSinceLike);\n\n  if (\n    inputSince.relative !== since.relative ||\n    inputSince.metric !== since.metric\n  ) {\n    return false;\n  }\n\n  if (since.metric === \"epoch\") {\n    return Epoch.from(inputSince.value).ge(since.value);\n  }\n\n  return inputSince.value >= since.value;\n}\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.getWitnessArgs(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.getWitnessArgs(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.setWitnessArgs(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    scriptLike: ScriptLike,\n    cellDeps: CellDepInfoLike[],\n  ) {\n    const tx = Transaction.from(txLike);\n    const script = Script.from(scriptLike);\n    const position = await tx.findInputIndexByLock(script, this.client);\n    if (position === undefined) {\n      return tx;\n    }\n\n    if (this.since) {\n      const since = this.since.toNum();\n\n      for (const input of tx.inputs) {\n        const { cellOutput } = await input.getCell(this.client);\n        if (\n          script.eq(cellOutput.lock) &&\n          !sinceSatisfiesConstraint(input.since, this.since)\n        ) {\n          input.since = since;\n        }\n      }\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.getWitnessArgs(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.setWitnessArgs(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()).subarray(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.setWitnessArgs(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.subarray(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.setWitnessArgs(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.setWitnessArgs(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","const CKB_MAINNET_NETWORK_ID = \"ckb-mainnet\";\nconst CKB_TESTNET_NETWORK_ID = \"ckb-testnet\";\n\n// TODO: In the next major version, read the network ID directly from Client\n// instead of inferring it from addressPrefix.\nexport function signerJsonRpcNetworkIdFromAddressPrefix(addressPrefix: string) {\n  if (addressPrefix === \"ckb\") {\n    return CKB_MAINNET_NETWORK_ID;\n  }\n  if (addressPrefix === \"ckt\") {\n    return CKB_TESTNET_NETWORK_ID;\n  }\n\n  throw new Error(`Unsupported address prefix: ${addressPrefix}`);\n}\n","import { randomBytes } from \"@noble/hashes/utils.js\";\nimport { CellInput, type Transaction } from \"../../ckb/index.js\";\nimport { JsonRpcTransformers } from \"../../client/jsonRpc/advanced.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { JsonRpcError, type JsonRpcPayload } from \"../../jsonRpc/index.js\";\nimport { abortSignalAny, sleep } from \"../../utils/index.js\";\nimport { OwnerUnique } from \"../../utils/owner/unique.js\";\nimport type { Signer } from \"../signer/index.js\";\nimport { signerJsonRpcNetworkIdFromAddressPrefix } from \"./network.js\";\nimport {\n  SignerJsonRpcTransformers,\n  type SignerJsonRpcInfo,\n  type SignerJsonRpcInfoPayload,\n  type SignerJsonRpcMessageToSign,\n} from \"./transformers.js\";\n\nexport type SignerJsonRpcConfirmation =\n  | { method: \"connect\"; networkId: string }\n  | { method: \"sign_message\"; message: SignerJsonRpcMessageToSign }\n  | { method: \"sign_transaction\"; transaction: Transaction };\n\nconst GET_RESULT_CACHE_MS = 120_000;\nconst GET_RESULT_HISTORY_CAPACITY = 128;\nconst GET_RESULT_WAIT_MS = 10_000;\nconst GET_RESULT_PENDING_RESULT = Symbol(\"pending\");\n\ntype SignerJsonRpcResultEntry = {\n  completion: Promise<unknown>;\n  retrieved: boolean;\n};\n\nexport enum SignerJsonRpcErrorCode {\n  MethodNotFound = -32601,\n  InvalidParams = -32602,\n  ServerError = -32000,\n  InvalidState = -32001,\n  NetworkMismatch = -32002,\n  UserRejected = -32003,\n  InvalidSession = -32004,\n  DuplicateRequestId = -32005,\n}\n\nexport type SignerJsonRpcProviderSessionOptions = {\n  /** Aborts when the provider session is disposed. */\n  signal?: AbortSignal;\n};\n\nexport type SignerJsonRpcResultRecord =\n  | { status: \"not_found\" }\n  | { status: \"pending\" }\n  | { status: \"completed\"; result: unknown };\n\nexport type SignerJsonRpcProviderSessionConfig = {\n  getSigner: () => Signer | undefined;\n  getSignerMetadata?: () => Pick<SignerJsonRpcInfo, \"name\" | \"icon\">;\n  /** Connects the requested network and returns its connected Signer. */\n  connect: (\n    networkId: string,\n    options?: SignerJsonRpcProviderSessionOptions,\n  ) => Promise<Signer>;\n  confirmRequest: (\n    request: SignerJsonRpcConfirmation,\n    options?: SignerJsonRpcProviderSessionOptions,\n  ) => Promise<boolean>;\n};\n\nexport class SignerJsonRpcProviderSession {\n  private readonly abortController = new AbortController();\n  private readonly id = hexFrom(randomBytes(16));\n  private readonly resultRecords = new Map<string, SignerJsonRpcResultEntry>();\n  private readonly resultHistory = new Map<string, SignerJsonRpcResultEntry>();\n  private readonly handlers;\n  private info?: SignerJsonRpcInfoPayload;\n  private connected = false;\n\n  private constructor(\n    private readonly config: SignerJsonRpcProviderSessionConfig,\n  ) {\n    this.handlers = new Map<\n      string,\n      readonly [\n        number,\n        (\n          params: unknown[],\n          options?: SignerJsonRpcProviderSessionOptions,\n        ) => unknown,\n      ]\n    >([\n      [\n        \"get_info\",\n        [\n          0,\n          () =>\n            (this.info ??= buildSignerInfo(\n              this.id,\n              this.requireSigner(),\n              this.config.getSignerMetadata?.() ?? {},\n            )),\n        ],\n      ],\n      [\n        \"connect\",\n        [\n          1,\n          async ([networkId], options) => {\n            this.connected = false;\n            if (typeof networkId !== \"string\" || !networkId) {\n              throw new JsonRpcError({\n                code: SignerJsonRpcErrorCode.InvalidParams,\n                message: \"Invalid network ID\",\n              });\n            }\n\n            await this.requireConfirmation(\n              { method: \"connect\", networkId },\n              options,\n            );\n\n            const signer = await this.config.connect(networkId, options);\n            options?.signal?.throwIfAborted();\n            const actualNetworkId = signerJsonRpcNetworkIdFromAddressPrefix(\n              signer.client.addressPrefix,\n            );\n            if (actualNetworkId !== networkId) {\n              throw new JsonRpcError({\n                code: SignerJsonRpcErrorCode.NetworkMismatch,\n                message: `Signer uses ${actualNetworkId}, expected ${networkId}`,\n              });\n            }\n\n            this.connected = true;\n            return null;\n          },\n        ],\n      ],\n      [\n        \"get_scripts\",\n        [\n          0,\n          async () =>\n            (await this.requireSigner().getAddressObjs()).map(({ script }) =>\n              JsonRpcTransformers.scriptFrom(script),\n            ),\n        ],\n      ],\n      [\n        \"get_native_address\",\n        [0, () => this.requireSigner().getInternalAddress()],\n      ],\n      [\"get_identity\", [0, () => this.requireSigner().getIdentity()]],\n      [\n        \"sign_message\",\n        [\n          1,\n          async ([message], options) => {\n            const parsedMessage = parseMessageParam(message);\n            await this.requireConfirmation(\n              {\n                method: \"sign_message\",\n                message: SignerJsonRpcTransformers.messageFrom(parsedMessage),\n              },\n              options,\n            );\n            return this.requireSigner().signMessageRaw(parsedMessage);\n          },\n        ],\n      ],\n      [\n        \"prepare_transaction\",\n        [\n          1,\n          async ([transaction]) =>\n            JsonRpcTransformers.transactionFrom(\n              await this.requireSigner().prepareTransaction(\n                parseTransactionParam(transaction),\n              ),\n            ),\n        ],\n      ],\n      [\n        \"sign_transaction\",\n        [\n          1,\n          async ([transaction], options) => {\n            const parsedTransaction = parseTransactionParam(transaction);\n            await this.requireConfirmation(\n              { method: \"sign_transaction\", transaction: parsedTransaction },\n              options,\n            );\n            return JsonRpcTransformers.transactionFrom(\n              await this.requireSigner().signOnlyTransaction(parsedTransaction),\n            );\n          },\n        ],\n      ],\n    ]);\n  }\n\n  static open(\n    config: SignerJsonRpcProviderSessionConfig,\n  ): OwnerUnique<SignerJsonRpcProviderSession> {\n    const session = new SignerJsonRpcProviderSession(config);\n    return new OwnerUnique(session, (session) => session.dispose());\n  }\n\n  get isConnected() {\n    return this.connected;\n  }\n\n  handle = (payload: JsonRpcPayload) => {\n    const signal = this.abortController.signal;\n    signal.throwIfAborted();\n\n    const [metadata, ...params] = requireParams(payload);\n    const { requestId, sessionId } = parseRequestMetadata(metadata);\n\n    if (payload.method === \"get_result\") {\n      const [targetRequestId] = params;\n      requireParams(payload, 2);\n      requireRequestId(targetRequestId);\n      return this.getResult(\n        this.resultRecords.get(targetRequestId) ??\n          this.resultHistory.get(targetRequestId),\n        signal,\n      );\n    }\n\n    requireRequestId(requestId);\n    if (\n      this.resultRecords.has(requestId) ||\n      this.resultHistory.has(requestId)\n    ) {\n      throw new JsonRpcError({\n        code: SignerJsonRpcErrorCode.DuplicateRequestId,\n        message: \"Request ID already exists\",\n      });\n    }\n\n    return this.executeRequest(requestId, async () => {\n      signal.throwIfAborted();\n      const isGetInfo = payload.method === \"get_info\";\n      if (isGetInfo) {\n        if (sessionId !== undefined) {\n          throw new JsonRpcError({\n            code: SignerJsonRpcErrorCode.InvalidParams,\n            message: \"get_info does not accept a session ID\",\n          });\n        }\n      } else {\n        this.requireSession(sessionId);\n      }\n\n      const entry = this.handlers.get(payload.method);\n      if (!entry) {\n        throw new JsonRpcError({\n          code: SignerJsonRpcErrorCode.MethodNotFound,\n          message: `Unsupported method: ${payload.method}`,\n        });\n      }\n      const [paramCount, handler] = entry;\n      requireParams(payload, paramCount + 1);\n\n      if (!isGetInfo && payload.method !== \"connect\" && !this.connected) {\n        throw new JsonRpcError({\n          code: SignerJsonRpcErrorCode.InvalidState,\n          message: \"Connect must be approved before this request\",\n        });\n      }\n      const result = await handler(params, { signal });\n      signal.throwIfAborted();\n      return result;\n    });\n  };\n\n  private dispose() {\n    this.connected = false;\n    this.resultRecords.clear();\n    this.resultHistory.clear();\n    this.abortController.abort(\n      new JsonRpcError({\n        code: SignerJsonRpcErrorCode.InvalidSession,\n        message: \"Invalid or expired session\",\n      }),\n    );\n  }\n\n  private requireSession(value: unknown) {\n    if (value === this.id) {\n      return;\n    }\n    throw new JsonRpcError({\n      code: SignerJsonRpcErrorCode.InvalidSession,\n      message: \"Invalid or expired session\",\n    });\n  }\n\n  private requireSigner() {\n    const signer = this.config.getSigner();\n    if (!signer) {\n      throw new JsonRpcError({\n        code: SignerJsonRpcErrorCode.ServerError,\n        message: \"No signer is connected\",\n      });\n    }\n\n    return signer;\n  }\n\n  private async requireConfirmation(\n    request: SignerJsonRpcConfirmation,\n    options?: SignerJsonRpcProviderSessionOptions,\n  ) {\n    const confirmed = await this.config.confirmRequest(request, options);\n    options?.signal?.throwIfAborted();\n    if (!confirmed) {\n      throw new JsonRpcError({\n        code: SignerJsonRpcErrorCode.UserRejected,\n        message: \"User rejected request\",\n      });\n    }\n  }\n\n  private executeRequest(requestId: string, request: () => unknown) {\n    const completion = Promise.resolve().then(request);\n    const entry = { completion, retrieved: false };\n    this.resultRecords.set(requestId, entry);\n    const expire = () => {\n      setTimeout(() => {\n        if (this.resultRecords.get(requestId) === entry) {\n          this.resultRecords.delete(requestId);\n          this.resultHistory.set(requestId, entry);\n          this.trimResultHistory();\n        }\n      }, GET_RESULT_CACHE_MS);\n    };\n    void completion.then(expire, expire);\n    return completion;\n  }\n\n  private trimResultHistory() {\n    while (this.resultHistory.size > GET_RESULT_HISTORY_CAPACITY) {\n      let oldestRetrieved: string | undefined;\n      for (const [requestId, entry] of this.resultHistory) {\n        if (entry.retrieved) {\n          oldestRetrieved = requestId;\n          break;\n        }\n      }\n\n      this.resultHistory.delete(\n        oldestRetrieved ?? this.resultHistory.keys().next().value!,\n      );\n    }\n  }\n\n  private async getResult(\n    entry: SignerJsonRpcResultEntry | undefined,\n    signal?: AbortSignal,\n  ): Promise<SignerJsonRpcResultRecord> {\n    if (!entry) {\n      return { status: \"not_found\" };\n    }\n\n    const controller = new AbortController();\n    try {\n      const result = await Promise.race([\n        entry.completion.then(\n          (value) => ({ status: \"fulfilled\" as const, value }),\n          (reason: unknown) => ({ status: \"rejected\" as const, reason }),\n        ),\n        sleep(\n          GET_RESULT_WAIT_MS,\n          signal\n            ? abortSignalAny([signal, controller.signal])\n            : controller.signal,\n        ).then(\n          (): typeof GET_RESULT_PENDING_RESULT => GET_RESULT_PENDING_RESULT,\n        ),\n      ]);\n      if (result === GET_RESULT_PENDING_RESULT) {\n        return { status: \"pending\" };\n      }\n\n      entry.retrieved = true;\n      if (result.status === \"rejected\") {\n        throw result.reason;\n      }\n      return { status: \"completed\", result: result.value };\n    } finally {\n      controller.abort();\n    }\n  }\n}\n\nfunction parseMessageParam(message: unknown) {\n  try {\n    return SignerJsonRpcTransformers.messageTo(message);\n  } catch (cause) {\n    throw new JsonRpcError({\n      code: SignerJsonRpcErrorCode.InvalidParams,\n      message:\n        cause instanceof Error ? cause.message : \"Invalid signer message\",\n    });\n  }\n}\n\nconst PSEUDO_INPUT_INDEX = 0xffffffffn;\nconst PSEUDO_INPUT_CAPACITY = 0xffffffffffffffffn;\n\n/**\n * A transaction whose only input is at out point index 0xffffffff, with a 32-byte tx hash that is\n * not all zero, can never be committed: no transaction has that many outputs. Such an input cannot\n * be looked up, so its cell is rebuilt here: capacity u64::MAX, the lock of the first output, no\n * type and empty data. The signer then signs for that lock, if it is one of its own. A lock proof is\n * such a transaction. Every other input is looked up as usual.\n */\nfunction rebuildPseudoInput(tx: Transaction): Transaction {\n  const lock = tx.outputs[0]?.lock;\n  if (tx.inputs.length !== 1 || lock === undefined) {\n    return tx;\n  }\n  const { previousOutput, since } = tx.inputs[0];\n  if (\n    previousOutput.index !== PSEUDO_INPUT_INDEX ||\n    !/^0x[0-9a-f]{64}$/.test(previousOutput.txHash) ||\n    /^0x0+$/.test(previousOutput.txHash)\n  ) {\n    return tx;\n  }\n  tx.inputs[0] = CellInput.from({\n    previousOutput,\n    since,\n    cellOutput: { capacity: PSEUDO_INPUT_CAPACITY, lock },\n    outputData: \"0x\",\n  });\n  return tx;\n}\n\nfunction parseTransactionParam(transaction: unknown) {\n  try {\n    return rebuildPseudoInput(\n      JsonRpcTransformers.transactionTo(\n        transaction as Parameters<typeof JsonRpcTransformers.transactionTo>[0],\n      ),\n    );\n  } catch (cause) {\n    throw new JsonRpcError({\n      code: SignerJsonRpcErrorCode.InvalidParams,\n      message:\n        cause instanceof Error ? cause.message : \"Invalid signer transaction\",\n    });\n  }\n}\n\nfunction requireParams(payload: JsonRpcPayload, count?: number) {\n  if (!Array.isArray(payload.params)) {\n    throw new JsonRpcError({\n      code: SignerJsonRpcErrorCode.InvalidParams,\n      message: `${payload.method} expects positional parameters`,\n    });\n  }\n  if (count !== undefined && payload.params.length !== count) {\n    throw new JsonRpcError({\n      code: SignerJsonRpcErrorCode.InvalidParams,\n      message: `${payload.method} expects ${count} parameter${count === 1 ? \"\" : \"s\"}`,\n    });\n  }\n\n  return payload.params;\n}\n\nfunction parseRequestMetadata(value: unknown) {\n  if (\n    typeof value !== \"object\" ||\n    value === null ||\n    (\"request_id\" in value && typeof value.request_id !== \"string\") ||\n    (\"session_id\" in value && typeof value.session_id !== \"string\")\n  ) {\n    throw new JsonRpcError({\n      code: SignerJsonRpcErrorCode.InvalidParams,\n      message: \"Invalid request metadata\",\n    });\n  }\n\n  return {\n    requestId: \"request_id\" in value ? value.request_id : undefined,\n    sessionId: \"session_id\" in value ? value.session_id : undefined,\n  };\n}\n\nfunction requireRequestId(value: unknown): asserts value is string {\n  if (typeof value !== \"string\" || !value) {\n    throw new JsonRpcError({\n      code: SignerJsonRpcErrorCode.InvalidParams,\n      message: \"Invalid request ID\",\n    });\n  }\n}\n\nfunction buildSignerInfo(\n  sessionId: string,\n  signer: Signer,\n  metadata: Pick<SignerJsonRpcInfo, \"name\" | \"icon\">,\n) {\n  return SignerJsonRpcTransformers.infoFrom({\n    sessionId,\n    type: signer.type,\n    signType: signer.signType,\n    name: metadata.name,\n    icon: metadata.icon,\n  });\n}\n","import { randomBytes } from \"@noble/hashes/utils.js\";\nimport { Address } from \"../../address/index.js\";\nimport { Script } from \"../../ckb/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport {\n  JsonRpcScript,\n  JsonRpcTransformers,\n} from \"../../client/jsonRpc/advanced.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { JsonRpcError, RequestorJsonRpc } from \"../../jsonRpc/index.js\";\nimport { retry, sleep, waitForAvailability } from \"../../utils/index.js\";\nimport { Signer } from \"../signer/index.js\";\nimport {\n  SignerJsonRpcErrorCode,\n  type SignerJsonRpcResultRecord,\n} from \"./handler.js\";\nimport { signerJsonRpcNetworkIdFromAddressPrefix } from \"./network.js\";\nimport {\n  SignerJsonRpcInfo,\n  SignerJsonRpcTransformers,\n} from \"./transformers.js\";\n\nexport type SignerJsonRpcConfig = Omit<\n  Parameters<typeof RequestorJsonRpc.new>[0],\n  \"onError\"\n> & {\n  /** Cleans up integration-owned resources before replacement is announced. */\n  disconnectHandler?: () => PromiseLike<void> | void;\n};\n\nconst GET_RESULT_RETRY_DELAYS = [1_000, 2_000, 4_000, 8_000] as const;\nconst GET_RESULT_MIN_POLL_INTERVAL_MS = 5_000;\nconst GET_RESULT_RETRY_REPEAT_MS = 10_000;\nconst GET_RESULT_TIMEOUT_MS = 20_000;\nconst REQUEST_RETRY_DELAYS = [5_000, 10_000, 20_000] as const;\nconst REQUEST_TIMEOUT_MS = 10_000;\n\nexport class SignerJsonRpc extends Signer {\n  private connecting?: Promise<void>;\n  private disconnecting?: Promise<void>;\n  private scriptsPromise?: Promise<Script[]>;\n  private internalAddressPromise?: Promise<string>;\n  private identityPromise?: Promise<string>;\n  private requestsController = new AbortController();\n  private readonly replacedListeners = new Set<() => void>();\n\n  private constructor(\n    client: Client,\n    readonly requestor: RequestorJsonRpc,\n    private info: SignerJsonRpcInfo,\n    private readonly disconnectHandler?: () => PromiseLike<void> | void,\n  ) {\n    super(client);\n  }\n\n  /** Creates a Signer that borrows an existing Transport. */\n  static async new(client: Client, config: SignerJsonRpcConfig) {\n    const { disconnectHandler, ...requestorConfig } = config;\n    const requestor = RequestorJsonRpc.new(requestorConfig);\n    const signer = new SignerJsonRpc(\n      client,\n      requestor,\n      {} as SignerJsonRpcInfo,\n      disconnectHandler,\n    );\n    signer.info = (await signer.request(\n      \"get_info\",\n      [],\n      [],\n      SignerJsonRpcTransformers.infoTo,\n    )) as SignerJsonRpcInfo;\n    return signer;\n  }\n\n  get type() {\n    return this.info.type;\n  }\n\n  get signType() {\n    return this.info.signType;\n  }\n\n  get name() {\n    return this.info.name;\n  }\n\n  get icon() {\n    return this.info.icon;\n  }\n\n  connect(): Promise<void> {\n    if (this.disconnecting) {\n      return this.disconnecting.then(() => this.connect());\n    }\n    if (this.connecting) {\n      return this.connecting;\n    }\n\n    const connecting = this.requestConnect(\n      signerJsonRpcNetworkIdFromAddressPrefix(this.client.addressPrefix),\n    ).catch((cause: unknown) => {\n      if (this.connecting === connecting) {\n        this.connecting = undefined;\n      }\n      throw cause;\n    });\n    this.connecting = connecting;\n    return connecting;\n  }\n\n  disconnect(): Promise<void> {\n    this.clearReadCache();\n    if (this.disconnecting) {\n      return this.disconnecting;\n    }\n    if (!this.connecting) {\n      return Promise.resolve();\n    }\n\n    this.connecting = undefined;\n    this.disconnecting = Promise.resolve()\n      .then(() => this.disconnectHandler?.())\n      .finally(() => {\n        this.replace();\n        this.disconnecting = undefined;\n      });\n    return this.disconnecting;\n  }\n\n  private requestConnect = this.buildSender(\"connect\", []) as (\n    networkId: string,\n  ) => Promise<void>;\n\n  onReplaced(listener: () => void) {\n    this.replacedListeners.add(listener);\n    return () => this.replacedListeners.delete(listener);\n  }\n\n  replace() {\n    const requestsController = this.requestsController;\n    this.requestsController = new AbortController();\n    requestsController.abort(new Error(\"Signer JSON-RPC was replaced\"));\n    this.connecting = undefined;\n    this.clearReadCache();\n    const listeners = [...this.replacedListeners];\n    this.replacedListeners.clear();\n    listeners.forEach((listener) => listener());\n  }\n\n  async isConnected() {\n    return (\n      this.connecting?.then(\n        () => true,\n        () => false,\n      ) ?? false\n    );\n  }\n\n  getScripts(): Promise<Script[]> {\n    if (this.scriptsPromise) {\n      return this.scriptsPromise.then((scripts) => [...scripts]);\n    }\n\n    const pending = this.request(\n      \"get_scripts\",\n      [],\n      [],\n      (scripts: JsonRpcScript[]) =>\n        scripts.map((script) => JsonRpcTransformers.scriptTo(script)),\n    ).catch((cause: unknown) => {\n      if (this.scriptsPromise === pending) {\n        this.scriptsPromise = undefined;\n      }\n      throw cause;\n    }) as Promise<Script[]>;\n    this.scriptsPromise = pending;\n    return pending.then((scripts) => [...scripts]);\n  }\n\n  async getAddressObjs() {\n    return (await this.getScripts()).map((script) =>\n      Address.fromScript(script, this.client),\n    );\n  }\n\n  getInternalAddress(): Promise<string> {\n    if (this.internalAddressPromise) {\n      return this.internalAddressPromise;\n    }\n\n    const pending = this.request(\"get_native_address\", [], []).catch(\n      (cause: unknown) => {\n        if (this.internalAddressPromise === pending) {\n          this.internalAddressPromise = undefined;\n        }\n        throw cause;\n      },\n    ) as Promise<string>;\n    this.internalAddressPromise = pending;\n    return pending;\n  }\n\n  getIdentity(): Promise<string> {\n    if (this.identityPromise) {\n      return this.identityPromise;\n    }\n\n    const pending = this.request(\"get_identity\", [], []).catch(\n      (cause: unknown) => {\n        if (this.identityPromise === pending) {\n          this.identityPromise = undefined;\n        }\n        throw cause;\n      },\n    ) as Promise<string>;\n    this.identityPromise = pending;\n    return pending;\n  }\n\n  signMessageRaw = this.buildSender(\"sign_message\", [\n    SignerJsonRpcTransformers.messageFrom,\n  ]) as Signer[\"signMessageRaw\"];\n\n  prepareTransaction = this.buildSender(\n    \"prepare_transaction\",\n    [JsonRpcTransformers.transactionFrom],\n    JsonRpcTransformers.transactionTo,\n  ) as Signer[\"prepareTransaction\"];\n\n  signOnlyTransaction = this.buildSender(\n    \"sign_transaction\",\n    [JsonRpcTransformers.transactionFrom],\n    JsonRpcTransformers.transactionTo,\n  ) as Signer[\"signOnlyTransaction\"];\n\n  buildSender(\n    rpcMethod: Parameters<RequestorJsonRpc[\"request\"]>[0],\n    inTransformers?: Parameters<RequestorJsonRpc[\"request\"]>[2],\n    outTransformer?: Parameters<RequestorJsonRpc[\"request\"]>[3],\n  ): (...request: unknown[]) => Promise<unknown> {\n    return async (...request: unknown[]) =>\n      this.request(rpcMethod, request, inTransformers, outTransformer);\n  }\n\n  private clearReadCache() {\n    this.scriptsPromise = undefined;\n    this.internalAddressPromise = undefined;\n    this.identityPromise = undefined;\n  }\n\n  private async request(\n    method: string,\n    params: unknown[],\n    inTransformers?: Parameters<RequestorJsonRpc[\"request\"]>[2],\n    outTransformer?: Parameters<RequestorJsonRpc[\"request\"]>[3],\n  ): Promise<unknown> {\n    const requestId = hexFrom(randomBytes(16));\n    const sessionId = method === \"get_info\" ? undefined : this.info.sessionId;\n    const signal = this.requestsController.signal;\n\n    const result = retry(\n      REQUEST_RETRY_DELAYS,\n      async ({ resolve, reject }) => {\n        try {\n          return resolve(\n            await this.requestor.request(\n              method,\n              [\n                {\n                  request_id: requestId,\n                  ...(sessionId ? { session_id: sessionId } : {}),\n                },\n                ...params,\n              ],\n              inTransformers ? [undefined, ...inTransformers] : undefined,\n              outTransformer,\n              { signal, timeout: REQUEST_TIMEOUT_MS },\n            ),\n          );\n        } catch (cause) {\n          if (cause instanceof JsonRpcError) {\n            return reject(cause);\n          }\n          throw cause;\n        }\n      },\n      { signal },\n    ).catch((cause: unknown) => {\n      signal.throwIfAborted();\n      if (\n        cause instanceof JsonRpcError &&\n        cause.code !== Number(SignerJsonRpcErrorCode.DuplicateRequestId)\n      ) {\n        throw cause;\n      }\n\n      return this.recoverResult(requestId, cause, signal, outTransformer);\n    });\n\n    try {\n      const value = await result;\n      signal.throwIfAborted();\n      return value;\n    } catch (cause) {\n      if (\n        cause instanceof JsonRpcError &&\n        cause.code === Number(SignerJsonRpcErrorCode.InvalidSession)\n      ) {\n        this.replace();\n      }\n      throw cause;\n    }\n  }\n\n  private async recoverResult(\n    requestId: string,\n    requestError: unknown,\n    signal: AbortSignal,\n    outTransformer?: Parameters<RequestorJsonRpc[\"request\"]>[3],\n  ) {\n    return retry(\n      [],\n      async ({ resolve, reject, next }) => {\n        try {\n          let getResultStartedAt = Date.now();\n          const result = await retry<SignerJsonRpcResultRecord>(\n            GET_RESULT_RETRY_DELAYS,\n            async ({ resolve, reject }) => {\n              await waitForAvailability(signal);\n              getResultStartedAt = Date.now();\n\n              try {\n                return resolve(\n                  (await this.requestor.request(\n                    \"get_result\",\n                    [{}, requestId],\n                    undefined,\n                    undefined,\n                    { signal, timeout: GET_RESULT_TIMEOUT_MS },\n                  )) as SignerJsonRpcResultRecord,\n                );\n              } catch (cause) {\n                if (cause instanceof JsonRpcError) {\n                  return reject(cause);\n                }\n                throw cause;\n              }\n            },\n            { repeat: GET_RESULT_RETRY_REPEAT_MS, signal },\n          );\n          signal.throwIfAborted();\n\n          if (result.status === \"not_found\") {\n            return reject(requestError);\n          }\n          if (result.status === \"pending\") {\n            const remaining =\n              GET_RESULT_MIN_POLL_INTERVAL_MS -\n              (Date.now() - getResultStartedAt);\n            if (remaining > 0) {\n              await sleep(remaining, signal);\n            }\n            return next();\n          }\n          if (result.status !== \"completed\" || !(\"result\" in result)) {\n            return reject(new Error(\"Invalid signer request result\"));\n          }\n          return resolve(\n            outTransformer ? outTransformer(result.result) : result.result,\n          );\n        } catch (cause) {\n          return reject(cause);\n        }\n      },\n      { repeat: 0, signal },\n    );\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.setWitnessArgs(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":"A,mwEAQA,IAAawL,GAAb,KAA+C,CAO7C,aAAc,CACZ,KAAK,OAASC,GAAW,OAAO,CAClC,CAgBA,OAAO,EAAkC,CAEvC,OADA,KAAK,OAAO,OAAOzI,EAAU0I,CAAI,CAAC,EAC3B,IACT,CAeA,QAAc,CACZ,OAAO1K,EAAQ,KAAK,OAAO,OAAO,CAAC,CACrC,CACF,E,wnCErCa4K,GAAb,MAAaA,UAAsDpK,EAAS,CAC1E,YACE,EACA,EACA,CACA,MAAM,EAHa,KAAA,OAAAqK,EACF,KAAA,OAAAC,CAGnB,CAGA,OAAO,KACL,EACuC,CACvC,GAAI,IAAI,IAAIA,CAAM,CAAC,CAAC,OAASA,EAAO,OAClC,MAAU,MAAM,gDAAgD,EAIlE,IAAMC,EAASD,EAAO,IACnB,GAAmBE,EAAM,KAC5B,EACMC,EAAQH,EAAO,IAAK,GAAU,KAAK,SAASE,CAAK,CAAC,EACxD,OAAO,IAAIJ,EAAgBG,EAAQE,CAAK,CAC1C,CAEA,MAAgB,SAAyB,CACvC,IAAMC,EAAU,MAAM,QAAQ,WAC5B,KAAK,OAAO,IAAK,GAAUF,EAAM,QAAQ,CAAC,CAC5C,EACMG,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAUF,EACfE,EAAO,SAAW,YACpBD,EAAO,KAAKC,EAAO,MAAiB,EAGxC,GAAID,EAAO,SAAW,EACpB,MAAU,eAAeA,EAAQ,qCAAqC,CAE1E,CACF,ECxBaE,GAAb,MAAaA,UAAyB7K,EAAS,CAC7C,YAAoB,EAA+C,CACjE,MAAM,EAD6B,KAAA,MAAA8K,CAErC,CAEA,IAAc,QAAY,CACxB,OAAO,KAAK,MAAM,MAAM,KAC1B,CA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