Custom Transactions from Contract Calls

Icon Link通过合约调用创建自定义交易

在上一个示例中,我们演示了如何实例化一个 ScriptTransactionRequest 来通过脚本定制并构建一个更复杂的交易。同样的方法也适用于合约,但这样做可以利用合约中可用的函数并访问链上状态。这样我们就可以利用调用作用域和交易请求的全部功能。

这个示例演示了如何利用合约调用来构建自定义交易,允许我们更新链上状态并将资产转移到接收地址。

// #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>