UNPKG

@vechain/sdk-network

Version:

This module serves as the standard interface connecting decentralized applications (dApps) and users to the VeChainThor blockchain

1,687 lines (1,518 loc) 262 kB
import { ABIEvent, TransactionClause, Revision, TransactionBody as TransactionBody$1, VET, VTHO, Address, HexUInt, BlockId, ClauseOptions, ContractClause, ABIFunction, DeployParams, Hex, Transaction, Clause } from '@vechain/sdk-core'; import { TypedDataDomain as TypedDataDomain$1, TypedDataParameter as TypedDataParameter$1, GetEventArgs, AbiEvent } from 'viem'; import { EventEmitter } from 'events'; import { Abi, ExtractAbiFunctionNames, AbiFunction, AbiParametersToPrimitiveTypes, ExtractAbiFunction, ExtractAbiEvent, ExtractAbiEventNames } from 'abitype'; import { JsonRpcApiProvider, JsonRpcPayload, JsonRpcResult, JsonRpcError } from 'ethers'; /** * Enumeration for HTTP methods. * * @property {string} GET - The GET method requests a representation of the specified resource. * @property {string} POST - The POST method is used to submit data to be processed to a specified resource. */ declare enum HttpMethod { GET = "GET", POST = "POST" } /** * Represents the parameters for making an HTTP request. * * This interface specifies options for configuring an HTTP request, * including query parameters, request body, custom headers, * and a function to validate response headers. */ interface HttpParams { /** * The request body, which can be of any type. */ body?: unknown; /** * Raw request body to be sent as-is without JSON.stringify. * If provided, this takes precedence over `body`. */ rawBody?: string | Uint8Array; /** * Custom headers to be included in the request. */ headers?: Record<string, string>; /** * Query parameters to include in the request. */ query?: Record<string, string>; /** * A callback function to validate response headers. * @param headers - The response headers to validate. */ validateResponseHeader?: (headers: Record<string, string>) => void; } /** * Interface representing an HTTP client. * * The HttpClient interface provides methods for making HTTP requests */ interface HttpClient { /** * The base URL for the API requests. * This endpoint serves as the root URL for constructing all subsequent API calls. */ baseURL: string; /** * Makes an HTTP GET request to the specified path with optional query parameters. * * @param {string} path - The endpoint path for the GET request. * @param {HttpParams} [params] - Optional query parameters to include in the request. * @return {Promise<unknown>} A promise that resolves to the response of the GET request. */ get: (path: string, params?: HttpParams) => Promise<unknown>; /** * Sends an HTTP request using the specified method, path, and optional parameters. * * @param {HttpMethod} method - The HTTP method to be used for the request (e.g., 'GET', 'POST'). * @param {string} path - The endpoint path for the HTTP request. * @param {HttpParams} [params] - Optional parameters to include in the HTTP request. * @returns {Promise<unknown>} A promise that resolves with the response of the HTTP request. */ http: (method: HttpMethod, path: string, params?: HttpParams) => Promise<unknown>; /** * Sends a POST request to the specified path with the given parameters. * * @param {string} path - The endpoint to which the POST request is sent. * @param {HttpParams} [params] - Optional parameters to be included in the POST request body. * @returns {Promise<unknown>} - A promise that resolves to the response of the POST request. */ post: (path: string, params?: HttpParams) => Promise<unknown>; } /** * This class implements the HttpClient interface using the Fetch API. * * The SimpleHttpClient allows making {@link HttpMethod} requests with timeout * and base URL configuration. */ declare class SimpleHttpClient implements HttpClient { /** * Represent the default timeout duration for network requests in milliseconds. */ static readonly DEFAULT_TIMEOUT = 10000; /** * Return the root URL for the API endpoints. */ readonly baseURL: string; readonly headers: HeadersInit; /** * Return the amount of time in milliseconds before a timeout occurs * when requesting with HTTP methods. */ readonly timeout: number; /** * Constructs an instance of SimpleHttpClient with the given base URL, * timeout period and HTTP headers. * The HTTP headers are used each time this client send a request to the URL, * if not overwritten by the {@link HttpParams} of the method sending the request. * * @param {string} baseURL - The base URL for HTTP requests. * @param {HeadersInit} [headers=new Headers()] - The default headers for HTTP requests. * @param {number} [timeout=SimpleHttpClient.DEFAULT_TIMEOUT] - The timeout duration in milliseconds. */ constructor(baseURL: string, headers?: HeadersInit, timeout?: number); /** * Sends an HTTP GET request to the specified path with optional query parameters. * * @param {string} path - The endpoint path to which the HTTP GET request is sent. * @param {HttpParams} [params] - Optional parameters for the request, * including query parameters, headers, body, and response validation. * {@link HttpParams.headers} override {@link SimpleHttpClient.headers}. * @return {Promise<unknown>} A promise that resolves with the response of the GET request. */ get(path: string, params?: HttpParams): Promise<unknown>; /** * Determines if specified url is valid * @param {string} url Url to check * @returns {boolean} if value */ private isValidUrl; /** * Executes an HTTP request with the specified method, path, and optional parameters. * * @param {HttpMethod} method - The HTTP method to use for the request (e.g., GET, POST). * @param {string} path - The URL path for the request. Leading slashes will be automatically removed. * @param {HttpParams} [params] - Optional parameters for the request, * including query parameters, headers, body, and response validation. * {@link HttpParams.headers} override {@link SimpleHttpClient.headers}. * @return {Promise<unknown>} A promise that resolves to the response of the HTTP request. * @throws {InvalidHTTPRequest} Throws an error if the HTTP request fails. */ http(method: HttpMethod, path: string, params?: HttpParams): Promise<unknown>; /** * Makes an HTTP POST request to the specified path with optional parameters. * * @param {string} path - The endpoint to which the POST request is made. * @param {HttpParams} [params] - Optional parameters for the request, * including query parameters, headers, body, and response validation. * {@link HttpParams.headers} override {@link SimpleHttpClient.headers}. * @return {Promise<unknown>} A promise that resolves with the response from the server. */ post(path: string, params?: HttpParams): Promise<unknown>; } /** * HTTP trace logger for detailed request/response logging * * This logger is only activated when the SDK_TRACE environment variable is set to 'true' * It helps developers debug the exact HTTP traffic between the SDK and Thor nodes */ /** * Checks if trace logging is enabled via environment variable */ declare const isTraceEnabled: () => boolean; /** * Interface for HTTP trace log data */ interface TraceLogData { category: string; method?: string; url?: string; requestHeaders?: Record<string, string>; requestBody?: unknown; responseHeaders?: Record<string, string>; responseBody?: unknown; timestamp: number; duration?: number; error?: unknown; } /** * Logs HTTP request details before sending */ declare const logRequest: (method: string, url: string, headers?: Record<string, string>, body?: unknown) => number; /** * Logs HTTP response details after receiving */ declare const logResponse: (startTimestamp: number, url: string, responseHeaders?: Record<string, string>, responseBody?: unknown) => void; /** * Logs HTTP error details */ declare const logError: (startTimestamp: number, url: string, method: string, error: unknown) => void; // @NOTE: Errors handling (https://eips.ethereum.org/EIPS/eip-1193#errors) will be delegated to `errors` package /** * Interface for EIP-1193 provider request arguments. * * @see https://eips.ethereum.org/EIPS/eip-1193#request */ interface EIP1193RequestArguments { readonly method: string; readonly params?: unknown[]; } /** * Standardized provider interface for EIP-1193. * * @see https://eips.ethereum.org/EIPS/eip-1193#message * * The Final usage will be: * * ```typescript * EIP1193ProviderMessage.request(args: EIP1193RequestArguments): Promise<unknown>; * ``` */ interface EIP1193ProviderMessage { request: (args: EIP1193RequestArguments) => Promise<unknown>; } /* --- Input options start --- */ /** * Range interface for specifying a range of data. */ interface Range { /** * The unit for specifying the range (block or time). */ unit?: 'block' | 'time'; // The unit for specifying the range (block or time). /** * The starting point of the range. */ from?: number; /** * The ending point of the range. */ to?: number; } /** * Options interface for specifying Pagination Options (offset and limits). */ interface PaginationOptions { /** * Offset for pagination. */ offset?: number; /** * Limit for the number of results to return. */ limit?: number; } /** * FilterCriteria interface for filtering event logs. */ interface FilterCriteria { criteria: EventCriteria; eventAbi: ABIEvent; } /** * EventCriteria interface for filtering event logs. */ interface EventCriteria { /** * Address filter for event criteria. */ address?: string; /** * Event topics filter. */ topic0?: string; topic1?: string; topic2?: string; topic3?: string; topic4?: string; } /** * Order interface for filtering event logs. */ type EventDisplayOrder = 'asc' | 'desc'; /** * FilterRawEventLogsArg interface for filtering raw event logs. */ interface FilterRawEventLogsOptions { /** * Block range */ range?: Range; /** * Pagination options */ options?: PaginationOptions; /** * Event filters */ criteriaSet?: EventCriteria[]; /** * Sorting order */ order?: EventDisplayOrder; } /** * FilterEventLogsArg interface for filtering decoded event logs. */ interface FilterEventLogsOptions { /** * Block range */ range?: Range; /** * Pagination options */ options?: PaginationOptions; /** * Event filters */ criteriaSet?: FilterCriteria[]; /** * Sorting order */ order?: EventDisplayOrder; } /** * FilterTransferLogsArg interface for filtering transfer logs. */ interface FilterTransferLogsOptions { /** * Block range to query */ range?: Range; /** * Pagination options */ options?: PaginationOptions; /** * Criteria to filter transfers by */ criteriaSet: TransferCriteria[]; /** * Ordering of results */ order: EventDisplayOrder; } /* --- Input options end --- */ /* --- Responses Outputs start --- */ /** * Event metadata for an entity. */ interface Metadata { /** * Block identifier associated with the entity */ blockID: string; /** * Block number associated with the entity */ blockNumber: number; /** * Timestamp of the block */ blockTimestamp: number; /** * Transaction ID associated with the entity */ txID: string; /** * Transaction origin information */ txOrigin: string; /** * Index of the clause */ clauseIndex: number; } /** * TransferCriteria interface for filtering transfer logs. */ interface TransferCriteria { /** * Transaction origin filter for transfer criteria. */ txOrigin?: string; /** * Sender's address filter. */ sender?: string; /** * Recipient's address filter. */ recipient?: string; } /** * Event interface representing event data. */ interface Event { /** * The address related to the event. */ address: string; /** * Event topics or categories. */ topics: string[]; /** * Event data. */ data: string; } /** * Transfer interface representing transfer data. */ interface Transfer { /** * The sender's address in the transfer. */ sender: string; /** * The recipient's address in the transfer. */ recipient: string; /** * The amount being transferred. */ amount: string; } /** * EventLogs interface, combining Event and EventMetadata. */ interface EventLogs extends Event { /** * Event logs with associated metadata */ meta: Metadata; /** * The decoded data from the event. */ decodedData?: unknown[]; } /** * TransferLogs interface, combining Transfer and WithMeta. */ interface TransferLogs extends Transfer { /** * Transfer logs with associated metadata */ meta: Metadata; } /** * The `LogsClient` class provides methods to interact with log-related endpoints * of the VeChainThor blockchain. It allows filtering event and transfer logs. */ declare class LogsModule { readonly blocksModule: BlocksModule; constructor(blocksModule: BlocksModule); /** * Filters event logs based on the provided criteria. Raw event logs are not decoded. * * @param filterOptions - An object specifying filtering criteria for event logs. * @returns A promise that resolves to filtered event logs. */ filterRawEventLogs(filterOptions: FilterRawEventLogsOptions): Promise<EventLogs[]>; /** * Filters event logs based on the provided criteria and decodes them using the provided ABI items. * The decoded data is added to the event logs as a new property. * @param filterOptions - An object specifying filtering criteria for event logs. */ filterEventLogs(filterOptions: FilterEventLogsOptions): Promise<EventLogs[]>; /** * Filters event logs based on the provided criteria and decodes them using the provided ABI items. * The decoded data is added to the event logs as a new property. * The result is an array of event logs grouped by the event topic hash. * @param filterOptions * @returns A promise that resolves to an array of event logs grouped by event. */ filterGroupedEventLogs(filterOptions: FilterEventLogsOptions): Promise<EventLogs[][]>; /** * Filters event logs based on the provided criteria without decoding them. * @param filterOptions - An object specifying filtering criteria for event logs. * @private Returns a promise that resolves to filtered non decoded event logs. */ private getRawEventLogs; /** * Removes duplicated ABI items from the provided array. ABI items are considered duplicated if they have the same topic hash. * @param eventAbis - An array of event ABI items. * @private Returns a map of unique ABI items. */ private removeDuplicatedAbis; /** * Filters transfer logs based on the provided criteria. * * @param filterOptions - An object specifying filtering criteria for transfer logs. * @returns A promise that resolves to filtered transfer logs. */ filterTransferLogs(filterOptions: FilterTransferLogsOptions): Promise<TransferLogs[]>; } /* --- Input options start --- */ /** * Input options for Blocks module. */ interface BlocksModuleOptions { /** * (Optional) Whether the polling is enabled. */ isPollingEnabled?: boolean; /** * (Optional) Callback function called when an error occurs. */ onBlockError?: (error: Error) => undefined; } /** * Options for `waitForBlockCompressed` and `waitForBlockExpanded` methods. */ interface WaitForBlockOptions { /** * Timeout in milliseconds. * After this time, the method will throw an error. */ timeoutMs?: number; /** * Interval in milliseconds. * The method will check the blocks status every `intervalMs` milliseconds. */ intervalMs?: number; } /* --- Input options end --- */ /* --- Responses Outputs start --- */ /** * BlockDetail is an interface representing detailed information about a blockchain block. */ interface BlockDetail { /** * Unique identifier for the block. */ id: string; /** * Block number in the blockchain. */ number: number; /** * Size of the block in bytes. */ size: number; /** * Identifier of the parent block. */ parentID: string; /** * Timestamp when the block was created. */ timestamp: number; /** * Maximum gas limit for transactions in the block. */ gasLimit: number; /** * Address of the beneficiary (miner) of the block. */ beneficiary: string; /** * Total gas used by transactions in the block. */ gasUsed: number; /** * The minimum amount of fee required to include a transaction in the current block */ baseFeePerGas?: string; /** * Represents the Accumulated Witness Number (AWN) of the block. * It is used when selecting the trunk block in the VeChainThor consensus algorithm. * * @link see [VeChainThor Trunk](https://docs.vechain.org/introduction-to-vechain/about-the-vechain-blockchain/consensus-deep-dive#meta-transaction-features-3) */ totalScore: number; /** * Root hash of the transactions in the block. */ txsRoot: string; /** * Optional features associated with transactions. */ txsFeatures?: number; /** * Root hash of the state tree after applying transactions. */ stateRoot: string; /** * Root hash of the receipts of transactions. */ receiptsRoot: string; /** * Address of the signer or validator for the block. */ signer: string; /** * Indicates if the block contains a community fund (com). */ com?: boolean; /** * Indicates if the block is finalized (optional). */ isFinalized?: boolean; /** * Since there is no computational competition in PoA, the "longest chain" rule does not apply. * Instead, we consider the better branch as the one witnessed by more AMs (Authority Master nodes). * * @link see [VeChainThor Trunk](https://docs.vechain.org/introduction-to-vechain/about-the-vechain-blockchain/consensus-deep-dive#meta-transaction-features-3) */ isTrunk: boolean; } /** * Type for the compressed block detail. * Here we have the transactions as an array of strings. */ interface CompressedBlockDetail extends BlockDetail { transactions: string[]; } /** * Type for the expanded block detail. * Here we have the transactions expanded with the details. */ interface ExpandedBlockDetail extends BlockDetail { transactions: TransactionsExpandedBlockDetail[]; } /** * Output represents the result or consequence of a blockchain transaction. */ interface Output { /** * address of the contract involved in the clause output. */ contractAddress: string | null; /** * Events emitted by executing the clause. */ events: Event[]; /** * Transfers of VET or VIP180 tokens that occur from the clause. */ transfers: Transfer[]; } /** * TransactionsExpandedBlockDetail is an interface representing detailed information about transactions in a blockchain block. */ interface TransactionsExpandedBlockDetail { /** * Unique identifier for the transaction. */ id: string; /** * Type of the transaction (ex: type 81). */ type?: number; /** * Chain tag of the blockchain. */ chainTag: string; /** * Reference to the block. */ blockRef: string; /** * Expiration timestamp of the transaction. */ expiration: number; /** * Clauses represent the individual conditions or terms in a blockchain transaction. */ clauses: TransactionClause[]; /** * The maximum amount that can be spent to pay for base fee and priority fee expressed in hex. * This is an optional hexadecimal expression or null. */ maxFeePerGas?: string | null; /** * The maximum amount that can be spent to pay for base fee and priority fee expressed in hex. * This is an optional hexadecimal expression or null. */ maxPriorityFeePerGas?: string | null; /** * Gas price coefficient for the transaction. */ gasPriceCoef?: number; /** * Gas limit for the transaction. */ gas: number; /** * Origin (sender) of the transaction. */ origin: string; /** * The address of the gas-payer of the transaction. * * **NOTE!** * * * The property name `delegator` is exposed by * [Tx](https://mainnet.vechain.org/doc/stoplight-ui/#/schemas/Tx) * response of the end-point * [Retrieve a block](https://mainnet.vechain.org/doc/stoplight-ui/#/paths/blocks-revision/get) * with query set as `?expanded=true`. * * In the rest of the SDK the address of the sponsor of the transaction is exposed by properties named * `gasPayer`. * It's suggested to read as "delegated" the term written as "delegator". * * This interface exposes the property {@link gasPayer} to express the address of the sponsor of the * transaction, either {@link origin} or {@link delegator}. */ delegator: string; /** * Nonce value for preventing replay attacks. */ nonce: string; /** * Transaction dependency. */ dependsOn: string; /** * Size of the transaction in bytes. */ size: number; /** * Gas used by the transaction. */ gasUsed: number; /** * Account paying for the gas. */ gasPayer: string; /** * Amount paid for the transaction. */ paid: string; /** * Reward associated with the transaction. */ reward: string; /** * Indicates if the transaction is reverted. */ reverted: boolean; /** * Outputs represent the results or consequences of a blockchain transaction. */ outputs: Output[]; } /** The `BlocksModule` class encapsulates functionality for interacting with blocks * on the VeChainThor blockchain. */ declare class BlocksModule { readonly httpClient: HttpClient; /** * The head block (best block). This is updated by the event poll instance every time a new block is produced. * @private */ private headBlock; /** * Error handler for block-related errors. */ onBlockError?: (error: Error) => undefined; /** * The Poll instance for event polling * @private */ private pollInstance?; /** * Initializes a new instance of the `Thor` class. * @param httpClient - The Thor instance used to interact with the VeChain blockchain API. * @param options - (Optional) Other optional parameters for polling and error handling. */ constructor(httpClient: HttpClient, options?: BlocksModuleOptions); /** * Destroys the instance by stopping the event poll. */ destroy(): void; /** * Sets up the event polling for the best block. * @private * */ private setupPolling; /** * Retrieves details of a compressed specific block identified by its revision (block number or ID). * * @param revision - The block number or ID to query details for. * @returns A promise that resolves to an object containing the details of the compressed block. * @throws {InvalidDataType} */ getBlockCompressed(revision: string | number): Promise<CompressedBlockDetail | null>; /** * Retrieves details of an expanded specific block identified by its revision (block number or ID). * * @param revision - The block number or ID to query details for. * @returns A promise that resolves to an object containing the details of the expanded block. * @throws {InvalidDataType} */ getBlockExpanded(revision: string | number): Promise<ExpandedBlockDetail | null>; /** * Retrieves details of the latest block. * * @returns A promise that resolves to an object containing the compressed block details. */ getBestBlockCompressed(): Promise<CompressedBlockDetail | null>; /** * Retrieves details of the latest block. * * @returns A promise that resolves to an object containing the expanded block details. */ getBestBlockExpanded(): Promise<ExpandedBlockDetail | null>; /** * Retrieves the base fee per gas of the best block. * * @returns A promise that resolves to the base fee per gas of the best block. */ getBestBlockBaseFeePerGas(): Promise<string | null>; /** * Asynchronously retrieves a reference to the best block in the blockchain. * * This method first calls `getBestBlockCompressed()` to obtain the current best block. If no block is found (i.e., if `getBestBlockCompressed()` returns `null`), * the method returns `null` indicating that there's no block to reference. Otherwise, it extracts and returns the first 18 characters of the * block's ID, providing the ref to the best block. * * @returns {Promise<string | null>} A promise that resolves to either a string representing the first 18 characters of the best block's ID, * or `null` if no best block is found. * * @Example: * const blockRef = await getBestBlockRef(); * if (blockRef) { * console.log(`Reference to the best block: ${blockRef}`); * } else { * console.log("No best block found."); * } */ getBestBlockRef(): Promise<string | null>; /** * Retrieves the finalized block. * * @returns A promise that resolves to an object containing the finalized block. */ getFinalBlockCompressed(): Promise<CompressedBlockDetail | null>; /** * Retrieves details of the finalized block. * * @returns A promise that resolves to an object containing the finalized block details. */ getFinalBlockExpanded(): Promise<ExpandedBlockDetail | null>; /** * Synchronously waits for a specific block revision using polling. * * @param blockNumber - The block number to wait for. * @param expanded - A boolean indicating whether to wait for an expanded block. * @param options - (Optional) Allows to specify timeout and interval in milliseconds * @returns A promise that resolves to an object containing the compressed block. * @throws {InvalidDataType} */ private _waitForBlock; /** * Synchronously waits for a specific block revision using polling. * * @param blockNumber - The block number to wait for. * @param options - (Optional) Allows to specify timeout and interval in milliseconds * @returns A promise that resolves to an object containing the compressed block. */ waitForBlockCompressed(blockNumber: number, options?: WaitForBlockOptions): Promise<CompressedBlockDetail | null>; /** * Synchronously waits for a specific expanded block revision using polling. * * @param blockNumber - The block number to wait for. * @param options - (Optional) Allows to specify timeout and interval in milliseconds * @returns A promise that resolves to an object containing the expanded block details. */ waitForBlockExpanded(blockNumber: number, options?: WaitForBlockOptions): Promise<ExpandedBlockDetail | null>; /** * Returns the head block (best block). * @returns {BlockDetail | null} The head block (best block). */ getHeadBlock(): CompressedBlockDetail | null; /** * Retrieves details of the genesis block. * * @returns A promise that resolves to an object containing the block details of the genesis block. */ getGenesisBlock(): Promise<CompressedBlockDetail | null>; /** * Retrieves all addresses involved in a given block. This includes beneficiary, signer, clauses, * gas payer, origin, contract addresses, event addresses, and transfer recipients and senders. * * @param {ExpandedBlockDetail} block - The block object to extract addresses from. * * @returns {string[]} - An array of addresses involved in the block, included * empty addresses, duplicate elements are removed. * */ getAllAddressesIntoABlock(block: ExpandedBlockDetail): string[]; } /** * Transaction clause type for transaction simulation having value only string. */ type SimulateTransactionClause = TransactionClause; /* --- Input options start --- */ /** * Options for `waitForTransaction` method. */ interface WaitForTransactionOptions { /** * Timeout in milliseconds. * After this time, the method will throw an error. */ timeoutMs?: number; /** * Interval in milliseconds. * The method will check the transaction status every `intervalMs` milliseconds. */ intervalMs?: number; } /** * Options for `buildTransactionBody` method. */ interface TransactionBodyOptions { /** * 8 bytes prefix of some block's ID */ blockRef?: string; /** * Last byte of genesis block ID */ chainTag?: number; /** * The ID of the transaction that this transaction depends on. */ dependsOn?: string; /** * The expiration time of the transaction. * The transaction will expire after the number of blocks specified by this value. */ expiration?: number; /** * The maximum amount of gas to allow this transaction to consume. */ gas?: string | number; /** * The maximum amount of gas to allow this transaction to consume. * @deprecated Use `gas` instead. This property will be removed in a future release. */ gasLimit?: string; /** * The gas price to use for legacy transactions or transactions on * legacy networks. * * Most of the time the ``max*FeePerGas`` is preferred. */ gasPrice?: string; /** * Coefficient used to calculate the gas price for the transaction. * Value must be between 0 and 255. */ gasPriceCoef?: number; /** * Whether the transaction is delegated to another account for gas payment. */ isDelegated?: boolean; /** * Nonce value for various purposes. * Basic is to prevent replay attack by make transaction unique. * Every transaction with same chainTag, blockRef, ... must have different nonce. */ nonce?: string | number; /** * The maximum fee per gas for the transaction. */ maxFeePerGas?: string | number; /** * The maximum priority fee per gas for the transaction. */ maxPriorityFeePerGas?: string | number; } /** * Options for `signTransaction` method. */ type SignTransactionOptions = | { gasPayerServiceUrl: string; gasPayerPrivateKey?: never } | { gasPayerPrivateKey: string; gasPayerServiceUrl?: never }; /** * Input options for: * * getTransactionReceipt * Methods */ interface GetTransactionReceiptInputOptions { /** * (Optional) The block number or ID to reference the transaction. */ head?: string; } /** * Input options for: * * getTransaction * Methods */ type GetTransactionInputOptions = GetTransactionReceiptInputOptions & { /** * (Optional) If true, returns the pending transaction details instead of the final transaction details. */ pending?: boolean; }; /** * Type for transaction simulation options. */ interface SimulateTransactionOptions { /** * The block number or block ID of which the transaction simulation is based on */ revision?: Revision; /** * The offered gas for the transaction simulation */ gas?: string | number; /** * The price of gas for the transaction simulation */ gasPrice?: string; /** * The caller of the transaction simulation. (i.e., the address that performs the transaction) */ caller?: string; // ------ START: EXTENDED EVM CONTEXT OPTIONS ------ // /* The following options are useful when simulating transactions that provide additional context to the EVM. The additional context is handled by the built-in Extension-V2 Smart contract (https://docs.vechain.org/developer-resources/built-in-contracts#extension-v2-sol) The contract allows for smart contract developers to obtain additional context about the transaction in their smart contract code, for example: - The expiration of the transaction - The block reference of the transaction - The gas payer of the transaction - The proved work of the transaction (https://docs.vechain.org/core-concepts/transactions/transaction-calculation#proof-of-work) */ /** * The VeChainThor blockchain allows for transaction-level proof of work (PoW) and converts the proved work into extra gas price that will be used by * the system to generate more reward to the block generator, the Authority Master node, that validates the transaction. * In other words, users can utilize their local computational power to make their transactions more likely to be included in a new block. * * @link [VeChainThor Proof of Work](https://docs.vechain.org/core-concepts/transactions/transaction-calculation#proof-of-work) */ provedWork?: string; /** * The address that pays for the gas fee of the transaction simulation. * If different from the caller, then a delegated transaction is simulated. */ gasPayer?: string; /** * The expiration of the transaction simulation. * Represents how long, in terms of the number of blocks, the transaction will be allowed to be mined in VeChainThor */ expiration?: number; /** * BlockRef stores the reference to a particular block whose next block is the earliest block the current transaction can be included. * * @link [VeChainThor BlockRef](https://docs.vechain.org/core-concepts/transactions/meta-transaction-features/controllable-transaction-lifecycle) */ blockRef?: string; // ------ END: EXTENDED EVM CONTEXT OPTIONS ------ // } /* --- Input options end --- */ /* --- Responses Outputs start --- */ /** * Represents the result of sending a transaction. * * @interface SendTransactionResult */ interface SendTransactionResult { /** * The unique identifier associated with the transaction. * * @type {string} */ id: string; wait: () => Promise<TransactionReceipt | null>; } /** * Represents the result of getting a delegation signature. */ interface GetDelegationSignatureResult { /** * The signature of the transaction. */ signature: string; } /** * Transaction Metadata interface. */ interface TransactionMetadata { blockID: string; blockNumber: number; blockTimestamp: number; txID?: string; txOrigin?: string; } /** * Type for RAW transaction detail. * It is the response of `getTransaction` with `raw` set to `true`. */ interface TransactionDetailRaw { /** * Raw data */ raw: string; /** * Transaction meta data */ meta: Omit<TransactionMetadata, 'txID' | 'txOrigin'>; } /** * Type for NO RAW transaction detail. * It is the response of `getTransaction` with `raw` set to `false`. */ type TransactionDetailNoRaw = TransactionBody$1 & { id: string; origin: string; gasPayer: string | null; size: number; meta: TransactionMetadata; type: number; }; /** * Type for transaction receipt. */ interface TransactionReceipt { /** * Gas used in the transaction */ gasUsed: number; /** * For delegated transactions the gas payer * */ gasPayer: string; /** * Energy paid for used gas */ paid: string; /** * Energy reward given to block proposer */ reward: string; /** * If the transaction has been reverted */ reverted: boolean; /** * Outputs of the transaction, e.g. contract, events, transfers */ outputs: Output[]; /** * Data associated with the transaction e.g. blockID, blockNumber, txID */ meta: TransactionMetadata; /** * The maximum fee per gas for the transaction. */ maxFeePerGas?: string; /** * The maximum priority fee per gas for the transaction. */ maxPriorityFeePerGas?: string; } /** * [Event](http://127.0.0.1:8669/doc/stoplight-ui/#/schemas/Event) */ interface TransactionSimulationEvent { /** * The address of the contract that emitted the event. */ address: string; /** * Topics are indexed parameters to an event. The first topic is always the event signature. */ topics: string[]; /** * The data associated with the event. */ data: string; } /** * Type for transaction call simulation result. */ interface TransactionSimulationResult { /** * Data returned from the transaction simulation */ data: string; /** * Events emitted from the transaction simulation */ events: TransactionSimulationEvent[]; /** * Transfers that occur from the transaction simulation */ transfers: Transfer[]; /** * Gas used from the transaction simulation */ gasUsed: number; /** * Boolean indicating if the transaction simulation reverted */ reverted: boolean; /** * Error message from the transaction simulation if it reverted */ vmError: string; } /** * Available types for the VeChainProvider's * * @NOTE: We use our supported providers instead of ethers providers. * If you create a new provider, you need to add it here. */ type AvailableVeChainProviders = VeChainProvider | HardhatVeChainProvider; /** * EIP-712 types in case we change the provider (viem as of now) */ type TypedDataDomain = Omit<TypedDataDomain$1, 'chainId'> & { chainId?: number | bigint | string; }; type TypedDataParameter = TypedDataParameter$1; /** * Type for transaction input * * @note Types of the properties can differ WRT ethers.TransactionRequest */ interface TransactionRequestInput { /** * The target of the transaction. */ to?: null | string; /** * The sender of the transaction. */ from?: null | string; /** * Nonce value for various purposes. * Basic is to prevent replay attack by make transaction unique. * Every transaction with same chainTag, blockRef, ... must have different nonce. */ nonce?: string | number; /** * The maximum amount of gas to allow this transaction to consume. */ gas?: string | number; /** * The maximum amount of gas to allow this transaction to consume. * @deprecated Use `gas` instead. This property will be removed in a future release. */ gasLimit?: string; /** * The gas price to use for legacy transactions or transactions on * legacy networks. * * Most of the time the ``max*FeePerGas`` is preferred. */ gasPrice?: string; /** * Coefficient used to calculate the gas price for the transaction. * Value must be between 0 and 255. */ gasPriceCoef?: number; /** * The transaction data. */ data?: string; /** * The transaction value (in wei). */ value?: string | number; /** * When using ``call`` or ``estimateGas``, this allows a specific * block to be queried. Many backends do not support this and when * unsupported errors are silently squelched and ``"latest"`` is used. */ blockTag?: string; /** * Add clauses to ethers.TransactionRequest */ clauses?: TransactionClause[]; /** * The ID of the transaction that this transaction depends on. */ dependsOn?: string; /** * The expiration time of the transaction. * The transaction will expire after the number of blocks specified by this value. */ expiration?: number; /** * 8 bytes prefix of some block's ID */ blockRef?: string; /** * Last byte of genesis block ID */ chainTag?: number; /** * A reserved field intended for features use. * * In standard EVM transactions, this reserved field typically is not present. * However, it's been designed to cater to VIP-191, which deals with fee delegation. * * If the `features` within the `reserved` field is set as `1111...111`, it indicates that the transaction has been delegated. * The method to check if the transaction is delegated is: * * ```typescript * reserved.features & 1 === 1 * ``` * * @example * * 1. * ```typescript * feature = 111101; * isDelegated = (111101 & 111111) === 111101; // false (not delegated) * ``` * * 2. * ```typescript * feature = 111111; * isDelegated = (111111 & 111111) === 111111; // true (delegated) * ``` * * @remarks * For more information on the subject, refer to {@link https://github.com/vechain/VIPs/blob/master/vips/VIP-191.md | VIP-191}. */ reserved?: { /** * Tx feature bits */ features?: number; /** * Unused */ unused?: Uint8Array[]; }; /** * The VeChainThor blockchain allows for transaction-level proof of work (PoW) and converts the proved work into extra gas price that will be used by * the system to generate more reward to the block generator, the Authority Masternode, that validates the transaction. * In other words, users can utilize their local computational power to make their transactions more likely to be included in a new block. * * @link [VeChainThor Proof of Work](https://docs.vechain.org/core-concepts/transactions/transaction-calculation#proof-of-work) */ provedWork?: string; /** * The address that pays for the gas fee of the transaction simulation. * If different from the caller, then a delegated transaction is simulated. */ gasPayer?: string; /** * The delegation URL to use to sponsor the transaction. */ delegationUrl?: string; /** * A comment describing the transaction request. */ comment?: string; // START: NOT SUPPORTED FIELDS in VeChain BUT added to take compatibility with ethers /** * The chain ID for the network this transaction is valid on. */ chainId?: string; /** * The [[link-eip-2930]] access list. Storage slots included in the access * list are //warmed// by preloading them, so their initial cost to * fetch is guaranteed, but then each additional access is cheaper. */ // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents accessList?: null | AccessListish; /** * A custom object, which can be passed along for network-specific * values. */ customData?: unknown; /** * The [[link-eip-1559]] maximum priority fee to pay per gas. */ maxPriorityFeePerGas?: string | number; /** * The [[link-eip-1559]] maximum total fee to pay per gas. The actual * value used is protocol enforced to be the block's base fee. */ maxFeePerGas?: string | number; /** * The transaction type. */ type?: null | number; /** * When using ``call``, this enables CCIP-read, which permits the * provider to be redirected to web-based content during execution, * which is then further validated by the contract. * * There are potential security implications allowing CCIP-read, as * it could be used to expose the IP address or user activity during * the fetch to unexpected parties. */ enableCcipRead?: boolean; // END: NOT SUPPORTED FIELDS in VeChain BUT added to take compatibility with ethers } /** * Options for signing typed data * * @NOTE: To enhance compatibility with extension and mobile and to allow account switching when signing typed data, we define this interface. */ interface SignTypedDataOptions { signer?: string; } /** * A signer for VeChain, adding specific methods for VeChain to the ethers signer * * @NOTE: Su support completely our providers (that already support ethers provider format) * We use our supported providers instead of ethers providers */ interface VeChainSigner { /** * The provider attached to this Signer (if any). */ provider?: AvailableVeChainProviders; /** * Returns a new instance of this Signer connected to //provider// or detached * from any Provider if undefined. * * @param provider - The provider to connect to * @returns a new instance of this Signer connected to //provider// or detached */ connect: (provider: AvailableVeChainProviders) => this; /** * Get the address of the Signer. * * @returns the address of the signer */ getAddress: () => Promise<string>; /** * Gets the next nonce required for this Signer to send a transaction. * * @param blockTag - The blocktag to base the transaction count on, keep in mind * many nodes do not honour this value and silently ignore it [default: ``"latest"``] * * @NOTE: This method generates a random number as nonce. It is because the nonce in VeChain is a 6-byte number. */ getNonce: (blockTag?: string) => Promise<string>; /** * Prepares a {@link TransactionRequestInput} for calling: * - resolves ``to`` and ``from`` addresses * - if ``from`` is specified, check that it matches this Signer * * @note: Here the base support of multi-clause transaction is added. * So, if clauses are provided in the transaction, it will be used as it is. * Otherwise, standard transaction will be prepared. * * @param transactionToPopulate - The call to prepare * @returns the prepared call transaction */ populateCall: ( transactionToPopulate: TransactionRequestInput ) => Promise<TransactionRequestInput>; /** * Prepares a {@link TransactionRequestInput} for sending to the network by * populating any missing properties: * - resolves ``to`` and ``from`` addresses * - if ``from`` is specified , check that it matches this Signer * - populates ``nonce`` via ``signer.getNonce("pending")`` * - populates gas parameters via ``signer.estimateGas(tx)`` * - ... and other necessary properties * * @param transactionToPopulate - The call to prepare * @returns the prepared transaction */ populateTransaction: ( transactionToPopulate: TransactionRequestInput ) => Promise<TransactionBody>; /** * Estimates the required gas required to execute //tx// on the Blockchain. This * will be the expected amount a transaction will require * to successfully run all the necessary computations and store the needed state * that the transaction intends. * * @param transactionToEstimate - The transaction to estimate gas for * @returns the total estimated gas required */ estimateGas: ( transactionToEstimate: TransactionRequestInput ) => Promise<number>; /** * Evaluates the //tx// by running it against the current Blockchain state. This * cannot change state and has no cost, as it is effectively simulating * execution. * * This can be used to have the Blockchain perform computations based on its state * (e.g. running a Contract's getters) or to simulate the effect of a transaction * before actually performing an operation. * * @param transactionToEvaluate - The transaction to evaluate * @param revision - The revision to evaluate the transaction against * @returns the result of the evaluation */ call: ( transactionToEvaluate: TransactionRequestInput, revision?: Revision ) => Promise<string>; /** * Signs %%transactionToSign%%, returning the fully signed transaction. This does not * populate any additional properties within the transaction. * * @param transactionToSign - The transaction to sign * @returns The fully signed transaction */ signTransaction: ( transactionToSign: TransactionRequestInput ) => Promise<string>; /** * Sends %%transactionToSend%% to the Network. The ``signer.populateTransaction(transactionToSend)`` * is called first to ensure all necessary properties for the * transaction to be valid have been populated first. * * @param transactionToSend - The transaction to send * @returns The transaction response */ sendTransaction: ( transactionToSend: TransactionRequestInput ) => Promise<string>; /** * Signs an [[link-eip-191]] prefixed a personal message. * * If the %%message%% is a string, it is signed as UTF-8 encoded byte