跳转到主要内容

Documentation Index

Fetch the complete documentation index at: https://docs.blockradar.co/llms.txt

Use this file to discover all available pages before exploring further.

简而言之
Blockradar 的 Smart Contract API 让您可以直接从钱包与任何智能合约交互,无需自行管理 RPC 端点、签名流程或合约部署。
Smart Contracts

先决条件

在使用 Smart Contract API 之前,请确保您已具备:
1

API 密钥

Blockradar Dashboard 获取您的 API 密钥。前往 Developers 即可生成。
2

已创建钱包

通过 Create Wallet API 或 dashboard 创建钱包。所有智能合约操作都需要 walletId
3

原生币余额

为您的钱包充值原生币(ETH、BNB、MATIC 等)以支付 gas 费用。在执行前,使用 Network Fee 端点 估算成本。

支持的区块链

Smart Contract API 支持 Blockradar 上提供的所有 EVM 兼容区块链以及 Tron。请参阅 Integrations 查看支持的网络完整列表和 faucet 链接。
Solana 不支持智能合约交互。Smart Contract API 仅适用于 EVM 兼容链和 Tron。
开发期间从 testnet 开始,避免消耗真实资金。

简介

Smart Contract API 将 Blockradar 从一个钱包基础设施转变为一个可编程的执行层。您可以读取合约状态、执行合约函数、估算 gas 费用并签名交易——全部通过统一的 API 接口完成。

读取操作

从受支持的区块链上的任何智能合约检索数据。

写入操作

执行智能合约函数,并完整管理交易。

费用估算

在执行前计算 gas 成本,以确保资金充足。

批量操作

在单个 API 请求中执行多个合约调用。

用例

Smart Contract API 为金融科技开发者解锁强大的能力:
  • DeFi 集成:连接到 Uniswap、Aave 或 Compound 等协议,进行收益和流动性管理
  • 资金运营:在您的金融科技平台内自动化资金管理
  • 代币化资产:将真实世界资产集成到产品流程中
  • 可编程结算:执行合规检查和自动化结算
  • 自定义资产:管理自定义资产、奖励系统和忠诚度计划

Master Wallet vs Child Address

Smart Contract API 提供两个层级:

Master Wallet

直接从您的 master wallet 执行合约操作。非常适合资金运营和集中式资金管理。

Child Address

从单个 child address 执行合约操作。非常适合特定用户的操作和分隔式资金管理。

Master Wallet 端点

操作端点描述
读取POST /v1/wallets/{walletId}/contracts/read从智能合约检索数据
写入POST /v1/wallets/{walletId}/contracts/write执行智能合约函数
Network FeePOST /v1/wallets/{walletId}/contracts/network-fee估算 gas 成本
Sign OnlyPOST /v1/wallets/{walletId}/contracts/write/sign签名但不广播

Child Address 端点

操作端点描述
读取POST /v1/wallets/{walletId}/addresses/{addressId}/contracts/read从智能合约检索数据
写入POST /v1/wallets/{walletId}/addresses/{addressId}/contracts/write执行智能合约函数
Network FeePOST /v1/wallets/{walletId}/addresses/{addressId}/contracts/network-fee估算 gas 成本
Sign OnlyPOST /v1/wallets/{walletId}/addresses/{addressId}/contracts/write/sign签名但不广播

请求结构

所有智能合约请求都需要以下参数:
参数类型必填描述
addressstring智能合约的区块链地址
methodstring要调用的函数名称
parametersarray与函数 ABI 顺序匹配的参数
abiarray合约的 Application Binary Interface
referencestring您用于跟踪交易的内部 ID
metadataobject用于附加交易详情的自定义键值对
referencemetadata 字段仅适用于写入操作。读取操作不支持这些字段。

理解 ABI

ABI(Application Binary Interface)定义了如何与智能合约交互。您可以从以下渠道获取 ABI:
  • 区块浏览器:Etherscan、BscScan、PolygonScan(已验证的合约)
  • 协议文档:DeFi 协议的官方文档
  • 合约源代码:从 Solidity 源代码编译

读取合约数据

使用读取端点查询合约状态,而不修改区块链。

Master Wallet 读取示例

curl --request POST \
  --url https://api.blockradar.co/v1/wallets/{walletId}/contracts/read \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: <api-key>' \
  --data '{
    "address": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd",
    "method": "balanceOf",
    "parameters": ["0x947514e4B803e312C312da0F1B41fEDdbe15ae7a"],
    "abi": [{
      "constant": true,
      "inputs": [{"name": "account", "type": "address"}],
      "name": "balanceOf",
      "outputs": [{"name": "", "type": "uint256"}],
      "stateMutability": "view",
      "type": "function"
    }]
  }'

Child Address 读取示例

curl --request POST \
  --url https://api.blockradar.co/v1/wallets/{walletId}/addresses/{addressId}/contracts/read \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: <api-key>' \
  --data '{
    "address": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd",
    "method": "balanceOf",
    "parameters": ["0x947514e4B803e312C312da0F1B41fEDdbe15ae7a"],
    "abi": [{
      "constant": true,
      "inputs": [{"name": "account", "type": "address"}],
      "name": "balanceOf",
      "outputs": [{"name": "", "type": "uint256"}],
      "stateMutability": "view",
      "type": "function"
    }]
  }'

读取响应

{
  "message": "Contract read successfully",
  "statusCode": 200,
  "data": "10052335235393043"
}

读取错误响应

{
  "message": "Invalid contract address",
  "statusCode": 400,
  "error": "BAD_REQUEST"
}
{
  "message": "Method 'balanceOf' not found in ABI",
  "statusCode": 400,
  "error": "ABI_METHOD_NOT_FOUND"
}
{
  "message": "Contract execution reverted",
  "statusCode": 400,
  "error": "EXECUTION_REVERTED",
  "data": {
    "reason": "ERC20: balance query for zero address"
  }
}
{
  "message": "Parameter count mismatch. Expected 1, got 2",
  "statusCode": 400,
  "error": "INVALID_PARAMETERS"
}

写入合约

执行更改智能合约状态的函数。

Master Wallet 写入示例

curl --request POST \
  --url https://api.blockradar.co/v1/wallets/{walletId}/contracts/write \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: <api-key>' \
  --data '{
    "address": "0xYOUR_TOKEN_CONTRACT",
    "method": "approve",
    "parameters": ["0xYOUR_SPENDER_ADDRESS", "1000000000000000000"],
    "abi": [{
      "inputs": [
        {"name": "spender", "type": "address"},
        {"name": "amount", "type": "uint256"}
      ],
      "name": "approve",
      "outputs": [{"name": "", "type": "bool"}],
      "stateMutability": "nonpayable",
      "type": "function"
    }]
  }'

Child Address 写入示例

curl --request POST \
  --url https://api.blockradar.co/v1/wallets/{walletId}/addresses/{addressId}/contracts/write \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: <api-key>' \
  --data '{
    "address": "0xYOUR_TOKEN_CONTRACT",
    "method": "approve",
    "parameters": ["0xYOUR_SPENDER_ADDRESS", "1000000000000000000"],
    "abi": [{
      "inputs": [
        {"name": "spender", "type": "address"},
        {"name": "amount", "type": "uint256"}
      ],
      "name": "approve",
      "outputs": [{"name": "", "type": "bool"}],
      "stateMutability": "nonpayable",
      "type": "function"
    }]
  }'

写入响应

{
  "message": "Contract write initiated",
  "statusCode": 200,
  "data": {
    "id": "tx-uuid",
    "hash": "0x...",
    "status": "PENDING"
  }
}
写入操作是异步的。初始响应显示 PENDING 状态。请监听 custom-smart-contract.success webhook 以确认交易完成。

写入错误响应

{
  "message": "Insufficient native token balance for gas",
  "statusCode": 400,
  "error": "INSUFFICIENT_GAS",
  "data": {
    "required": "0.005",
    "available": "0.001",
    "token": "ETH"
  }
}
{
  "message": "Insufficient token balance",
  "statusCode": 400,
  "error": "INSUFFICIENT_BALANCE",
  "data": {
    "required": "1000000000000000000",
    "available": "500000000000000000"
  }
}
{
  "message": "Transaction would revert",
  "statusCode": 400,
  "error": "EXECUTION_REVERTED",
  "data": {
    "reason": "ERC20: transfer amount exceeds allowance"
  }
}
{
  "message": "Invalid ABI format",
  "statusCode": 400,
  "error": "INVALID_ABI",
  "data": {
    "details": "Missing 'inputs' field in ABI definition"
  }
}
{
  "message": "Wallet not found",
  "statusCode": 404,
  "error": "NOT_FOUND"
}

估算网络费用

在执行写入操作之前始终估算费用,以确保您的钱包有足够的原生币。

Master Wallet 费用估算

curl --request POST \
  --url https://api.blockradar.co/v1/wallets/{walletId}/contracts/network-fee \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: <api-key>' \
  --data '{
    "address": "0xYOUR_TOKEN_CONTRACT",
    "method": "approve",
    "parameters": ["0xYOUR_SPENDER_ADDRESS", "1000000000000000000"],
    "abi": [{
      "inputs": [
        {"name": "spender", "type": "address"},
        {"name": "amount", "type": "uint256"}
      ],
      "name": "approve",
      "outputs": [{"name": "", "type": "bool"}],
      "stateMutability": "nonpayable",
      "type": "function"
    }]
  }'

Child Address 费用估算

curl --request POST \
  --url https://api.blockradar.co/v1/wallets/{walletId}/addresses/{addressId}/contracts/network-fee \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: <api-key>' \
  --data '{
    "address": "0xYOUR_TOKEN_CONTRACT",
    "method": "approve",
    "parameters": ["0xYOUR_SPENDER_ADDRESS", "1000000000000000000"],
    "abi": [{
      "inputs": [
        {"name": "spender", "type": "address"},
        {"name": "amount", "type": "uint256"}
      ],
      "name": "approve",
      "outputs": [{"name": "", "type": "bool"}],
      "stateMutability": "nonpayable",
      "type": "function"
    }]
  }'

费用响应

{
  "message": "Network fee retrieved",
  "statusCode": 200,
  "data": {
    "networkFee": "0.00001247904",
    "networkFeeInUSD": "0.01",
    "nativeBalance": "0.5",
    "nativeBalanceInUSD": "450.00",
    "estimatedArrivalTime": 30
  }
}

实践示例:在 Uniswap 上进行资产兑换

本节演示了执行资产兑换的两种方法:不使用批量操作(顺序调用)和使用批量操作(单次 API 调用)。

示例 1:不使用批量操作的资产兑换

此方法为每个步骤进行单独的 API 调用。当您需要对每笔交易进行精细控制,或当操作依赖于先前调用的结果时,请使用此方法。

步骤 1:检查资产余额

const balanceOfAbi = {
  constant: true,
  inputs: [{ name: 'account', type: 'address' }],
  name: 'balanceOf',
  outputs: [{ name: '', type: 'uint256' }],
  stateMutability: 'view',
  type: 'function'
};

const balance = await fetch(
  `https://api.blockradar.co/v1/wallets/${walletId}/contracts/read`,
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey },
    body: JSON.stringify({
      address: TOKEN_ADDRESS,
      method: 'balanceOf',
      parameters: [walletAddress],
      abi: [balanceOfAbi]
    })
  }
).then(r => r.json());

console.log('Asset Balance:', balance.data);

步骤 2:批准资产花费

const approveAbi = {
  inputs: [
    { name: 'spender', type: 'address' },
    { name: 'amount', type: 'uint256' }
  ],
  name: 'approve',
  outputs: [{ name: '', type: 'bool' }],
  stateMutability: 'nonpayable',
  type: 'function'
};

const approval = await fetch(
  `https://api.blockradar.co/v1/wallets/${walletId}/contracts/write`,
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey },
    body: JSON.stringify({
      address: TOKEN_ADDRESS,
      method: 'approve',
      parameters: [UNISWAP_ROUTER, amountIn],
      abi: [approveAbi]
    })
  }
).then(r => r.json());

console.log('Approval TX:', approval.data.hash);
// IMPORTANT: Wait for webhook confirmation before proceeding
在执行 swap 之前,请始终等待 custom-smart-contract.success webhook 确认批准交易已被打包。

步骤 3:估算 swap 费用

const swapAbi = {
  inputs: [
    { name: 'amountIn', type: 'uint256' },
    { name: 'amountOutMin', type: 'uint256' },
    { name: 'path', type: 'address[]' },
    { name: 'to', type: 'address' },
    { name: 'deadline', type: 'uint256' }
  ],
  name: 'swapExactTokensForTokens',
  outputs: [{ name: 'amounts', type: 'uint256[]' }],
  stateMutability: 'nonpayable',
  type: 'function'
};

const fees = await fetch(
  `https://api.blockradar.co/v1/wallets/${walletId}/contracts/network-fee`,
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey },
    body: JSON.stringify({
      address: UNISWAP_ROUTER,
      method: 'swapExactTokensForTokens',
      parameters: [
        amountIn,
        amountOutMin,
        [TOKEN_A, TOKEN_B],
        walletAddress,
        deadline
      ],
      abi: [swapAbi]
    })
  }
).then(r => r.json());

console.log('Estimated Fee:', fees.data.networkFee);

步骤 4:执行 swap

const swap = await fetch(
  `https://api.blockradar.co/v1/wallets/${walletId}/contracts/write`,
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey },
    body: JSON.stringify({
      address: UNISWAP_ROUTER,
      method: 'swapExactTokensForTokens',
      parameters: [
        amountIn,
        amountOutMin,
        [TOKEN_A, TOKEN_B],
        walletAddress,
        deadline
      ],
      abi: [swapAbi]
    })
  }
).then(r => r.json());

console.log('Swap TX:', swap.data.hash);

示例 2:使用批量操作的资产兑换

此方法使用 calls 数组将 approve + swap 合并到单次 API 调用中。当您希望将多个操作排队执行以提高效率时,请使用此方法。
批量操作按顺序执行。每个操作作为单独的交易提交,但您只需要一次 API 调用。

批量请求:在一次调用中完成 approve + swap

const approveAbi = {
  inputs: [
    { name: 'spender', type: 'address' },
    { name: 'amount', type: 'uint256' }
  ],
  name: 'approve',
  outputs: [{ name: '', type: 'bool' }],
  stateMutability: 'nonpayable',
  type: 'function'
};

const swapAbi = {
  inputs: [
    { name: 'amountIn', type: 'uint256' },
    { name: 'amountOutMin', type: 'uint256' },
    { name: 'path', type: 'address[]' },
    { name: 'to', type: 'address' },
    { name: 'deadline', type: 'uint256' }
  ],
  name: 'swapExactTokensForTokens',
  outputs: [{ name: 'amounts', type: 'uint256[]' }],
  stateMutability: 'nonpayable',
  type: 'function'
};

const batchSwap = await fetch(
  `https://api.blockradar.co/v1/wallets/${walletId}/contracts/write`,
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey },
    body: JSON.stringify({
      calls: [
        {
          address: TOKEN_ADDRESS,
          method: 'approve',
          parameters: [UNISWAP_ROUTER, amountIn],
          abi: [approveAbi],
          reference: 'approve-tx',
          metadata: { step: 'approval' }
        },
        {
          address: UNISWAP_ROUTER,
          method: 'swapExactTokensForTokens',
          parameters: [
            amountIn,
            amountOutMin,
            [TOKEN_A, TOKEN_B],
            walletAddress,
            deadline
          ],
          abi: [swapAbi],
          reference: 'swap-tx',
          metadata: { step: 'swap' }
        }
      ]
    })
  }
).then(r => r.json());

console.log('Batch Result:', batchSwap.data);

批量响应

{
  "message": "Batch contract write initiated successfully",
  "statusCode": 200,
  "data": {
    "success": [
      {
        "index": 0,
        "id": "tx-uuid-1",
        "hash": "0xapprove...",
        "status": "PENDING",
        "reference": "approve-tx"
      },
      {
        "index": 1,
        "id": "tx-uuid-2",
        "hash": "0xswap...",
        "status": "PENDING",
        "reference": "swap-tx"
      }
    ],
    "errors": []
  }
}

处理批量中的部分失败

const result = await batchSwap.json();

// Check for successful operations
result.data.success.forEach(tx => {
  console.log(`✓ ${tx.reference}: ${tx.hash}`);
});

// Check for failed operations
result.data.errors.forEach(error => {
  console.error(`✗ Operation ${error.index} (${error.method}): ${error.error}`);
});

批量操作规则

规则
批量最大大小20 个操作
执行顺序顺序
错误处理部分成功(失败不会阻止后续操作)

何时使用每种方法

场景推荐方法
需要在步骤之间检查结果不使用批量
基于先前结果的动态参数不使用批量
简单的 approve + 操作模式使用批量
多个独立操作使用批量
最小化 API 调用使用批量

Webhook 事件

智能合约操作会触发 webhook 通知:
事件描述
custom-smart-contract.success合约操作成功完成
custom-smart-contract.failed合约操作失败

Webhook 负载

{
  "event": "custom-smart-contract.success",
  "data": {
    "id": "tx-uuid",
    "hash": "0x...",
    "status": "SUCCESS",
    "method": "approve",
    "contractAddress": "0x...",
    "blockchain": {
      "name": "ethereum",
      "network": "mainnet"
    }
  }
}

最佳实践

安全

  • 验证合约地址:在交互前始终仔细核对合约地址
  • 使用可信的 ABI:从已验证的来源(如区块浏览器)获取 ABI
  • 设置合理的限制:对 DeFi 操作使用滑点保护和金额上限

Gas 管理

  • 执行前估算:始终先调用 network-fee 端点
  • 监控原生币余额:确保有足够的 ETH/BNB/MATIC 用于支付 gas 费用
  • 使用批量操作:通过批量处理相关操作来减少开销

错误处理

  • 实现 webhook 监听器:不要仅依赖 API 响应
  • 处理部分失败:检查批量响应中的 successerrors 数组
  • 使用退避重试:为暂时性故障实现指数退避

API 参考

Master Wallet 端点

端点描述
Read Contract读取合约状态
Write Contract执行合约函数
Network Fee估算 gas 成本
Sign Only签名但不广播

Child Address 端点

端点描述
Read Contract读取合约状态
Write Contract执行合约函数
Network Fee估算 gas 成本
Sign Only签名但不广播

支持

Smart Contract API 让您无需管理基础设施复杂性即可构建复杂的区块链集成。从简单的读取操作开始,随着对系统的熟悉逐步引入写入操作。