UNPKG

@vechain/sdk-core

Version:

This module is crafted for dApp development and various blockchain operations that seamlessly unfold offline

1,179 lines (1,155 loc) 238 kB
import * as s_bip32 from '@scure/bip32'; import { AbiParameter, AbiFunction, AbiEvent, Abi, ContractEventName, DecodeEventLogReturnType, EncodeEventTopicsReturnType, ContractFunctionName, DecodeFunctionDataReturnType, DecodeFunctionResultReturnType } from 'viem'; import { Input, NestedUint8Array } from '@ethereumjs/rlp'; /** * In the VeChainThor blockchain, a certificate is a data structure used * for client-side self-signed certificates. * It plays a crucial role in providing a mechanism for secure identification * and validation of data. * * Certificates are primarily used for purposes like attestation, validation, * and verification of data authenticity. * They are used as proofs of authenticity and origin for data exchanged * within the VeChain ecosystem. */ interface CertificateData { /** * The purpose field indicates the intended use or context of the certificate. * For example, it could be used for identification, verification, * or attestation. */ purpose: string; /** * The payload field holds the actual content of the certificate. * This content can be of various types, such as text, images, or other data. */ payload: { type: string; content: string; }; /** * The domain field represents the specific context or domain * for which the certificate is valid. * It helps ensure that the certificate is only applicable * within the intended context. */ domain: string; /** * The timestamp field records the time at which the certificate * was created or issued. * This provides a temporal reference for the certificate's validity. * * The value is expressed as of milliseconds elapsed since the * [epoch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), * which is defined as the midnight at the beginning of January 1, 1970, UTC. * * @remarks * The value is a natural number in the safe integer range of JS `number` type. */ timestamp: number; /** * The signer field indicates the address of the entity * that signs the certificate. * It is the public key address of the entity that issues the certificate. */ signer: string; /** * The signature field contains the cryptographic signature * generated by the issuer's private key. * This signature ensures the integrity and authenticity * of the certificate's content. * * @remarks * The signature is a lowercase hexadecimal expression prefixed with `0x`. */ signature?: string; } /** * The Certificate class provides functionality to create, sign, and verify certificates. * It implements the CertificateData interface. * * @remarks * The properties of those class are immutable, except {@link signature}, * because properties are part of the {@link signature} computation. * The signature is used of extract and match the {@link signer}. * The fact the properties are immutable assure is not possible to create * an object tampering properties and carry on the legitimate signature and * signer address of the object before tampering to make tampered content * to result in a validated certificate. * * @remarks * Classes extending {@link Certificate} should expose immutable properties. * * @remarks * This class implementation supports {@link signer} * [mixed-case checksum address encoding](https://eips.ethereum.org/EIPS/eip-55). * * @implements CertificateData */ declare class Certificate implements CertificateData { /** * Return the intended use or context of the certificate. */ readonly purpose: string; /** * Returns the content of the certificate. */ readonly payload: { /** * Return the description of the type of content. */ readonly type: string; /** * Return the content serialized as a string. */ readonly content: string; }; /** * Return the description of the context of validity of this certificate. */ readonly domain: string; /** * The value expressed as of milliseconds elapsed since the * [epoch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), * when the certificate was issued. * * @remarks * The value is a natural number in the safe integer range of JS `number` type. */ readonly timestamp: number; /** * Return the address of the entity signed the certificate, as * a lowercase hexadecimal expression prefixed by `0x`. * * @remarks * Normalized lowercase prefixed expression is needed because * the content of this property is part of the {@signature} computation: * certificates made from checksum case address of the signer should * result valid as the certificate made from the same signer address * not checksum case. */ readonly signer: string; /** * Return the signature computed evaluating the properties of this object * and the private key of the signer. * * @remarks * The signature is a lowercase hexadecimal expression prefixed with `0x`. */ signature?: string; /** * Returns a new instance of this class assuring the formal validity of the * arguments used to build the object. * * @param {string} purpose - The purpose of the certificate. * @param {Object} payload - The payload containing type and content. * @param {string} payload.type - The type of the payload. * @param {string} payload.content - The content of the payload. * @param {string} domain - The domain associated with the certificate. * @param {number} timestamp - The time at which the certificate is created; * must be a positive safe integer. * @param {string} signer - The signer of the certificate; * must be a valid address. * @param {string|undefined} [signature] - The signature of the certificate; * optional parameter. * * @throws {InvalidDataType} If timestamp is not a positive safe integer. * @throws {InvalidDataType} If signer is not a valid address. * @throws {InvalidDataType} If signature is invalid. * * @remarks * The `signer` address is represented lowercase and `0x` prefixed. */ protected constructor(purpose: string, payload: { type: string; content: string; }, domain: string, timestamp: number, signer: string, signature?: string); /** * Encodes a given object into a Uint8Array representation * applying the following operation to normalize the content: * - the properties are sorted in ascending alphabetic order; * - the key/value properties are delimited with `"` when serialized as JSON * before to be encoded as bytes; * - any not meaningful blank characters are ignored; * - the JSON representation of this object is byte encoded using the UTF-8 * [normalization form for canonical composition](https://en.wikipedia.org/wiki/Unicode_equivalence#Normal_forms). * * @param {unknown} object - The input object to be encoded. * @return {Uint8Array} The encoded Uint8Array representation of the input object. */ protected static encode(object: unknown): Uint8Array; /** * Encodes the current certificate instance into a Uint8Array representation. * * @remarks * This method normalizes the content by: * - Sorting the properties in ascending alphabetic order. * - Delimiting key/value properties with `"` when serialized as JSON before encoding as bytes. * - Ignoring any not meaningful blank characters. * - Using the UTF-8 normalization form for canonical composition for byte encoding. * * @return {Uint8Array} The encoded Uint8Array representation of the current certificate instance. */ encode(): Uint8Array; /** * Return `true` if the current instance has a signature. * * @return {boolean} `true` if the signature is a valid hexadecimal string, * otherwise `false`. */ isSigned(): boolean; /** * Creates a new Certificate instance from the provided CertificateData. * * @param {CertificateData} data - The data required to create the Certificate. * @return {Certificate} A new Certificate instance. * @throws {InvalidDataType} If the provided data is invalid: * - if timestamp is not a positive safe integer; * - if signer is not a valid address; * - if signature is an invalid hexadecimal expression. * * @remarks * This method supports {@link signer} * [mixed-case checksum address encoding](https://eips.ethereum.org/EIPS/eip-55). * * @see constructor */ static of(data: CertificateData): Certificate; /** * Signs the current object using a given private key. * * The {@link signature} is computed encoding this object according * the following normalization rules: * - the {@link signature} property is ignored, because its value * is the result of this method. * - the properties are sorted in ascending alphabetic order; * - the key/value properties are delimited with `"` when serialized as JSON * before to be encoded as bytes; * - any not meaningful blank characters are ignored; * - the JSON representation of this object is byte encoded using the UTF-8 * [normalization form for canonical composition](https://en.wikipedia.org/wiki/Unicode_equivalence#Normal_forms). * * @param {Uint8Array} privateKey - The private key used for signing. * @return {this} The current instance after signing. * * @throws {InvalidOperation} - If a hash error occurs. * @throws {InvalidSecp256k1PrivateKey} - If the private key is not a valid 32-byte private key. * * @remarks Security auditable method, depends on * * {@link Blake2b256.of}; * * {@link Secp256k1.sign}. * * @see encode * @see verify */ sign(privateKey: Uint8Array): this; /** * Verifies the certificate by checking its signature. * * @throws {CertificateSignatureMismatch} if the certificate * - is not signed, or * - the signature does not match the signer's public key. * * @remarks * This method supports {@link signer} * [mixed-case checksum address encoding](https://eips.ethereum.org/EIPS/eip-55). * * @remarks Security auditable method, depends on * * {@link Blake2b256.of}; * * {@link Secp256k1.recover}. */ verify(): void; } /** * This class extends the * [BIP32 Hierarchical Deterministic Key](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) * [HDKey](https://github.com/paulmillr/scure-bip32) class * to provide interoperability with * [ethers.js 6 HDNodeWallet](https://docs.ethers.org/v6/api/wallet/#HDNodeWallet). * * @extends s_bip32.HDKey */ declare class HDKey extends s_bip32.HDKey { /** * Prefix for extended private key */ static readonly EXTENDED_PRIVATE_KEY_PREFIX: Uint8Array<ArrayBufferLike>; /** * Prefix for extended public key */ static readonly EXTENDED_PUBLIC_KEY_PREFIX: Uint8Array<ArrayBufferLike>; /** * Default VET derivation path. * * See * [SLIP-0044 : Registered coin types for BIP-0044](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) * for more info. */ static readonly VET_DERIVATION_PATH = "m/44'/818'/0'/0"; /** * Creates a * [BIP32 Hierarchical Deterministic Key](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) * from * [BIP39 Mnemonic Words](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) * and the given derivation path. * * @param {string[]} words - An array of words representing the mnemonic. * @param {string} path - The derivation path to derive the child node. * Default value is {@link VET_DERIVATION_PATH}. * * @return The derived child hierarchical deterministic key. * * @throws {InvalidHDKey} If `path` is not valid to derive a node wallet. * @throws {InvalidHDKeyMnemonic} If `words` is an invalid array mnemonic. * * @remarks Security auditable method, depends on * * [s_bip32.HDKey.derive](https://github.com/paulmillr/scure-bip32); * * [s_bip32.HDKey.fromMasterSeed](https://github.com/paulmillr/scure-bip32); * * [s_bip39.mnemonicToSeedSync](https://github.com/paulmillr/scure-bip39). */ static fromMnemonic(words: string[], path?: string): HDKey; /** * Creates a * [BIP32 Hierarchical Deterministic Key](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) * from a private key and chain code. * * @param {Uint8Array} - privateKey The private key. * @param {Uint8Array} - chainCode The chain code. * * @returns Returns the hierarchical deterministic key from `privateKey` and `chainCode`. * * @throws {InvalidSecp256k1PrivateKey} If the `privateKey` is invalid. * * @remarks **This method wipes `privateKey`** for security reasons. * @remarks Security auditable method, depends on * * [base58.encode](https://github.com/paulmillr/scure-base); * * {@link Sha256}; * * [s_bip32.HDKey.fromExtendedKey](https://github.com/paulmillr/scure-bip32). */ static fromPrivateKey(privateKey: Uint8Array, chainCode: Uint8Array): HDKey; /** * Creates a * [BIP32 Hierarchical Deterministic Key](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) * key from a public key and chain code. * * @param {Uint8Array} publicKey - The public key bytes. * @param {Uint8Array} chainCode - The chain code bytes. * * @returns {HDKey} Returns the hierarchical deterministic key from `public` and `chainCode`. * * @throws {InvalidHDKey} if the `publicKey` is invalid. * * @remarks Security auditable method, depends on * * [base58.encode](https://github.com/paulmillr/scure-base); * * {@link Secp256k1.compressPublicKey}; * * {@link Sha256}; * * [HDKey.fromExtendedKey](https://github.com/paulmillr/scure-bip32). */ static fromPublicKey(publicKey: Uint8Array, chainCode: Uint8Array): HDKey; /** * Checks if derivation path single component is valid * * @param component - Derivation path single component to check * @param index - Derivation path single component index * * @returns `true`` if derivation path single component is valid, otherwise `false`. * */ private static isDerivationPathComponentValid; /** * Checks if BIP32 derivation path is valid. * * @param derivationPath - Derivation path to check. * * @returns `true` if derivation path is valid, otherwise `false`. */ static isDerivationPathValid(derivationPath: string): boolean; } /** * @interface Keystore * Represents a * [Web3 Secret Storage](https://ethereum.org/en/developers/docs/data-structures-and-encoding/web3-secret-storage) * keystore object that holds information about a private cryptographic key. * and its associated wallet address. * * @property {string} address - The wallet address associated with the stored private key. * @property {Object} crypto - The encryption information for the key. * @property {string} crypto.cipher - The encryption algorithm used. * @property {Object} crypto.cipherparams - Additional parameters for the encryption algorithm. * @property {string} crypto.cipherparams.iv - The initialization vector (IV) used for encryption. * @property {string} crypto.ciphertext - The encrypted private key. * @property {string} crypto.kdf - The key derivation function (KDF) used. * @property {Object} crypto.kdfparams - Additional parameters for the KDF. * @property {number} crypto.kdfparams.dklen - The derived private key length. * @property {number} crypto.kdfparams.n - The CPU/memory cost parameter for the key derivation function. * @property {number} crypto.kdfparams.p - The parallelization factor. * @property {number} crypto.kdfparams.r - The block size factor. * @property {string} crypto.kdfparams.salt - The salt value used in the KDF. * @property {string} crypto.mac - The MAC (Message Authentication Code) * to match the KDF function with the private key derived by the cyphered text stored. * @property {string} id - The * [unique identifier version 4](https://en.wikipedia.org/wiki/Universally_unique_identifier) * for the key store. * @property {number} version - The version number of the key store. */ interface Keystore { address: string; crypto: { cipher: string; cipherparams: { iv: string; }; ciphertext: string; kdf: string; kdfparams: { dklen: number; n: number; p: number; r: number; salt: string; }; mac: string; }; id: string; version: number; } /** * Interface representing a keystore account. * * **WARNING:** call * ```javascript * privateKey.fill(0) * ``` * after use to avoid to invalidate any security audit and certification granted to this code. * * @property {string} address - The address associated with the account. * @property {Uint8Array} privateKey - The private key associated with the account. * * @remarks **Differently from * [ethers KeystoreAccount](https://github.com/ethers-io/ethers.js/blob/main/src.ts/wallet/json-keystore.ts), * this type represents the private key as a buffer of bytes to avoid * [Memory Dumping](https://github.com/paulmillr/noble-hashes?tab=readme-ov-file#memory-dumping) * attack.** */ interface KeystoreAccount { address: string; privateKey: string; // @NOTE: Added ONLY for compatibility with ethers KeystoreAccount of ethers. mnemonic?: { path?: string; locale?: string; entropy: string; }; } /** * Sets the keystore cryptography to experimental mode. * * @param experimentalCryptography - A boolean indicating whether the keystore cryptography is experimental or not. */ declare function useExperimentalCryptography(experimentalCryptography: boolean): void; /** * Encrypts a given private key into a keystore format using the specified password. * * @param privateKey - The private key to be encrypted. * @param password - The password used for the encryption. * @returns A Promise that resolves to the encrypted keystore. */ declare function encrypt(privateKey: Uint8Array, password: string): Promise<Keystore>; /** * Decrypts a keystore to obtain the private key using the given password. * * @throws {InvalidKeystoreError, InvalidKeystorePasswordError} * @param keystore - The keystore containing the encrypted private key. * @param password - The password used to decrypt the keystore. * @returns A Promise that resolves to the decrypted KeystoreAccount or rejects if the keystore or password is invalid. */ declare function decrypt(keystore: Keystore, password: string): Promise<KeystoreAccount>; /** * Validates if the provided keystore adheres to the expected format and structure. * * @param keystore - The keystore to be validated. * @returns A boolean indicating whether the keystore is valid or not. */ declare function isValid(keystore: Keystore): boolean; /** * Exports the keystore functions for encryption, decryption, and validation. */ declare const keystore: { encrypt: typeof encrypt; decrypt: typeof decrypt; isValid: typeof isValid; useExperimentalCryptography: typeof useExperimentalCryptography; }; /** * The Secp256k1 class provides cryptographic utilities for the * [SECP256K1](https://en.bitcoin.it/wiki/Secp256k1) * [elliptic curve](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm), * including compressing and inflating public keys, * generating private keys, and validating message hashes and private keys. */ declare class Secp256k1 { /** * This value is used to identify compressed public key. */ private static readonly COMPRESSED_PREFIX; /** * Represents the fixed length of the cryptographic signature. * The value is set to 65, which is the size in bytes * required for a 520-bit signature. * * @constant {number} SIGNATURE_LENGTH */ static readonly SIGNATURE_LENGTH = 65; /** * This value is used to identify uncompressed public key. */ private static readonly UNCOMPRESS_PREFIX; /** * Defines the required length for a valid hash. */ private static readonly VALID_HASH_LENGTH; /** * Compresses an uncompressed public key. * * @param {Uint8Array} publicKey - The uncompressed public key to be compressed. * @return {Uint8Array} - The compressed public key. * * @see Secp256k1.inflatePublicKey */ static compressPublicKey(publicKey: Uint8Array): Uint8Array; /** * Derives the public key from a given private key. * * @param {Uint8Array} privateKey - The private key in Uint8Array format. Must be a valid 32-byte secp256k1 private key. * @param {boolean} [isCompressed=true] - Indicates whether the derived public key should be in compressed format. * @return {Uint8Array} The derived public key in Uint8Array format. * @throws {InvalidSecp256k1PrivateKey} Throws an error if the provided private key is not valid. * * @remarks Security auditable method, depends on * * [nc_secp256k1.getPublicKey](https://github.com/paulmillr/noble-secp256k1). */ static derivePublicKey(privateKey: Uint8Array, isCompressed?: boolean): Uint8Array; /** * Generates a new Secp256k1 private key using a secure random number generator. * * @return {Promise<Uint8Array>} A promise that resolves to a Uint8Array representing the generated private key. * This encoded private key is suitable for cryptographic operations. * @throws {InvalidSecp256k1PrivateKey} Throws an error if private key generation fails if a secure random number * generator is not provided by the hosting operating system. * * @remarks Security auditable method, depends on * * [nc_secp256k1.utils.randomPrivateKey](https://github.com/paulmillr/noble-secp256k1). */ static generatePrivateKey(): Promise<Uint8Array>; /** * Inflate a compressed public key to its uncompressed form. * * @param {Uint8Array} publicKey - The compressed public key to be inflated. * @return {Uint8Array} - The uncompressed public key. * * @remarks Security auditable method, depends on * * [nc_secp256k1.ProjectivePoint.fromAffine](https://github.com/paulmillr/noble-secp256k1); * * [nc_secp256k1.ProjectivePoint.fromHex](https://github.com/paulmillr/noble-secp256k1); * * [nc_secp256k1.ProjectivePoint.toAffine](https://github.com/paulmillr/noble-secp256k1). * * @see Secp256K1.compressPublicKey */ static inflatePublicKey(publicKey: Uint8Array): Uint8Array; /** * Checks whether the provided hash is a valid message hash. * * @param {Uint8Array} hash - The hash to be validated. * @return {boolean} `true` if the hash is 32 bytes long, otherwise `false`. */ static isValidMessageHash(hash: Uint8Array): boolean; /** * Checks if the provided private key is valid. * * @param {Uint8Array} privateKey - The private key to validate. * @return {boolean} `true` if the private key is valid, `false` otherwise. * * @remarks Security auditable method, depends on * * [nc_secp256k1.utils.isValidPrivateKey](https://github.com/paulmillr/noble-secp256k1). */ static isValidPrivateKey(privateKey: Uint8Array): boolean; /** * Generates a random sequence of bytes. * If an error occurs during generation using * [nc_secp256k1](https://github.com/paulmillr/noble-secp256k1), * {@link {@link global.crypto} is used as fall back togenerate * the random sequence. * * @param {number} [bytesLength=32] - Optional. The number of random bytes to generate, 32 by default. * @return {Uint8Array} - A Uint8Array containing the random bytes. * * @remarks Security auditable method, depends on * * {@link global.crypto.getRandomValues}; * * [nh_randomBytes](https://github.com/paulmillr/noble-hashes). */ static randomBytes(bytesLength?: number): Uint8Array; /** * Recovers the public key associated with the message hash from the given signature. * * @param {Uint8Array} messageHash - The 32-byte message hash to be verified. * @param {Uint8Array} sig - The 65-byte signature used for recovery, consisting of the compact signature and recovery byte. * @return {Uint8Array} The recovered public key in its raw bytes form. * @throws {InvalidSecp256k1MessageHash} If the provided message hash is invalid. * @throws {InvalidSecp256k1Signature} If the provided signature is not 65 bytes or contains an invalid recovery value. * * @remarks Security auditable method, depends on * * [nc_secp256k1.Signature](https://github.com/paulmillr/noble-secp256k1). * * @see Secp256k1.isValidMessageHash */ static recover(messageHash: Uint8Array, sig: Uint8Array): Uint8Array; /** * Signs a given message hash using the provided private key. * * @param messageHash - A 32-byte message hash that needs to be signed. * @param privateKey - A 32-byte private key used for signing the message hash. * @return The signature of the message hash consisting of the r, s, and recovery values. * @throws InvalidSecp256k1MessageHash if the message hash is not a valid 32-byte hash. * @throws InvalidSecp256k1PrivateKey if the private key is not a valid 32-byte private key. * * @remarks Security auditable method, depends on * * [nc_secp256k1.sign](https://github.com/paulmillr/noble-secp256k1). * * @see Secp256k1.isValidMessageHash * @see Secp256k1.isValidPrivateKey */ static sign(messageHash: Uint8Array, privateKey: Uint8Array): Uint8Array; } /** * Root interface for all the classes part of the `VeChain Data Model` * to provide a coherent API to represent, encode, and cast data among data types. * * @interface */ interface VeChainDataModel<T> { // Properties. /** * Return this instance cast to a big integer value * @throws InvalidOperation if this object can't cast to a big integer. */ get bi(): bigint; /** * Return this instance cast to a buffer of bytes. */ get bytes(): Uint8Array; /** * Return this object cast to number value. * @throws InvalidOperation if this object can't cast to a big integer. */ get n(): number; // Methods. /** * Compare this instance with `that` in a lexicographic meaningful way. * * @param {T} that object to compare. * @return a negative number if `this` < `that`, zero if `this` = `that`, a positive number if `this` > that`. */ compareTo: (that: T) => number; /** * Checks if the given value is equal to the current instance. * * @param {T} that - The value to compare. * @returns {boolean} - True if the values are equal, false otherwise. */ isEqual: (that: T) => boolean; } /** * Represents a hexadecimal value expressed as * * `-` sign if the value is negative, * * `0x` hexadecimal notation tag, * * a not empty string of hexadecimal digits from `0` to `9` and from `a` to `f`. * * @description This hexadecimal notation is coherent with the decimal notation: * * the sign is only expressed for negative values, and it is always the first symbol, * * the `0x` tags the string as a hexadecimal expression, * * hexadecimal digits follow. * * An empty content results is no digits. * * @implements {VeChainDataModel<Hex>} */ declare class Hex implements VeChainDataModel<Hex> { /** * Negative multiplier of the {@link digits} absolute value. * * @type {number} */ protected static readonly NEGATIVE: number; /** * Positive multiplier of the {@link digits} absolute value. * * @type {number} */ protected static readonly POSITIVE: number; /** * A constant string prefix used in hexadecimal notation. */ static readonly PREFIX = "0x"; /** * The radix used for representing numbers base 16 in a positional numeral notation system. * * @typedef {number} RADIX */ static readonly RADIX: number; /** * Regular expression for matching hexadecimal strings. * An empty input is represented as a empty digits. * * @type {RegExp} */ private static readonly REGEX_HEX; /** * Regular expression pattern to match a prefix indicating hexadecimal number. * * @type {RegExp} */ protected static readonly REGEX_HEX_PREFIX: RegExp; /** * Returns the hexadecimal digits expressing this absolute value, sign and `0x` prefix omitted. * @remarks An empty content results in an empty string returned. */ readonly digits: string; /** * Represents the sign multiplier of a given number: * * {@link NEGATIVE} `-1` if negative, * * {@link POSITIVE} `1` if positive. */ readonly sign: number; /** * Creates a new instance of this class to represent the value * built multiplying `sign` for the absolute value expressed by the hexadecimal `digits`. * * @param {number} sign - The sign of the value. * @param {string} digits - The digits of the absolute value in hexadecimal base. * @param {function} [normalize] - The function used to normalize the digits. Defaults to converting digits to lowercase. */ protected constructor(sign: number, digits: string, normalize?: (digits: string) => string); /** * Returns the absolute value of this Hex object. * * @return {Hex} A new Hex object representing the absolute value of this Hex. */ get abs(): Hex; /** * Returns the value of `bi` as a `BigInt` type. * * @returns {bigint} The value of `bi` as a `BigInt`. */ get bi(): bigint; /** * Returns the Uint8Array representation of the aligned bytes. * * @return {Uint8Array} The Uint8Array representation of the aligned bytes. */ get bytes(): Uint8Array; /** * Returns the value of n. * * @return {number} The value of n. * * @throws {InvalidOperation<Hex>} Throws an error if this instance doesn't represent * an [IEEE 754 double precision 64 bits floating point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). */ get n(): number; /** * Aligns the hexadecimal string to bytes by adding a leading '0' if the string length is odd. * * @returns {Hex} - The aligned hexadecimal string. */ alignToBytes(): Hex; /** * Compares the current Hex object with another Hex object. * * @param {Hex} that - The Hex object to compare with. * * @return {number} - Returns a negative number if the current Hex object is less than the given Hex object, * zero if they are equal, or a positive number if the current Hex object is greater than the given Hex object. */ compareTo(that: Hex): number; /** * Returns a new instance of the Hex class, its value fits to the specified number of digits. * * @param {number} digits - The number of digits to fit the Hex value into. * * @returns {Hex} - A new Hex instance that represents the fitted Hex value. * * @throws {InvalidDataType} - If the Hex value cannot be fit into the specified number of digits. */ fit(digits: number): Hex; /** * Determines whether this Hex instance is equal to the given Hex instance. * * @param {Hex} that - The Hex instance to compare with. * @return {boolean} - True if the Hex instances are equal, otherwise false. */ isEqual(that: Hex): boolean; /** * Checks if this instance expresses a valid {@link Number} value * according the * [IEEE 754 double precision 64 bits floating point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). * * @returns {boolean} Returns true if this instance expresses 32 hex digits (16 bytes, 128 bits) needed to represent * a {@link Number} value, else it returns false. */ isNumber(): boolean; /** * Checks if the given string expression is a valid hexadecimal value. * * @param {string} exp - The string representation of a hexadecimal value. * * @return {boolean} - True if the expression is a valid hexadecimal value, case-insensitive, * optionally prefixed with `0x`; false otherwise. */ static isValid(exp: string): boolean; /** * Determines whether the given string is a valid hexadecimal number prefixed with '0x'. * * @param {string} exp - The string to be evaluated. * @return {boolean} - True if the string is a valid hexadecimal number prefixed with '0x', otherwise false. */ static isValid0x(exp: string): boolean; /** * Create a Hex instance from a bigint, number, string, or Uint8Array. * * @param {bigint | number | string | Uint8Array} exp - The value to represent in a Hex instance: * * bigint is always representable in hexadecimal base notation; * * number, encoded as [IEEE 754 double precision 64 bits floating point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format); * * string is parsed as the hexadecimal expression of a bigint value, optionally tagged with `0x`; * * Uint8Array is interpreted as the sequence of bytes. * * @returns {Hex} - A Hex instance representing the input value. * * @throws {InvalidDataType} if the given `exp` can't be represented as a hexadecimal expression. */ static of(exp: bigint | number | string | Uint8Array): Hex; /** * Generates a random Hex value of the given number of bytes length. * * @param {number} bytes - The number of bytes to generate. * @throws {InvalidDataType} - If the bytes argument is not greater than 0. * @returns {Hex} - A randomly generated Hex value. * * @remarks Security auditable method, depends on * * [`nh_utils.randomBytes`](https://github.com/paulmillr/noble-hashes?tab=readme-ov-file#utils). */ static random(bytes: number): Hex; /** * Returns a string representation of the object. * * @param {boolean} compact - Whether to compact the string representation. * @return {string} The string representation of the object. */ toString(compact?: boolean): string; } /** * Represents an ABI (Application Binary Interface). * @extends VeChainDataModel */ declare class ABI implements VeChainDataModel<ABI> { private readonly types; private readonly values; /** * ABI constructor from types and values. * * @param {string | AbiParameter[]} types - A list of ABI types representing the types of the values. * @param {unknown[]} values - An array of values according to the specified ABI types. **/ protected constructor(types?: string | AbiParameter[], values?: unknown[]); /** * Compares the current ABI instance with another ABI instance. * @param that The ABI to compare with. * @returns {number} A non-zero number if the current ABI is different to the other ABI or zero if they are equal. * @override {@link VeChainDataModel#compareTo} * @remark The comparison is done by comparing the types and values of the ABI instances. **/ compareTo(that: ABI): number; /** * Checks if the current ABI object is equal to the given ABI object. * @param that The ABI object to compare with. * @returns {boolean} True if the objects are equal, false otherwise. * @override {@link VeChainDataModel#isEqual} * @remark The comparison is done by comparing the types and values of the ABI instances. **/ isEqual(that: ABI): boolean; /** * Throws an exception because the ABI cannot be represented as a big integer. * @returns {bigint} The BigInt representation of the ABI. * @throws {InvalidOperation} The ABI cannot be represented as a bigint. * @override {@link VeChainDataModel#bi} * @remark The conversion to BigInt is not supported for an ABI. */ get bi(): bigint; /** * Encodes the values according to the specified ABI types when creating the ABI instance. * * @returns The ABI-encoded bytes representing the given values. * @throws {InvalidAbiDataToEncodeOrDecode, InvalidDataType} */ get bytes(): Uint8Array; /** * Throws an exception because the ABI cannot be represented as a number. * @returns {bigint} The number representation of the ABI. * @throws {InvalidOperation} The mnemonic cannot be represented as a number. * @override {@link VeChainDataModel#n} * @remark The conversion to number is not supported for an ABI. */ get n(): number; /** * Instantiates an ABI object from the given types and values. * @param {string | AbiParameter[]} types ABI parameters representing the types of the values. * @param {unknown[]} values ABI values. * @returns {ABI} The ABI object with the given types and values. */ static of(types: string | AbiParameter[], values: unknown[]): ABI; /** * Decodes the ABI values from the given ABI types and encoded data. * @param {string| AbiParameter[]} types The list of ABI types representing the types of the values to decode. * @param {Hex} dataEncoded The encoded data to decode. * @returns An ABI instance with the decoded values. */ static ofEncoded(types: string | AbiParameter[], dataEncoded: string | Uint8Array): ABI; /** * Recursively parses an object and collects the values of each attribute into an array, * with nested arrays for nested objects. * @param {object} obj - The object to parse. * @returns {unknown[]} An array of values from the object, with nested arrays for nested objects. */ parseObjectValues(obj: object): unknown[]; /** * It gets the first decoded value from the ABI. * @returns {ReturnType} The first decoded value from the ABI. */ getFirstDecodedValue<ReturnType>(): ReturnType; /** * Parses an ABI to its Hex representation. * @returns {Hex} The Hex representation of the ABI. */ toHex(): Hex; } type SignatureType = string | AbiFunction | AbiEvent; /** * Represents an ABI (Application Binary Interface) item. * @extends ABI */ declare abstract class ABIItem extends ABI { readonly signature: AbiFunction | AbiEvent; readonly stringSignature: string; /** * ABIItem constructor from item (Event, Function...) signature. * * @param {SignatureType} signature - The signature of the ABI item (Function, Event...). **/ constructor(signature: SignatureType); static ofSignature<T extends ABIItem>(ABIItemConstructor: new (signature: string) => T, signature: string): T; static ofSignature<T extends ABIItem>(ABIItemConstructor: new (signature: AbiFunction) => T, signature: AbiFunction): T; static ofSignature<T extends ABIItem>(ABIItemConstructor: new (signature: AbiEvent) => T, signature: AbiEvent): T; /** * Returns a string representation of a JSON object or a string. * @param {'json' | 'string'} formatType Either JSON or String * @returns The string representation of the ABI item. */ format(formatType?: 'json' | 'string'): string; /** * The signature hash of the ABIItem. * @returns {string} The signature hash of the ABIItem. * @remarks Wrapper for {@link toFunctionHash}. **/ get signatureHash(): string; /** * Compares the current ABIItem instance with another ABIItem instance. * @param {ABIItem} that The item to compare with. * @returns {number} A non-zero number if the current ABIItem is different to the other ABI or zero if they are equal. * @override {@link VeChainDataModel#compareTo} **/ compareTo(that: ABIItem): number; } interface ABIEventData { data: Hex; topics: Array<null | Hex | Hex[]>; } /** * Represents a function call in the Event ABI. * @extends ABIItem */ declare class ABIEvent<TAbi extends Abi = Abi, TEventName extends ContractEventName<TAbi> = ContractEventName<TAbi>> extends ABIItem { private readonly abiEvent; constructor(signature: string); constructor(signature: AbiEvent); /** * Decode event log data using the event's ABI. * * @param abi - Event to decode. * @returns Decoding results. * @throws {InvalidAbiDataToEncodeOrDecode} */ static parseLog<TAbi extends Abi, TEventName extends ContractEventName<TAbi>>(abi: TAbi, eventData: ABIEventData): DecodeEventLogReturnType<TAbi, TEventName>; /** * Decode event log data using the event's ABI. * * @param event - Event to decode. * @returns Decoding results. * @throws {InvalidAbiDataToEncodeOrDecode} */ decodeEventLog(event: ABIEventData): DecodeEventLogReturnType<TAbi, TEventName>; /** * Decode event log data as an array of values * @param {ABIEvent} event The data to decode. * @returns {unknown[]} The decoded data as array of values. */ decodeEventLogAsArray(event: ABIEventData): unknown[]; /** * Encode event log data returning the encoded data and topics. * @param dataToEncode - Data to encode. * @returns {ABIEventData} Encoded data along with topics. * @remarks There is no equivalent to encodeEventLog in viem {@link https://viem.sh/docs/ethers-migration}. Discussion started here {@link https://github.com/wevm/viem/discussions/2676}. */ encodeEventLog(dataToEncode: unknown[]): ABIEventData; /** * Encode event log topics using the event's ABI. * * @param valuesToEncode - values to encode as topics. Non-indexed values are ignored. * Only the values of the indexed parameters are needed. * @returns Encoded topics array. * @throws {InvalidAbiDataToEncodeOrDecode} */ encodeFilterTopics(valuesToEncode: Record<string, unknown> | unknown[] | undefined): EncodeEventTopicsReturnType; /** * Encode event log topics using the event's ABI, replacing null values with undefined. * @param valuesToEncode - values to encode as topics. Non-indexed values are ignored. * Only the values of the indexed parameters are needed. * @returns Encoded topics array. * @throws {InvalidAbiDataToEncodeOrDecode} */ encodeFilterTopicsNoNull(valuesToEncode: Record<string, unknown> | unknown[] | undefined): Array<string | undefined>; } /** * Represents a function call in the Function ABI. * @extends ABIItem */ declare class ABIFunction<TAbi extends Abi = Abi, TFunctionName extends ContractFunctionName<TAbi> = ContractFunctionName<TAbi>> extends ABIItem { private readonly abiFunction; constructor(signature: string); constructor(signature: AbiFunction); /** * Get the function selector. * @returns {string} The function selector. * @override {@link ABIItem#signatureHash} */ get signatureHash(): string; /** * Decode data using the function's ABI. * * @param {Hex} data - Data to decode. * @returns Decoding results. * @throws {InvalidAbiDataToEncodeOrDecode} */ decodeData(data: Hex): DecodeFunctionDataReturnType<TAbi, TFunctionName>; /** * Encode data using the function's ABI. * * @param dataToEncode - Data to encode. * @returns {Hex} Encoded data. * @throws {InvalidAbiDataToEncodeOrDecode} */ encodeData<TValue>(dataToEncode?: TValue[]): Hex; /** * Decodes the output data from a transaction based on ABI (Application Binary Interface) specifications. * This method attempts to decode the given hex-like data into a readable format using the contract's interface. * * @param {Hex} data - The data to be decoded, typically representing the output of a contract function call. * @returns {DecodeFunctionResultReturnType} An object containing the decoded data. * @throws {InvalidAbiDataToEncodeOrDecode} * * @example * ```typescript * const decoded = abiFunctionInstance.decodeResult(rawTransactionOutput); * console.log('Decoded Output:', decoded); * ``` */ decodeResult(data: Hex): DecodeFunctionResultReturnType<TAbi, TFunctionName>; /** * Decodes a function output returning an array of values. * @param {Hex} data The data to be decoded * @returns {unknown[]} The decoded data as array of values */ decodeOutputAsArray(data: Hex): unknown[]; } declare class ABIContract<TAbi extends Abi> extends ABI { readonly abi: TAbi; private readonly viemABI; constructor(abi: TAbi); /** * Creates an ABIContract instance from a viem ABI. * @param {ViemABI} abi representation of the contract. * @returns New instance of ABIContract. */ static ofAbi<TAbi extends Abi>(abi: TAbi): ABIContract<TAbi>; /** * Returns the function with the given name. * @param {string} name The function's name. * @returns {ABIFunction} The function with the given name. * @throws {InvalidAbiItem} */ getFunction<TFunctionName extends ContractFunctionName<TAbi>>(name: TFunctionName | string): ABIFunction<TAbi, TFunctionName>; /** * Returns the event with the given name. * @param {string} name The event's name. * @returns {ABIEvent} The event with the given name. * @throws {InvalidAbiItem} */ getEvent<TEventName extends ContractEventName<TAbi>>(name: TEventName | string): ABIEvent<TAbi, TEventName>; /** * Encode function data that can be used to send a transaction. * @param {string} functionName The name of the function defined in the ABI. * @param {unknown[]} functionData The data to pass to the function. * @returns {Hex} The encoded data in hexadecimal that can be used to send a transaction. * @throws {InvalidAbiDataToEncodeOrDecode} */ encodeFunctionInput<TFunctionName extends ContractFunctionName<TAbi>>(functionName: TFunctionName | string, functionData?: unknown[]): Hex; /** * Decode the function data of an encoded function * @param {string} functionName The name of the function defined in the ABI. * @param {Hex} encodedFunctionInput The encoded function data. * @returns {DecodeFunctionDataReturnType} an array of the decoded function data * @throws {InvalidAbiDataToEncodeOrDecode} */ decodeFunctionInput<TFunctionName extends ContractFunctionName<TAbi>>(functionName: TFunctionName | string, encodedFunctionInput: Hex): DecodeFunctionDataReturnType<TAbi, TFunctionName>; /** * Decodes the output from a contract function using the specified ABI and function name. * It takes the encoded function output and attempts to decode it according to the ABI definition. * * @param {string} functionName - The name of the function in the contract to decode the output for. * @param {Hex} encodedFunctionOutput - The encoded output data from the contract function. * @returns {DecodeFunctionResultReturnType} - The decoded output, which provides a user-friendly way * to interact with the decoded data. * @throws {InvalidAbiDataToEncodeOrDecode} * * @example * // Example of decoding output for a function called "getValue": * const decodedOutput = decodeFunctionOutput('getValue', encodedValue); * */ decodeFunctionOutput<TFunctionName extends ContractFunctionName<TAbi>>(functionName: TFunctionName | string, encodedFunctionOutput: Hex): DecodeFunctionResultReturnType<TAbi, TFunctionName>; /** * Encodes event log data based on the provided event name, and data to encode. * @param {string} eventName - The name of the event to be encoded. * @param {unknown[]} eventArgs - An array of data to be encoded in the event log. * @returns {ABIEventData} An object containing the encoded data and topics. * @throws {InvalidAbiDataToEncodeOrDecode} */ encodeEventLog<TEventName extends ContractEventName<TAbi>>(eventName: TEventName | string, eventArgs: unknown[]): ABIEventData; /** * Decodes event log data based on the provided event name, and data/topics to decode. * @param {string} eventName - The name of the event to be decoded. * @param {ABIEventData} eventToDecode - An object containing the data and topics to be decoded. * @returns {DecodeEventLogReturnType} The decoded data of the event log. * @throws {InvalidAbiDataToEncodeOrDecode} */ decodeEventLog<TEventName extends ContractEventName<TAbi>>(eventName: TEventName | string, eventToDecode: ABIEventData): DecodeEventLogReturnType<TAbi, TEventName>; /** * Decodes a VeChain log based on the ABI definition. * * This method takes raw `data` and `topics` from a VeChain log and a