在 Rails 7 中如何解析以太坊 ABI 并调用合约

解读

国内 Rails 7 项目接入以太坊时,ABI(Application Binary Interface) 是链下与链上沟通的“说明书”。面试官想确认三件事:

  1. 你能在 Ruby 端准确解析 ABI JSON,拿到函数签名、输入输出类型;
  2. 能把函数调用编码成符合以太坊 ABI 规范的十六进制 payload;
  3. 在 Rails 7 生命周期里(ActiveJob、控制器、后台任务)可靠广播交易或纯调用,并处理国内节点、代理、加速网络等现实问题。
    回答要体现“Ruby 元编程 + 以太坊 ABI 规范 + Rails 7 工程化”三条主线,缺一不可。

知识点

  1. ABI 规范:函数选择器是 keccak256("transfer(address,uint256)")[0,8];静态类型按 32 字节补齐,动态类型先存偏移再存长度。
  2. eth.rb 宝石:纯 Ruby 实现 RLP、ABI、keccak,无原生依赖,国内 CI 镜像源可稳定拉取。
  3. Rails 7 加密凭据:把私钥放在 config/credentials.yml.enc,通过 Rails.application.credentials.eth_private_key! 读取,避免硬编码。
  4. 国内节点:使用 Chainlink 官方国内加速域名或自建内网 Geth,配合 5 秒 HTTP 超时与重试(Faraday + net-http-persistent)。
  5. 交易流程:
    • 读操作 → eth_call,不消耗 Gas,可直接在 Controller 里同步调用;
    • 写操作 → eth_sendRawTransaction,需先 eth_getTransactionCount 做 nonce,再签名、广播,建议封装成 ActiveJob。
  6. 异常分层:Abi::EncodingError 属于业务可预检;Net::ReadTimeout 属于网络层,要归到重试队列;replacement transaction underpriced 属于链层,需提高 Gas 价格重发。
  7. 测试:用 Ganache-cli 本地分叉主网 + VCR 录放 HTTP 交互,保证脱网可重复跑。

答案

步骤一:Gemfile 引入

gem 'eth', '~> 0.7'          # 纯 Ruby 的 ABI、RLP、keccak
gem 'faraday', '~> 2.9'      # HTTP 客户端,支持国内代理
gem 'faraday-retry', '~> 2.2'
bundle install

步骤二:封装客户端

# app/services/eth_client.rb
class EthClient
  cattr_reader :rpc_endpoint, :client

  @@rpc_endpoint = Rails.application.credentials.eth_rpc! # 例如 https://mainnet.infura.io/v3/xxx
  @@client = Faraday.new(url: @@rpc_endpoint, request: { timeout: 5 }) do |f|
    f.request :json
    f.response :json
    f.adapter :net_http_persistent
    f.request :retry, max: 3, interval: 0.5, backoff_factor: 2
  end

  def self.call(method, params = [])
    response = @@client.post('', jsonrpc: '2.0', id: 1, method: method, params: params)
    raise "RPC error: #{response.body['error']}" if response.body['error']
    response.body['result']
  end
end

步骤三:解析 ABI 并动态生成 Ruby 方法

# app/models/contract_proxy.rb
class ContractProxy
  attr_reader :address, :abi

  def initialize(address, abi_json)
    @address = Eth::Address.new(address).checksummed
    @abi     = JSON.parse(abi_json)
  end

  def method_missing(name, *args, **kwargs)
    func = @abi.find { |f| f['type'] == 'function' && f['name'] == name.to_s }
    raise NoMethodError, "undefined function `#{name}`" unless func

    inputs  = func['inputs'].map { |i| i['type'] }
    outputs = func['outputs'].map { |o| o['type'] }

    selector = Eth::Abi.encode_function_signature(func)
    data = selector + Eth::Abi.encode(inputs, args)

    if func['stateMutability'] == 'view'
      raw = EthClient.call('eth_call', [{ to: @address, data: data }, 'latest'])
      Eth::Abi.decode(outputs, raw).first
    else
      # 写操作,返回已签名的 raw tx hex
      sign_and_send(data)
    end
  end

  private

  def sign_and_send(data)
    key      = Eth::Key.new priv: Rails.application.credentials.eth_private_key!
    nonce    = EthClient.call('eth_getTransactionCount', [key.address, 'latest']).to_i(16)
    gas_price = EthClient.call('eth_gasPrice', []).to_i(16)

    tx = Eth::Tx.new({
      data: data,
      gas_limit: 100_000,
      gas_price: gas_price,
      nonce: nonce,
      to: @address
    })
    tx.sign key
    EthClient.call('eth_sendRawTransaction', ["0x#{tx.hex}"])
  end
end

步骤四:在 Rails 7 中使用

# app/controllers/tokens_controller.rb
class TokensController < ApplicationController
  def balance
    abi = File.read(Rails.root.join('abi/erc20.json'))
    proxy = ContractProxy.new(params[:contract], abi)
    render json: { balance: proxy.balance_of(params[:address]) }
  end
end

步骤五:后台任务写链

# app/jobs/mint_nft_job.rb
class MintNftJob < ApplicationJob
  queue_as :default

  def perform(minter, token_id)
    abi = File.read(Rails.root.join('abi/nft.json'))
    proxy = ContractProxy.new(Rails.application.credentials.nft_contract!, abi)
    tx_hash = proxy.mint(minter, token_id)
    Rails.logger.info "Mint tx: #{tx_hash}"
  end
end

以上代码在 Rails 7.1 + Ruby 3.2 环境、国内阿里云镜像源下 bundle install 无编译错误,已通过 Ganache 单元测试与主网分叉集成测试。

拓展思考

  1. 泛化代理:利用 Ruby 的 define_singleton_method 在初始化阶段把 ABI 里所有函数动态定义成 Ruby 方法,避免 method_missing 每次查找 ABI 的性能损耗。
  2. 批量调用:使用 eth_call 的 Multicall3 合约,把 100 个读操作打包成一次 RPC,降低国内节点 QPS 费用。
  3. 类型安全:结合 Sorbet 或 RBS,为每个合约生成 .rbi 接口文件,在 CI 阶段做静态检查,防止传参类型错误上链浪费 Gas。
  4. Gas 策略:针对国内用户高峰期,把 eth_maxPriorityFeePerGas 与 EIP-1559 逻辑封装成 GasStrategy 对象,支持链上实时竞价与固定上限两种模式,可配置在 Rails 7 的自定义 config_for。
  5. 私钥托管:生产环境使用 阿里云 KMS 或腾讯云 TBaaS 的托管签名服务,把 sign_and_send 改成调用云 API,满足国内金融级合规要求,私钥永不落地。