Transaction API
交易 API 提供完整的交易生命周期管理,包括交易构建、执行、跟踪和状态查询功能。
端点
POST /v1/transaction/build
POST /v1/transaction/execute
GET /v1/transaction/{txId}/status
POST /v1/transaction/batch交易构建
构建交易数据
POST /v1/transaction/build
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY请求参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
quoteId | string | ✅ | 报价 ID(来自 Quote API) |
userAddress | string | ✅ | 用户钱包地址 |
recipient | string | ❌ | 接收地址,默认为用户地址 |
deadline | number | ❌ | 交易截止时间(Unix 时间戳) |
gasSettings | GasSettings | ❌ | Gas 设置 |
GasSettings 对象
interface GasSettings {
gasLimit?: string; // Gas 限制
maxFeePerGas?: string; // 最大 Gas 费用
maxPriorityFeePerGas?: string; // 最大优先费用
gasPrice?: string; // Gas 价格(Legacy)
}示例请求
{
"quoteId": "quote_1759231185333_abc123",
"userAddress": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8",
"recipient": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8",
"deadline": 1759234785,
"gasSettings": {
"gasLimit": "650000",
"maxFeePerGas": "1000483",
"maxPriorityFeePerGas": "1000000"
}
}响应格式
{
"success": true,
"data": {
"transactionId": "tx_1759231185333_def456",
"transactions": [
{
"chainId": 10,
"to": "0x89415a82d909a7238d69094C3Dd1dCC1aCbDa85C",
"data": "0x095ea7b3000000000000000000000000...",
"value": "0",
"gas": "46000",
"maxFeePerGas": "1000483",
"maxPriorityFeePerGas": "1000000",
"type": "approval",
"description": "Approve USDC.e spending"
},
{
"chainId": 10,
"to": "0x89415a82d909a7238d69094C3Dd1dCC1aCbDa85C",
"data": "0x3593564c000000000000000000000000...",
"value": "0",
"gas": "649910",
"maxFeePerGas": "1000483",
"maxPriorityFeePerGas": "1000000",
"type": "swap",
"description": "Execute cross-chain swap"
}
],
"summary": {
"totalGasEstimate": "695910",
"totalGasCostUsd": "2.70",
"requiredApprovals": 1,
"estimatedTime": 420
},
"validUntil": 1759231485
},
"timestamp": "2024-01-01T00:00:00Z"
}交易执行
执行交易
POST /v1/transaction/execute
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY请求参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
transactionId | string | ✅ | 交易 ID(来自构建 API) |
signatures | string[] | ✅ | 交易签名数组 |
broadcast | boolean | ❌ | 是否广播交易,默认 true |
示例请求
{
"transactionId": "tx_1759231185333_def456",
"signatures": [
"0x1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b",
"0x2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c"
],
"broadcast": true
}响应格式
{
"success": true,
"data": {
"transactionId": "tx_1759231185333_def456",
"status": "submitted",
"transactions": [
{
"hash": "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b",
"chainId": 10,
"type": "approval",
"status": "confirmed",
"blockNumber": 118234567,
"gasUsed": "46000"
},
{
"hash": "0x2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c",
"chainId": 10,
"type": "swap",
"status": "pending",
"estimatedConfirmation": 1759231245
}
],
"progress": {
"currentStep": 2,
"totalSteps": 3,
"percentage": 66.7,
"estimatedCompletion": 1759231605
}
},
"timestamp": "2024-01-01T00:00:00Z"
}交易状态查询
获取交易状态
GET /v1/transaction/{transactionId}/status
Authorization: Bearer YOUR_API_KEY路径参数
| 参数 | 类型 | 描述 |
|---|---|---|
transactionId | string | 交易 ID |
查询参数
| 参数 | 类型 | 描述 |
|---|---|---|
includeDetails | boolean | 是否包含详细信息 |
响应格式
{
"success": true,
"data": {
"transactionId": "tx_1759231185333_def456",
"status": "completed",
"result": {
"success": true,
"finalAmountOut": "1000000",
"actualGasUsed": "645230",
"totalGasCostUsd": "2.65"
},
"timeline": [
{
"step": "approval",
"status": "completed",
"txHash": "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b",
"timestamp": 1759231215,
"gasUsed": "46000"
},
{
"step": "originSwap",
"status": "completed",
"txHash": "0x2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c",
"timestamp": 1759231245,
"gasUsed": "599230",
"amountOut": "1010025"
},
{
"step": "bridge",
"status": "completed",
"txHash": "0x3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d",
"timestamp": 1759231605,
"amountOut": "1000000"
}
],
"createdAt": 1759231185,
"completedAt": 1759231605,
"totalTime": 420
},
"timestamp": "2024-01-01T00:00:00Z"
}批量交易
批量执行交易
POST /v1/transaction/batch
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY请求参数
{
"transactions": [
{
"id": "batch_1",
"quoteId": "quote_1759231185333_abc123",
"userAddress": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8"
},
{
"id": "batch_2",
"quoteId": "quote_1759231185333_def456",
"userAddress": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8"
}
],
"gasSettings": {
"gasLimit": "1000000",
"maxFeePerGas": "1000483"
}
}响应格式
{
"success": true,
"data": {
"batchId": "batch_1759231185333_ghi789",
"transactions": [
{
"id": "batch_1",
"transactionId": "tx_1759231185333_jkl012",
"status": "built",
"gasEstimate": "650000"
},
{
"id": "batch_2",
"transactionId": "tx_1759231185333_mno345",
"status": "built",
"gasEstimate": "620000"
}
],
"summary": {
"totalTransactions": 2,
"totalGasEstimate": "1270000",
"totalGasCostUsd": "5.20",
"estimatedSavings": "0.30"
}
}
}交易状态
状态类型
| 状态 | 描述 |
|---|---|
building | 正在构建交易 |
built | 交易已构建,等待签名 |
signing | 正在签名 |
submitting | 正在提交到网络 |
submitted | 已提交,等待确认 |
confirming | 正在确认 |
completed | 交易完成 |
failed | 交易失败 |
expired | 交易过期 |
步骤类型
| 步骤 | 描述 |
|---|---|
approval | 代币授权 |
originSwap | 源链交换 |
bridge | 跨链桥接 |
destinationSwap | 目标链交换 |
错误处理
常见错误
| 错误码 | 描述 | 解决方案 |
|---|---|---|
INVALID_QUOTE | 无效的报价 ID | 使用有效的报价 ID |
QUOTE_EXPIRED | 报价已过期 | 重新获取报价 |
INSUFFICIENT_BALANCE | 余额不足 | 检查账户余额 |
INSUFFICIENT_ALLOWANCE | 授权不足 | 增加代币授权 |
TRANSACTION_FAILED | 交易失败 | 检查交易参数和网络状态 |
INVALID_SIGNATURE | 无效签名 | 重新签名交易 |
GAS_LIMIT_EXCEEDED | Gas 限制超出 | 增加 Gas 限制 |
DEADLINE_EXCEEDED | 超过截止时间 | 设置更长的截止时间 |
错误响应示例
{
"success": false,
"data": null,
"error": {
"code": "TRANSACTION_FAILED",
"message": "Transaction execution failed",
"details": {
"step": "originSwap",
"txHash": "0x2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c",
"reason": "Slippage tolerance exceeded",
"gasUsed": "599230"
}
},
"timestamp": "2024-01-01T00:00:00Z"
}代码示例
JavaScript/TypeScript
import { CyberPaySDK } from '@cyberpay/sdk';
const sdk = new CyberPaySDK({
apiKey: 'YOUR_API_KEY'
});
// 完整的交易流程
async function executeSwap() {
try {
// 1. 获取报价
const quote = await sdk.quote.get({
tokenIn: {
address: '0x7F5c764cBc14f9669B88837ca1490cCa17c31607',
decimals: 6,
symbol: 'USDC.e',
chainId: 10
},
tokenOut: {
address: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',
decimals: 6,
symbol: 'USDC',
chainId: 137
},
amountIn: '1000000'
});
// 2. 构建交易
const transaction = await sdk.transaction.build({
quoteId: quote.quoteId,
userAddress: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8'
});
// 3. 签名交易
const signatures = [];
for (const tx of transaction.transactions) {
const signature = await wallet.signTransaction(tx);
signatures.push(signature);
}
// 4. 执行交易
const execution = await sdk.transaction.execute({
transactionId: transaction.transactionId,
signatures: signatures
});
// 5. 监控交易状态
const status = await sdk.transaction.getStatus(execution.transactionId);
console.log('Transaction status:', status);
return execution;
} catch (error) {
console.error('Error executing swap:', error);
}
}React Hook 示例
import { useTransaction } from '@cyberpay/react';
function SwapExecutor({ quoteId, userAddress }) {
const {
buildTransaction,
executeTransaction,
getStatus,
loading,
error,
transaction
} = useTransaction();
const handleExecute = async () => {
try {
// 构建交易
const built = await buildTransaction({
quoteId,
userAddress
});
// 这里需要用户签名
const signatures = await signTransactions(built.transactions);
// 执行交易
const executed = await executeTransaction({
transactionId: built.transactionId,
signatures
});
// 监控状态
const status = await getStatus(executed.transactionId);
console.log('Status:', status);
} catch (err) {
console.error('Execution failed:', err);
}
};
return (
<div>
<button
onClick={handleExecute}
disabled={loading}
>
{loading ? 'Executing...' : 'Execute Swap'}
</button>
{error && (
<div className="error">
Error: {error.message}
</div>
)}
{transaction && (
<div className="status">
Status: {transaction.status}
Progress: {transaction.progress?.percentage}%
</div>
)}
</div>
);
}最佳实践
1. 交易前检查
- 验证用户余额和授权
- 检查报价是否仍然有效
- 确认网络状态正常
2. Gas 管理
- 使用动态 Gas 价格
- 为复杂交易预留足够的 Gas
- 监控网络拥堵情况
3. 错误处理
- 实现重试机制
- 提供清晰的错误信息
- 记录失败原因用于调试
4. 用户体验
- 显示交易进度
- 提供预估完成时间
- 允许用户取消未确认的交易
5. 安全考虑
- 验证所有交易参数
- 使用安全的签名方法
- 实现交易限额检查
交易监控
WebSocket 状态更新
const ws = new WebSocket('wss://api.cyberpay.org/v1/transaction/stream');
ws.onopen = function() {
// 订阅交易状态更新
ws.send(JSON.stringify({
action: 'subscribe',
transactionId: 'tx_1759231185333_def456'
}));
};
ws.onmessage = function(event) {
const update = JSON.parse(event.data);
console.log('Transaction update:', update);
};状态更新消息格式
{
"type": "transaction_update",
"data": {
"transactionId": "tx_1759231185333_def456",
"status": "confirming",
"step": "originSwap",
"txHash": "0x2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c",
"confirmations": 3,
"requiredConfirmations": 12,
"timestamp": 1759231245
}
}费用优化
Gas 费用预估
// 获取当前网络的 Gas 价格建议
const gasPrice = await sdk.gas.getPrice(chainId);
// 使用建议的 Gas 设置
const gasSettings = {
gasLimit: gasPrice.gasLimit,
maxFeePerGas: gasPrice.fast.maxFeePerGas,
maxPriorityFeePerGas: gasPrice.fast.maxPriorityFeePerGas
};批量操作优化
// 批量执行多个交换以节省 Gas
const batchResult = await sdk.transaction.batch({
transactions: [
{ quoteId: 'quote1', userAddress: address },
{ quoteId: 'quote2', userAddress: address },
{ quoteId: 'quote3', userAddress: address }
]
});通过 Transaction API,您可以安全、高效地执行跨链代币交换,并实时跟踪交易状态。API 提供了完整的交易生命周期管理,确保用户获得最佳的交易体验。
