Icon HelpCircleForumIcon Link

⌘K

Icon HelpCircleForumIcon Link
Custom Transactions from Contract Calls

Icon LinkCustom Transactions From Contract Calls

In the previous example we demonstrated how you can instantiate a ScriptTransactionRequest to customize and build out a more complex transaction via a script. The same can be done using contracts, but this allows us to utilize functions available in the contract and access on-chain state. Allowing us to harness all of the power from an invocation scope and a transaction request.

This cookbook demonstrates how we can utilize a contract call to build out a custom transaction, allowing us to update on-chain state and transfer assets to a recipient address.

// #import { bn, Contract, FunctionInvocationResult };
 
const amountToRecipient = bn(10_000); // 0x2710
// Connect to the contract
const contractInstance = new Contract(contract.id, abi, senderWallet);
// Create an invocation scope for the contract function you'd like to call in the transaction
const scope = contractInstance.functions.increment_count(amountToRecipient).addTransfer({
  amount: amountToRecipient,
  destination: receiverWallet.address,
  assetId: baseAssetId,
});
 
// Build a transaction request from the invocation scope
const transactionRequest = await scope.getTransactionRequest();
// Add coin output for the recipient
transactionRequest.addCoinOutput(receiverWallet.address, amountToRecipient, baseAssetId);
 
const txCost = await senderWallet.provider.getTransactionCost(transactionRequest);
 
transactionRequest.gasLimit = txCost.gasUsed;
transactionRequest.maxFee = txCost.maxFee;
 
await senderWallet.fund(transactionRequest, txCost);
 
// Submit the transaction
const response = await senderWallet.sendTransaction(transactionRequest);
await response.waitForResult();
// Get result of contract call
const { value } = await FunctionInvocationResult.build([scope], response, false, contract);
// <BN: 0x2710>