This documentation provides a guide on how to transfer assets between wallets and to contracts using the SDK.
The wallet.transfer
function is used to initiate a transaction that transfers an asset from one wallet to another. This function requires three parameters:
Upon execution, this function returns a promise that resolves to a transaction response. To wait for the transaction to be mined, call response.wait()
.
Here is an illustration on how to use the wallet.transfer
function:
import { Wallet, BN, BaseAssetId } from 'fuels';
const senderWallet = Wallet.fromPrivateKey('...');
const destinationWallet = Wallet.generate();
const amountToTransfer = 500;
const assetId = BaseAssetId;
const response = await senderWallet.transfer(
destinationWallet.address,
amountToTransfer,
assetId
);
await response.wait();
// Retrieve balances
const receiverBalance = await destinationWallet.getBalance(assetId);
// Validate new balance
expect(new BN(receiverBalance).toNumber()).toEqual(amountToTransfer);
When transferring assets to a deployed contract, we use the transferToContract
method. This method closely mirrors the wallet.transfer
method in terms of parameter structure.
However, instead of supplying the target wallet's address, as done in myWallet.address
for the transfer method, we need to provide an instance of Address created from the deployed contract id.
If you have the Contract instance of the deployed contract, you can simply use its id
property. However, if the contract was deployed with forc deploy
or not by you, you will likely only have its ID in a hex string format. In such cases, you can create an Address instance from the contract ID using Address.fromAddressOrString('0x123...')
.
Here's an example demonstrating how to use transferToContract
:
import { Wallet, BN, BaseAssetId } from 'fuels';
const senderWallet = Wallet.fromPrivateKey('...');
const amountToTransfer = 400;
const assetId = BaseAssetId;
const contractId = Address.fromAddressOrString('0x123...');
const contractBalance = await deployedContract.getBalance(assetId);
const tx = await senderWallet.transferToContract(contractId, amountToTransfer, assetId);
expect(new BN(contractBalance).toNumber()).toBe(0);
await tx.waitForResult();
expect(new BN(await deployedContract.getBalance(assetId)).toNumber()).toBe(amountToTransfer);
Remember to always invoke the waitForResult()
function on the transaction response. This ensures that the transaction has been successfully mined before proceeding.