/** * Represents the possible encoding formats for converting bytes. * @public */ type BytesFromEncoding = "utf8" | "base64" | "base64url" | "hex"; /** * @public */ type Bytes$1 = Uint8Array; /** * @public */ declare const Bytes$1: Uint8ArrayConstructor; /** * @public */ type BytesLike = string | Uint8Array | ArrayBuffer | ArrayLike; /** * Concatenates multiple byte-like arrays to the first number array. * @public * * @param result - The number array as result * @param args - The byte-like arrays to concatenate. * @returns The first number array * * @example * ```typescript * const concatenatedBytes = [1, 2]; * bytesConcatTo( * concatenatedBytes * new Uint8Array([3, 4]), * "hello", * [5, 6, 7] * ); * console.log(concatenatedBytes); // Outputs [1, 2, 3, 4, /* bytes of "hello" *\/, 5, 6, 7] * ``` */ declare function bytesConcatTo(result: number[], ...args: BytesLike[]): number[]; /** * Concatenates multiple byte-like arrays into a single byte array. * @public * * @param args - The byte-like arrays to concatenate. * @returns A Uint8Array containing the concatenated bytes. * * @example * ```typescript * const concatenatedBytes = bytesConcat( * new Uint8Array([1, 2]), * new Uint8Array([3, 4]), * "hello", * [5, 6, 7] * ); * console.log(concatenatedBytes); // Outputs Uint8Array [1, 2, 3, 4, /* bytes of "hello" *\/, 5, 6, 7] * ``` */ declare function bytesConcat(...args: BytesLike[]): Bytes$1; /** * Converts a byte-like value to a string using the specified encoding. * @public * * @param val - The byte-like value to convert. * @param encoding - The encoding to use for the conversion, as defined by the BytesFromEncoding type. * @returns A string representing the encoded bytes. * * @example * ```typescript * const encodedString = bytesTo(new Uint8Array([104, 101, 108, 108, 111]), "utf8"); * console.log(encodedString); // Outputs "hello" * * const base64String = bytesTo(new Uint8Array([104, 101, 108, 108, 111]), "base64"); * console.log(base64String); // Outputs "aGVsbG8=" * ``` */ declare function bytesTo(val: BytesLike, encoding: BytesFromEncoding): string; /** * Converts various types of byte-like values to a Uint8Array. * @public * * @param bytes - The byte-like value to convert. It can be a string, Uint8Array, ArrayBuffer, or number array. * @param encoding - Optional encoding to use if the input is a string. Defaults to hexadecimal if not specified. * @returns A Uint8Array representing the input bytes. * * @throws Will throw an error if the input bytes are invalid or out of range. * * @example * ```typescript * const bytes1 = bytesFrom(new Uint8Array([1, 2, 3])); * console.log(bytes1); // Outputs Uint8Array [1, 2, 3] * * const bytes2 = bytesFrom("68656c6c6f", "hex"); * console.log(bytes2); // Outputs Uint8Array [104, 101, 108, 108, 111] * * const bytes3 = bytesFrom("hello", "utf8"); * console.log(bytes3); // Outputs Uint8Array [104, 101, 108, 108, 111] * * const bytes4 = bytesFrom([1, 2, 255]); * console.log(bytes4); // Outputs Uint8Array [1, 2, 255] * ``` */ declare function bytesFrom(bytes: BytesLike, encoding?: BytesFromEncoding): Bytes$1; /** * Compares two byte-like values for equality. * @public * * @param a - The first byte-like value to compare. * @param b - The second byte-like value to compare. * @returns A boolean indicating whether the two byte-like values are equal. * * @example * ```typescript * bytesEq([1], Uint8Array.from([1])) // true * ``` */ declare function bytesEq(a: BytesLike, b: BytesLike): boolean; /** * Represents a hexadecimal string prefixed with "0x". * @public */ type Hex = `0x${string}`; /** * Represents a value that can be converted to a hexadecimal string. * It extends the BytesLike type. * @public */ type HexLike = BytesLike; /** * Returns the hexadecimal representation of the given value. * * @param hex - The value to convert, which can be a string, Uint8Array, ArrayBuffer, or number array. * @returns A Hex string representing the value. * * @example * ```typescript * const hexString = hexFrom("68656c6c6f"); // Outputs "0x68656c6c6f" * const hexStringFromBytes = hexFrom(new Uint8Array([104, 101, 108, 108, 111])); // Outputs "0x68656c6c6f" * ``` */ declare function hexFrom(hex: HexLike): Hex; /** * Return the number of bytes occupied by `hexLike`. * * @param hexLike - Hex-like value * @returns Byte length of `hexLike`. * * @example * ```typescript * bytesLen("0x48656c6c6f") // 5 * bytesLen(new Uint8Array([1, 2, 3])) // 3 * bytesLen(new ArrayBuffer(4)) // 4 * bytesLen([1, 2]) // 2 * ``` * * @see bytesLenUnsafe - Fast version for already-normalized Hex strings * * @note Prefer direct `.length`/`.byteLength` access on Uint8Array/ArrayBuffer when you already have bytes. * Use `bytesLen()` only when you need length without performing additional operations. * @see bytesFrom - Convert values to Bytes (Uint8Array) */ declare function bytesLen(hexLike: HexLike): number; /** * Fast byte length for Hex strings. * * This function efficiently calculates the byte length of Hex values: * - Skips validation (caller must ensure input is valid Hex) * - Handles odd-digit hex as if it were padded with a leading zero (e.g., "0x123" is treated as "0x0123"). * * @param hex - A valid Hex string (with "0x" prefix). * @returns Byte length of the hex string. * * @example * ```typescript * bytesLenUnsafe("0x48656c6c6f") // 5 * bytesLenUnsafe("0x123") // 2 (odd digits round up via padding) * ``` * * @see bytesLen - Validated version for untrusted input */ declare function bytesLenUnsafe(hex: Hex): number; /** * @public */ type AddressLike = { script: ScriptLike; prefix: string; }; /** * Represents a ckb address with associated script and prefix. * @public */ declare class Address { script: Script; prefix: string; /** * Creates an instance of Address. * * @param script - The script associated with the address. * @param prefix - The address prefix. */ constructor(script: Script, prefix: string); /** * Creates an Address instance from an AddressLike object. * * @param address - An AddressLike object or an instance of Address. * @returns An Address instance. */ static from(address: AddressLike): Address; /** * Creates an Address instance from an address string. * * @param address - The address string to parse. If it does not parse, a * single Client's `addressResolver` may resolve it. * @param client - The Client instance used to parse or resolve the address. * @returns A promise that resolves to an Address instance. * * @throws Will throw an error if the address prefix is unknown or mismatched, * or if the resolver handles the address but does not find it. */ static fromString(address: string, client: Client): Promise
; /** * @deprecated Pass a single Client instead. Callers supporting multiple * prefixes should try each Client themselves. */ static fromString(address: string, clients: Record): Promise
; /** * Creates an Address instance from a script and client. * * @param script - The script-like object. * @param client - The client instance used to fetch the address prefix. * @returns A promise that resolves to an Address instance. */ static fromScript(script: ScriptLike, client: Client): Address; static fromKnownScript(client: Client, script: KnownScript, args: HexLike): Promise
; /** * Converts the Address instance to a string. * * @returns The address as a string. */ toString(): string; } type CodecLike = { readonly encode: (encodable: Encodable) => Bytes$1; readonly decode: (decodable: BytesLike, context?: Context) => Decoded; readonly byteLength?: number; }; declare class Codec { readonly encode: (encodable: Encodable) => Bytes$1; readonly decode: (decodable: BytesLike, context?: Context) => Decoded; readonly byteLength?: number | undefined; constructor(encode: (encodable: Encodable) => Bytes$1, decode: (decodable: BytesLike, context?: Context) => Decoded, byteLength?: number | undefined); encodeOr(encodable: Encodable, fallback: T): Bytes$1 | T; decodeOr(decodable: BytesLike, fallback: T, context?: Context): Decoded | T; static from({ encode, decode, byteLength }: CodecLike): Codec; map({ inMap, outMap }: { inMap?: (encodable: NewEncodable) => Encodable; outMap?: (decoded: Decoded) => NewDecoded; }): Codec; mapIn(map: (encodable: NewEncodable) => Encodable): Codec; mapOut(map: (decoded: Decoded) => NewDecoded): Codec; } type EncodableType> = T extends CodecLike ? Encodable : never; type DecodedType> = T extends CodecLike ? Decoded : never; type IsAny = 0 extends 1 & T ? true : false; /** * The context a codec specifically requires when composed with other codecs. * Legacy `any` is normalized to `unknown`, while `Extract` preserves that the * normalized type is assignable to the codec's original context. */ type ContextType> = T extends { readonly decode: (decodable: BytesLike, context?: infer Context) => unknown; } ? Extract extends true ? unknown : Context, Context> : unknown; /** * The combined context required by every codec in a record. * * Map each child context to a function parameter before forming the union so a * legacy `any` (normalized to `unknown` by {@link ContextType}) cannot absorb * the other contexts. Inferring from the resulting contravariant parameter * position converts the function union into an intersection of its contexts. */ type ChildContext>> = { [K in keyof T]: (context: ContextType) => void; }[keyof T] extends ((context: infer Context) => void) ? Context : unknown; type TableDecodeContext = { isExtraFieldIgnored?: boolean; }; /** * Vector with fixed size item codec * @param itemCodec fixed-size vector item codec */ declare function fixedItemVec(itemCodec: CodecLike): Codec, Array, ContextType>; /** * Vector with dynamic size item codec, you can create a recursive vector with this function * @param itemCodec the vector item codec. It can be fixed-size or dynamic-size. */ declare function dynItemVec(itemCodec: CodecLike): Codec, Array, ContextType>; /** * General vector codec, if `itemCodec` is fixed size type, it will create a fixvec codec, otherwise a dynvec codec will be created. * @param itemCodec */ declare function vector(itemCodec: CodecLike): Codec, Array, ContextType>; /** * Option is a dynamic-size type. * Serializing an option depends on whether it is empty or not: * - if it's empty, there is zero bytes (the size is 0). * - if it's not empty, just serialize the inner item (the size is same as the inner item's size). * @param innerCodec */ declare function option(innerCodec: CodecLike): Codec>; /** * Wrap the encoded value with a fixed-length buffer * @param codec */ declare function byteVec(codec: CodecLike): Codec>; type EncodableRecordOptionalKeys>> = { [K in keyof T]: Extract, undefined> extends never ? never : K; }[keyof T]; type EncodableRecord>> = { [key in keyof Pick>]+?: EncodableType; } & { [key in keyof Omit>]: EncodableType; }; type DecodedRecordOptionalKeys>> = { [K in keyof T]: Extract, undefined> extends never ? never : K; }[keyof T]; type DecodedRecord>> = { [key in keyof Pick>]+?: DecodedType; } & { [key in keyof Omit>]: DecodedType; }; /** * Table is a dynamic-size type. It can be considered as a dynvec but the length is fixed. * @param codecLayout */ declare function table>, Encodable extends EncodableRecord, Decoded extends DecodedRecord>(codecLayout: T): Codec & TableDecodeContext>; type UnionEncodable>, K extends keyof T = keyof T> = K extends unknown ? { type: K; value: EncodableType; } : never; type UnionDecoded>, K extends keyof T = keyof T> = K extends unknown ? { type: K; value: DecodedType; } : never; type UnionMatchHandlers, any>, Result> = { [T in DecodedType["type"]]: (value: Extract, { type: T; }>["value"]) => Result; }; /** * Constructs a union codec that can serialize and deserialize values tagged with a type identifier. * * In accordance with the Molecule specification, `union` is always a dynamic-size type, * regardless of whether its variants have identical fixed lengths. * * If you need a fixed-size union type compatible with fixed containers like `struct`, * `array`, or `vector` (as FixVec), use {@link fixedUnion} instead. * * Serialization format: * 1. 4-byte little-endian unsigned integer for the variant ItemId (tag). * 2. Encoded bytes of the selected variant. * * @typeParam T * A record mapping variant names to codecs. * @param codecLayout * An object whose keys are variant names and values are codecs for each variant. * @param fields * Optional mapping from variant names to custom numeric IDs. If omitted, the index * of each variant in `codecLayout` is used as its ID. * * @example * // Union without custom numeric IDs * union({ cafe: Uint8, bee: Uint16 }); * * // Union with custom numeric IDs * union({ cafe: Uint8, bee: Uint16 }, { cafe: 0xcafe, bee: 0xbee }); * * // Fixed-size union (explicit extension): * fixedUnion({ cafe: Uint16, bee: Uint16 }); */ declare function union>>(codecLayout: T, fields?: Record): Codec | { inner: UnionEncodable; }, UnionDecoded, ChildContext>; /** * FixedUnion is a fixed-size union type where all variants must be fixed-size types of identical byte length. * The total byteLength is `payloadByteLength + 4` (4-byte uint32 ItemId tag). * * Compatibility note: * `fixedUnion` is a CCC extension for scenarios requiring fixed memory layouts (such as embedding * inside `mol.struct`, `mol.array`, or `mol.vector` as FixVec). While the standalone wire format * (4-byte tag + variant payload) is binary-compatible with a union encoding, composing it into * `struct`, `array`, or FixVec is not part of the standard upstream Molecule union schema specification. * * Migration guide: * ```typescript * // Preserve legacy equal-length union fixed container layout (FixVec): * const Legacy = mol.vector(mol.fixedUnion(layout)); * * // Use canonical Molecule union vector (DynVec): * const Canonical = mol.vector(mol.union(layout)); * ``` * * @param codecLayout an object mapping variant names to fixed-size codecs of identical byteLength * @param fields optional mapping from variant names to custom numeric IDs */ declare function fixedUnion>>(codecLayout: T, fields?: Record): Codec | { inner: UnionEncodable; }, UnionDecoded, ChildContext>; /** * Struct is a fixed-size type: all fields in struct are fixed-size and it has a fixed quantity of fields. * The size of a struct is the sum of all fields' size. * @param codecLayout a object contains all fields' codec */ declare function struct>, Encodable extends EncodableRecord, Decoded extends DecodedRecord>(codecLayout: T): Codec>; /** * The array is a fixed-size type: it has a fixed-size inner type and a fixed length. * The size of an array is the size of inner type times the length. * @param itemCodec the fixed-size array item codec * @param itemCount */ declare function array(itemCodec: CodecLike, itemCount: number): Codec, Array, ContextType>; /** * Represents a numeric value as a bigint. * @public */ type Num = bigint; /** * Represents a value that can be converted to a numeric value. * It can be a string, number, bigint, or HexLike. * @public */ type NumLike = string | number | bigint | HexLike; /** * Get the min among all numbers. * @public * * @param numbers - numbers. * @returns The min numbers among them. * * @example * ```typescript * numMin(1, 2, 3); // Outputs 1n * ``` */ declare function numMin(a: NumLike, ...numbers: NumLike[]): Num; /** * Get the max among all numbers. * @public * * @param numbers - numbers. * @returns The max numbers among them. * * @example * ```typescript * numMax(1, 2, 3); // Outputs 3n * ``` */ declare function numMax(a: NumLike, ...numbers: NumLike[]): Num; /** * Converts a NumLike value to a Num (bigint). * @public * * @param val - The value to convert, which can be a string, number, bigint, or HexLike. * @returns A Num (bigint) representing the value. * * @example * ```typescript * const num = numFrom("12345"); // Outputs 12345n * const numFromHex = numFrom("0x3039"); // Outputs 12345n * ``` */ declare function numFrom(val: NumLike): Num; /** * Converts a {@link NumLike} value into its hexadecimal string representation, prefixed with `0x`. * * @remarks * This function returns the direct hexadecimal representation of the number, which may have an odd number of digits. * For a full-byte representation (an even number of hex digits), consider using {@link numToBytes}, {@link numLeToBytes}, or {@link numBeToBytes} and then converting the resulting byte array to a hex string. * * @public * * @param val - The value to convert, which can be a string, number, bigint, or HexLike. * @returns A Hex string representing the number. * * @throws {Error} If the normalized numeric value is negative. * * @example * ```typescript * const hex = numToHex(4660); // "0x1234" * const oddLengthHex = numToHex(10); // "0xa" * ``` */ declare function numToHex(val: NumLike): Hex; /** * Converts a NumLike value to a byte array in little-endian order. * @public * * @param val - The value to convert, which can be a string, number, bigint, or HexLike. * @param bytes - The number of bytes to use for the representation. If not provided, the exact number of bytes needed is used. * @returns A Uint8Array containing the byte representation of the numeric value. * * @example * ```typescript * const bytes = numToBytes(12345, 4); // Outputs Uint8Array [57, 48, 0, 0] * ``` */ declare function numToBytes(val: NumLike, bytes?: number): Bytes$1; /** * Converts a NumLike value to a byte array in little-endian order. * @public * * @param val - The value to convert, which can be a string, number, bigint, or HexLike. * @param bytes - The number of bytes to use for the representation. If not provided, the exact number of bytes needed is used. * @returns A Uint8Array containing the byte representation of the numeric value. * * @example * ```typescript * const bytes = numLeToBytes(12345, 4); // Outputs Uint8Array [57, 48, 0, 0] * ``` */ declare function numLeToBytes(val: NumLike, bytes?: number): Bytes$1; /** * Converts a NumLike value to a byte array in big-endian order. * @public * * @param val - The value to convert, which can be a string, number, bigint, or HexLike. * @param bytes - The number of bytes to use for the representation. If not provided, the exact number of bytes needed is used. * @returns A Uint8Array containing the byte representation of the numeric value. * * @example * ```typescript * const bytes = numBeToBytes(12345, 4); // Outputs Uint8Array [0, 0, 48, 57] * ``` */ declare function numBeToBytes(val: NumLike, bytes?: number): Bytes$1; /** * Converts a byte array to a Num (bigint) assuming little-endian order. * @public * * @param val - The byte array to convert. * @returns A Num (bigint) representing the numeric value. * * @example * ```typescript * const num = numFromBytes(new Uint8Array([57, 48, 0, 0])); // Outputs 12345n * ``` */ declare function numFromBytes(val: BytesLike): Num; /** * Converts a byte array to a Num (bigint) assuming little-endian order. * @public * * @param val - The byte array to convert. * @returns A Num (bigint) representing the numeric value. * * @example * ```typescript * const num = numLeFromBytes(new Uint8Array([57, 48, 0, 0])); // Outputs 12345n * ``` */ declare function numLeFromBytes(val: BytesLike): Num; /** * Converts a byte array to a Num (bigint) assuming big-endian order. * @public * * @param val - The byte array to convert. * @returns A Num (bigint) representing the numeric value. * * @example * ```typescript * const num = numBeFromBytes(new Uint8Array([0, 0, 48, 57])); // Outputs 12345n * ``` */ declare function numBeFromBytes(val: BytesLike): Num; /** * Creates a signal that aborts when any of the input signals aborts. * * Uses the native `AbortSignal.any` when available and falls back to an * `AbortController` implementation for older runtimes. * * @public */ declare function abortSignalAny(signals: readonly AbortSignal[]): AbortSignal; /** * Returns a promise that rejects with the abort reason when the signal aborts. * * @public */ declare function abortSignalToPromise(signal: AbortSignal): Promise; type Constructor = new (...args: Args) => T; type AbstractConstructor = abstract new (...args: Args) => T; /** * An ownership claim moved out of an {@link Owner}. * * @public */ declare class OwnerMoved { /** The owned value. */ readonly value: T; private readonly disposer; private disposing?; constructor( /** The owned value. */ value: T, disposer: (value: T) => PromiseLike | void); /** Disposes this ownership claim. */ dispose(): Promise; } declare const ownerId: unique symbol; /** * Owns the lifecycle of a value. * * @example * ```ts * class ConnectionOwner extends Owner { * constructor(protected readonly value_: Connection) { * super(); * } * * protected release(connection: Connection): Promise { * return connection.close(); * } * } * ``` * * @public */ declare abstract class Owner { protected abstract readonly value_: T; private readonly [ownerId]; private disposing?; /** Whether this ownership claim has not been moved or disposed. */ get isValid(): boolean; /** Returns whether a value implements CCC Owner semantics. */ static is(value: unknown): value is Owner; /** * The owned value. * * @throws If this ownership has been moved or disposed. */ get value(): T; /** * Releases this ownership claim. * * Implementations decide whether this disposes the value immediately or, * for example, only decrements a reference count. */ protected abstract release(value: T): PromiseLike | void; /** * Disposes this ownership claim. Repeated calls are safe. */ dispose(): Promise; /** * Maps the owned value while transferring this ownership claim. * * The mapper runs before the claim is moved, so a mapper failure leaves this * Owner active. After a successful mapping, this Owner is invalidated and the * returned Owner retains its release semantics. */ map(mapper: (value: T) => U): Owner; /** * Moves the ownership claim out of this owner without disposing it. * * Access is invalidated synchronously and the moved claim retains this * Owner's release semantics. * * @throws If this owner no longer has an ownership claim. */ protected move(): OwnerMoved; /** * Moves an ownership claim between Owner implementations. * * @throws If the source owner has already been moved or disposed. */ protected static moveFrom(owner: Owner): OwnerMoved; } type Owners = readonly Owner[]; type OwnerValues = { [K in keyof T]: T[K] extends Owner ? U : never; }; /** * An Owner that aggregates multiple ownership claims. * * Disposing it attempts to release every claim and aggregates any failures. * * @public */ declare class OwnerAggregated extends Owner { protected readonly value_: T; private readonly owners; private constructor(); /** Moves multiple ownership claims into one Owner. */ static from(owners: TOwners): OwnerAggregated>; protected release(): Promise; } /** * A reference-counted Owner for a shared value. * * The source ownership is disposed after the final OwnerRefCount is disposed. * Each clone owns one reference and can be disposed independently. * * @example * ```ts * const controller = new AbortController(); * const first = OwnerRefCount.new( * controller, * (controller) => controller.abort(), * ); * const second = first.clone(); * * await first.dispose(); * console.log(controller.signal.aborted); // false * * await second.dispose(); * console.log(controller.signal.aborted); // true * ``` * * @public */ declare class OwnerRefCount extends Owner { private readonly state; private constructor(); protected get value_(): T; /** Creates the first reference-counted Owner for a value. */ static new(value: T, disposer: (value: T) => PromiseLike | void): OwnerRefCount; /** * Moves an ownership claim into a new reference-counted Owner. * * @throws If the source Owner has already been moved or disposed. */ static from(owner: Owner): OwnerRefCount; /** Creates another Owner for the same shared value. */ clone(): OwnerRefCount; protected release(): Promise | void; } /** * An Owner with a single, transferable ownership claim. * * @example * ```ts * const owner = new OwnerUnique( * new AbortController(), * (controller) => controller.abort(), * ); * * const signal = owner.value.signal; * await owner.dispose(); * ``` * * @public */ declare class OwnerUnique extends Owner { protected readonly value_: T; private readonly disposer; constructor(value_: T, disposer: (value: T) => PromiseLike | void); protected release(value: T): void | PromiseLike; } /** * Utilities for creating composition wrappers. * * @example * ```ts * class Wrapper extends Proxy.Base(Client) { * static readonly [Proxy.localKeys] = ["feeRate"]; * public feeRate = 1000; * * request(): void { * this[Proxy.inner].request(); * } * } * * const wrapper = new Wrapper(client); * ``` * * @public */ declare namespace Proxy { /** The property key for accessing the immediately wrapped object. */ const inner = "@ckb-ccc/core.Proxy.inner"; /** * The static metadata key for instance fields that belong to the wrapper. * Every wrapper instance field must be listed here. Prototype members are * detected automatically. */ const localKeys: unique symbol; /** * Creates a wrapper base that delegates non-local members to an inner instance. * Its constructor accepts the inner instance and does not invoke `BaseClass`. * * @remarks * Wrapping an abstract class may require suppressing TS2655 because its abstract * members are implemented by runtime delegation. * * @param BaseClass - The class represented by the wrapper. */ function Base>(BaseClass: BaseClass): Omit & Constructor & { readonly [inner]: InstanceType; }, [InstanceType]>; } /** * A type safe way to apply a transformer on a value if it's not empty. * @public * * @param transformer - The transformer. * @param value - The value to be transformed. * @returns If the value is empty, it becomes undefined. Otherwise it will be transformed. */ declare function apply(transformer: (val: T) => R, value: undefined): undefined; /** * A type safe way to apply a transformer on a value if it's not empty. * @public * * @param transformer - The transformer. * @param value - The value to be transformed. * @returns If the value is empty, it becomes undefined. Otherwise it will be transformed. */ declare function apply(transformer: (val: T) => R, value: null): undefined; /** * A type safe way to apply a transformer on a value if it's not empty. * @public * * @param transformer - The transformer. * @param value - The value to be transformed. * @returns If the value is empty, it becomes undefined. Otherwise it will be transformed. */ declare function apply(transformer: (val: T) => R, value: T): R; /** * A type safe way to apply a transformer on a value if it's not empty. * @public * * @param transformer - The transformer. * @param value - The value to be transformed. * @returns If the value is empty, it becomes undefined. Otherwise it will be transformed. */ declare function apply(transformer: (val: T) => R, value: T | undefined): R | undefined; /** * A type safe way to apply a transformer on a value if it's not empty. * @public * * @param transformer - The transformer. * @param value - The value to be transformed. * @returns If the value is empty, it becomes undefined. Otherwise it will be transformed. */ declare function apply(transformer: (val: T) => R, value: T | null): R | undefined; /** * A type safe way to apply a transformer on a value if it's not empty. * @public * * @param transformer - The transformer. * @param value - The value to be transformed. * @returns If the value is empty, it becomes undefined. Otherwise it will be transformed. */ declare function apply(transformer: (val: T) => R, value: undefined | null): undefined; /** /** * A type safe way to apply a transformer on a value if it's not empty. * @public * * @param transformer - The transformer. * @param value - The value to be transformed. * @returns If the value is empty, it becomes undefined. Otherwise it will be transformed. */ declare function apply(transformer: (val: T) => R, value: T | undefined | null): R | undefined; /** * Similar to Array.reduce, but the accumulator can returns Promise. * @public * * @param values - The array to be reduced. * @param accumulator - A callback to be called for each value. If it returns null, the previous result will be kept. * @returns The accumulated result. */ declare function reduceAsync(values: T[], accumulator: (a: T, b: T) => Promise | T | undefined | null | void): Promise; /** * Similar to Array.reduce, but the accumulator can returns Promise. * @public * * @param values - The array to be reduced. * @param accumulator - A callback to be called for each value. If it returns null, the previous result will be kept. * @param init - The initial value. * @returns The accumulated result. */ declare function reduceAsync(values: V[], accumulator: (a: T, b: V, i: number, values: V[]) => Promise | T | undefined | null | void, init: T | Promise): Promise; /** * Waits for the given duration, rejecting with the abort reason if cancelled. * @public */ declare function sleep(ms: NumLike, signal?: AbortSignal): Promise; type RetryOptions = { /** Repeats indefinitely with this delay after the delay iterable is exhausted. */ repeat?: NumLike; /** Cancels waiting between attempts. */ signal?: AbortSignal; }; /** A result returned by a retry operation. @public */ type RetryResult = { status: "resolved"; value: T; } | { status: "rejected"; error: unknown; } | { status: "retry"; value?: never; }; /** Values available to each retry attempt. @public */ type RetryOperationOptions = { /** Zero-based attempt index. */ index: number; resolve: (value: T) => RetryResult; reject: (error: unknown) => RetryResult; next: () => RetryResult; }; /** * Retries an asynchronous operation when it throws. The iterable supplies one * delay per retry and stops retrying when it is exhausted unless `repeat` is * configured. Returning `resolve(value)` or `reject(error)` settles * immediately. Returning `next()` consumes the next delay without throwing * an error. * @public */ declare function retry(delays: Iterable, operation: (options: RetryOperationOptions) => PromiseLike> | RetryResult, options?: RetryOptions): Promise; /** * Waits until the current browser page is visible and the browser reports it * is online. This does not guarantee that a remote endpoint is reachable. * Resolves immediately outside a browser and rejects with the abort reason * when the optional signal is aborted. * @public */ declare function waitForAvailability(signal?: AbortSignal): Promise; /** * @public */ declare function isWebview(userAgent: string): boolean; /** * @public */ declare function stringify(val: unknown): string; /** * Calculate the greatest common divisor (GCD) of two NumLike values using the Euclidean algorithm. * * @param a - First operand. * @param b - Second operand. * @returns GCD(a, b) as a Num. */ declare function gcd(a: NumLike, b: NumLike): Num; /** * The base class of CCC to create a serializable instance. This should be used with the {@link codec} decorator. * @public */ declare abstract class Entity { /** * Generate a base class of CCC to create a serializable instance. * This should be used with the {@link codec} decorator. * @public */ static Base(): (abstract new () => { /** * Convert the entity to bytes * @public * @returns The bytes representation of the entity */ toBytes(): Bytes$1; /** * Create a clone of the entity * @public * @returns A clone of the entity */ clone(): SubType; /** * Check if the entity is equal to another entity * @public * @param other - The other entity to compare with * @returns True if the entities are equal, false otherwise */ eq(other: SubTypeLike): boolean; /** * Calculate the hash of the entity * @public * @returns The hash of the entity */ hash(): Hex; /** * Convert the entity to a full-byte untrimmed Hex representation * @public * @returns The entity full-byte untrimmed hexadecimal representation */ toHex(): Hex; }) & { /** * The bytes length of the entity, if it is fixed, otherwise undefined * @public * @static */ byteLength?: number; /** * Encode the entity into bytes * @public * @static * @param _ - The entity to encode * @returns The encoded bytes * @throws Will throw an error if the entity is not serializable */ encode(_: SubTypeLike): Bytes$1; /** * Decode the entity from bytes * @public * @static * @param _ - The bytes to decode * @param _context - Optional context passed to the codec * @returns The decoded entity * @throws Will throw an error if the entity is not serializable */ decode(_: BytesLike, _context?: Context): SubType; /** * Create an entity from bytes * @public * @static * @param _ - The bytes to create the entity from * @param _context - Optional context passed to the codec * @returns The created entity * @throws Will throw an error if the entity is not serializable */ fromBytes(_bytes: BytesLike, _context?: Context): SubType; /** * Create an entity from a serializable object * @public * @static * @param _ - The serializable object to create the entity from * @returns The created entity * @throws Will throw an error if the entity is not serializable */ from(_: SubTypeLike): SubType; Base(): /*elided*/ any; /** * Generate a base class of CCC to create a serializable Union instance. * This should be used with the {@link codec} decorator. * @public */ BaseUnion, any>, SubTypeLike_1, SubType_1 = SubTypeLike_1>(): (abstract new (inner: DecodedType) => { readonly inner: DecodedType; /** * Match the union type with a set of handlers. * @public * @param handlers - A map of type-specific handlers, all variants must be handled if no default handler `_` is provided. * @returns The result returned by the matching handler. */ match(handlers: UnionMatchHandlers & { _?: undefined | null; }): Result; /** * Match the union type with a set of handlers. * @public * @param handlers - A map of type-specific handlers, unmatched variants will be handled by the default handler `_`. * @returns The result returned by the matching handler. */ match(handlers: Partial> & { _: (inner: DecodedType) => Result; }): Result; /** * Convert the entity to bytes * @public * @returns The bytes representation of the entity */ toBytes(): Bytes$1; /** * Create a clone of the entity * @public * @returns A clone of the entity */ clone(): SubType_1; /** * Check if the entity is equal to another entity * @public * @param other - The other entity to compare with * @returns True if the entities are equal, false otherwise */ eq(other: SubTypeLike_1): boolean; /** * Calculate the hash of the entity * @public * @returns The hash of the entity */ hash(): Hex; /** * Convert the entity to a full-byte untrimmed Hex representation * @public * @returns The entity full-byte untrimmed hexadecimal representation */ toHex(): Hex; }) & { /** * The bytes length of the entity, if it is fixed, otherwise undefined * @public * @static */ byteLength?: number; /** * Encode the entity into bytes * @public * @static * @param _ - The entity to encode * @returns The encoded bytes * @throws Will throw an error if the entity is not serializable */ encode(_: SubTypeLike_1): Bytes$1; /** * Decode the entity from bytes * @public * @static * @param _ - The bytes to decode * @param _context - Optional context passed to the codec * @returns The decoded entity * @throws Will throw an error if the entity is not serializable */ decode(_: BytesLike, _context?: ContextType | undefined): SubType_1; /** * Create an entity from bytes * @public * @static * @param _ - The bytes to create the entity from * @param _context - Optional context passed to the codec * @returns The created entity * @throws Will throw an error if the entity is not serializable */ fromBytes(_bytes: BytesLike, _context?: ContextType | undefined): SubType_1; /** * Create an entity from a serializable object * @public * @static * @param _ - The serializable object to create the entity from * @returns The created entity * @throws Will throw an error if the entity is not serializable */ from(_: SubTypeLike_1): SubType_1; /** * Generate a base class of CCC to create a serializable instance. * This should be used with the {@link codec} decorator. * @public */ Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike_1, SubType_1 = SubTypeLike_1>(): /*elided*/ any; }; }; /** * Convert the entity to bytes. * @public * @returns The bytes representation of the entity. */ abstract toBytes(): Bytes$1; /** * Calculate the hash of the entity. * @public * @returns The hash of the entity. */ abstract hash(): Hex; /** * Convert the entity to a full-byte untrimmed Hex representation. * @public * @returns The entity full-byte untrimmed hexadecimal representation. */ abstract toHex(): Hex; /** * Create a clone of the entity. * @public * @returns A clone of the entity. */ abstract clone(): Entity; /** * Generate a base class of CCC to create a serializable Union instance. * This should be used with the {@link codec} decorator. * @public */ static BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): (abstract new (inner: DecodedType) => { readonly inner: DecodedType; /** * Match the union type with a set of handlers. * @public * @param handlers - A map of type-specific handlers, all variants must be handled if no default handler `_` is provided. * @returns The result returned by the matching handler. */ match(handlers: UnionMatchHandlers & { _?: undefined | null; }): Result; /** * Match the union type with a set of handlers. * @public * @param handlers - A map of type-specific handlers, unmatched variants will be handled by the default handler `_`. * @returns The result returned by the matching handler. */ match(handlers: Partial> & { _: (inner: DecodedType) => Result; }): Result; /** * Convert the entity to bytes * @public * @returns The bytes representation of the entity */ toBytes(): Bytes$1; /** * Create a clone of the entity * @public * @returns A clone of the entity */ clone(): SubType; /** * Check if the entity is equal to another entity * @public * @param other - The other entity to compare with * @returns True if the entities are equal, false otherwise */ eq(other: SubTypeLike): boolean; /** * Calculate the hash of the entity * @public * @returns The hash of the entity */ hash(): Hex; /** * Convert the entity to a full-byte untrimmed Hex representation * @public * @returns The entity full-byte untrimmed hexadecimal representation */ toHex(): Hex; }) & { /** * The bytes length of the entity, if it is fixed, otherwise undefined * @public * @static */ byteLength?: number; /** * Encode the entity into bytes * @public * @static * @param _ - The entity to encode * @returns The encoded bytes * @throws Will throw an error if the entity is not serializable */ encode(_: SubTypeLike): Bytes$1; /** * Decode the entity from bytes * @public * @static * @param _ - The bytes to decode * @param _context - Optional context passed to the codec * @returns The decoded entity * @throws Will throw an error if the entity is not serializable */ decode(_: BytesLike, _context?: ContextType | undefined): SubType; /** * Create an entity from bytes * @public * @static * @param _ - The bytes to create the entity from * @param _context - Optional context passed to the codec * @returns The created entity * @throws Will throw an error if the entity is not serializable */ fromBytes(_bytes: BytesLike, _context?: ContextType | undefined): SubType; /** * Create an entity from a serializable object * @public * @static * @param _ - The serializable object to create the entity from * @returns The created entity * @throws Will throw an error if the entity is not serializable */ from(_: SubTypeLike): SubType; /** * Generate a base class of CCC to create a serializable instance. * This should be used with the {@link codec} decorator. * @public */ Base(): (abstract new () => { /** * Convert the entity to bytes * @public * @returns The bytes representation of the entity */ toBytes(): Bytes$1; /** * Create a clone of the entity * @public * @returns A clone of the entity */ clone(): SubType_1; /** * Check if the entity is equal to another entity * @public * @param other - The other entity to compare with * @returns True if the entities are equal, false otherwise */ eq(other: SubTypeLike_1): boolean; /** * Calculate the hash of the entity * @public * @returns The hash of the entity */ hash(): Hex; /** * Convert the entity to a full-byte untrimmed Hex representation * @public * @returns The entity full-byte untrimmed hexadecimal representation */ toHex(): Hex; }) & { /** * The bytes length of the entity, if it is fixed, otherwise undefined * @public * @static */ byteLength?: number; /** * Encode the entity into bytes * @public * @static * @param _ - The entity to encode * @returns The encoded bytes * @throws Will throw an error if the entity is not serializable */ encode(_: SubTypeLike_1): Bytes$1; /** * Decode the entity from bytes * @public * @static * @param _ - The bytes to decode * @param _context - Optional context passed to the codec * @returns The decoded entity * @throws Will throw an error if the entity is not serializable */ decode(_: BytesLike, _context?: Context): SubType_1; /** * Create an entity from bytes * @public * @static * @param _ - The bytes to create the entity from * @param _context - Optional context passed to the codec * @returns The created entity * @throws Will throw an error if the entity is not serializable */ fromBytes(_bytes: BytesLike, _context?: Context): SubType_1; /** * Create an entity from a serializable object * @public * @static * @param _ - The serializable object to create the entity from * @returns The created entity * @throws Will throw an error if the entity is not serializable */ from(_: SubTypeLike_1): SubType_1; Base(): /*elided*/ any; /** * Generate a base class of CCC to create a serializable Union instance. * This should be used with the {@link codec} decorator. * @public */ BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): /*elided*/ any; }; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): /*elided*/ any; }; } /** * A class decorator to add methods implementation on the {@link Entity.Base} class * @example * ```typescript * @codec( * mol.table({ * codeHash: mol.Byte32, * hashType: HashTypeCodec, * args: mol.Bytes, * }), * ) * export class Script extends Entity.Base() { * from(scriptLike: ScriptLike): Script {} * } * ``` */ declare function codec$1(codec: { encode: (encodable: Encodable) => Bytes$1; decode: (decodable: Bytes$1, context?: Context) => Decoded; byteLength?: number; }): & { from(decoded: TypeLike): Type; byteLength?: number; encode(encodable: TypeLike): Bytes$1; decode(bytesLike: BytesLike, context?: Context): Type; fromBytes(bytes: BytesLike, context?: Context): Type; }>(Constructor: ConstructorType, ..._: unknown[]) => ConstructorType; /** * Create a codec to deal with fixed LE or BE bytes. * @param byteLength * @param littleEndian */ declare function codecUint(byteLength: number, littleEndian?: boolean): Codec; /** * Create a codec to deal with fixed LE or BE bytes. * @param byteLength * @param littleEndian */ declare function codecUintNumber(byteLength: number, littleEndian?: boolean): Codec; /** * Create a codec for padding bytes. * The padding bytes are zero-filled when encoding and ignored when decoding. * @param byteLength The length of the padding in bytes. */ declare function codecPadding(byteLength: number): Codec; declare const CodecRaw: Codec; declare const CodecBytes: Codec; declare const CodecUint8: Codec; declare const CodecUint16LE: Codec; declare const CodecUint16BE: Codec; declare const CodecUint16: Codec; declare const CodecUint32LE: Codec; declare const CodecUint32BE: Codec; declare const CodecUint32: Codec; declare const CodecUint64LE: Codec; declare const CodecUint64BE: Codec; declare const CodecUint64: Codec; declare const CodecUint128LE: Codec; declare const CodecUint128BE: Codec; declare const CodecUint128: Codec; declare const CodecUint256LE: Codec; declare const CodecUint256BE: Codec; declare const CodecUint256: Codec; declare const CodecUint512LE: Codec; declare const CodecUint512BE: Codec; declare const CodecUint512: Codec; declare const CodecBool: Codec; declare const CodecByte: Codec; declare const CodecByte4: Codec; declare const CodecByte8: Codec; declare const CodecByte16: Codec; declare const CodecByte32: Codec; /** * Represents a fixed point value as a bigint. * @public */ type FixedPoint = bigint; /** * Represents a value that can be converted to a fixed point value. * It can be a bigint, string, or number. * @public */ type FixedPointLike = bigint | string | number; /** * Converts a FixedPointLike value to its string representation with fixed-point decimals. * @public * * @param val - The value to convert, which can be a bigint, string, or number. * @param decimals - The number of decimal places for the fixed-point representation. Default is 8. * @returns A string representing the fixed-point value. * * @example * ```typescript * const str = fixedPointToString(123456789n, 8); // Outputs "1.23456789" * const strFromString = fixedPointToString("1.23456789", 8); // Outputs "1.23456789" * const strFromNumber = fixedPointToString(1.23456789, 8); // Outputs "1.23456789" * ``` */ declare function fixedPointToString(val: FixedPointLike, decimals?: number): string; /** * Converts a FixedPointLike value to a FixedPoint (bigint) with fixed-point decimals. * @public * * @param val - The value to convert, which can be a bigint, string, or number. * @param decimals - The number of decimal places for the fixed-point representation. Default is 8. * @returns A FixedPoint (bigint) representing the value with fixed-point decimals. * * @example * ```typescript * const fixedPoint = fixedPointFrom(123456789n, 8); // Outputs 123456789n * const fixedPointFromString = fixedPointFrom("1.23456789", 8); // Outputs 123456789n * const fixedPointFromNumber = fixedPointFrom(1.23456789, 8); // Outputs 123456789n * ``` */ declare function fixedPointFrom(val: FixedPointLike, decimals?: number): FixedPoint; /** * Represents the fixed point value of zero as a bigint. * @public */ declare const Zero: FixedPoint; /** * Represents the fixed point value of one as a FixedPoint (bigint). * Equivalent to 1 in fixed-point representation with default decimals (8). * @public */ declare const One: FixedPoint; /** * @public */ interface Hasher { /** * Updates the hash with the given data. * * @param data - The data to update the hash with. * @returns The current Hasher instance for chaining. * * @example * ```typescript * const hasher = new Hasher(); * hasher.update("some data").update("more data"); * const hash = hasher.digest(); * ``` */ update(data: BytesLike): Hasher; /** * Finalizes the hash and returns the digest as a hexadecimal string. * * @returns The hexadecimal string representation of the hash. * * @example * ```typescript * const hasher = new Hasher(); * hasher.update("some data"); * const hash = hasher.digest(); // Outputs something like "0x..." * ``` */ digest(): Hex; } declare const HASH_CKB_LENGTH = 32; declare const HASH_CKB_SHORT_LENGTH = 20; /** * @public */ declare class HasherCkb implements Hasher { private readonly hasher; /** * Creates an instance of Hasher. * * @param outLength - The output length of the hash in bytes. Default is 32. * @param personal - The personal string for the Blake2b algorithm. Default is CKB_BLAKE2B_PERSONAL. */ constructor(outLength?: number, personal?: Bytes$1); /** * Updates the hash with the given data. * * @param data - The data to update the hash with. * @returns The current Hasher instance for chaining. * * @example * ```typescript * const hasher = new Hasher(); * hasher.update("some data").update("more data"); * const hash = hasher.digest(); * ``` */ update(data: BytesLike): HasherCkb; /** * Finalizes the hash and returns the digest as a hexadecimal string. * * @returns The hexadecimal string representation of the hash. * * @example * ```typescript * const hasher = new Hasher(); * hasher.update("some data"); * const hash = hasher.digest(); // Outputs something like "0x..." * ``` */ digest(): Hex; } /** * Computes the CKB hash of the given data using the Blake2b algorithm. * @public * * @param data - The data to hash. * @returns The hexadecimal string representation of the hash. * * @example * ```typescript * const hash = hashCkb("some data"); // Outputs something like "0x..." * ``` */ declare function hashCkb(...data: BytesLike[]): Hex; declare function hashCkbShort(...data: BytesLike[]): Hex; /** * @public */ declare class HasherKeecak256 implements Hasher { private readonly hasher; /** * Creates an instance of Hasher. */ constructor(); /** * Updates the hash with the given data. * * @param data - The data to update the hash with. * @returns The current Hasher instance for chaining. * * @example * ```typescript * const hasher = new Hasher(); * hasher.update("some data").update("more data"); * const hash = hasher.digest(); * ``` */ update(data: BytesLike): HasherKeecak256; /** * Finalizes the hash and returns the digest as a hexadecimal string. * * @returns The hexadecimal string representation of the hash. * * @example * ```typescript * const hasher = new Hasher(); * hasher.update("some data"); * const hash = hasher.digest(); // Outputs something like "0x..." * ``` */ digest(): Hex; } type JsonRpcId = string | number; type JsonRpcPayload = { id: JsonRpcId; jsonrpc: "2.0"; method: string; params: unknown[] | Record; }; type JsonRpcErrorLike = { code: number; message: string; data?: Data; }; declare class JsonRpcError extends Error { readonly code: number; readonly data?: Data; constructor(error: JsonRpcErrorLike); } type JsonRpcResponse = { id: JsonRpcId; jsonrpc: "2.0"; } & ({ result: Result; error?: never; } | { result?: never; error: JsonRpcErrorLike; }); type JsonRpcTransportRequestOptions = { /** Cancels this individual request without disposing the transport. */ signal?: AbortSignal; /** Overrides the transport's default timeout for this request. */ timeout?: number; }; interface JsonRpcTransport { /** * Sends a JSON-RPC request to the server. * * @param payload - The JSON-RPC payload to send. * @returns The JSON-RPC response. */ request(payload: JsonRpcPayload, options?: JsonRpcTransportRequestOptions): Promise; } declare class JsonRpcTransportFallback implements JsonRpcTransport { private readonly transports; private i; constructor(transports: JsonRpcTransport[]); request(data: JsonRpcPayload, options?: JsonRpcTransportRequestOptions): Promise; } declare class JsonRpcTransportHttp implements JsonRpcTransport { private readonly url; private readonly timeout; constructor(url: string, timeout?: number); request(payload: JsonRpcPayload, options?: JsonRpcTransportRequestOptions): Promise; } declare class JsonRpcTransportWebSocket implements JsonRpcTransport { private readonly url; private readonly timeout; private ongoing; private firstTimeout?; private disposed; private socket?; private openSocket?; /** * @deprecated Use {@link JsonRpcTransportWebSocket.open} to make lifecycle * ownership explicit. This constructor will become private in a future * release. */ constructor(url: string, timeout?: number); /** Opens an owned WebSocket transport. */ static open(url: string, timeout?: number): OwnerUnique; request(data: JsonRpcPayload, options?: JsonRpcTransportRequestOptions): Promise; private dispose; } /** * @deprecated Used only by the legacy positional constructor. Use the static * {@link RequestorJsonRpc.new} or {@link RequestorJsonRpc.open} methods. */ type RequestorJsonRpcConfig = { fallbacks?: string[]; timeout?: number; maxConcurrent?: number; transport?: JsonRpcTransport; }; declare class RequestorJsonRpc { private readonly url_; private readonly onError?; readonly maxConcurrent?: number; private concurrent; private readonly pending; readonly transport: JsonRpcTransport; private id; /** * Creates a Requestor using legacy positional arguments. * * @param url_ - The URL of the JSON-RPC server. * @param timeout - The timeout for requests in milliseconds * @deprecated Use {@link RequestorJsonRpc.new} with a borrowed Transport or * {@link RequestorJsonRpc.open} when creating Transports. */ constructor(url_: string, config?: RequestorJsonRpcConfig, onError?: ((err: unknown) => Promise | void) | undefined); /** * Creates a Requestor that borrows an existing Transport. * The caller manages the transport's lifecycle. * * Do not share a WebSocket transport across requestors: request IDs can collide, * mixing up responses or leaving requests unresolved. Reuse one requestor, or * create separate transports with {@link RequestorJsonRpc.open}. */ static new({ transport, maxConcurrent, onError }: { transport: JsonRpcTransport; maxConcurrent?: number; onError?: (err: unknown) => Promise | void; }): RequestorJsonRpc; /** Opens a Requestor with ownership of its default transports. */ static open({ urls: [url, ...fallbacks], onError, ...config }: { urls: readonly [string, ...string[]]; timeout?: number; maxConcurrent?: number; onError?: (err: unknown) => Promise | void; }): Owner; /** * Returns the URL of the JSON-RPC server. * * @returns The URL of the JSON-RPC server. * @deprecated URL belongs to Transport construction and is unavailable for * Requestors created with {@link RequestorJsonRpc.new}. */ get url(): string; /** * request a JSON-RPC method. * * @param rpcMethod - The JSON-RPC method. * @param params - Params for the method. * @param inTransformers - An array of input transformers. * @param outTransformer - An output transformer function. * @returns Method response. */ request(rpcMethod: string, params: unknown[], inTransformers?: (((_: any) => unknown) | undefined)[], outTransformer?: (_: any) => unknown, options?: JsonRpcTransportRequestOptions): Promise; requestPayload(payload: JsonRpcPayload, options?: JsonRpcTransportRequestOptions): Promise; /** * Builds a JSON-RPC payload for the given method and parameters. * * @param method - The JSON-RPC method name. * @param req - The parameters for the JSON-RPC method. * @returns The JSON-RPC payload. */ buildPayload(method: string, req: unknown[]): JsonRpcPayload; } /** * @public */ declare function keystoreEncrypt(privateKeyLike: BytesLike, chainCodeLike: BytesLike, password: string): Promise<{ id: string; crypto: { ciphertext: string; cipherparams: { iv: string; }; cipher: string; kdf: string; kdfparams: { n: number; r: number; p: number; dklen: number; salt: string; }; mac: string; }; }>; /** * @public */ declare function keystoreDecrypt(keystore: unknown, password: string): Promise<{ privateKey: Bytes$1; chainCode: Bytes$1; }>; declare const Uint8Opt: Codec; declare const Uint8Vec: Codec; declare const Uint16Opt: Codec; declare const Uint16Vec: Codec; declare const Uint32Opt: Codec; declare const Uint32Vec: Codec; declare const Uint64Opt: Codec; declare const Uint64Vec: Codec; declare const Uint128Opt: Codec; declare const Uint128Vec: Codec; declare const Uint256Opt: Codec; declare const Uint256Vec: Codec; declare const Uint512Opt: Codec; declare const Uint512Vec: Codec; declare const Bytes: Codec; declare const BytesOpt: Codec; declare const BytesVec: Codec; declare const BoolOpt: Codec; declare const BoolVec: Codec; declare const ByteOpt: Codec; declare const ByteVec: Codec; declare const Byte4Opt: Codec; declare const Byte4Vec: Codec; declare const Byte8Opt: Codec; declare const Byte8Vec: Codec; declare const Byte16Opt: Codec; declare const Byte16Vec: Codec; declare const Byte32Opt: Codec; declare const Byte32Vec: Codec; declare const String: Codec; declare const StringVec: Codec; declare const StringOpt: Codec; declare namespace barrel_d_exports$1 { export { CodecBool as Bool, BoolOpt, BoolVec, CodecByte as Byte, CodecByte16 as Byte16, Byte16Opt, Byte16Vec, CodecByte32 as Byte32, Byte32Opt, Byte32Vec, CodecByte4 as Byte4, Byte4Opt, Byte4Vec, CodecByte8 as Byte8, Byte8Opt, Byte8Vec, ByteOpt, ByteVec, Bytes, BytesOpt, BytesVec, Codec, CodecLike, DecodedRecord, DecodedRecordOptionalKeys, DecodedType, EncodableRecord, EncodableRecordOptionalKeys, EncodableType, Entity, String, StringOpt, StringVec, TableDecodeContext, CodecUint128 as Uint128, CodecUint128BE as Uint128BE, CodecUint128LE as Uint128LE, Uint128Opt, Uint128Vec, CodecUint16 as Uint16, CodecUint16BE as Uint16BE, CodecUint16LE as Uint16LE, Uint16Opt, Uint16Vec, CodecUint256 as Uint256, CodecUint256BE as Uint256BE, CodecUint256LE as Uint256LE, Uint256Opt, Uint256Vec, CodecUint32 as Uint32, CodecUint32BE as Uint32BE, CodecUint32LE as Uint32LE, Uint32Opt, Uint32Vec, CodecUint512 as Uint512, CodecUint512BE as Uint512BE, CodecUint512LE as Uint512LE, Uint512Opt, Uint512Vec, CodecUint64 as Uint64, CodecUint64BE as Uint64BE, CodecUint64LE as Uint64LE, Uint64Opt, Uint64Vec, CodecUint8 as Uint8, Uint8Opt, Uint8Vec, UnionDecoded, UnionEncodable, UnionMatchHandlers, array, byteVec, codec$1 as codec, dynItemVec, fixedItemVec, fixedUnion, option, struct, table, codecUint as uint, codecUintNumber as uintNumber, union, vector }; } /** * Options for signing a PSBT (Partially Signed Bitcoin Transaction) */ type SignPsbtOptionsLike = { /** * Whether to attempt to finalize the signed inputs after signing. * Default is true. */ autoFinalized?: boolean; /** * Array of inputs to sign */ inputsToSign?: InputToSignLike[]; }; declare class SignPsbtOptions { autoFinalized: boolean; inputsToSign: InputToSign[]; constructor(autoFinalized: boolean, inputsToSign: InputToSign[]); static from(options?: SignPsbtOptionsLike | SignPsbtOptions): SignPsbtOptions; } /** * Specification for an input to sign in a PSBT. * Must specify at least one of: address or pubkey. */ type InputToSignLike = { /** * Which input to sign (index in the PSBT inputs array) */ index: number; /** * (Optional) Sighash types to use for signing. */ sighashTypes?: number[]; /** * (Optional) When signing and unlocking Taproot addresses, the tweakSigner is used by default * for signature generation. Setting this to true allows for signing with the original private key. * Default value is false. */ disableTweakSigner?: boolean; } & ({ /** * The address whose corresponding private key to use for signing. */ address: string; /** * The public key whose corresponding private key to use for signing. */ publicKey?: HexLike; } | { /** * The address whose corresponding private key to use for signing. */ address?: string; /** * The public key whose corresponding private key to use for signing. */ publicKey: HexLike; }); declare class InputToSign { index: number; sighashTypes?: number[] | undefined; disableTweakSigner?: boolean | undefined; address?: string | undefined; publicKey?: Hex | undefined; constructor(index: number, sighashTypes?: number[] | undefined, disableTweakSigner?: boolean | undefined, address?: string | undefined, publicKey?: Hex | undefined); static from(input: InputToSignLike): InputToSign; } /** * @public */ declare enum SignerSignType { Unknown = "Unknown", BtcEcdsa = "BtcEcdsa", EvmPersonal = "EvmPersonal", JoyId = "JoyId", NostrEvent = "NostrEvent", CkbSecp256k1 = "CkbSecp256k1", DogeEcdsa = "DogeEcdsa" } /** * An enumeration of signer display types in wallet. * @public */ declare enum SignerType { EVM = "EVM", BTC = "BTC", CKB = "CKB", Nostr = "Nostr", Doge = "Doge" } /** * @public * @deprecated Wallet integrations now expose one signer per selectable network. * This compatibility type will be removed in the next major release. */ type NetworkPreference = { addressPrefix: string; signerType: SignerType; network: string; }; /** * @public */ declare class Signature { signature: string; identity: string; signType: SignerSignType; constructor(signature: string, identity: string, signType: SignerSignType); } /** * An abstract class representing a generic signer. * This class provides methods to connect, get addresses, and sign transactions. * @public */ declare abstract class Signer { protected client_: Client; constructor(client_: Client); abstract get type(): SignerType; abstract get signType(): SignerSignType; get client(): Client; /** * @deprecated Wallet integrations now use fixed-network signers. */ matchNetworkPreference(preferences: NetworkPreference[], currentNetwork: string | undefined): NetworkPreference | undefined; static verifyMessage(message: string | BytesLike, signature: Signature): Promise; /** * Connects to the signer. * * @returns A promise that resolves when the connection is complete. */ abstract connect(): Promise; /** * Register a listener to be called when this signer is replaced. * * @returns A function for unregister */ onReplaced(_: () => void): () => void; /** * Disconnects to the signer. * * @returns A promise that resolves when the signer is disconnected. */ disconnect(): Promise; /** * Check if the signer is connected. * * @returns A promise that resolves the connection status. */ abstract isConnected(): Promise; /** * Gets the internal address associated with the signer. * * @returns A promise that resolves to a string representing the internal address. */ abstract getInternalAddress(): Promise; /** * Gets the identity for verifying signature, usually it's address * * @returns A promise that resolves to a string representing the identity */ getIdentity(): Promise; /** * Gets an array of Address objects associated with the signer. * * @returns A promise that resolves to an array of Address objects. */ abstract getAddressObjs(): Promise; /** * Gets the recommended Address object for the signer. * * @param _preference - Optional preference parameter. * @returns A promise that resolves to the recommended Address object. */ getRecommendedAddressObj(_preference?: unknown): Promise
; /** * Gets the recommended address for the signer as a string. * * @param preference - Optional preference parameter. * @returns A promise that resolves to the recommended address as a string. */ getRecommendedAddress(preference?: unknown): Promise; /** * Gets an array of addresses associated with the signer as strings. * * @returns A promise that resolves to an array of addresses as strings. */ getAddresses(): Promise; /** * Find cells of this signer * * @param filter - The filter for the search key. * @param withData - Whether to include cell data in the response. * @param order - The order of the returned cells, can be "asc" or "desc". * @param limit - The maximum number of cells for every querying chunk. * @returns A async generator that yields all matching cells */ findCellsOnChain(filter: ClientIndexerSearchKeyFilterLike, withData?: boolean | null, order?: "asc" | "desc", limit?: number): AsyncGenerator; /** * Find cells of this signer * * @returns A async generator that yields all matches cells */ findCells(filter: ClientCollectableSearchKeyFilterLike, withData?: boolean | null, order?: "asc" | "desc", limit?: number): AsyncGenerator; /** * Find transactions of this signer * * @returns A async generator that yields all matches transactions */ findTransactions(filter: ClientCollectableSearchKeyFilterLike, groupByTransaction?: false | null, order?: "asc" | "desc", limit?: number): AsyncGenerator; /** * Find transactions of this signer * * @returns A async generator that yields all matches transactions */ findTransactions(filter: ClientCollectableSearchKeyFilterLike, groupByTransaction: true, order?: "asc" | "desc", limit?: number): AsyncGenerator; /** * Find transactions of this signer * * @returns A async generator that yields all matches transactions */ findTransactions(filter: ClientCollectableSearchKeyFilterLike, groupByTransaction?: boolean | null, order?: "asc" | "desc", limit?: number): AsyncGenerator; /** * Gets balance of all addresses * * @returns A promise that resolves to the balance */ getBalance(): Promise; /** * Signs a message. * * @param message - The message to sign, as a string or BytesLike object. * @returns A promise that resolves to the signature info. * @throws Will throw an error if not implemented. */ signMessage(message: string | BytesLike): Promise; /** * Signs a message and returns signature only. This method is not implemented and should be overridden by subclasses. * * @param _ - The message to sign, as a string or BytesLike object. * @returns A promise that resolves to the signature as a string. * @throws Will throw an error if not implemented. */ signMessageRaw(_: string | BytesLike): Promise; /** * Verify a signature. * * @param message - The original message. * @param signature - The signature to verify. * @returns A promise that resolves to the verification result. * @throws Will throw an error if not implemented. */ verifyMessage(message: string | BytesLike, signature: string | Signature): Promise; /** * Sends a transaction after signing it. * * @param tx - The transaction to send, represented as a TransactionLike object. * @returns A promise that resolves to the transaction hash as a Hex string. */ sendTransaction(tx: TransactionLike): Promise; /** * Signs a transaction. * * @param tx - The transaction to sign, represented as a TransactionLike object. * @returns A promise that resolves to the signed Transaction object. */ signTransaction(tx: TransactionLike): Promise; /** * Prepares a transaction before signing. * This method can be overridden by subclasses to perform any necessary steps, * such as adding cell dependencies or witnesses, before the transaction is signed. * The default implementation converts the {@link TransactionLike} object to a {@link Transaction} object * without modification. * * @remarks * Note that this default implementation does not add any cell dependencies or dummy witnesses. * This may lead to an underestimation of transaction size and fees if used with methods * like `Transaction.completeFee`. Subclasses for signers that are intended to sign * transactions should override this method to perform necessary preparations. * * @param tx - The transaction to prepare. * @returns A promise that resolves to the prepared {@link Transaction} object. */ prepareTransaction(tx: TransactionLike): Promise; /** * Signs a transaction without preparing information for it. This method is not implemented and should be overridden by subclasses. * * @param _ - The transaction to sign, represented as a TransactionLike object. * @returns A promise that resolves to the signed Transaction object. * @throws Will throw an error if not implemented. */ signOnlyTransaction(_: TransactionLike): Promise; } /** * An abstract class representing a multisig signer. * @public */ declare abstract class SignerMultisig extends Signer { /** * Get the number of members in the multisig script. * @returns The number of members. */ abstract getMemberCount(): Promise; /** * Get the threshold of the multisig script. * @returns The threshold. */ abstract getMemberThreshold(): Promise; /** * Get the count of required member of the multisig script. * @returns The must match count. */ abstract getMemberRequiredCount(): Promise; /** * Get the number of valid signatures for matching multisig inputs in the transaction. * * @remarks * Returns `undefined` when the transaction has no inputs locked by any multisig address * supported by this signer. This method only evaluates matching multisig inputs and does * not indicate whether the transaction itself is expected to be signed by this multisig. * * @param _ - The transaction. * @returns The matched multisig signature count, or `undefined` when the transaction is unrelated to any multisig address supported by this signer. */ abstract getSignaturesCount(_: TransactionLike): Promise; /** * Check if related multisig inputs in the transaction need more signatures. * * @remarks * Returns `false` when the transaction has no inputs locked by any multisig address * supported by this signer. * A `false` result therefore means either the related multisig inputs are already fulfilled, * or the transaction is unrelated to all multisig addresses supported by this signer. * * @param txLike - The transaction to check. * @returns A promise that resolves to `true` when related multisig inputs still need signatures, and `false` otherwise. */ abstract needMoreSignatures(_: TransactionLike): Promise; /** * Aggregate transactions. * @param _ - The transactions to aggregate. * @returns The aggregated transaction. */ abstract aggregateTransactions(_: TransactionLike[]): Promise; /** * Send a transaction. * * @remarks * This method rejects the transaction only when related multisig inputs still need signatures. * It does not verify that the transaction actually contains inputs locked by any multisig * address supported by this signer, so transactions unrelated to those multisig addresses * are not rejected by this check. * * @param tx - The transaction to send. * @returns The transaction hash. */ sendTransaction(tx: TransactionLike): Promise; } /** * Thrown when a multisig transaction is sent before enough signatures are collected. * * @public */ declare class SignerMultisigNotEnoughSignaturesError extends Error { readonly signaturesCount: number; readonly threshold: number; constructor(signaturesCount: number, threshold: number); } /** * A class representing information about a signer, including its type and the signer instance. * @public */ declare class SignerInfo { name: string; signer: Signer; constructor(name: string, signer: Signer); } /** * Represents a wallet with a name, icon, and an array of signer information. * @public */ type Wallet = { name: string; icon: string; }; /** * An abstract class extending the Signer class for Bitcoin-like signing operations. * This class provides methods to get Bitcoin account, public key, and internal address, * as well as signing transactions. * @public */ declare abstract class SignerBtc extends Signer { get type(): SignerType; get signType(): SignerSignType; /** * Sign and broadcast a PSBT. * * @param psbtHex - The hex string of PSBT to sign and broadcast. * @param options - Options for signing the PSBT. * @returns A promise that resolves to the transaction ID as a Hex string. */ signAndBroadcastPsbt(psbtHex: HexLike, options?: SignPsbtOptionsLike): Promise; /** * Gets the Bitcoin account associated with the signer. * * @returns A promise that resolves to a string representing the Bitcoin account. */ abstract getBtcAccount(): Promise; /** * Gets the Bitcoin public key associated with the signer. * * @returns A promise that resolves to a HexLike value representing the Bitcoin public key. */ abstract getBtcPublicKey(): Promise; /** * Gets the internal address, which is the Bitcoin account in this case. * * @returns A promise that resolves to a string representing the internal address. */ getInternalAddress(): Promise; /** * Gets the identity, which is the Bitcoin public key in this case. * * @returns A promise that resolves to a string representing the identity */ getIdentity(): Promise; /** * Gets an array of Address objects representing the known script addresses for the signer. * * @returns A promise that resolves to an array of Address objects. */ getAddressObjs(): Promise; /** * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses. * * @param txLike - The transaction to prepare, represented as a TransactionLike object. * @returns A promise that resolves to the prepared Transaction object. */ prepareTransaction(txLike: TransactionLike): Promise; /** * Signs a transaction without modifying it. * * @param txLike - The transaction to sign, represented as a TransactionLike object. * @returns A promise that resolves to a signed Transaction object. */ signOnlyTransaction(txLike: TransactionLike): Promise; /** * Signs a Partially Signed Bitcoin Transaction (PSBT). * * @param psbtHex - The hex string of PSBT to sign. * @param options - Options for signing the PSBT * @returns A promise that resolves to the signed PSBT as a Hex string. */ abstract signPsbt(psbtHex: HexLike, options?: SignPsbtOptionsLike): Promise; /** * Broadcasts a PSBT to the Bitcoin network. * * @param psbtHex - The hex string of the PSBT to broadcast. * @param options - Options for broadcasting the PSBT. * @returns A promise that resolves to the transaction ID as a Hex string. */ abstract broadcastPsbt(psbtHex: HexLike, options?: SignPsbtOptionsLike): Promise; } /** * A class extending SignerBtc that provides read-only access to a Bitcoin public key and account. * This class does not support signing operations. * @public */ declare class SignerBtcPublicKeyReadonly extends SignerBtc { private readonly account; private readonly publicKey; /** * Creates an instance of SignerBtcPublicKeyReadonly. * * @param client - The client instance used for communication. * @param account - The Bitcoin account associated with the signer. * @param publicKey - The public key associated with the signer. */ constructor(client: Client, account: string, publicKey: HexLike); /** * Connects to the client. This implementation does nothing as the class is read-only. * * @returns A promise that resolves when the connection is complete. */ connect(): Promise; /** * Check if the signer is connected. * * @returns A promise that resolves the connection status. */ isConnected(): Promise; /** * Gets the Bitcoin account associated with the signer. * * @returns A promise that resolves to a string representing the Bitcoin account. * * @example * ```typescript * const account = await signer.getBtcAccount(); // Outputs the Bitcoin account * ``` */ getBtcAccount(): Promise; /** * Gets the Bitcoin public key associated with the signer. * * @returns A promise that resolves to a Hex string representing the Bitcoin public key. * * @example * ```typescript * const publicKey = await signer.getBtcPublicKey(); // Outputs the Bitcoin public key * ``` */ getBtcPublicKey(): Promise; signPsbt(_psbtHex: HexLike, _options?: SignPsbtOptionsLike): Promise; broadcastPsbt(_psbtHex: HexLike, _options?: SignPsbtOptionsLike): Promise; } /** * Encodes a number into a variable-length byte array according to the Bitcoin protocol. * This format is used for encoding lengths of data, such as script lengths. * * @param len - The number to encode. Can be a NumLike. * @returns The encoded length as a Bytes. * @public */ declare function btcVarLengthBytesFrom(len: NumLike): Bytes$1; /** * Computes the message hash for Bitcoin ECDSA signatures. * This function follows the Bitcoin message signing standard, which involves * prefixing the message with a magic string and its length, then double SHA256 hashing the result. * * @param message - The message to be hashed. Can be a string or BytesLike. * @param messagePrefix - Optional. A custom prefix to use instead of the default "\u0018Bitcoin Signed Message:\n". * @returns The Bitcoin hash of the prefixed message as Bytes. * @public */ declare function messageHashBtcEcdsa(message: string | BytesLike, messagePrefix?: string | BytesLike): Bytes$1; /** * @public */ declare function btcEcdsaPublicKeyHash(publicKey: BytesLike): Bytes$1; /** * @public */ declare function btcP2pkhAddressFromPublicKey(publicKey: BytesLike, network: number): string; /** * @public */ declare function btcPublicKeyFromP2pkhAddress(address: string): Hex; /** * @public */ declare function verifyMessageBtcEcdsa(message: string | BytesLike, signature: string, publicKey: string): boolean; declare const SECP256K1_SIGNATURE_LENGTH = 65; /** * Sign a message using Secp256k1. * * @param message - The message to sign. * @param privateKey - The private key. * @returns The signature. * @public */ declare function signMessageSecp256k1(message: BytesLike, privateKey: BytesLike): Hex; /** * Verify a message using Secp256k1. * * @param message - The message to verify. * @param signature - The signature. * @param publicKey - The public key. * @returns True if the signature is valid, false otherwise. * @public */ declare function verifyMessageSecp256k1(message: BytesLike, signature: BytesLike, publicKey: BytesLike): boolean; /** * Recover the public key from a Secp256k1 signature. * * @param message - The message. * @param signature - The signature. * @returns The recovered public key. * @public */ declare function recoverMessageSecp256k1(message: BytesLike, signature: BytesLike): Hex; /** * @public */ declare function messageHashCkbSecp256k1(message: string | BytesLike): Hex; /** * @public */ declare function verifyMessageCkbSecp256k1(message: string | BytesLike, signature: string, publicKey: string): boolean; /** * A signer for the well-known always-success lock script. * * The always-success script does not require a signature, so signing a * transaction only needs to add its cell dependency. * * @public */ declare class SignerCkbAlwaysSuccess extends Signer { get type(): SignerType; get signType(): SignerSignType; /** * Creates an instance of SignerCkbAlwaysSuccess. * * @param client - The client instance used for communication and resolving * the always-success deployment. */ constructor(client: Client); connect(): Promise; isConnected(): Promise; getInternalAddress(): Promise; /** * Gets the address of the always-success lock script. */ getAddressObjs(): Promise; /** * Adds the always-success cell dependency to a transaction. */ prepareTransaction(txLike: TransactionLike): Promise; /** * The always-success script requires no signature. */ signOnlyTransaction(txLike: TransactionLike): Promise; } /** * @public */ declare class SignerCkbPublicKey extends Signer { get type(): SignerType; get signType(): SignerSignType; readonly publicKey: Hex; constructor(client: Client, publicKey: HexLike); connect(): Promise; isConnected(): Promise; getInternalAddress(): Promise; getIdentity(): Promise; getAddressObjSecp256k1(): Promise
; getRecommendedAddressObj(_preference?: unknown): Promise
; getAddressObjs(): Promise; getRelatedScripts(txLike: TransactionLike): Promise<{ script: Script; cellDeps: CellDepInfo[]; }[]>; prepareTransaction(txLike: TransactionLike): Promise; } /** * @public */ declare class SignerCkbPrivateKey extends SignerCkbPublicKey { readonly privateKey: Hex; constructor(client: Client, privateKey: HexLike); _signMessage(message: HexLike): Promise; signMessageRaw(message: string | BytesLike): Promise; signOnlyTransaction(txLike: TransactionLike): Promise; } /** * A read-only signer for a CKB script. It can be used to get addresses, * but not to sign transactions. This is useful when you want to watch an address * without having the private key. * * @public */ declare class SignerCkbScriptReadonly extends Signer { /** * The type of the signer. */ get type(): SignerType; /** * The sign type of the signer. * As this is a read-only signer, the sign type is {@link SignerSignType.Unknown}. */ get signType(): SignerSignType; /** * The scripts associated with the signer. */ readonly scripts: Script[]; /** * Creates an instance of SignerCkbScriptReadonly. * * @param client - The client instance used for communication. * @param scripts - The scripts associated with the signer. Can be a single script, an array of scripts, or multiple script arguments. */ constructor(client: Client, ...scripts: (ScriptLike | ScriptLike[])[]); /** * Connects to the client. This implementation does nothing as the class is read-only. * * @returns A promise that resolves when the connection is complete. */ connect(): Promise; /** * Check if the signer is connected. * * @returns A promise that resolves the connection status. */ isConnected(): Promise; /** * Gets the internal address for the script. * * @returns A promise that resolves to a string representing the internal address. * * @example * ```typescript * const internalAddress = await signer.getInternalAddress(); // Outputs the internal address * ``` */ getInternalAddress(): Promise; /** * Gets an array of Address objects representing the script address. * * @returns A promise that resolves to an array of Address objects. * * @example * ```typescript * const addressObjs = await signer.getAddressObjs(); // Outputs the array of Address objects * ``` */ getAddressObjs(): Promise; } type MultisigCkbWitnessLike = ({ publicKeyHashes: HexLike[]; publicKeys?: undefined | null; } | { publicKeyHashes?: undefined | null; publicKeys: HexLike[]; }) & { threshold: NumLike; mustMatch?: NumLike | null; signatures?: HexLike[] | null; }; declare const MultisigCkbWitness_base: (abstract new () => { toBytes(): Bytes$1; clone(): MultisigCkbWitness; eq(other: MultisigCkbWitnessLike): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: MultisigCkbWitnessLike): Bytes$1; decode(_: BytesLike, _context?: any): MultisigCkbWitness; fromBytes(_bytes: BytesLike, _context?: any): MultisigCkbWitness; from(_: MultisigCkbWitnessLike): MultisigCkbWitness; Base(): (abstract new () => { toBytes(): Bytes$1; clone(): SubType; eq(other: SubTypeLike): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike): Bytes$1; decode(_: BytesLike, _context?: Context): SubType; fromBytes(_bytes: BytesLike, _context?: Context): SubType; from(_: SubTypeLike): SubType; Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike_1, SubType_1 = SubTypeLike_1>(): (abstract new (inner: DecodedType) => { readonly inner: DecodedType; match(handlers: UnionMatchHandlers & { _?: undefined | null; }): Result; match(handlers: Partial> & { _: (inner: DecodedType) => Result; }): Result; toBytes(): Bytes$1; clone(): SubType_1; eq(other: SubTypeLike_1): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike_1): Bytes$1; decode(_: BytesLike, _context?: ContextType | undefined): SubType_1; fromBytes(_bytes: BytesLike, _context?: ContextType | undefined): SubType_1; from(_: SubTypeLike_1): SubType_1; Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike_1, SubType_1 = SubTypeLike_1>(): /*elided*/ any; }; }; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): (abstract new (inner: DecodedType) => { readonly inner: DecodedType; match(handlers: UnionMatchHandlers & { _?: undefined | null; }): Result; match(handlers: Partial> & { _: (inner: DecodedType) => Result; }): Result; toBytes(): Bytes$1; clone(): SubType; eq(other: SubTypeLike): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike): Bytes$1; decode(_: BytesLike, _context?: ContextType | undefined): SubType; fromBytes(_bytes: BytesLike, _context?: ContextType | undefined): SubType; from(_: SubTypeLike): SubType; Base(): (abstract new () => { toBytes(): Bytes$1; clone(): SubType_1; eq(other: SubTypeLike_1): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike_1): Bytes$1; decode(_: BytesLike, _context?: Context): SubType_1; fromBytes(_bytes: BytesLike, _context?: Context): SubType_1; from(_: SubTypeLike_1): SubType_1; Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): /*elided*/ any; }; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): /*elided*/ any; }; }; /** * A class representing multisig information, holding information ingredients and containing utilities. * @public */ declare class MultisigCkbWitness extends MultisigCkbWitness_base { publicKeyHashes: Hex[]; threshold: number; mustMatch: number; signatures: Hex[]; /** * @param publicKeyHashes - The public key hashes. * @param threshold - The threshold. * @param mustMatch - The number of signatures that must match. * @param signatures - The signatures. */ constructor(publicKeyHashes: Hex[], threshold: number, mustMatch: number, signatures: Hex[]); /** * Create a MultisigCkbWitness from a MultisigCkbWitnessLike. * * @param witness - The witness like object. * @returns The MultisigCkbWitness. */ static from(witness: MultisigCkbWitnessLike): MultisigCkbWitness; /** * Get the threshold of flexible signatures. */ get flexibleThreshold(): number; /** * Get the script args of the multisig script. * * @param since - The since value. * @returns The script args. */ scriptArgs(since?: SinceLike | null): Bytes$1; /** * Check if the multisig info is equal to another. * * @param otherLike - The other multisig info. * @returns True if the multisig info is equal, false otherwise. */ eqInfo(otherLike: MultisigCkbWitnessLike): boolean; /** * Generate valid public key hashes and their signatures from the witness. * This method filters out invalid signatures, duplicate signatures, and signatures not in the multisig script. * * @param message - The message signed. * @returns A generator of public key hashes, signatures, and whether the signature is required. */ generatePublicKeyHashesFromSignatures(message: BytesLike): Generator<{ pubkeyHash: Hex; signature: Hex; isRequired: boolean; }>; /** * Calculate the number of matched signatures in the witness. * * @param message - The message signed. * @returns The number of required and flexible signatures. */ calcMatchedSignaturesCount(message: BytesLike): { required: number; flexible: number; }; } /** * A class extending Signer that provides access to a CKB multisig script. * This class does not support signing operations. * @public */ declare class SignerMultisigCkbReadonly extends SignerMultisig { static EmptySignature: `0x${string}`; get type(): SignerType; get signType(): SignerSignType; readonly multisigInfo: MultisigCkbWitness; readonly since?: Since; readonly scriptInfos: Promise<{ script: Script; cellDeps: CellDepInfo[]; }[]>; /** * Creates an instance of SignerMultisigCkbReadonly. * * @param client - The client instance. * @param multisigInfoLike - The multisig information. * @param options - The options. */ constructor(client: Client, multisigInfoLike: MultisigCkbWitnessLike, options?: { since?: SinceLike | null; scriptInfos?: (KnownScript | ScriptInfoLike)[] | null; } | null); /** * Get the number of members in the multisig script. * * @returns The number of members. */ getMemberCount(): Promise; /** * Get the threshold of the multisig script. * * @returns The threshold. */ getMemberThreshold(): Promise; /** * Get the count of required member of the multisig script. * * @returns The must match count. */ getMemberRequiredCount(): Promise; connect(): Promise; isConnected(): Promise; getInternalAddress(): Promise; getAddressObjs(): Promise; /** * Decode the witness args at a specific index. * * @param txLike - The transaction. * @param index - The index of the witness args. * @returns The decoded MultisigCkbWitness. */ decodeWitnessArgsAt(txLike: TransactionLike, index: number): MultisigCkbWitness | undefined; /** * Decode the witness args. * * @param witnessLike - The witness args like object. * @returns The decoded MultisigCkbWitness. */ decodeWitnessArgs(witnessLike?: WitnessArgsLike | null): MultisigCkbWitness | undefined; /** * Prepare the witness args at a specific index. * * @param txLike - The transaction. * @param index - The index of the witness args. * @param transformer - The transformer function. * @returns The prepared transaction. */ prepareWitnessArgsAt(txLike: TransactionLike, index: number, transformer?: ((witness: MultisigCkbWitness, witnessArgs: WitnessArgs) => MultisigCkbWitnessLike | undefined | null | void | Promise) | null): Promise; /** * Prepare multisig witness, if the existence of multisig witness is detected, nothing happens * * @param txLike - The transaction to prepare. * @param scriptLike - The script to prepare. * @returns A promise that resolves to the prepared transaction */ prepareTransactionOneScript(txLike: TransactionLike, scriptLike: ScriptLike, cellDeps: CellDepInfoLike[]): Promise; /** * Prepare transaction for multisig witness and adding related cell deps * * @param txLike - The transaction to prepare. * @returns A promise that resolves to the prepared transaction */ prepareTransaction(txLike: TransactionLike): Promise; /** * Get the number of valid signatures for matching multisig inputs in the transaction. * * @remarks * Returns `undefined` when the transaction has no inputs locked by any multisig address * supported by this signer. This method only counts signatures for matching multisig inputs * and does not imply that the transaction should be signed by this multisig. * * @param txLike - The transaction. * @returns The matched multisig signature count, or `undefined` when the transaction is unrelated to any multisig address supported by this signer. */ getSignaturesCount(txLike: TransactionLike): Promise; /** * Check if related multisig inputs in the transaction need more signatures. * * @remarks * Returns `false` when the transaction has no inputs locked by any multisig address * supported by this signer. * A `false` result therefore means either the related multisig inputs are already fulfilled, * or the transaction is unrelated to all multisig addresses supported by this signer. * * @param txLike - The transaction to check. * @returns A promise that resolves to `true` when related multisig inputs still need signatures, and `false` otherwise. */ needMoreSignatures(txLike: TransactionLike): Promise; /** * Get the sign info for a script. * * @param txLike - The transaction. * @param script - The script. * @returns The sign info. */ getSignInfo(txLike: TransactionLike, script: ScriptLike): Promise<{ message: Hex; position: number; } | undefined>; /** * Aggregate transactions. * * @param txs - The transactions to aggregate. * @returns The aggregated transaction. */ aggregateTransactions(txs: TransactionLike[]): Promise; } /** * A class extending Signer that provides access to a CKB multisig script and supports signing operations. * @public */ declare class SignerMultisigCkbPrivateKey extends SignerMultisigCkbReadonly { private readonly privateKey; private readonly signer; /** * Creates an instance of SignerMultisigCkbPrivateKey. * * @param client - The client instance. * @param privateKey - The private key. * @param multisigInfo - The multisig information. * @param options - The options. */ constructor(client: Client, privateKey: HexLike, multisigInfo: MultisigCkbWitnessLike, options?: { since?: SinceLike | null; scriptInfos?: (KnownScript | ScriptInfoLike)[] | null; } | null); /** * Sign a transaction only (without preparing). * * @param txLike - The transaction to sign. * @returns The signed transaction. */ signOnlyTransaction(txLike: TransactionLike): Promise; } /** * @public */ declare function verifyMessageJoyId(message: string | BytesLike, signature: string, identity: string): Promise; /** * An abstract class extending the Signer class for Dogecoin-like signing operations. * This class provides methods to get Doge account, public key, and internal address, * as well as signing transactions. * @public */ declare abstract class SignerDoge extends Signer { get type(): SignerType; get signType(): SignerSignType; /** * Gets the Doge address associated with the signer. * * @returns A promise that resolves to a string representing the Doge account. */ abstract getDogeAddress(): Promise; /** * Gets the internal address, which is the Doge account in this case. * * @returns A promise that resolves to a string representing the internal address. */ getInternalAddress(): Promise; /** * Gets the identity, which is the Doge address in this case. * * @returns A promise that resolves to a string representing the identity */ getIdentity(): Promise; /** * Gets an array of Address objects representing the known script addresses for the signer. * * @returns A promise that resolves to an array of Address objects. */ getAddressObjs(): Promise; /** * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses. * * @param txLike - The transaction to prepare, represented as a TransactionLike object. * @returns A promise that resolves to the prepared Transaction object. */ prepareTransaction(txLike: TransactionLike): Promise; /** * Signs a transaction without modifying it. * * @param txLike - The transaction to sign, represented as a TransactionLike object. * @returns A promise that resolves to a signed Transaction object. */ signOnlyTransaction(txLike: TransactionLike): Promise; } /** * A class extending SignerDoge that provides read-only access to a Doge address. * This class does not support signing operations. * @public */ declare class SignerDogeAddressReadonly extends SignerDoge { private readonly address; /** * Creates an instance of SignerDogeAddressReadonly. * * @param client - The client instance used for communication. * @param address - The Doge address with the signer. */ constructor(client: Client, address: string); /** * Connects to the client. This implementation does nothing as the class is read-only. * * @returns A promise that resolves when the connection is complete. */ connect(): Promise; /** * Check if the signer is connected. * * @returns A promise that resolves the connection status. */ isConnected(): Promise; /** * Gets the Doge address associated with the signer. * * @returns A promise that resolves to a string representing the Doge address. * * @example * ```typescript * const account = await signer.getDogeAddress(); // Outputs the Doge address * ``` */ getDogeAddress(): Promise; } /** * A class extending SignerDoge that provides access to a Doge address. * @public */ declare class SignerDogePrivateKey extends SignerDoge { readonly dogeNetwork: number; private readonly privateKey; /** * Creates an instance of SignerDogePrivateKey * * @param client - The client instance used for communication. * @param privateKey - The Doge private key with the signer. */ constructor(client: Client, privateKey: BytesLike, dogeNetwork?: number); /** * Connects to the client. This implementation does nothing as the class is always connected. * * @returns A promise that resolves when the connection is complete. */ connect(): Promise; /** * Check if the signer is connected. * * @returns A promise that resolves the connection status. */ isConnected(): Promise; getDogePublicKey(): Promise; /** * Gets the Doge address associated with the signer. * * @returns A promise that resolves to a string representing the Doge address. * * @example * ```typescript * const account = await signer.getDogeAddress(); // Outputs the Doge address * ``` */ getDogeAddress(): Promise; /** * Signs a message and returns signature only. * * @param msg - The message to sign, as a string or BytesLike object. * @returns A promise that resolves to the signature as a string. * @throws Will throw an error if not implemented. */ signMessageRaw(msg: string | BytesLike): Promise; } /** * Computes the message hash for Dogecoin ECDSA signatures. * This function follows the Dogecoin message signing standard, which involves * prefixing the message with a magic string and its length, then double SHA256 hashing the result. * * @param message - The message to be hashed. Can be a string or BytesLike. * @param messagePrefix - Optional. A custom prefix to use instead of the default "\x19Dogecoin Signed Message:\n". * @returns The Dogecoin hash of the prefixed message as Bytes. * @public */ declare function messageHashDogeEcdsa(message: string | BytesLike, messagePrefix?: string | BytesLike): Bytes$1; /** * @public */ declare function verifyMessageDogeEcdsa(message: string | BytesLike, signature: string, address: string): boolean; /** * @public */ declare abstract class SignerDummy extends Signer { readonly type: SignerType; get signType(): SignerSignType; constructor(client: Client, type: SignerType); isConnected(): Promise; getInternalAddress(): Promise; getAddressObjs(): Promise; } /** * @public */ declare class SignerAlwaysError extends SignerDummy { private readonly message; constructor(client: Client, type: SignerType, message: string); connect(): Promise; } /** * @public */ declare class SignerOpenLink extends SignerDummy { private readonly link; constructor(client: Client, type: SignerType, link: string); connect(): Promise; } /** * An abstract class extending Signer for Ethereum Virtual Machine (EVM) based signing operations. * This class provides methods to get EVM account, internal address, and signing transactions. * @public */ declare abstract class SignerEvm extends Signer { get type(): SignerType; get signType(): SignerSignType; /** * Gets the EVM account associated with the signer. * * @returns A promise that resolves to a string representing the EVM account. */ abstract getEvmAccount(): Promise; /** * Gets the internal address, which is the EVM account in this case. * * @returns A promise that resolves to a string representing the internal address. */ getInternalAddress(): Promise; /** * Gets an array of Address objects representing the known script addresses for the signer. * * @returns A promise that resolves to an array of Address objects. */ getAddressObjs(): Promise; _getOmniLockAddresses(account: HexLike): Promise; _getPWLockAddresses(account: HexLike): Promise; _getOmniLockEvmAddressObj(account: HexLike): Promise
; _getOmniLockOldEvmAddressObj(account: HexLike): Promise
; _getPWLockEvmAddressObj(account: HexLike): Promise
; /** * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses. * * @param txLike - The transaction to prepare, represented as a TransactionLike object. * @returns A promise that resolves to the prepared Transaction object. */ prepareTransaction(txLike: TransactionLike): Promise; /** * Signs a transaction without modifying it. * * @param txLike - The transaction to sign, represented as a TransactionLike object. * @returns A promise that resolves to a signed Transaction object. */ signOnlyTransaction(txLike: TransactionLike): Promise; _signOmniLockScriptForTransaction(tx: Transaction, script: Script, messageTransformer: (hash: string) => BytesLike): Promise; _signPWLockScriptForTransaction(tx: Transaction, script: Script, messageTransformer: (hash: string) => BytesLike): Promise; _signPersonalEvmForTransaction(tx: Transaction, script: Script, messageTransformer: (hash: string) => BytesLike, hasher?: Hasher): Promise<{ signature: Bytes$1; position: number; } | undefined>; } /** * A class extending SignerEvm that provides read-only access to an EVM address. * This class does not support signing operations. * @public */ declare class SignerEvmAddressReadonly extends SignerEvm { private readonly address; /** * Creates an instance of SignerEvmAddressReadonly. * * @param client - The client instance used for communication. * @param address - The EVM address associated with the signer. */ constructor(client: Client, address: HexLike); /** * Connects to the client. This implementation does nothing as the class is read-only. * * @returns A promise that resolves when the connection is complete. * * @example * ```typescript * await signer.connect(); * ``` */ connect(): Promise; /** * Check if the signer is connected. * * @returns A promise that resolves the connection status. */ isConnected(): Promise; /** * Gets the EVM account associated with the signer. * * @returns A promise that resolves to a string representing the EVM account. * * @example * ```typescript * const account = await signer.getEvmAccount(); // Outputs the EVM account * ``` */ getEvmAccount(): Promise; } /** * @public */ declare function verifyMessageEvmPersonal(message: string | BytesLike, signature: string, address: string): boolean; type SignerJsonRpcInfo = { sessionId: string; type: SignerType; signType: SignerSignType; name?: string; icon?: string; }; type SignerJsonRpcInfoPayload = { session_id: string; type: SignerType; sign_type: SignerSignType; name?: string; icon?: string; }; type SignerJsonRpcMessageToSign = { type: "string"; value: string; } | { type: "bytes"; value: Hex; }; declare class SignerJsonRpcTransformers { static infoFrom(info: SignerJsonRpcInfo): SignerJsonRpcInfoPayload; static infoTo(info: SignerJsonRpcInfoPayload): SignerJsonRpcInfo; static messageFrom(message: string | BytesLike): SignerJsonRpcMessageToSign; static messageTo(message: unknown): string | Uint8Array; } type SignerJsonRpcConfirmation = { method: "connect"; networkId: string; } | { method: "sign_message"; message: SignerJsonRpcMessageToSign; } | { method: "sign_transaction"; transaction: Transaction; }; declare enum SignerJsonRpcErrorCode { MethodNotFound = -32601, InvalidParams = -32602, ServerError = -32000, InvalidState = -32001, NetworkMismatch = -32002, UserRejected = -32003, InvalidSession = -32004, DuplicateRequestId = -32005 } type SignerJsonRpcProviderSessionOptions = { /** Aborts when the provider session is disposed. */ signal?: AbortSignal; }; type SignerJsonRpcResultRecord = { status: "not_found"; } | { status: "pending"; } | { status: "completed"; result: unknown; }; type SignerJsonRpcProviderSessionConfig = { getSigner: () => Signer | undefined; getSignerMetadata?: () => Pick; /** Connects the requested network and returns its connected Signer. */ connect: (networkId: string, options?: SignerJsonRpcProviderSessionOptions) => Promise; confirmRequest: (request: SignerJsonRpcConfirmation, options?: SignerJsonRpcProviderSessionOptions) => Promise; }; declare class SignerJsonRpcProviderSession { private readonly config; private readonly abortController; private readonly id; private readonly resultRecords; private readonly resultHistory; private readonly handlers; private info?; private connected; private constructor(); static open(config: SignerJsonRpcProviderSessionConfig): OwnerUnique; get isConnected(): boolean; handle: (payload: JsonRpcPayload) => Promise; private dispose; private requireSession; private requireSigner; private requireConfirmation; private executeRequest; private trimResultHistory; private getResult; } type SignerJsonRpcConfig = Omit[0], "onError"> & { /** Cleans up integration-owned resources before replacement is announced. */ disconnectHandler?: () => PromiseLike | void; }; declare class SignerJsonRpc extends Signer { readonly requestor: RequestorJsonRpc; private info; private readonly disconnectHandler?; private connecting?; private disconnecting?; private scriptsPromise?; private internalAddressPromise?; private identityPromise?; private requestsController; private readonly replacedListeners; private constructor(); /** Creates a Signer that borrows an existing Transport. */ static new(client: Client, config: SignerJsonRpcConfig): Promise; get type(): SignerType; get signType(): SignerSignType; get name(): string | undefined; get icon(): string | undefined; connect(): Promise; disconnect(): Promise; private requestConnect; onReplaced(listener: () => void): () => boolean; replace(): void; isConnected(): Promise; getScripts(): Promise; getAddressObjs(): Promise; getInternalAddress(): Promise; getIdentity(): Promise; signMessageRaw: Signer["signMessageRaw"]; prepareTransaction: Signer["prepareTransaction"]; signOnlyTransaction: Signer["signOnlyTransaction"]; buildSender(rpcMethod: Parameters[0], inTransformers?: Parameters[2], outTransformer?: Parameters[3]): (...request: unknown[]) => Promise; private clearReadCache; private request; private recoverResult; } /** * @public */ interface NostrEvent { id?: string; pubkey?: string; sig?: string; created_at: number; kind: number; tags: string[][]; content: string; } /** * @public */ declare abstract class SignerNostr extends Signer { static CKB_SIG_HASH_ALL_TAG: string; static CKB_UNLOCK_EVENT_KIND: number; static CKB_UNLOCK_EVENT_CONTENT: string; get type(): SignerType; get signType(): SignerSignType; /** * Gets the Nostr public key associated with the signer. * * @returns A promise that resolves to a string representing the Nostr public key. */ abstract getNostrPublicKey(): Promise; /** * Sign a nostr event. * * @returns A promise that resolves to the signed event. */ signNostrEvent(_event: NostrEvent): Promise>; /** * Sign a message. * * @returns A promise that resolves to the signature. */ signMessageRaw(message: string | BytesLike): Promise; /** * Gets the internal address, which is the EVM account in this case. * * @returns A promise that resolves to a string representing the internal address. */ getInternalAddress(): Promise; /** * Gets an array of Address objects representing the known script addresses for the signer. * * @returns A promise that resolves to an array of Address objects. */ getAddressObjs(): Promise; /** * prepare a transaction before signing. * * @param txLike - The transaction to prepare, represented as a TransactionLike object. * @returns A promise that resolves to the prepared Transaction object. */ prepareTransaction(txLike: TransactionLike): Promise; /** * Signs a transaction without modifying it. * * @param txLike - The transaction to sign, represented as a TransactionLike object. * @returns A promise that resolves to a signed Transaction object. */ signOnlyTransaction(txLike: TransactionLike): Promise; } /** * Signer from Nostr public key * Support npub and hex format */ declare class SignerNostrPublicKeyReadonly extends SignerNostr { readonly publicKey: Hex; constructor(client: Client, publicKey: HexLike); connect(): Promise; isConnected(): Promise; getNostrPublicKey(): Promise; } /** * Signer from Nostr private key * Support nsec and hex format */ declare class SignerNostrPrivateKey extends SignerNostrPublicKeyReadonly { private readonly privateKey; constructor(client: Client, privateKeyLike: BytesLike); signNostrEvent(event: NostrEvent): Promise>; } /** * @public */ declare function buildNostrEventFromMessage(message: string | BytesLike): NostrEvent; declare function nostrEventHash(event: NostrEvent): Bytes$1; declare function verifyMessageNostrEvent(message: string | BytesLike, signature: string, address: string): boolean; declare namespace barrel_d_exports { export { AbstractConstructor, Address, AddressLike, AddressResolver, Bytes$1 as Bytes, BytesLike, Cell, CellAny, CellAnyLike, CellDep, CellDepInfo, CellDepInfoLike, CellDepLike, CellDepVec, CellInput, CellInputLike, CellInputVec, CellLike, CellOutput, CellOutputLike, CellOutputVec, ChildContext, Client, ClientBlock, ClientBlockHeader, ClientBlockHeaderLike, ClientBlockLike, ClientBlockUncle, ClientBlockUncleLike, ClientCache, ClientCacheMemory, ClientConfig, ClientFindCellsResponse, ClientFindTransactionsGroupedResponse, ClientFindTransactionsResponse, ClientIndexerSearchKey, ClientIndexerSearchKeyFilter, ClientIndexerSearchKeyFilterLike, ClientIndexerSearchKeyLike, ClientIndexerSearchKeyTransaction, ClientIndexerSearchKeyTransactionLike, ClientJsonRpc, ClientJsonRpcConfig, ClientPublicMainnet, ClientPublicTestnet, ClientTransactionResponse, ClientTransactionResponseLike, Codec, CodecBool, CodecByte, CodecByte16, CodecByte32, CodecByte4, CodecByte8, CodecBytes, CodecLike, CodecRaw, CodecUint128, CodecUint128BE, CodecUint128LE, CodecUint16, CodecUint16BE, CodecUint16LE, CodecUint256, CodecUint256BE, CodecUint256LE, CodecUint32, CodecUint32BE, CodecUint32LE, CodecUint512, CodecUint512BE, CodecUint512LE, CodecUint64, CodecUint64BE, CodecUint64LE, CodecUint8, Constructor, ContextType, DecodedType, DepType, DepTypeCodec, DepTypeLike, EncodableType, Entity, Epoch, EpochLike, ErrorClientBase, ErrorClientBaseLike, ErrorClientDuplicatedTransaction, ErrorClientMaxFeeRateExceeded, ErrorClientRBFRejected, ErrorClientResolveUnknown, ErrorClientVerification, ErrorClientWaitTransactionTimeout, ErrorTransactionInsufficientCapacity, ErrorTransactionInsufficientCoin, FixedPoint, FixedPointLike, HASH_CKB_LENGTH, HASH_CKB_SHORT_LENGTH, HashType, HashTypeCodec, HashTypeLike, Hasher, HasherCkb, HasherKeecak256, Hex, HexLike, InputToSign, InputToSignLike, JsonRpcError, JsonRpcErrorLike, JsonRpcId, JsonRpcPayload, JsonRpcResponse, JsonRpcTransport, JsonRpcTransportFallback, JsonRpcTransportHttp, JsonRpcTransportRequestOptions, JsonRpcTransportWebSocket, KnownScript, LumosTransactionSkeletonType, MultisigCkbWitness, MultisigCkbWitnessLike, NetworkPreference, NostrEvent, Num, NumLike, One, OutPoint, OutPointLike, OutputsValidator, Owner, OwnerAggregated, OwnerMoved, OwnerRefCount, OwnerUnique, Proxy, RawTransaction, RequestorJsonRpc, RequestorJsonRpcConfig, RetryOperationOptions, RetryOptions, RetryResult, SECP256K1_SIGNATURE_LENGTH, Script, ScriptInfo, ScriptInfoLike, ScriptLike, ScriptOpt, ScriptVec, SignPsbtOptions, SignPsbtOptionsLike, Signature, Signer, SignerAlwaysError, SignerBtc, SignerBtcPublicKeyReadonly, SignerCkbAlwaysSuccess, SignerCkbPrivateKey, SignerCkbPublicKey, SignerCkbScriptReadonly, SignerDoge, SignerDogeAddressReadonly, SignerDogePrivateKey, SignerDummy, SignerEvm, SignerEvmAddressReadonly, SignerInfo, SignerJsonRpc, SignerJsonRpcConfig, SignerJsonRpcConfirmation, SignerJsonRpcErrorCode, SignerJsonRpcProviderSession, SignerJsonRpcProviderSessionConfig, SignerJsonRpcProviderSessionOptions, SignerJsonRpcResultRecord, SignerMultisig, SignerMultisigCkbPrivateKey, SignerMultisigCkbReadonly, SignerMultisigNotEnoughSignaturesError, SignerNostr, SignerNostrPrivateKey, SignerNostrPublicKeyReadonly, SignerOpenLink, SignerSignType, SignerType, Since, SinceLike, Transaction, TransactionLike, TransactionStatus, Wallet, WitnessArgs, WitnessArgsLike, Zero, abortSignalAny, abortSignalToPromise, apply, btcEcdsaPublicKeyHash, btcP2pkhAddressFromPublicKey, btcPublicKeyFromP2pkhAddress, btcVarLengthBytesFrom, buildNostrEventFromMessage, bytesConcat, bytesConcatTo, bytesEq, bytesFrom, bytesLen, bytesLenUnsafe, bytesTo, calcDaoClaimEpoch, calcDaoProfit, codec$1 as codec, codecPadding, codecUint, codecUintNumber, depTypeFrom, depTypeFromBytes, depTypeToBytes, epochFrom, epochFromHex, epochToHex, fixedPointFrom, fixedPointToString, gcd, hashCkb, hashCkbShort, hashTypeFrom, hashTypeFromBytes, hashTypeId, hashTypeToBytes, hexFrom, isDaoOutputLimitExceeded, isWebview, keystoreDecrypt, keystoreEncrypt, messageHashBtcEcdsa, messageHashCkbSecp256k1, messageHashDogeEcdsa, barrel_d_exports$1 as mol, nostrEventHash, numBeFromBytes, numBeToBytes, numFrom, numFromBytes, numLeFromBytes, numLeToBytes, numMax, numMin, numToBytes, numToHex, recoverMessageSecp256k1, reduceAsync, retry, signMessageSecp256k1, sleep, stringify, udtBalanceFrom, verifyMessageBtcEcdsa, verifyMessageCkbSecp256k1, verifyMessageDogeEcdsa, verifyMessageEvmPersonal, verifyMessageJoyId, verifyMessageNostrEvent, verifyMessageSecp256k1, waitForAvailability }; } declare const DEFAULT_MAX_FEE_RATE: bigint; declare const DEFAULT_MIN_FEE_RATE: bigint; declare function clientSearchKeyRangeFrom([a, b]: [NumLike, NumLike]): [Num, Num]; type ClientCollectableSearchKeyFilterLike = { script?: ScriptLike | null; scriptLenRange?: [NumLike, NumLike] | null; outputData?: HexLike | null; outputDataSearchMode?: "prefix" | "exact" | "partial" | null; outputDataLenRange?: [NumLike, NumLike] | null; outputCapacityRange?: [NumLike, NumLike] | null; }; type ClientCollectableSearchKeyLike = { script: ScriptLike; scriptType: "lock" | "type"; scriptSearchMode: "prefix" | "exact" | "partial"; filter?: ClientCollectableSearchKeyFilterLike | null; withData?: boolean | null; }; /** * @public */ type CellDepInfoLike = { cellDep: CellDepLike; type?: ScriptLike | null; }; /** * @public */ declare class CellDepInfo { cellDep: CellDep; type?: Script | undefined; constructor(cellDep: CellDep, type?: Script | undefined); static from(cellDepInfoLike: CellDepInfoLike): CellDepInfo; } /** * @public */ type ScriptInfoLike = { codeHash: HexLike; hashType: HashTypeLike; cellDeps: CellDepInfoLike[]; }; /** * @public */ declare class ScriptInfo { codeHash: Hex; hashType: HashType; cellDeps: CellDepInfo[]; constructor(codeHash: Hex, hashType: HashType, cellDeps: CellDepInfo[]); static from(scriptInfoLike: ScriptInfoLike): ScriptInfo; } /** * @public */ type OutputsValidator = "passthrough" | "well_known_scripts_only"; /** * @public */ type TransactionStatus = "sent" | "pending" | "proposed" | "committed" | "unknown" | "rejected"; /** * @public */ type ClientTransactionResponseLike = { transaction: TransactionLike; status: TransactionStatus; cycles?: NumLike; blockHash?: HexLike; blockNumber?: NumLike; txIndex?: NumLike; reason?: string; }; /** * @public */ declare class ClientTransactionResponse { transaction: Transaction; status: TransactionStatus; cycles?: Num | undefined; blockHash?: Hex | undefined; blockNumber?: Num | undefined; txIndex?: Num | undefined; reason?: string | undefined; constructor(transaction: Transaction, status: TransactionStatus, cycles?: Num | undefined, blockHash?: Hex | undefined, blockNumber?: Num | undefined, txIndex?: Num | undefined, reason?: string | undefined); static from(responseLike: ClientTransactionResponseLike): ClientTransactionResponse; clone(): ClientTransactionResponse; } /** * @public */ type ClientIndexerSearchKeyFilterLike = ClientCollectableSearchKeyFilterLike & { blockRange?: [NumLike, NumLike] | null; }; /** * @public */ declare class ClientIndexerSearchKeyFilter { script: Script | undefined; scriptLenRange: [Num, Num] | undefined; outputData: Hex | undefined; outputDataSearchMode: "prefix" | "exact" | "partial" | undefined; outputDataLenRange: [Num, Num] | undefined; outputCapacityRange: [Num, Num] | undefined; blockRange: [Num, Num] | undefined; constructor(script: Script | undefined, scriptLenRange: [Num, Num] | undefined, outputData: Hex | undefined, outputDataSearchMode: "prefix" | "exact" | "partial" | undefined, outputDataLenRange: [Num, Num] | undefined, outputCapacityRange: [Num, Num] | undefined, blockRange: [Num, Num] | undefined); static from(filterLike: ClientIndexerSearchKeyFilterLike): ClientIndexerSearchKeyFilter; } /** * @public */ type ClientIndexerSearchKeyLike = ClientCollectableSearchKeyLike & { filter?: ClientIndexerSearchKeyFilterLike | null; }; /** * @public */ declare class ClientIndexerSearchKey { script: Script; scriptType: "lock" | "type"; scriptSearchMode: "prefix" | "exact" | "partial"; filter: ClientIndexerSearchKeyFilter | undefined; withData: boolean | undefined; constructor(script: Script, scriptType: "lock" | "type", scriptSearchMode: "prefix" | "exact" | "partial", filter: ClientIndexerSearchKeyFilter | undefined, withData: boolean | undefined); static from(keyLike: ClientIndexerSearchKeyLike): ClientIndexerSearchKey; } /** * @public */ type ClientFindCellsResponse = { lastCursor: string; cells: Cell[]; }; /** * @public */ type ClientIndexerSearchKeyTransactionLike = Omit & { filter?: ClientIndexerSearchKeyFilterLike | null; groupByTransaction?: boolean | null; }; /** * @public */ declare class ClientIndexerSearchKeyTransaction { script: Script; scriptType: "lock" | "type"; scriptSearchMode: "prefix" | "exact" | "partial"; filter: ClientIndexerSearchKeyFilter | undefined; groupByTransaction: boolean | undefined; constructor(script: Script, scriptType: "lock" | "type", scriptSearchMode: "prefix" | "exact" | "partial", filter: ClientIndexerSearchKeyFilter | undefined, groupByTransaction: boolean | undefined); static from(keyLike: ClientIndexerSearchKeyTransactionLike): ClientIndexerSearchKeyTransaction; } /** * @public */ type ClientFindTransactionsResponse = { lastCursor: string; transactions: { txHash: Hex; blockNumber: Num; txIndex: Num; isInput: boolean; cellIndex: Num; }[]; }; /** * @public */ type ClientFindTransactionsGroupedResponse = { lastCursor: string; transactions: { txHash: Hex; blockNumber: Num; txIndex: Num; cells: { isInput: boolean; cellIndex: Num; }[]; }[]; }; /** * @public */ type ClientBlockHeaderLike = { compactTarget: NumLike; dao: { /** * C_i: the total issuance up to and including block i. */ c: NumLike; /** * AR_i: the current accumulated rate at block i. * AR_j / AR_i reflects the CKByte amount if one deposit 1 CKB to Nervos DAO at block i, and withdraw at block j. */ ar: NumLike; /** * S_i: the total unissued secondary issuance up to and including block i, * including unclaimed Nervos DAO compensation and treasury funds. */ s: NumLike; /** * U_i: the total occupied capacities currently in the blockchain up to and including block i. * Occupied capacity is the sum of capacities used to store all cells. */ u: NumLike; }; epoch: EpochLike; extraHash: HexLike; hash: HexLike; nonce: NumLike; number: NumLike; parentHash: HexLike; proposalsHash: HexLike; timestamp: NumLike; transactionsRoot: HexLike; version: NumLike; }; /** * @public */ declare class ClientBlockHeader { compactTarget: Num; dao: { /** * C_i: the total issuance up to and including block i. */ c: Num; /** * AR_i: the current accumulated rate at block i. * AR_j / AR_i reflects the CKByte amount if one deposit 1 CKB to Nervos DAO at block i, and withdraw at block j. */ ar: Num; /** * S_i: the total unissued secondary issuance up to and including block i, * including unclaimed Nervos DAO compensation and treasury funds. */ s: Num; /** * U_i: the total occupied capacities currently in the blockchain up to and including block i. * Occupied capacity is the sum of capacities used to store all cells. */ u: Num; }; epoch: Epoch; extraHash: Hex; hash: Hex; nonce: Num; number: Num; parentHash: Hex; proposalsHash: Hex; timestamp: Num; transactionsRoot: Hex; version: Num; constructor(compactTarget: Num, dao: { /** * C_i: the total issuance up to and including block i. */ c: Num; /** * AR_i: the current accumulated rate at block i. * AR_j / AR_i reflects the CKByte amount if one deposit 1 CKB to Nervos DAO at block i, and withdraw at block j. */ ar: Num; /** * S_i: the total unissued secondary issuance up to and including block i, * including unclaimed Nervos DAO compensation and treasury funds. */ s: Num; /** * U_i: the total occupied capacities currently in the blockchain up to and including block i. * Occupied capacity is the sum of capacities used to store all cells. */ u: Num; }, epoch: Epoch, extraHash: Hex, hash: Hex, nonce: Num, number: Num, parentHash: Hex, proposalsHash: Hex, timestamp: Num, transactionsRoot: Hex, version: Num); static from(headerLike: ClientBlockHeaderLike): ClientBlockHeader; } /** * @public */ type ClientBlockUncleLike = { header: ClientBlockHeaderLike; proposals: HexLike[]; }; /** * @public */ declare class ClientBlockUncle { header: ClientBlockHeader; proposals: Hex[]; constructor(header: ClientBlockHeader, proposals: Hex[]); static from(uncleLike: ClientBlockUncleLike): ClientBlockUncle; } /** * @public */ type ClientBlockLike = { header: ClientBlockHeaderLike; proposals: HexLike[]; transactions: TransactionLike[]; uncles: ClientBlockUncleLike[]; }; /** * @public */ declare class ClientBlock { header: ClientBlockHeader; proposals: Hex[]; transactions: Transaction[]; uncles: ClientBlockUncle[]; constructor(header: ClientBlockHeader, proposals: Hex[], transactions: Transaction[], uncles: ClientBlockUncle[]); static from(blockLike: ClientBlockLike): ClientBlock; } interface ErrorClientBaseLike { message?: string; code?: number; data: string; } declare class ErrorClientBase extends Error { readonly code?: number; readonly data: string; constructor(origin: ErrorClientBaseLike); } declare class ErrorClientResolveUnknown extends ErrorClientBase { readonly outPoint: OutPoint; constructor(origin: ErrorClientBaseLike, outPointLike: OutPointLike); } declare class ErrorClientVerification extends ErrorClientBase { readonly source: "lock" | "inputType" | "outputType"; readonly errorCode: number; readonly scriptHashType: "data" | "type"; readonly sourceIndex: Num; readonly scriptCodeHash: Hex; constructor(origin: ErrorClientBaseLike, source: "lock" | "inputType" | "outputType", sourceIndex: NumLike, errorCode: number, scriptHashType: "data" | "type", scriptCodeHash: HexLike); } declare class ErrorClientDuplicatedTransaction extends ErrorClientBase { readonly txHash: Hex; constructor(origin: ErrorClientBaseLike, txHash: HexLike); } declare class ErrorClientRBFRejected extends ErrorClientBase { readonly currentFee: Num; readonly leastFee: Num; constructor(origin: ErrorClientBaseLike, currentFee: NumLike, leastFee: NumLike); } declare class ErrorClientWaitTransactionTimeout extends ErrorClientBase { constructor(timeoutLike: NumLike); } declare class ErrorClientMaxFeeRateExceeded extends ErrorClientBase { constructor(limitLike: NumLike, actualLike: NumLike); } /** * EpochLike * * Union type that represents any allowed input shapes that can be converted * into an Epoch instance. * * Accepted shapes: * - Tuple: [integer, numerator, denominator] where each element is NumLike * - Object: { integer, numerator, denominator } where each field is NumLike * - Packed numeric form: Num (bigint) or Hex (RPC-style packed hex) * * Notes: * - When constructing an Epoch from a Num or Hex the packed numeric representation * encodes integer (24 bits), numerator (16 bits) and denominator (16 bits). * - Use Epoch.from() to convert any EpochLike into an Epoch instance. * * @example * // From tuple * Epoch.from([1n, 0n, 1n]); */ type EpochLike = [NumLike, NumLike, NumLike] | { integer: NumLike; numerator: NumLike; denominator: NumLike; } | Num | Hex; declare const Epoch_base: (abstract new () => { toBytes(): Bytes$1; clone(): Epoch; eq(other: EpochLike): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: EpochLike): Bytes$1; decode(_: BytesLike, _context?: any): Epoch; fromBytes(_bytes: BytesLike, _context?: any): Epoch; from(_: EpochLike): Epoch; Base(): (abstract new () => { toBytes(): Bytes$1; clone(): SubType; eq(other: SubTypeLike): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike): Bytes$1; decode(_: BytesLike, _context?: Context): SubType; fromBytes(_bytes: BytesLike, _context?: Context): SubType; from(_: SubTypeLike): SubType; Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike_1, SubType_1 = SubTypeLike_1>(): (abstract new (inner: DecodedType) => { readonly inner: DecodedType; match(handlers: UnionMatchHandlers & { _?: undefined | null; }): Result; match(handlers: Partial> & { _: (inner: DecodedType) => Result; }): Result; toBytes(): Bytes$1; clone(): SubType_1; eq(other: SubTypeLike_1): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike_1): Bytes$1; decode(_: BytesLike, _context?: ContextType | undefined): SubType_1; fromBytes(_bytes: BytesLike, _context?: ContextType | undefined): SubType_1; from(_: SubTypeLike_1): SubType_1; Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike_1, SubType_1 = SubTypeLike_1>(): /*elided*/ any; }; }; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): (abstract new (inner: DecodedType) => { readonly inner: DecodedType; match(handlers: UnionMatchHandlers & { _?: undefined | null; }): Result; match(handlers: Partial> & { _: (inner: DecodedType) => Result; }): Result; toBytes(): Bytes$1; clone(): SubType; eq(other: SubTypeLike): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike): Bytes$1; decode(_: BytesLike, _context?: ContextType | undefined): SubType; fromBytes(_bytes: BytesLike, _context?: ContextType | undefined): SubType; from(_: SubTypeLike): SubType; Base(): (abstract new () => { toBytes(): Bytes$1; clone(): SubType_1; eq(other: SubTypeLike_1): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike_1): Bytes$1; decode(_: BytesLike, _context?: Context): SubType_1; fromBytes(_bytes: BytesLike, _context?: Context): SubType_1; from(_: SubTypeLike_1): SubType_1; Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): /*elided*/ any; }; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): /*elided*/ any; }; }; /** * Epoch * * Represents a blockchain epoch consisting of a whole integer part and an * optional fractional part represented as numerator/denominator. * * Behavior highlights: * - Internally stores values as Num (bigint). * - Provides normalization routines to canonicalize the fractional part: * - normalizeBase(): fixes zero/negative denominators * - normalizeCanonical(): reduces fraction, borrows/carries whole units * - Supports arithmetic (add/sub), comparison and conversion utilities. * * @example * const e = Epoch.from([1n, 1n, 2n]); // 1 + 1/2 * * @remarks * This class is primarily a thin value-object; operations return new Epoch instances. */ declare class Epoch extends Epoch_base { readonly integer: Num; readonly numerator: Num; readonly denominator: Num; /** * Construct a new Epoch instance. * * @param integer - Whole epoch units (Num/bigint) * @param numerator - Fractional numerator (Num). * @param denominator - Fractional denominator (Num). */ constructor(integer: Num, numerator: Num, denominator: Num); /** * Normalize simpler base invariants: * - If denominator === 0, set denominator to 1 and numerator to 0 for arithmetic convenience. * - If denominator is negative flip signs of numerator and denominator to keep denominator positive. * * This is a minimal correction used before arithmetic or canonical normalization. * * @returns New Epoch with denominator corrected (but fraction not reduced). */ normalizeBase(): Epoch; /** * Perform full canonical normalization of the epoch value. * * Steps: * 1. Apply base normalization (normalizeBase). * 2. If numerator is negative, borrow whole denominator(s) from the integer part * so numerator becomes non-negative. This ensures 0 <= numerator < denominator whenever possible. * 3. Reduce numerator/denominator by their greatest common divisor (gcd). * 4. Carry any whole units from the reduced numerator into the integer part. * 5. Ensure numerator is the strict remainder (numerator < denominator). * * @returns Canonicalized Epoch with a non-negative, reduced fractional part and integer adjusted accordingly. */ normalizeCanonical(): Epoch; /** * Backwards-compatible array-style index 0 referencing the whole epoch integer. * * @returns integer portion (Num) * @deprecated Use `.integer` property instead. */ get 0(): Num; /** * Backwards-compatible array-style index 1 referencing the epoch fractional numerator. * * @returns numerator portion (Num) * @deprecated Use `.numerator` property instead. */ get 1(): Num; /** * Backwards-compatible array-style index 2 referencing the epoch fractional denominator. * * @returns denominator portion (Num) * @deprecated Use `.denominator` property instead. */ get 2(): Num; /** * Convert this Epoch into its RPC-style packed numeric representation (Num). * * Packing layout (little-endian style fields): * - integer: lower 24 bits * - numerator: next 16 bits * - denominator: next 16 bits * * Throws if any component is negative since packed representation assumes non-negative components. * * @throws {Error} If integer, numerator or denominator are negative. * @throws {Error} If integer, numerator or denominator overflow the packing limits. * @returns Packed numeric representation (Num) suitable for RPC packing. */ toNum(): Num; /** * Convert epoch to hex string representation of the RPC-style packed numeric form. * * Returns the same representation used by CKB RPC responses where the * packed numeric bytes may be trimmed of leading zeros, see {@link numToHex} * * @returns Hex string corresponding to the packed epoch. */ toPackedHex(): Hex; /** * Construct an Epoch by unpacking a RPC-style packed numeric form. * * @param v - NumLike packed epoch (like Num and Hex) * @returns Epoch whose integer, numerator and denominator are extracted from the packed layout. */ static fromNum(v: NumLike): Epoch; /** * Create an Epoch from an EpochLike value. * * Accepts: * - an Epoch instance (returned as-is) * - an array [integer, numerator, denominator] where each element is NumLike * - an object { integer, numerator, denominator } where each field is NumLike * - a packed numeric-like value handled by fromNum * * All numeric-like inputs are converted with numFrom() to produce internal Num values. * * @param e - Value convertible to Epoch * @returns Epoch instance */ static from(e: EpochLike): Epoch; /** * Return a deep copy of this Epoch. * * @returns New Epoch instance with identical components. */ clone(): Epoch; /** * Return the genesis epoch. * * Note: for historical reasons the genesis epoch is represented with all-zero * fields, no other epoch instance should use a zero denominator. * * @returns Epoch with integer = 0, numerator = 0, denominator = 0. */ static get Genesis(): Epoch; /** * Return an Epoch representing one Nervos DAO cycle (180 epochs exactly). * * @returns Epoch equal to 180 with denominator set to 1 to represent an exact whole unit. */ static get OneNervosDaoCycle(): Epoch; /** * Compare this epoch to another EpochLike. * * The comparison computes scaled integer values so fractions are compared without precision loss: * scaled = (integer * denominator + numerator) * other.denominator * * Special-case: identical object references return equality immediately. * * @param other - Epoch-like value to compare against. * @returns 1 if this > other, 0 if equal, -1 if this < other. * * @example * epochA.compare(epochB); // -1|0|1 */ compare(other: EpochLike): 1 | 0 | -1; /** * Check whether this epoch is less than another EpochLike. * * @param other - EpochLike to compare against. * @returns true if this < other. */ lt(other: EpochLike): boolean; /** * Check whether this epoch is less than or equal to another EpochLike. * * @param other - EpochLike to compare against. * @returns true if this <= other. */ le(other: EpochLike): boolean; /** * Check whether this epoch equals another EpochLike. * * @param other - EpochLike to compare against. * @returns true if equal. */ eq(other: EpochLike): boolean; /** * Check whether this epoch is greater than or equal to another EpochLike. * * @param other - EpochLike to compare against. * @returns true if this >= other. */ ge(other: EpochLike): boolean; /** * Check whether this epoch is greater than another EpochLike. * * @param other - EpochLike to compare against. * @returns true if this > other. */ gt(other: EpochLike): boolean; /** * Add another EpochLike to this epoch and return the normalized result. * * Rules and edge-cases: * - Whole parts are added directly; fractional parts are aligned to a common denominator and added. * - Final result is canonicalized to reduce the fraction and carry any overflow to the integer part. * * @param other - Epoch-like value to add. * @returns Normalized Epoch representing the sum. */ add(other: EpochLike): Epoch; /** * Subtract an EpochLike from this epoch and return the normalized result. * * Implementation notes: * - Delegates to add by negating the other epoch's integer and numerator while preserving denominator. * - normalizeCanonical will handle negative numerators by borrowing from integer as necessary. * * @param other - Epoch-like value to subtract. * @returns Normalized Epoch representing this - other. */ sub(other: EpochLike): Epoch; /** * Convert this epoch to an estimated Unix timestamp in milliseconds using a reference header. * * Note: This is an estimation that assumes a constant epoch duration. * * @param reference - Object providing `epoch` (Epoch) and `timestamp` (Num) fields, such as a ClientBlockHeader. * @param epochInMilliseconds - Duration of a single epoch in milliseconds. Defaults to 4 hours. * @returns Estimated Unix timestamp in milliseconds as bigint. */ toUnix(reference: Pick, epochInMilliseconds?: Num): bigint; } /** * epochFrom * * @deprecated prefer using Epoch.from() directly. * * @param epochLike - Epoch-like value to convert. * @returns Epoch instance corresponding to the input. */ declare function epochFrom(epochLike: EpochLike): Epoch; /** * epochFromHex * * @deprecated use Epoch.fromNum() with numeric input instead. * * @param hex - Hex-like or numeric-like value encoding a packed epoch. * @returns Decoded Epoch instance. */ declare function epochFromHex(hex: HexLike): Epoch; /** * epochToHex * * @deprecated use Epoch.from(epochLike).toPackedHex() instead. * * @param epochLike - Value convertible to an Epoch (object, tuple or Epoch). * @returns Hex string representing the packed epoch encoding. */ declare function epochToHex(epochLike: EpochLike): Hex; /** * @public */ declare enum KnownScript { NervosDao = "NervosDao", Secp256k1Blake160 = "Secp256k1Blake160", Secp256k1Multisig = "Secp256k1Multisig", Secp256k1MultisigV2Beta = "Secp256k1MultisigV2Beta", // Fix rare failing case (https://github.com/nervosnetwork/ckb-system-scripts/pull/98) Secp256k1MultisigV2 = "Secp256k1MultisigV2", // Enhanced since handling (https://github.com/nervosnetwork/ckb-system-scripts/pull/99) AnyoneCanPay = "AnyoneCanPay", TypeId = "TypeId", SUdt = "SUdt", XUdt = "XUdt", JoyId = "JoyId", COTA = "COTA", PWLock = "PWLock", OmniLock = "OmniLock", NostrLock = "NostrLock", UniqueType = "UniqueType", DidCkb = "DidCkb", AlwaysSuccess = "AlwaysSuccess", InputTypeProxyLock = "InputTypeProxyLock", OutputTypeProxyLock = "OutputTypeProxyLock", LockProxyLock = "LockProxyLock", SingleUseLock = "SingleUseLock", TypeBurnLock = "TypeBurnLock", EasyToDiscoverType = "EasyToDiscoverType", TimeLock = "TimeLock" } /** * Resolves address representations that `Address.fromString` cannot parse, * such as human-readable names, to scripts. * * @public */ interface AddressResolver { /** Whether this resolver handles the representation. */ shouldResolve(address: string): boolean; /** The script it points to, or `undefined` if it is not found. */ resolve(address: string, client: Client): Promise; } type ClientConfig = { cache?: ClientCache; scripts?: Partial>; addressResolver?: AddressResolver; }; /** * @public */ declare abstract class Client { cache: ClientCache; private readonly scripts; readonly addressResolver?: AddressResolver; constructor(config?: ClientConfig); /** * The legacy primary URL associated with this Client. * * @deprecated A Client may use multiple endpoints or a Transport without a * URL, so this value does not reliably identify its connection. */ abstract get url(): string; abstract get addressPrefix(): string; /** * Get the deployment info for a well-known CKB script. * Returns the cell deps and type script info needed to use the script. * * @param script - The KnownScript enum value. * @returns Script info including cellDeps and type hash. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * * // Get xUDT script deployment info * const xudtInfo = await client.getKnownScript(ccc.KnownScript.XUdt); * console.log(`xUDT cellDeps:`, xudtInfo.cellDeps); * * // Build an xUDT type script * const xudtType = await ccc.Script.fromKnownScript( * client, * ccc.KnownScript.XUdt, * "0xOWNER_LOCK_HASH...", * ); * ``` */ getKnownScript(script: KnownScript): Promise; abstract getFeeRateStatistics(blockRange?: NumLike): Promise<{ mean: Num; median: Num; }>; /** * Get the recommended transaction fee rate based on recent blocks. * Returns the median fee rate, clamped between min and max fee rates. * * @param blockRange - Number of recent blocks to analyze. * @param options - Optional max fee rate cap. * @returns The recommended fee rate in Shannons per KB. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const feeRate = await client.getFeeRate(); * console.log(`Current fee rate: ${feeRate} Shannons/KB`); * ``` */ getFeeRate(blockRange?: NumLike, options?: { maxFeeRate?: NumLike; }): Promise; /** * Get the latest block number (tip) of the chain. * * @returns The current tip block number. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const tipBlockNumber = await client.getTip(); * console.log(`Current block height: ${tipBlockNumber}`); * ``` */ abstract getTip(): Promise; /** * Get the header of the latest block. * * @param verbosity - Deprecated; this parameter has no effect. * @returns The tip block header. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const header = await client.getTipHeader(); * console.log(`Block #${header.number}, hash: ${header.hash}`); * ``` */ abstract getTipHeader( /** @deprecated This parameter has no effect and will be removed. */ verbosity?: number | null): Promise; abstract getBlockByNumberNoCache(blockNumber: NumLike, /** @deprecated This parameter has no effect and will be removed. */ verbosity?: number | null, /** * @deprecated This parameter has no effect and will be removed. */ withCycles?: boolean | null): Promise; abstract getBlockByHashNoCache(blockHash: HexLike, /** @deprecated This parameter has no effect and will be removed. */ verbosity?: number | null, /** * @deprecated This parameter has no effect and will be removed. */ withCycles?: boolean | null): Promise; abstract getHeaderByNumberNoCache(blockNumber: NumLike, /** @deprecated This parameter has no effect and will be removed. */ verbosity?: number | null): Promise; abstract getHeaderByHashNoCache(blockHash: HexLike, /** @deprecated This parameter has no effect and will be removed. */ verbosity?: number | null): Promise; getBlockByNumber(blockNumber: NumLike, /** @deprecated This parameter has no effect and will be removed. */ verbosity?: number | null, /** * @deprecated This parameter has no effect and will be removed. */ withCycles?: boolean | null): Promise; getBlockByHash(blockHash: HexLike, /** @deprecated This parameter has no effect and will be removed. */ verbosity?: number | null, /** * @deprecated This parameter has no effect and will be removed. */ withCycles?: boolean | null): Promise; getHeaderByNumber(blockNumber: NumLike, /** @deprecated This parameter has no effect and will be removed. */ verbosity?: number | null): Promise; getHeaderByHash(blockHash: HexLike, /** @deprecated This parameter has no effect and will be removed. */ verbosity?: number | null): Promise; abstract estimateCycles(transaction: TransactionLike): Promise; abstract sendTransactionDry(transaction: TransactionLike, validator?: OutputsValidator): Promise; abstract sendTransactionNoCache(transaction: TransactionLike, validator?: OutputsValidator): Promise; abstract getTransactionNoCache(txHash: HexLike): Promise; /** * Get a cell by its out point. * The cell will be cached if it is found. * * @param outPointLike - The out point of the cell to get. * @returns The cell if it exists, otherwise undefined. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const cell = await client.getCell({ * txHash: "0xTX_HASH...", * index: 0, * }); * if (cell) { * console.log(`Capacity: ${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`); * console.log(`Lock: ${cell.cellOutput.lock.codeHash}`); * console.log(`Data: ${cell.outputData}`); * } * ``` */ getCell(outPointLike: OutPointLike): Promise; getCellWithHeader(outPointLike: OutPointLike): Promise<{ cell: Cell; header?: ClientBlockHeader; } | undefined>; abstract getCellLiveNoCache(outPointLike: OutPointLike, withData?: boolean | null, includeTxPool?: boolean | null): Promise; /** * Get a live (unspent) cell by its out point. * Unlike getCell(), this verifies the cell is still live on-chain. * * @param outPointLike - The out point of the cell. * @param withData - Whether to include cell data. * @param includeTxPool - Whether to include cells in the transaction pool. * @returns The live cell, or undefined if spent or not found. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const cell = await client.getCellLive( * { txHash: "0xTX_HASH...", index: 0 }, * true, // include data * true, // include tx pool * ); * if (cell) { * console.log("Cell is still live!"); * } else { * console.log("Cell has been spent or does not exist."); * } * ``` */ getCellLive(outPointLike: OutPointLike, withData?: boolean | null, includeTxPool?: boolean | null): Promise; abstract findCellsPagedNoCache(key: ClientIndexerSearchKeyLike, order?: "asc" | "desc", limit?: NumLike, after?: string): Promise; /** * Find cells with pagination support. * Returns one page of results at a time with a cursor for the next page. * * @param key - The indexer search key. * @param order - Sort order ("asc" or "desc"). * @param limit - Maximum cells per page. * @param after - Cursor from previous page for pagination. * @returns A page of cells with a cursor for the next page. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const { script: lock } = await ccc.Address.fromString("ckt1q...", client); * * // Get first page of cells * const page1 = await client.findCellsPaged({ * script: lock, * scriptType: "lock", * }, "asc", 20); * console.log(`Found ${page1.cells.length} cells`); * * // Get next page * if (page1.cells.length === 20) { * const page2 = await client.findCellsPaged( * { script: lock, scriptType: "lock" }, * "asc", 20, page1.lastCursor, * ); * } * ``` */ findCellsPaged(key: ClientIndexerSearchKeyLike, order?: "asc" | "desc", limit?: NumLike, after?: string): Promise; findCellsOnChain(key: ClientIndexerSearchKeyLike, order?: "asc" | "desc", limit?: number): AsyncGenerator; /** * Find cells by search key designed for collectable cells. * The result also includes cached cells, the order param only works for cells fetched from RPC. * * @param keyLike - The search key. * @returns A async generator for yielding cells. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const { script: lock } = await ccc.Address.fromString("ckt1q...", client); * * // Find all cells owned by a lock script * for await (const cell of client.findCells({ * script: lock, * scriptType: "lock", * scriptSearchMode: "exact", * withData: true, * })) { * console.log(`Cell: ${cell.outPoint.txHash}:${cell.outPoint.index}`); * console.log(`Capacity: ${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`); * } * ``` */ findCells(keyLike: ClientCollectableSearchKeyLike, order?: "asc" | "desc", limit?: number): AsyncGenerator; /** * Find cells by lock script, optionally filtered by type script. * * @param lock - The lock script to search by. * @param type - Optional type script filter. * @param withData - Whether to include cell data (default: true). * @param order - Sort order by block number ("asc" or "desc"). * @param limit - Page size for each RPC call (default: 10). * @returns An async generator yielding matching cells. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const { script: lock } = await ccc.Address.fromString("ckt1q...", client); * * // Find all cells belonging to this address * for await (const cell of client.findCellsByLock(lock)) { * console.log(`${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`); * } * * // Find only xUDT cells belonging to this address * const xudtType = await ccc.Script.fromKnownScript( * client, ccc.KnownScript.XUdt, "0xOWNER_LOCK_HASH...", * ); * for await (const cell of client.findCellsByLock(lock, xudtType)) { * console.log(`UDT cell found`); * } * ``` */ findCellsByLock(lock: ScriptLike, type?: ScriptLike | null, withData?: boolean, order?: "asc" | "desc", limit?: number): AsyncGenerator; /** * Find cells by type script. * * @param type - The type script to search by. * @param withData - Whether to include cell data (default: true). * @param order - Sort order by block number. * @param limit - Page size for each RPC call (default: 10). * @returns An async generator yielding matching cells. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * // Find all xUDT cells of a specific token * const xudtType = await ccc.Script.fromKnownScript( * client, ccc.KnownScript.XUdt, "0xOWNER_LOCK_HASH...", * ); * for await (const cell of client.findCellsByType(xudtType)) { * console.log(`Token cell: ${cell.outPoint.txHash}:${cell.outPoint.index}`); * } * ``` */ findCellsByType(type: ScriptLike, withData?: boolean, order?: "asc" | "desc", limit?: number): AsyncGenerator; findSingletonCellByType(type: ScriptLike, withData?: boolean): Promise; /** * Resolve cell dependency info into concrete CellDep objects. * * If a CellDepInfo specifies a type script, the live cell carrying it is looked up * on-chain and, when found, its outpoint is used instead of the configured one. When * the lookup finds nothing, the configured outpoint is used as written. A CellDepInfo * without a type script is always used as written. * * @param cellDepsInfoLike - One or more CellDepInfo or arrays of CellDepInfo. * @returns Resolved CellDep array ready to be added to a transaction. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const xudtInfo = await client.getKnownScript(ccc.KnownScript.XUdt); * const cellDeps = await client.getCellDeps(xudtInfo.cellDeps); * // cellDeps can be added to a transaction: * // tx.cellDeps.push(...cellDeps); * ``` */ getCellDeps(...cellDepsInfoLike: (CellDepInfoLike | CellDepInfoLike[])[]): Promise; abstract findTransactionsPaged(key: Omit & { groupByTransaction: true; }, order?: "asc" | "desc", limit?: NumLike, after?: string): Promise; abstract findTransactionsPaged(key: Omit & { groupByTransaction?: false | null; }, order?: "asc" | "desc", limit?: NumLike, after?: string): Promise; abstract findTransactionsPaged(key: ClientIndexerSearchKeyTransactionLike, order?: "asc" | "desc", limit?: NumLike, after?: string): Promise; findTransactions(key: Omit & { groupByTransaction: true; }, order?: "asc" | "desc", limit?: number): AsyncGenerator; findTransactions(key: Omit & { groupByTransaction?: false | null; }, order?: "asc" | "desc", limit?: number): AsyncGenerator; findTransactions(key: ClientIndexerSearchKeyTransactionLike, order?: "asc" | "desc", limit?: number): AsyncGenerator; /** * Find transactions related to a lock script, optionally filtered by type script. * * @param lock - The lock script to search by. * @param type - Optional type script filter. * @param groupByTransaction - If true, group results by transaction. * @param order - Sort order by block number. * @param limit - Page size per RPC call. * @returns An async generator yielding transaction records. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const { script: lock } = await ccc.Address.fromString("ckt1q...", client); * * // List all transactions related to an address (grouped) * for await (const txRecord of client.findTransactionsByLock(lock, null, true)) { * console.log(`TX: ${txRecord.txHash}, Block: ${txRecord.blockNumber}`); * } * ``` */ findTransactionsByLock(lock: ScriptLike, type: ScriptLike | undefined | null, groupByTransaction: true, order?: "asc" | "desc", limit?: number): AsyncGenerator; findTransactionsByLock(lock: ScriptLike, type?: ScriptLike | null, groupByTransaction?: false | null, order?: "asc" | "desc", limit?: number): AsyncGenerator; findTransactionsByLock(lock: ScriptLike, type?: ScriptLike | null, groupByTransaction?: boolean | null, order?: "asc" | "desc", limit?: number): AsyncGenerator; findTransactionsByType(type: ScriptLike, groupByTransaction: true, order?: "asc" | "desc", limit?: number): AsyncGenerator; findTransactionsByType(type: ScriptLike, groupByTransaction?: false | null, order?: "asc" | "desc", limit?: number): AsyncGenerator; findTransactionsByType(type: ScriptLike, groupByTransaction?: boolean | null, order?: "asc" | "desc", limit?: number): AsyncGenerator; abstract getCellsCapacity(key: ClientIndexerSearchKeyLike): Promise; /** * Get the total CKB balance of a single lock script. * Only counts cells with no type script and no data (pure CKB capacity cells). * * @param lock - The lock script to query balance for. * @returns The total capacity in Shannons as a bigint. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const { script: lock } = await ccc.Address.fromString( * "ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsq...", * client, * ); * const balance = await client.getBalanceSingle(lock); * console.log(`Balance: ${ccc.fixedPointToString(balance)} CKB`); * ``` */ getBalanceSingle(lock: ScriptLike): Promise; /** * Get the total CKB balance across multiple lock scripts. * Sums the balance from each lock script. * * @param locks - An array of lock scripts to query. * @returns The combined total capacity in Shannons as a bigint. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const signer = new ccc.SignerCkbPrivateKey(client, "0x..."); * await signer.connect(); * * const locks = await signer.getRecommendedAddressObj() * .then(({ script }) => [script]); * const totalBalance = await client.getBalance(locks); * console.log(`Total: ${ccc.fixedPointToString(totalBalance)} CKB`); * ``` */ getBalance(locks: ScriptLike[]): Promise; /** * Send a signed transaction to the CKB network. * Validates the fee rate against the maximum before sending. * * @param transaction - The transaction to send. * @param validator - Optional outputs validator ("passthrough" or "well_known_scripts_only"). * @param options - Optional configuration including maxFeeRate. * @returns The transaction hash. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const signer = new ccc.SignerCkbPrivateKey(client, "0x..."); * await signer.connect(); * * const tx = ccc.Transaction.from({ * outputs: [{ capacity: ccc.fixedPointFrom(100), lock: receiverLock }], * }); * await tx.completeInputsByCapacity(signer); * await tx.completeFeeBy(signer); * * // Usually you call signer.sendTransaction(tx) which signs then sends. * // client.sendTransaction expects an already-signed transaction. * const txHash = await client.sendTransaction(tx); * ``` */ sendTransaction(transaction: TransactionLike, validator?: OutputsValidator, options?: { maxFeeRate?: NumLike; }): Promise; /** * Get a transaction by its hash, including its status and block info. * * @param txHashLike - The transaction hash to look up. * @returns The transaction response with status, or undefined if not found. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * const txResponse = await client.getTransaction("0xTX_HASH..."); * if (txResponse) { * console.log(`Status: ${txResponse.status}`); * console.log(`Block: ${txResponse.blockNumber}`); * console.log(`Outputs: ${txResponse.transaction.outputs.length}`); * } * ``` */ getTransaction(txHashLike: HexLike): Promise; /** * This method gets specified transaction with its block header (if existed). * This is mainly for caching because we need the header to test if we can safely trust the cached tx status. * @param txHashLike */ getTransactionWithHeader(txHashLike: HexLike): Promise<{ transaction: ClientTransactionResponse; header?: ClientBlockHeader; } | undefined>; /** * Wait for a transaction to be confirmed on-chain. * Polls the node until the transaction reaches the specified confirmation depth. * * @param txHash - The transaction hash to wait for. * @param confirmations - Number of block confirmations to wait for (default: 0 = committed). * @param timeout - Maximum wait time in milliseconds (default: 60000). * @param interval - Polling interval in milliseconds (default: 2000). * @returns The transaction response once confirmed, or throws on timeout. * * @example * ```typescript * import { ccc } from "@ckb-ccc/core"; * * const clientOwner = ccc.ClientPublicTestnet.open(); * const client = clientOwner.value; * // Call `await clientOwner.dispose()` when the client is no longer needed. * // Wait for transaction to be committed (0 confirmations) * const tx = await client.waitTransaction("0xTX_HASH..."); * console.log(`Confirmed in block: ${tx?.blockNumber}`); * * // Wait for 4 confirmations with 2 minute timeout * const confirmedTx = await client.waitTransaction( * "0xTX_HASH...", * 4, // confirmations * 120000, // timeout: 2 minutes * ); * ``` */ waitTransaction(txHash: HexLike, confirmations?: number, timeout?: number, interval?: number): Promise; } declare const HashTypeCodec: Codec; /** * @public */ type HashTypeLike = string | number | bigint; /** * @public */ type HashType = "type" | "data" | "data1" | "data2"; /** * Converts a HashTypeLike value to a HashType. * @public * * @param val - The value to convert, which can be a string, number, or bigint. * @returns The corresponding HashType. * * @throws Will throw an error if the input value is not a valid hash type. * * @example * ```typescript * const hashType = hashTypeFrom(1); // Outputs "data" * const hashType = hashTypeFrom("type"); // Outputs "type" * ``` */ declare function hashTypeFrom(val: HashTypeLike): HashType; /** * Converts a HashTypeLike value to its corresponding byte representation. * @public * * @param hashType - The hash type value to convert. * @returns A Uint8Array containing the byte representation of the hash type. * * @example * ```typescript * const hashTypeBytes = hashTypeToBytes("type"); // Outputs Uint8Array [0] * ``` */ declare function hashTypeToBytes(hashType: HashTypeLike): Bytes$1; /** * Converts a byte-like value to a HashType. * @public * * @param bytes - The byte-like value to convert. * @returns The corresponding HashType. * * @throws Will throw an error if the input bytes do not correspond to a valid hash type. * * @example * ```typescript * const hashType = hashTypeFromBytes(new Uint8Array([0])); // Outputs "type" * ``` */ declare function hashTypeFromBytes(bytes: BytesLike): HashType; /** * @public */ type ScriptLike = { codeHash: BytesLike; hashType: HashTypeLike; args: BytesLike; }; declare const Script_base: (abstract new () => { toBytes(): Bytes$1; clone(): Script; eq(other: ScriptLike): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: ScriptLike): Bytes$1; decode(_: BytesLike, _context?: any): Script; fromBytes(_bytes: BytesLike, _context?: any): Script; from(_: ScriptLike): Script; Base(): (abstract new () => { toBytes(): Bytes$1; clone(): SubType; eq(other: SubTypeLike): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike): Bytes$1; decode(_: BytesLike, _context?: Context): SubType; fromBytes(_bytes: BytesLike, _context?: Context): SubType; from(_: SubTypeLike): SubType; Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike_1, SubType_1 = SubTypeLike_1>(): (abstract new (inner: DecodedType) => { readonly inner: DecodedType; match(handlers: UnionMatchHandlers & { _?: undefined | null; }): Result; match(handlers: Partial> & { _: (inner: DecodedType) => Result; }): Result; toBytes(): Bytes$1; clone(): SubType_1; eq(other: SubTypeLike_1): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike_1): Bytes$1; decode(_: BytesLike, _context?: ContextType | undefined): SubType_1; fromBytes(_bytes: BytesLike, _context?: ContextType | undefined): SubType_1; from(_: SubTypeLike_1): SubType_1; Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike_1, SubType_1 = SubTypeLike_1>(): /*elided*/ any; }; }; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): (abstract new (inner: DecodedType) => { readonly inner: DecodedType; match(handlers: UnionMatchHandlers & { _?: undefined | null; }): Result; match(handlers: Partial> & { _: (inner: DecodedType) => Result; }): Result; toBytes(): Bytes$1; clone(): SubType; eq(other: SubTypeLike): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike): Bytes$1; decode(_: BytesLike, _context?: ContextType | undefined): SubType; fromBytes(_bytes: BytesLike, _context?: ContextType | undefined): SubType; from(_: SubTypeLike): SubType; Base(): (abstract new () => { toBytes(): Bytes$1; clone(): SubType_1; eq(other: SubTypeLike_1): boolean; hash(): Hex; toHex(): Hex; }) & { byteLength?: number; encode(_: SubTypeLike_1): Bytes$1; decode(_: BytesLike, _context?: Context): SubType_1; fromBytes(_bytes: BytesLike, _context?: Context): SubType_1; from(_: SubTypeLike_1): SubType_1; Base(): /*elided*/ any; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): /*elided*/ any; }; BaseUnion, any>, SubTypeLike, SubType = SubTypeLike>(): /*elided*/ any; }; }; /** * @public */ declare class Script extends Script_base { codeHash: Hex; hashType: HashType; args: Hex; /** * Creates an instance of Script. * * @param codeHash - The code hash of the script. * @param hashType - The hash type of the script. * @param args - The arguments for the script. */ constructor(codeHash: Hex, hashType: HashType, args: Hex); get occupiedSize(): number; /** * Clone a script. * * @returns A cloned Script instance. * * @example * ```typescript * const script1 = script0.clone(); * ``` */ clone(): Script; /** * Check if the script is equal to another script. * @public * @param other - The other script to compare with * @returns True if the scripts are equal, false otherwise * * @example * ```typescript * const isEqual = script0.eq(script1); * ``` */ eq(other: ScriptLike): boolean; /** * Creates a Script instance from a ScriptLike object. * * @param script - A ScriptLike object or an instance of Script. * @returns A Script instance. * * @example * ```typescript * const script = Script.from({ * codeHash: "0x1234...", * hashType: "type", * args: "0xabcd..." * }); * ``` */ static from(script: ScriptLike): Script; /** * Creates a Script instance from client and known script. * * @param knownScript - A KnownScript enum. * @param args - Args for the script. * @param client - A ScriptLike object or an instance of Script. * @returns A promise that resolves to the script instance. * * @example * ```typescript * const script = await Script.fromKnownScript( * client, * KnownScript.XUdt, * args: "0xabcd..." * ); * ``` */ static fromKnownScript(client: Client, knownScript: KnownScript, args: HexLike): Promise