Good day,
I implemented a function to send a specified amount of funds from one wallet to another.
I added the calculation of fees and gas. Everything worked well when I sent the entire wallet balance.
However, when I sent only 50%, I encountered a situation where the remaining funds in the sender’s wallet disappeared.
Transaction via my code
After that, I compared the transaction generated by my method with the one created by the Fuel wallet.
I discovered that my transaction lacks the CHANGE
block, which contains the remaining wallet balance.
Transaction via wallet
I would like to ask for your assistance:
- What is the mistake in my code?
export async function transferWithFeeAdjustment(
wallet: WalletUnlocked,
destination: AddressLike,
assetId: BytesLike,
amountToSend: BN
): Promise<void> {
const txRequest = new ScriptTransactionRequest();
const resources = await wallet.getResourcesToSpend([
{ amount: amountToSend, assetId },
]);
txRequest.addResources(resources);
txRequest.addCoinOutput(destination, amountToSend, assetId);
const chainInfo = wallet.provider.getChain();
const minGas = txRequest.calculateMinGas(chainInfo);
const maxGas = txRequest.calculateMaxGas(chainInfo, minGas);
txRequest.maxFee = maxGas.mul(1.1);
const txCost = await wallet.getTransactionCost(txRequest);
const transactionFee = txCost.maxGas
txRequest.gasLimit = transactionFee;
if (amountToSend.lte(transactionFee)) {
throw new Error(
"Insufficient balance to cover transaction fee. Please add more funds."
);
}
const adjustedAmount = amountToSend.sub(transactionFee);
if (adjustedAmount.lte(new BN(0))) {
throw new Error(
"Insufficient amount after deducting transaction fee. Unable to proceed."
);
}
txRequest.outputs = [];
txRequest.addCoinOutput(destination, adjustedAmount, assetId);
const response = await wallet.sendTransaction(txRequest);
await retry(async () => {
return await response.wait();
}, 10);
return Promise.resolve()
}
- I found documentation on sending funds using a Predicate. Would it be better for me to use this method instead?
Fuel TS SDK | Fuel Docs