diff --git a/.changeset/friendly-carpets-work.md b/.changeset/friendly-carpets-work.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/friendly-carpets-work.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/packages/account/src/account.ts b/packages/account/src/account.ts index 78068b920f5..cb759c12a9b 100644 --- a/packages/account/src/account.ts +++ b/packages/account/src/account.ts @@ -70,6 +70,9 @@ export class Account extends AbstractAccount { */ protected _provider?: Provider; + /** + * The connector for use with external wallets + */ protected _connector?: FuelConnector; /** @@ -77,6 +80,7 @@ export class Account extends AbstractAccount { * * @param address - The address of the account. * @param provider - A Provider instance (optional). + * @param connector - A FuelConnector instance (optional). */ constructor(address: string | AbstractAddress, provider?: Provider, connector?: FuelConnector) { super(); @@ -123,12 +127,12 @@ export class Account extends AbstractAccount { /** * Retrieves resources satisfying the spend query for the account. * - * @param quantities - IDs of coins to exclude. - * @param excludedIds - IDs of resources to be excluded from the query. + * @param quantities - Quantities of resources to be obtained. + * @param excludedIds - IDs of resources to be excluded from the query (optional). * @returns A promise that resolves to an array of Resources. */ async getResourcesToSpend( - quantities: CoinQuantityLike[] /** IDs of coins to exclude */, + quantities: CoinQuantityLike[], excludedIds?: ExcludeResourcesOption ): Promise { return this.provider.getResourcesToSpend(this.address, quantities, excludedIds); @@ -137,7 +141,7 @@ export class Account extends AbstractAccount { /** * Retrieves coins owned by the account. * - * @param assetId - The asset ID of the coins to retrieve. + * @param assetId - The asset ID of the coins to retrieve (optional). * @returns A promise that resolves to an array of Coins. */ async getCoins(assetId?: BytesLike): Promise { @@ -206,7 +210,7 @@ export class Account extends AbstractAccount { /** * Retrieves the balance of the account for the given asset. * - * @param assetId - The asset ID to check the balance for. + * @param assetId - The asset ID to check the balance for (optional). * @returns A promise that resolves to the balance amount. */ async getBalance(assetId?: BytesLike): Promise { @@ -255,7 +259,7 @@ export class Account extends AbstractAccount { * @typeParam T - The type of the TransactionRequest. * @param request - The transaction request to fund. * @param params - The estimated transaction parameters. - * @returns The funded transaction request. + * @returns A promise that resolves to the funded transaction request. */ async fund(request: T, params: EstimatedTxParams): Promise { const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee } = params; @@ -370,18 +374,14 @@ export class Account extends AbstractAccount { * * @param destination - The address of the destination. * @param amount - The amount of coins to transfer. - * @param assetId - The asset ID of the coins to transfer. - * @param txParams - The transaction parameters (gasLimit, tip, maturity, maxFee, witnessLimit). + * @param assetId - The asset ID of the coins to transfer (optional). + * @param txParams - The transaction parameters (optional). * @returns A promise that resolves to the prepared transaction request. */ async createTransfer( - /** Address of the destination */ destination: string | AbstractAddress, - /** Amount of coins */ amount: BigNumberish, - /** Asset ID of coins */ assetId?: BytesLike, - /** Tx Params */ txParams: TxParamsType = {} ): Promise { let request = new ScriptTransactionRequest(txParams); @@ -395,18 +395,14 @@ export class Account extends AbstractAccount { * * @param destination - The address of the destination. * @param amount - The amount of coins to transfer. - * @param assetId - The asset ID of the coins to transfer. - * @param txParams - The transaction parameters (gasLimit, maturity). + * @param assetId - The asset ID of the coins to transfer (optional). + * @param txParams - The transaction parameters (optional). * @returns A promise that resolves to the transaction response. */ async transfer( - /** Address of the destination */ destination: string | AbstractAddress, - /** Amount of coins */ amount: BigNumberish, - /** Asset ID of coins */ assetId?: BytesLike, - /** Tx Params */ txParams: TxParamsType = {} ): Promise { const request = await this.createTransfer(destination, amount, assetId, txParams); @@ -472,18 +468,14 @@ export class Account extends AbstractAccount { * * @param contractId - The address of the contract. * @param amount - The amount of coins to transfer. - * @param assetId - The asset ID of the coins to transfer. - * @param txParams - The optional transaction parameters. + * @param assetId - The asset ID of the coins to transfer (optional). + * @param txParams - The transaction parameters (optional). * @returns A promise that resolves to the transaction response. */ async transferToContract( - /** Contract address */ contractId: string | AbstractAddress, - /** Amount of coins */ amount: BigNumberish, - /** Asset ID of coins */ assetId?: BytesLike, - /** Tx Params */ txParams: TxParamsType = {} ): Promise { if (bn(amount).lte(0)) { @@ -531,15 +523,12 @@ export class Account extends AbstractAccount { * * @param recipient - Address of the recipient on the base chain. * @param amount - Amount of base asset. - * @param txParams - The optional transaction parameters. + * @param txParams - The transaction parameters (optional). * @returns A promise that resolves to the transaction response. */ async withdrawToBaseLayer( - /** Address of the recipient on the base chain */ recipient: string | AbstractAddress, - /** Amount of base asset */ amount: BigNumberish, - /** Tx Params */ txParams: TxParamsType = {} ): Promise { const recipientAddress = Address.fromAddressOrString(recipient); @@ -576,7 +565,14 @@ export class Account extends AbstractAccount { return this.sendTransaction(request); } - /** @hidden * */ + /** + * Sign a message from the account via the connector. + * + * @param message - the message to sign. + * @returns a promise that resolves to the signature. + * + * @hidden + */ async signMessage(message: string): Promise { if (!this._connector) { throw new FuelError(ErrorCode.MISSING_CONNECTOR, 'A connector is required to sign messages.'); @@ -585,7 +581,7 @@ export class Account extends AbstractAccount { } /** - * Signs a transaction with the wallet's private key. + * Signs a transaction from the account via the connector.. * * @param transactionRequestLike - The transaction request to sign. * @returns A promise that resolves to the signature of the transaction. @@ -604,6 +600,7 @@ export class Account extends AbstractAccount { * Sends a transaction to the network. * * @param transactionRequestLike - The transaction request to be sent. + * @param sendTransactionParams - The provider send transaction parameters (optional). * @returns A promise that resolves to the transaction response. */ async sendTransaction( @@ -629,6 +626,7 @@ export class Account extends AbstractAccount { * Simulates a transaction. * * @param transactionRequestLike - The transaction request to be simulated. + * @param estimateTxParams - The estimate transaction params (optional). * @returns A promise that resolves to the call result. */ async simulateTransaction( diff --git a/packages/account/src/providers/provider.ts b/packages/account/src/providers/provider.ts index 12a3a67871e..d032c7afcd5 100644 --- a/packages/account/src/providers/provider.ts +++ b/packages/account/src/providers/provider.ts @@ -292,22 +292,39 @@ export type ProviderOptions = { }; /** - * UTXO Validation Param + * UTXO validation params */ export type UTXOValidationParams = { utxoValidation?: boolean; }; /** - * Transaction estimation Param + * Transaction estimation params */ export type EstimateTransactionParams = { + /** + * Estimate the transaction dependencies. + */ estimateTxDependencies?: boolean; }; export type TransactionCostParams = EstimateTransactionParams & { + /** + * The account that will provide the resources for the transaction. + */ resourcesOwner?: AbstractAccount; + + /** + * The quantities to forward to the contract. + */ quantitiesToContract?: CoinQuantity[]; + + /** + * A callback to sign the transaction. + * + * @param request - The transaction request to sign. + * @returns A promise that resolves to the signed transaction request. + */ signatureCallback?: (request: ScriptTransactionRequest) => Promise; }; @@ -325,7 +342,6 @@ export type ProviderSendTxParams = EstimateTransactionParams & { * * If set to true, the promise will resolve only when the transaction changes status * from `SubmittedStatus` to one of `SuccessStatus`, `FailureStatus` or `SqueezedOutStatus`. - * */ awaitExecution?: boolean; }; @@ -347,12 +363,15 @@ export default class Provider { operations: ReturnType; cache?: MemoryCache; + /** @hidden */ static clearChainAndNodeCaches() { Provider.nodeInfoCache = {}; Provider.chainInfoCache = {}; } + /** @hidden */ private static chainInfoCache: ChainInfoCache = {}; + /** @hidden */ private static nodeInfoCache: NodeInfoCache = {}; options: ProviderOptions = { @@ -362,6 +381,9 @@ export default class Provider { retryOptions: undefined, }; + /** + * @hidden + */ private static getFetchFn(options: ProviderOptions): NonNullable { const { retryOptions, timeout } = options; @@ -384,12 +406,10 @@ export default class Provider { * Constructor to initialize a Provider. * * @param url - GraphQL endpoint of the Fuel node - * @param chainInfo - Chain info of the Fuel node * @param options - Additional options for the provider * @hidden */ protected constructor( - /** GraphQL endpoint of the Fuel node */ public url: string, options: ProviderOptions = {} ) { @@ -402,10 +422,13 @@ export default class Provider { /** * Creates a new instance of the Provider class. This is the recommended way to initialize a Provider. + * * @param url - GraphQL endpoint of the Fuel node * @param options - Additional options for the provider + * + * @returns A promise that resolves to a Provider instance. */ - static async create(url: string, options: ProviderOptions = {}) { + static async create(url: string, options: ProviderOptions = {}): Promise { const provider = new Provider(url, options); await provider.fetchChainAndNodeInfo(); return provider; @@ -413,8 +436,10 @@ export default class Provider { /** * Returns the cached chainInfo for the current URL. + * + * @returns the chain information configuration. */ - getChain() { + getChain(): ChainInfo { const chain = Provider.chainInfoCache[this.url]; if (!chain) { throw new FuelError( @@ -427,8 +452,10 @@ export default class Provider { /** * Returns the cached nodeInfo for the current URL. + * + * @returns the node information configuration. */ - getNode() { + getNode(): NodeInfo { const node = Provider.nodeInfoCache[this.url]; if (!node) { throw new FuelError( @@ -460,8 +487,11 @@ export default class Provider { /** * Updates the URL for the provider and fetches the consensus parameters for the new URL, if needed. + * + * @param url - The URL to connect to. + * @param options - Additional options for the provider. */ - async connect(url: string, options?: ProviderOptions) { + async connect(url: string, options?: ProviderOptions): Promise { this.url = url; this.options = options ?? this.options; this.operations = this.createOperations(); @@ -469,9 +499,9 @@ export default class Provider { } /** - * Fetches both the chain and node information, saves it to the cache, and return it. + * Return the chain and node information. * - * @returns NodeInfo and Chain + * @returns A promise that resolves to the Chain and NodeInfo. */ async fetchChainAndNodeInfo() { const chain = await this.fetchChain(); @@ -485,6 +515,9 @@ export default class Provider { }; } + /** + * @hidden + */ private static ensureClientVersionIsSupported(nodeInfo: NodeInfo) { const { isMajorSupported, isMinorSupported, supportedVersion } = checkFuelCoreVersionCompatibility(nodeInfo.nodeVersion); @@ -504,6 +537,7 @@ Supported fuel-core version: ${supportedVersion}.` * Create GraphQL client and set operations. * * @returns The operation SDK object + * @hidden */ private createOperations() { const fetchFn = Provider.getFetchFn(this.options); @@ -556,9 +590,9 @@ Supported fuel-core version: ${supportedVersion}.` } /** - * Returns the block number. + * Returns the latest block number. * - * @returns A promise that resolves to the block number + * @returns A promise that resolves to the latest block number. */ async getBlockNumber(): Promise { const { chain } = await this.operations.getChain(); @@ -566,9 +600,9 @@ Supported fuel-core version: ${supportedVersion}.` } /** - * Returns the chain information. - * @param url - The URL of the Fuel node - * @returns NodeInfo object + * Returns the node information for the current provider network. + * + * @returns a promise that resolves to the node information. */ async fetchNode(): Promise { const { nodeInfo } = await this.operations.getNodeInfo(); @@ -587,9 +621,9 @@ Supported fuel-core version: ${supportedVersion}.` } /** - * Fetches the `chainInfo` for the given node URL. - * @param url - The URL of the Fuel node - * @returns ChainInfo object + * Returns the chain information for the current provider network. + * + * @returns a promise that resolves to the chain information. */ async fetchChain(): Promise { const { chain } = await this.operations.getChain(); @@ -602,8 +636,9 @@ Supported fuel-core version: ${supportedVersion}.` } /** - * Returns the chain ID - * @returns A promise that resolves to the chain ID number + * Returns the chain ID for the current provider network. + * + * @returns A promise that resolves to the chain ID number. */ getChainId() { const { @@ -613,9 +648,9 @@ Supported fuel-core version: ${supportedVersion}.` } /** - * Returns the base asset ID for the current provider network + * Returns the base asset ID for the current provider network. * - * @returns the base asset ID + * @returns the base asset ID. */ getBaseAssetId() { const { @@ -646,6 +681,7 @@ Supported fuel-core version: ${supportedVersion}.` * the transaction will be mutated and those dependencies will be added. * * @param transactionRequestLike - The transaction request object. + * @param sendTransactionParams - The provider send transaction parameters (optional). * @returns A promise that resolves to the transaction response object. */ // #region Provider-sendTransaction @@ -703,7 +739,7 @@ Supported fuel-core version: ${supportedVersion}.` * the transaction will be mutated and those dependencies will be added. * * @param transactionRequestLike - The transaction request object. - * @param utxoValidation - Additional provider call parameters. + * @param sendTransactionParams - The provider call parameters (optional). * @returns A promise that resolves to the call result object. */ async call( @@ -728,6 +764,8 @@ Supported fuel-core version: ${supportedVersion}.` /** * Verifies whether enough gas is available to complete transaction. * + * @template T - The type of the transaction request object. + * * @param transactionRequest - The transaction request object. * @returns A promise that resolves to the estimated transaction request object. */ @@ -772,9 +810,8 @@ Supported fuel-core version: ${supportedVersion}.` * If there are missing variable outputs, * `addVariableOutputs` is called on the transaction. * - * * @param transactionRequest - The transaction request object. - * @returns A promise. + * @returns A promise that resolves to the estimate transaction dependencies. */ async estimateTxDependencies( transactionRequest: TransactionRequest @@ -919,6 +956,14 @@ Supported fuel-core version: ${supportedVersion}.` return results; } + /** + * Dry runs multiple transactions. + * + * @param transactionRequests - Array of transaction request objects. + * @param sendTransactionParams - The provider call parameters (optional). + * + * @returns A promise that resolves to an array of results for each transaction call. + */ async dryRunMultipleTransactions( transactionRequests: TransactionRequest[], { utxoValidation, estimateTxDependencies = true }: ProviderCallParams = {} @@ -1018,6 +1063,7 @@ Supported fuel-core version: ${supportedVersion}.` * the transaction will be mutated and those dependencies will be added * * @param transactionRequestLike - The transaction request object. + * @param estimateTxParams - The estimate transaction params (optional). * @returns A promise that resolves to the call result object. */ async simulate( @@ -1051,14 +1097,9 @@ Supported fuel-core version: ${supportedVersion}.` * to set gasLimit and also reserve balance amounts * on the the transaction. * - * @privateRemarks - * The tolerance is add on top of the gasUsed calculated - * from the node, this create a safe margin costs like - * change states on transfer that don't occur on the dryRun - * transaction. The default value is 0.2 or 20% - * * @param transactionRequestLike - The transaction request object. - * @param tolerance - The tolerance to add on top of the gasUsed. + * @param transactionCostParams - The transaction cost parameters (optional). + * * @returns A promise that resolves to the transaction cost object. */ async getTransactionCost( @@ -1162,6 +1203,15 @@ Supported fuel-core version: ${supportedVersion}.` }; } + /** + * Get the required quantities and associated resources for a transaction. + * + * @param owner - address to add resources from. + * @param transactionRequestLike - transaction request to populate resources for. + * @param quantitiesToContract - quantities for the contract (optional). + * + * @returns a promise resolving to the required quantities for the transaction. + */ async getResourcesForTransaction( owner: string | AbstractAddress, transactionRequestLike: TransactionRequestLike, @@ -1197,13 +1247,16 @@ Supported fuel-core version: ${supportedVersion}.` /** * Returns coins for the given owner. + * + * @param owner - The address to get coins for. + * @param assetId - The asset ID of coins to get (optional). + * @param paginationArgs - Pagination arguments (optional). + * + * @returns A promise that resolves to the coins. */ async getCoins( - /** The address to get coins for */ owner: string | AbstractAddress, - /** The asset ID of coins to get */ assetId?: BytesLike, - /** Pagination arguments */ paginationArgs?: CursorPaginationArgs ): Promise { const ownerAddress = Address.fromAddressOrString(owner); @@ -1229,16 +1282,13 @@ Supported fuel-core version: ${supportedVersion}.` * Returns resources for the given owner satisfying the spend query. * * @param owner - The address to get resources for. - * @param quantities - The quantities to get. - * @param excludedIds - IDs of excluded resources from the selection. + * @param quantities - The coin quantities to get. + * @param excludedIds - IDs of excluded resources from the selection (optional). * @returns A promise that resolves to the resources. */ async getResourcesToSpend( - /** The address to get coins for */ owner: string | AbstractAddress, - /** The quantities to get */ quantities: CoinQuantityLike[], - /** IDs of excluded resources from the selection. */ excludedIds?: ExcludeResourcesOption ): Promise { const ownerAddress = Address.fromAddressOrString(owner); @@ -1302,12 +1352,9 @@ Supported fuel-core version: ${supportedVersion}.` * Returns block matching the given ID or height. * * @param idOrHeight - ID or height of the block. - * @returns A promise that resolves to the block. + * @returns A promise that resolves to the block or null. */ - async getBlock( - /** ID or height of the block */ - idOrHeight: string | number | 'latest' - ): Promise { + async getBlock(idOrHeight: string | number | 'latest'): Promise { let variables; if (typeof idOrHeight === 'number') { variables = { height: bn(idOrHeight).toString(10) }; @@ -1465,13 +1512,11 @@ Supported fuel-core version: ${supportedVersion}.` * Returns balances for the given owner. * * @param owner - The address to get coins for. - * @param paginationArgs - Pagination arguments. + * @param paginationArgs - Pagination arguments (optional). * @returns A promise that resolves to the balances. */ async getBalances( - /** The address to get coins for */ owner: string | AbstractAddress, - /** Pagination arguments */ paginationArgs?: CursorPaginationArgs ): Promise { const result = await this.operations.getBalances({ @@ -1492,13 +1537,11 @@ Supported fuel-core version: ${supportedVersion}.` * Returns message for the given address. * * @param address - The address to get message from. - * @param paginationArgs - Pagination arguments. + * @param paginationArgs - Pagination arguments (optional). * @returns A promise that resolves to the messages. */ async getMessages( - /** The address to get message from */ address: string | AbstractAddress, - /** Pagination arguments */ paginationArgs?: CursorPaginationArgs ): Promise { const result = await this.operations.getMessages({ @@ -1531,12 +1574,11 @@ Supported fuel-core version: ${supportedVersion}.` * * @param transactionId - The transaction to get message from. * @param messageId - The message id from MessageOut receipt. - * @param commitBlockId - The commit block id. - * @param commitBlockHeight - The commit block height. + * @param commitBlockId - The commit block id (optional). + * @param commitBlockHeight - The commit block height (optional). * @returns A promise that resolves to the message proof. */ async getMessageProof( - /** The transaction to get message from */ transactionId: string, nonce: string, commitBlockId?: string, @@ -1641,11 +1683,22 @@ Supported fuel-core version: ${supportedVersion}.` }; } + /** + * Get the latest gas price from the node. + * + * @returns A promise that resolves to the latest gas price. + */ async getLatestGasPrice(): Promise { const { latestGasPrice } = await this.operations.getLatestGasPrice(); return bn(latestGasPrice.gasPrice); } + /** + * Returns the estimate gas price for the given block horizon. + * + * @param blockHorizon - The block horizon to estimate gas price for. + * @returns A promise that resolves to the estimated gas price. + */ async estimateGasPrice(blockHorizon: number): Promise { const { estimateGasPrice } = await this.operations.estimateGasPrice({ blockHorizon: String(blockHorizon), @@ -1670,8 +1723,8 @@ Supported fuel-core version: ${supportedVersion}.` /** * Lets you produce blocks with custom timestamps and the block number of the last block produced. * - * @param amount - The amount of blocks to produce - * @param startTime - The UNIX timestamp (milliseconds) to set for the first produced block + * @param amount - The amount of blocks to produce. + * @param startTime - The UNIX timestamp (milliseconds) to set for the first produced block (optional). * @returns A promise that resolves to the block number of the last produced block. */ async produceBlocks(amount: number, startTime?: number) { @@ -1682,6 +1735,12 @@ Supported fuel-core version: ${supportedVersion}.` return bn(latestBlockHeight); } + /** + * Get the transaction response for the given transaction ID. + * + * @param transactionId - The transaction ID to get the response for. + * @returns A promise that resolves to the transaction response. + */ // eslint-disable-next-line @typescript-eslint/require-await async getTransactionResponse(transactionId: string): Promise { return new TransactionResponse(transactionId, this); @@ -1691,7 +1750,7 @@ Supported fuel-core version: ${supportedVersion}.` * Returns Message for given nonce. * * @param nonce - The nonce of the message to retrieve. - * @returns A promise that resolves to the Message object. + * @returns A promise that resolves to the Message object or null. */ async getMessageByNonce(nonce: string): Promise { const { message } = await this.operations.getMessageByNonce({ nonce }); @@ -1703,6 +1762,12 @@ Supported fuel-core version: ${supportedVersion}.` return message; } + /** + * Get the relayed transaction for the given transaction ID. + * + * @param relayedTransactionId - The relayed transaction ID to get the response for. + * @returns A promise that resolves to the relayed transaction. + */ async getRelayedTransactionStatus( relayedTransactionId: string ): Promise { @@ -1717,6 +1782,9 @@ Supported fuel-core version: ${supportedVersion}.` return relayedTransactionStatus; } + /** + * @hidden + */ private extractDryRunError( transactionRequest: ScriptTransactionRequest, receipts: TransactionResultReceipt[], diff --git a/packages/account/src/providers/transaction-request/script-transaction-request.ts b/packages/account/src/providers/transaction-request/script-transaction-request.ts index c213eaada22..9261ec26b1f 100644 --- a/packages/account/src/providers/transaction-request/script-transaction-request.ts +++ b/packages/account/src/providers/transaction-request/script-transaction-request.ts @@ -152,6 +152,13 @@ export class ScriptTransactionRequest extends BaseTransactionRequest { return this.outputs.length - 1; } + /** + * Calculates the maximum gas for the transaction. + * + * @param chainInfo - The chain information. + * @param minGas - The minimum gas. + * @returns the maximum gas. + */ calculateMaxGas(chainInfo: ChainInfo, minGas: BN): BN { const { consensusParameters } = chainInfo; const { diff --git a/packages/account/src/wallet/base-wallet-unlocked.ts b/packages/account/src/wallet/base-wallet-unlocked.ts index 46b5d4ea168..8100b1e3815 100644 --- a/packages/account/src/wallet/base-wallet-unlocked.ts +++ b/packages/account/src/wallet/base-wallet-unlocked.ts @@ -107,6 +107,8 @@ export class BaseWalletUnlocked extends Account { * Populates the witness signature for a transaction and sends it to the network using `provider.sendTransaction`. * * @param transactionRequestLike - The transaction request to send. + * @param estimateTxDependencies - Whether to estimate the transaction dependencies. + * @param awaitExecution - Whether to wait for the transaction to be executed. * @returns A promise that resolves to the TransactionResponse object. */ async sendTransaction( @@ -146,6 +148,12 @@ export class BaseWalletUnlocked extends Account { ); } + /** + * Encrypts an unlocked wallet with a password. + * + * @param password - the password to encrypt the wallet with. + * @returns - the encrypted wallet. + */ async encrypt(password: string): Promise { return encryptKeystoreWallet(this.privateKey, this.address, password); }