@ gelatocloud/ 无气态
无气交易全能解决方案.
特征
- 三个抽象层次 - 为您的应用程序选择最佳集成模式:
- 涡轮更新器: 以零气高通的链上交易提交速度最快,效率最高的方法,理想为耐久敏感的工作流程.
- 有智能账户的涡轮更新器 - 利用智能账户来简化交易编码和签名,同时保留涡轮级的性能.
- ERC-4337 邦德勒号 - 完全合规的ERC-4337捆绑器,用于本土账户抽象流.
- 通过煤气罐提供赞助 - 支持用你的油罐进行赞助的交易.
- 2D 非现金支持 - 采用两种方法进行高级非现金管理
nonce财务报告和审定财务报表nonceKey用于平行执行. - 类型安全 - 已执行 维姆,提供完整的TypeScript类型安全性和开发者人机学.
- 同步方法: 发送交易并在一次通话中获取收据
- 网络软件: 通过 WebSockets 实时通知和更新
学我们多一点 文档
安装
pnpm install viem @gelatocloud/gasless
同伴依赖性 : viem
快速启动
- 获取您的 API 密钥 https://app.gelato.cloud/ 互联网档案馆的存檔,存档日期2013-12-21
- 设置环境变量 :
export GELATO_API_KEY="your-api-key"
使用量
涡轮更新器
无智能账户的直接无气交易中继. 简单的担保交易最好.
同步 :
import { createGelatoEvmRelayerClient } from '@gelatocloud/gasless';
import { baseSepolia } from 'viem/chains';
const relayer = createGelatoEvmRelayerClient({
apiKey: process.env.GELATO_API_KEY,
testnet: true
});
// Send and wait for inclusion in one call
const receipt = await relayer.sendTransactionSync({
chainId: baseSepolia.id,
to: '0xTargetContract...',
data: '0xCalldata...'
});
console.log(`Transaction hash: ${receipt.transactionHash}`);
同步 :
import { createGelatoEvmRelayerClient } from '@gelatocloud/gasless';
import { baseSepolia } from 'viem/chains';
const relayer = createGelatoEvmRelayerClient({
apiKey: process.env.GELATO_API_KEY,
testnet: true
});
// Send transaction (returns immediately with ID)
const id = await relayer.sendTransaction({
chainId: baseSepolia.id,
to: '0xTargetContract...',
data: '0xCalldata...'
});
// Poll for status separately
const receipt = await relayer.waitForReceipt({ id });
console.log(`Transaction hash: ${receipt.transactionHash}`);
账户( Gelato 智能账户)
Gelato智能账户执行ERC-7821授权模式.
同步 :
import {
createGelatoSmartAccountClient,
toGelatoSmartAccount } from '@gelatocloud/gasless';
import { createPublicClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { baseSepolia } from 'viem/chains';
const owner = privateKeyToAccount('0xYourPrivateKey...');
const publicClient = createPublicClient({
chain: baseSepolia,
transport: http()
});
// Create a Gelato smart account
const account = toGelatoSmartAccount({ client: publicClient, owner });
// Create the smart account client
const client = await createGelatoSmartAccountClient({
account,
apiKey: process.env.GELATO_API_KEY
});
// Send and wait for inclusion in one call
const receipt = await client.sendTransactionSync({
calls: [
{ to: '0xContract1...', data: '0xCalldata1...' },
{ to: '0xContract2...', data: '0xCalldata2...' }
]// Optional: nonce or nonceKey for 2D nonce management
});
console.log(`Transaction hash: ${receipt.transactionHash}`);
同步 :
import {
createGelatoSmartAccountClient,
toGelatoSmartAccount } from '@gelatocloud/gasless';
// ... same setup as above ...
// Send transaction (returns immediately with ID)
const id = await client.sendTransaction({
calls: [{ to: '0xContract...', data: '0xCalldata...' }] });
// Poll for status separately
const receipt = await client.waitForReceipt({ id });
console.log(`Transaction hash: ${receipt.transactionHash}`);
邦德勒(ERC-4337)
与任何ERC-4337智能账户兼容.
import { createGelatoBundlerClient } from '@gelatocloud/gasless';
import { to7702SimpleSmartAccount } from 'permissionless/accounts';
import { createPublicClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { baseSepolia } from 'viem/chains';
const owner = privateKeyToAccount('0xYourPrivateKey...');
const client = createPublicClient({
chain: baseSepolia,
transport: http()
});
// Create a smart account
const account = await to7702SimpleSmartAccount({
client,
owner
});
// Create the Gelato bundler client
const bundler = await createGelatoBundlerClient({
account,
client,
apiKey: process.env.GELATO_API_KEY,
sponsored: true
});
// Send a user operation
const hash = await bundler.sendUserOperation({
calls: [{ to: '0x...', data: '0x...' }]
});
// Wait for the receipt
const { receipt } = await bundler.waitForUserOperationReceipt({ hash });
console.log(`Transaction hash: ${receipt.transactionHash}`);
网页订阅
WebSockets 默认启用. 方法自动对WebSocket的投票进行比赛,结果最快. 要禁用 :
const relayer = createGelatoEvmRelayerClient({
apiKey: process.env.GELATO_API_KEY,
ws: { disable: true }
});
重级——单项交易 :
const id = await relayer.sendTransaction({
chainId: baseSepolia.id,
to: '0xTargetContract...',
data: '0xCalldata...'
});
const subscription = await relayer.ws.subscribe({ id });
subscription.on('success', (data) => {
console.log(`Included in block ${data.receipt.blockNumber}`);
});
subscription.on('reverted', (data) => {
console.log(`Reverted: ${data.receipt.blockNumber}`);
});
// Cleanup when done
await relayer.ws.unsubscribe(subscription.subscriptionId);
relayer.ws.disconnect();
更新——全球(所有交易):
const subscription = await relayer.ws.subscribe();
subscription.on('submitted', (data) => console.log(`${data.id} submitted`));
subscription.on('success', (data) => console.log(`${data.id} success`));
subscription.on('rejected', (data) => console.log(`${data.id} rejected`));
邦德勒语Name - 同样的模式通过 bundler.ws数字 :
const subscription = await bundler.ws.subscribe({ id: userOpHash });
subscription.on('success', (data) => console.log(data.receipt));
活动 :
| 活动 | 说明 |
|---|---|
pending | 待处理的交易 |
submitted | 提交网络 |
success | 成功纳入链条 |
rejected | 被中继器拒绝 |
reverted | 在链上还原 |
清理 :
await relayer.ws.unsubscribe(subscription.subscriptionId);
relayer.ws.disconnect();
获得平衡
检查你的油罐平衡。 所有客户类型都有.
const { balance, decimals, unit } = await relayer.getBalance();
// Also: client.getBalance(), bundler.getBalance()
同步 vs 同步
SDK提供了两种发送交易的方法:
同步( E)sendTransactionSync(中文(简体) ) | 阿辛克语( A)sendTransaction + WS) 单相机 | |
|---|---|---|
| 回返 | 最终 TransactionReceipt | 身份证(Hex页:1 |
| 生命周期事件 | 无(内部处理) | 都说: pending, (中文(简体) ), submitted, (中文(简体) ), success, (中文(简体) ), rejected, (中文(简体) ), reverted |
| 关于(再次)提交的散列 | 未曝光 | hash 每个字段 submitted 事件 |
| 控制权 | 最小的——火灾和遗忘 | Full – 通过 WS 订阅对每个状态变化作出反应 |
| Reorg 保护 | 无 | 是, 发布新的更新活动 |
同步 - 打电话 sendTransactionSync 发送交易并在同一电话中获取收据。 如果交易不包含在内, SDK 将进行内部处理并返回最终 TransactionReceipt http 民调和Ws更新。 当你只需要结果时最简单的方法:
const receipt = await relayer.sendTransactionSync({ chainId, to, data });
自动同步 - 打电话 sendTransaction 然后通过WebSocket订阅,以更新颗粒状态. WS 订阅可以完全控制交易周期 ——你可以对重新提交作出反应,实时向用户显示tx散列,立即处理拒绝,以及更多. 这个 submitted 事件包括交易 hash 每次中继( 重接) 交接交易( 如用起伏气体) :
const id = await relayer.sendTransaction({ chainId, to, data });
const subscription = await relayer.ws.subscribe({ id });
subscription.on('submitted', (data) => {
console.log(`Tx hash: ${data.hash}`); // available on every (re)submission
});
subscription.on('success', (data) => {
console.log(`Confirmed in block ${data.receipt.blockNumber}`);
});
API 参考
更新 API
createGelatoEvmRelayerClient(config)
创建一个低级中继器客户端,用于直接提交交易.
const client = createGelatoEvmRelayerClient({
apiKey: string, // Your Gelato API key
testnet: boolean // true for testnets, false for mainnet
});
方法:
| 方法 | 参数 | 回返 | 说明 |
|---|---|---|---|
sendTransaction | { chainId, to, data, authorizationList?, context? } | Promise<Hex> | 提交交易 |
sendTransactionSync | { chainId, to, data, timeout?, pollingInterval?, throwOnReverted?, ... } | Promise<TransactionReceipt> | 发送和等待收到 |
getStatus | { id: string } | Promise<Status> | 获取交易状态 |
waitForReceipt | { id: string, timeout?, pollingInterval?, throwOnReverted? } | Promise<TransactionReceipt> | 等待收货,投出失败 |
getBalance | - 说吧 | Promise<Balance> | 获取油箱余额 |
getCapabilities | - 说吧 | Promise<Capabilities> | 获得支持链 |
getFeeData | { chainId, gas, l1Fee? } | Promise<FeeData> | 获取网络收费数据 |
账户 API
toGelatoSmartAccount(params)
使用 ERC-7821 授权创建 Gelato 智能账户 .
const account = toGelatoSmartAccount({
client: Client, // viem public client
owner: Account // EOA that owns the smart account
});
createGelatoSmartAccountClient(config)
创建与 Gelato 智能账户互动的客户端 .
const client = await createGelatoSmartAccountClient({
apiKey: string, // Your Gelato API key
account: SmartAccount // From toGelatoSmartAccount()
});
方法:
| 方法 | 参数 | 回返 | 说明 |
|---|---|---|---|
sendTransaction | { calls, nonce?, nonceKey?} | Promise<Hex> | 发送交易 |
sendTransactionSync | { calls, nonce?, nonceKey?, timeout?, pollingInterval?, throwOnReverted?, ... } | Promise<TransactionReceipt> | 发送和等待收到 |
getStatus | { id: string } | Promise<Status> | 获取交易状态 |
waitForReceipt | { id: string, timeout?, pollingInterval?, throwOnReverted? } | Promise<TransactionReceipt> | 等待收货,投出失败 |
getBalance | - 说吧 | Promise<Balance> | 获取油箱余额 |
getCapabilities | - 说吧 | Promise<Capabilities> | 获得支持链 |
非选项 :
nonce: 明确非货币价值nonceKey: 2D 非ce 的密钥( 允许并行交易)
投票配置 :
所有同步方法sendTransactionSync, (中文(简体) ), sendUserOperationSync, (中文(简体) ), waitForReceipt支持自定义的投票行为:
timeout(可选):最大等待时间以毫秒计- 默认 :
120000(2分钟) - 不得超过
600000(10分钟)
- 默认 :
pollingInterval(可选) : 检查状态的频率( 毫秒)- 默认 :
1000(1秒钟)
- 默认 :
示例
// Wait up to 30 seconds, checking every 500ms
const receipt = await relayer.sendTransactionSync({
chainId: baseSepolia.id,
to: '0xTargetContract...',
data: '0xCalldata...',
timeout: 30000,
pollingInterval: 500
});
邦德勒 API
createGelatoBundlerClient(config)
创建 ERC-4337 捆绑客户端. 扩展viem的 BundlerClient。 。 。 .
const bundler = await createGelatoBundlerClient({
account: SmartAccount, // Any ERC-4337 smart account
client: Client, // viem public client
apiKey: string, // Your Gelato API key
sponsored: boolean, // Whether to use sponsored payment via Gas Tank
pollingInterval?: number // Polling interval in ms
});
方法:
| 方法 | 参数 | 回返 | 说明 |
|---|---|---|---|
sendUserOperation | { calls } | Promise<Hex> | 发送用户操作 |
sendUserOperationSync | { calls, timeout?, pollingInterval? } | Promise<UserOperationReceipt> | 发送和等待收到 |
waitForUserOperationReceipt | { hash } | Promise<{ receipt }> | 等待收货 |
getBalance | - 说吧 | Promise<Balance> | 获取油箱余额 |
estimateUserOperationGas | UserOperationParams | Promise<GasEstimate> | 估计天然气 |
prepareUserOperation | UserOperationParams | Promise<UserOperation> | 准备行动 |
getUserOperationGasPrice | - 说吧 | Promise<GasPrice> | 获取当前天然气价格 |
getUserOperationQuote | UserOperationParams | Promise<Quote> | 获取费用报价 |
类型
状态代码
enum StatusCode {
Pending = 100, // Transaction pending
Submitted = 110, // Submitted to network
Success = 200, // Successfully included
Rejected = 400, // Rejected by relayer
Reverted = 500 // Reverted on-chain
}
错误代码
enum ErrorCode {
// JSON-RPC
ParseError = -32700,
InvalidRequest = -32600,
MethodNotFound = -32601,
InvalidParams = -32602,
InternalError = -32603,
TimeoutError = -32070,
// Relayer
Unauthorized = 4100,
UnsupportedPaymentToken = 4202,
InsufficientPayment = 4200,
InsufficientBalance = 4205,
UnsupportedChain = 4206,
UnknownTransactionId = 4208,
InvalidAuthorizationList = 4210,
SimulationFailed = 4211,
// Bundler
ValidationFailed = -32500,
PaymasterValidationFailed = -32501,
InvalidSignature = -32507,
ExecutionFailed = -32521
}
打电话
type Call = {
to: Address; // Target contract address
data?: Hex; // Calldata (optional)
value?: bigint; // ETH value (optional)
};
状态处理
const status = await client.getStatus({ id: hash });
switch (status.status) {
case StatusCode.Success:
console.log('Success:', status.receipt.transactionHash);
break;
case StatusCode.Rejected:
console.log('Rejected:', status.message);
break;
case StatusCode.Reverted:
console.log('Reverted:', status.data);
break;
}
处理错误
超时出错
同步方法( E)sendTransactionSync, (中文(简体) ), waitForReceipt投掷 TimeoutError 当操作未在配置的超时内完成时 :
import { TimeoutError } from '@gelatocloud/gasless';
try {
const receipt = await relayer.sendTransactionSync({
chainId: baseSepolia.id,
to: '0xTargetContract...',
data: '0xCalldata...',
timeout: 10000
});
} catch (error) {
if (error instanceof TimeoutError) {
console.error('Transaction timed out:', error.message);
// Transaction may still be pending - you can retry with longer timeout
// or use async methods to check status manually
} else {
console.error('Other error:', error);
}
}
还原处理
默认, sendTransactionSync 财务报告和审定财务报表 waitForReceipt 即使交易在交易链上恢复时,也要返还收据。 设定 throwOnReverted: true 丢出一个 TransactionRevertedError 相反:
import { TransactionRevertedError } from '@gelatocloud/gasless';
try {
const receipt = await relayer.sendTransactionSync({
chainId: baseSepolia.id,
to: '0xTargetContract...',
data: '0xCalldata...',
throwOnReverted: true
});
} catch (error) {
if (error instanceof TransactionRevertedError) {
console.error('Transaction reverted:', error.receipt.transactionHash);
console.error('Error message:', error.erroMessage);
console.error('Error data:', error.errorData);
// Also available: error.id, error.chainId, error.createdAt
}
}
中继器和账户客户均可通过 sendTransactionSync 财务报告和审定财务报表 waitForReceipt属性 TransactionRevertedError数字 : receipt, (中文(简体) ), id, (中文(简体) ), chainId, (中文(简体) ), createdAt, (中文(简体) ), errorData, (中文(简体) ), errorMessage。 。 。 .
模拟错误
当中继器在提交前模拟交易,模拟返回时,a SimulationFailedRpcError 用错误代码投出 4211。发生这种情况 在此之前 交易在链上发送:
import { SimulationFailedRpcError } from '@gelatocloud/gasless';
try {
const receipt = await relayer.sendTransactionSync({
chainId: baseSepolia.id,
to: '0xTargetContract...',
data: '0xCalldata...'
});
} catch (error) {
if (error instanceof SimulationFailedRpcError) {
console.error('Simulation reverted:', error.message);
console.error('Revert data:', error.revertData);
// error.params contains the original { to, chainId, data } sent
}
}
属性于 SimulationFailedRpcError数字 : revertData, (中文(简体) ), params, (中文(简体) ), code (单位:千美元)4211) (中文(简体) ).
自动检索
更新方法sendTransaction, (中文(简体) ), sendTransactionSync)在遇到特定错误代码时支持自动重试. 这对于模拟出错等瞬时性故障(4211),在随后的尝试中可能成功.
const receipt = await relayer.sendTransactionSync(
{
chainId: baseSepolia.id,
to: '0xTargetContract...',
data: '0xCalldata...'
},
{
retries: {
max: 3, // Retry up to 3 times (default: 0, max: 5)
delay: 1000, // Wait 1s between retries (default: 200ms)
backoff: 'fixed', // 'exponential' (default) or 'fixed'
errorCodes: [4211] // Error codes that trigger a retry (default: [4211])
}
}
);
选项 :
| 选项 | 类型 | 默认 | 说明 |
|---|---|---|---|
max | number | 0 | 复试次数最多( 0– 5). 被烧成5分. |
delay | number | 200 | 每次重试前以毫秒为基数延迟 . |
backoff | 'fixed' | 'exponential' | 'exponential' | 后退战略. 'fixed' 不断拖延; 'exponential' 每次重试( t)delay × 2^attempt) (中文(简体) ). |
maxDelay | number | 10000 | 最大延迟为 ms. 盖子指数倒置,所以它不会超过这个值. |
errorCodes | number[] | [4211] | 触发重试的 RPC 错误代码 。 默认是 SimulationFailedRpcError。 。 。 . |
使用同步和同步中继器方法:
// Async
const id = await relayer.sendTransaction(
{ chainId, to, data },
{ retries: { max: 3 } }
);
// Sync
const receipt = await relayer.sendTransactionSync(
{ chainId, to, data },
{ retries: { max: 3 } }
);
只有匹配错误 code 财产被重审。 所有其他错误都立即抛出.
超时时自动退后
何时 sendTransactionSync rpc请求出站时间,SDK会自动回归投票,以获取交易状态. 如果您看到警告信息, 如:
Transaction 0x... sync call timed out, falling back to polling for completion. DO NOT RETRY this transaction.
这意味着您的交易已成功提交, 但同步方法已超时 。 SDK将继续投票 自动完成. 不重试操作 因为这可能导致重复交易.
复原战略
如果出现超时:
- 等待自动后退数字 :
sendTransactionSync超时后自动投票 - 手动检查状态: 使用
getStatus({ id })检查交易是否还在处理中 - 用更长的超时重试页:1
timeout打电话waitForReceipt再来一次 - 使用同步方法: 切换到同步模式以获取更多控件
配置限制
SDK执行以下限制以防止拒绝服务:
import {
TimeoutError,
TransactionRevertedError,
SimulationFailedRpcError,
MIN_TIMEOUT,
MAX_TIMEOUT,
MIN_POLLING_INTERVAL,
MAX_POLLING_INTERVAL
} from '@gelatocloud/gasless';
console.log(MIN_TIMEOUT); // 1000ms (1 second)
console.log(MAX_TIMEOUT); // 600000ms (10 minutes)
console.log(MIN_POLLING_INTERVAL); // 100ms
console.log(MAX_POLLING_INTERVAL); // 300000ms (5 minutes)
您可以在客户端设置默认超时和投票间隔 :
const relayer = createGelatoEvmRelayerClient({
apiKey: process.env.GELATO_API_KEY,
timeout: 30000, // Default 30 second timeout
pollingInterval: 500 // Default 500ms polling interval
});
// Methods use client defaults unless overridden
const receipt = await relayer.sendTransactionSync({
chainId: baseSepolia.id,
to: '0xTargetContract...',
data: '0xCalldata...',
// timeout: 60000 // Optional: override client default
});
所需资源
- 节点.js 23
- 同伴依赖性 :
viem, (中文(简体) ),zod - 可选 :
typescript
实例
见 /examples 完整工作示例目录 :
examples/relayer/sponsored- 直接中继器的使用examples/relayer/get-balance- 获得油罐余额examples/account/sponsored- Gelato智能账户examples/bundler/sponsored- ERC-4337捆绑机examples/bundler/get-balance- 获得油罐余额(散货机)examples/relayer/ws- 更新WebSocket的使用examples/bundler/ws- Bundler WebSocket的使用examples/account/ws- 账户WebSocket的使用
运行示例 :
cd examples/account/sponsored
npm install
GELATO_API_KEY=your-key npm run dev
链接
许可证
麻省理工学院