在某些情况下,您可能需要构建涉及多种程序类型和资产的交易;这可以通过实例化一个 ScriptTransactionRequest
来实现。这个类允许您将多个程序类型和资产附加到单个交易中。
考虑以下脚本,它将多个资产转移到一个合约中:
script;
use std::asset::transfer;
fn main(
contract_address: b256,
asset_a: AssetId,
amount_asset_a: u64,
asset_b: AssetId,
amount_asset_b: u64,
) -> bool {
let wrapped_contract = ContractId::from(contract_address);
let contract_id = Identity::ContractId(wrapped_contract);
transfer(contract_id, asset_a, amount_asset_a);
transfer(contract_id, asset_b, amount_asset_b);
true
}
可以通过创建一个 ScriptTransactionRequest
,附加资源和合约输入/输出,然后发送交易来执行这个脚本,如下所示:
// #import { BN, ScriptTransactionRequest };
// 1. Create a script transaction using the script binary
const request = new ScriptTransactionRequest({
...defaultTxParams,
gasLimit: 3_000_000,
script: scriptBin,
});
// 2. Instantiate the script main arguments
const scriptArguments = [
contract.id.toB256(),
{ bits: ASSET_A },
new BN(1000),
{ bits: ASSET_B },
new BN(500),
];
// 3. Populate the script data and add the contract input and output
request.setData(abiContents, scriptArguments).addContractInputAndOutput(contract.id);
// 4. Get the transaction resources
const quantities = [coinQuantityfy([1000, ASSET_A]), coinQuantityfy([500, ASSET_B])];
// 5. Calculate the transaction fee
const txCost = await provider.getTransactionCost(request, { quantitiesToContract: quantities });
request.gasLimit = txCost.gasUsed;
request.maxFee = txCost.maxFee;
await wallet.fund(request, txCost);
// 6. Send the transaction
const tx = await wallet.sendTransaction(request);
await tx.waitForResult();