我正在尝试使用USDC (AVAX)进行批量事务处理。我发现建议使用事务构建器。但我不清楚如何使用它。我希望有人能帮助我澄清或提供一些正确的步骤。
它还允许我先在testnet上测试事务吗?
非常感谢!
发布于 2023-03-24 05:00:42
这个过程是非常直接的。我会用代码列出步骤。
const { Avalanche, BinTools, BN, Buffer, utils } = require("avalanche");
const { AVMAPI, KeyChain } = require("avalanche/dist/apis/avm");
const { UnixNow } = utils; const networkID = 5; // Use 1 for mainnet, 5 for testnet (Fuji)
const avalanche = new Avalanche("api.avax-test.network", 443, "https", networkID);
const avm = avalanche.XChain(); // Connect to the X-Chain const mnemonic = "your-mnemonic-phrase-here"; // Replace with your mnemonic phrase
const keychain = avm.keyChain();
keychain.importKey(mnemonic);
const senderAddress = keychain.getAddressStrings()[0];
const recipients = [
{ address: "X-avax1...", amount: 1000 }, // Replace with the recipient's address and desired amount
// Add more recipients as needed
]; async function sendBulkTransaction() {
// Fetch the UTXOs for the sender
const { utxos } = await avm.getUTXOs(senderAddress);
const inputs = [];
const outputs = [];
const binTools = BinTools.getInstance();
// Fetch the assetID for the USDC on Avalanche
const usdcAssetIDBuf = await avm.getAssetID("USDC");
const usdcAssetID = binTools.cb58Encode(usdcAssetIDBuf);
// Iterate through the UTXOs and create the inputs and outputs
for (const utxo of utxos.getAllUTXOs()) {
const assetID = binTools.cb58Encode(utxo.getAssetID());
const output = utxo.getOutput();
const amount = output.getAmount().clone();
const locktime = output.getLocktime();
const threshold = output.getThreshold();
const addresses = output.getAddresses();
if (usdcAssetID === assetID) {
const input = utxo.getInput();
inputs.push(input);
const change = new utils.Output(amount, locktime, threshold, addresses);
outputs.push(change);
}
}
// Create the outputs for the recipients
recipients.forEach(({ address, amount }) => {
const recipientOutput = new utils.Output(
new BN(amount),
0,
1,
[avm.parseAddress(address)]
);
outputs.push(recipientOutput);
});
// Build, sign, and send the transaction
const unsignedTx = await avm.buildUnsignedTransaction(
new UnixNow().getValue(),
new BN(0),
senderAddress,
usdcAssetIDBuf,
inputs,
outputs
);
const signedTx = unsignedTx.sign(keychain);
const txid = await avm.sendTx(signedTx);
console.log(`Transaction submitted! TXID: ${txid}`);
}
sendBulkTransaction()
.then(() => console.log("Bulk transaction completed."))
.catch((error) => console.error("Error during the transaction:", error));此代码段通过签名和发送来完成事务。如果所有设置都正确,那么在运行脚本后,您应该在控制台输出中看到事务ID。
要在testnet上测试事务,请确保在代码中将networkID设置为5(对于富士测试网),如步骤3所示。
若要运行脚本,请导航到包含bulk_transaction.js文件的文件夹,并在终端中执行以下命令:
node bulk_transaction.js请记住用自己的地址替换助记符、发件人地址和收件人地址。此外,在尝试事务之前,请确保发送方的地址中有足够的USDC和AVAX (用于支付事务费)。
https://ethereum.stackexchange.com/questions/147873
复制相似问题