进阶
批量请求
高效处理多个交易或查询
概述
在某些场景下,你可能需要一次性发送多笔交易。SDK 为此场景提供了优化方案,但需要开发者做一些额外工作。本指南涵盖了具体案例和高效批量处理的建议。
批量转账交易
基础方式(低效)
// 逐个发送转账 - 不推荐
for (const { address, amount } of spends) {
await aeSdk.spend(amount, address);
}
这种方式很慢,因为每次迭代 SDK 都会:
- 请求发送方账户数据(类型和 nonce)
- 验证交易(包含额外请求)
- 等待交易上链
优化方式(推荐)
// 获取起始 nonce
const base = (await aeSdk.api.getAccountNextNonce(aeSdk.address)).nextNonce;
// 并行发送所有交易
await Promise.all(
spends.map(({ amount, address }, idx) =>
aeSdk.spend(amount, address, {
nonce: base + idx, // 手动指定递增 nonce
verify: false, // 跳过验证
waitMined: false // 不等待上链
})
)
);
优化效果:SDK 只请求一次账户信息,然后并行发送所有交易。你还可以设置
gasPrice 和 fee 来预测支出。
通过合约批量转账
如果需要从同一账户向 超过 24 个地址 转账固定金额,使用智能合约更高效。
合约代码
include "List.aes"
contract MultipleSpends =
payable stateful entrypoint spend(addresses: list(address), amount: int) =
List.foreach(addresses, (address) => Chain.spend(address, amount))
调用方式
// 部署后调用合约
await contract.spend(addresses, amount, {
amount: amount * addresses.length // 转入总金额
});
优点
- 超过 24 个接收方时手续费更低
- 执行更快,只需确认一笔交易
缺点
- 单笔交易接收方上限约 800 个(受区块 gas 限制)
- 实现较复杂
手续费对比
| 接收方数量 | 使用合约节省的费用 |
|---|---|
| 1,000 | 0.0107 AE |
| 100,000 | 1.07 AE |
| 10,000,000 | 107 AE |
批量合约只读调用
基础方式(低效)
// 逐个调用 - 每次都创建新的 dry-run 请求
const results = [];
for (const d of data) {
results.push(await contract.foo(d));
}
优化方式(推荐)
// 获取起始 nonce
const base = (await aeSdk.api.getAccountNextNonce(aeSdk.address)).nextNonce;
// 使用 combine 标志合并所有调用到单个 dry-run 请求
const results = await Promise.all(
data.map((d, idx) => contract.foo(d, {
nonce: base + idx,
combine: true // 关键!合并到单个请求
}))
);
限制:默认 dry-run 限制为 6,000,000 gas,约够执行 32 次普通合约调用。可通过调整节点配置或使用 debug 端点解除限制。
优化技巧总结
| 场景 | 关键选项 | 效果 |
|---|---|---|
| 批量转账 | nonce, verify: false, waitMined: false |
并行发送,减少请求 |
| 大量转账 | 使用智能合约 | 超过 24 人时更省费 |
| 批量查询 | combine: true |
合并为单个 dry-run |