用F#生成Solidity接口代码

解读

国内区块链团队普遍采用“双栈”模式:链上用 Solidity 写业务合约,链下用 .NET/F# 做量化策略、后端索引或清算服务。面试现场抛出该题,核心想验证三点:

  1. 你是否把 F# 当成“代码生成器”而非“业务胶水”——能否用类型系统把 Solidity 的 ABI 语义一次性建模到位;
  2. 是否熟悉 Solidity 接口(interface)语法细节——事件、错误、结构体、函数选择器、状态可变性(view/pure/payable);
  3. 是否具备工程级思维——生成代码要可编译、可审计、可回归测试,而不是一次性脚本。

因此,题目隐含要求:给定一段 ABI JSON(或 F# 领域模型),输出可直接扔进 hardhat/foundry 工程的 *.sol 接口文件,且字段顺序、选择器、事件 topic 必须与 Solidity 编译器保持一致,否则链上链下对不上直接翻车。

知识点

  1. Solidity 接口语法规则

    • 不能包含构造函数、状态变量、函数实现;
    • 函数可见性只能是 external;
    • 需要标注 view/pure/payable;
    • 结构体、事件、错误必须在接口内部重声明,且字段名可省略但类型必须对齐;
    • 事件 topic 与函数选择器 keccak256 算法必须一致。
  2. F# 类型系统与代码生成套路

    • 递归判别联合(DU)对 Solidity 的“类型层级”建模:TyUint256 | TyInt128 | TyBool | TyBytesN of int | TyArray of Ty * int option | TyMapping of Ty * Ty …
    • 活动模式(Active Pattern)把 ABI JSON 节点做模式匹配,一次性拆出 name、inputs、outputs、stateMutability。
    • 计算表达式(CE)+ StringBuilder 实现缩进敏感的 Solidity 语法树渲染;
    • 使用 FSharp.Compiler.Service 做“自宿主”编译检查,保证生成的接口能 pass solc 0.8.x,面试现场可跑单元测试加分。
  3. 国内工程链配套

    • 必须兼容 foundry 的 fmt 规则:接口内事件在前,函数在后,结构体在中间;
    • 生成文件头要插入 SPDX-License-Identifier 与 pragma solidity ^0.8.0,否则 CI 直接报错;
    • 需要输出同名的 .md 注释文档,方便审计公司(慢雾、派盾)人工复核。

答案

以下示例把“ERC20 的 ABI 子集”硬编码成 F# 领域模型,再生成 Solidity 接口。面试时可直接粘进 dotnet fsi 执行,生成文件可通过 solc --abi --hashes 验证选择器一致。

// 面试现场可直接跑:dotnet fsi generate.fsx
#r "nuget: FSharp.Data, 4.2.7"

open System
open System.IO
open System.Text

// 1. 领域模型
type SolType =
    | Uint256 | Uint8 | Bool | String | Address
    | Array of SolType * int option  // int=Some 8 表示固定数组[8]
    | Tuple of SolType list

type StateMutability = Pure | View | Payable | NonPayable

type Event =
    { Name: string
      Inputs: (string * SolType * bool) list } // name*type*indexed

type Function =
    { Name: string
      Inputs: (string * SolType) list
      Outputs: SolType list
      StateMut: StateMutability }

type InterfaceDecl =
    { Name: string
      Events: Event list
      Functions: Function list }

// 2. 渲染器
let rec typeName = function
    | Uint256 -> "uint256"
    | Uint8   -> "uint8"
    | Bool    -> "bool"
    | String  -> "string"
    | Address -> "address"
    | Array(t, None) -> $"{typeName t}[]"
    | Array(t, Some n) -> $"{typeName t}[{n}]"
    | Tuple ts -> $"({ts |> List.map typeName |> String.concat ","})"

let renderEvent (e: Event) =
    let args =
        e.Inputs
        |> List.map (fun (n,t,indexed) ->
            let idx = if indexed then " indexed" else ""
            $"{typeName t}{idx} {n}")
        |> String.concat ", "
    $"event {e.Name}({args});"

let renderFunc (f: Function) =
    let mut =
        match f.StateMut with
        | Pure -> " pure"
        | View -> " view"
        | Payable -> " payable"
        | NonPayable -> ""
    let ins =
        f.Inputs
        |> List.map (fun (n,t) -> $"{typeName t} {n}")
        |> String.concat ", "
    let outs =
        match f.Outputs with
        | [] -> ""
        | [t] -> $" returns ({typeName t})"
        | ts  -> $" returns (({ts |> List.map typeName |> String.concat ","}))"
    $"function {f.Name}({ins}) external{mut}{outs};"

let renderInterface (decl: InterfaceDecl) =
    let sb = StringBuilder()
    sb.AppendLine("// SPDX-License-Identifier: MIT") |> ignore
    sb.AppendLine("pragma solidity ^0.8.0;") |> ignore
    sb.AppendLine("") |> ignore
    sb.AppendLine($"interface {decl.Name} {{") |> ignore
    // 事件在前
    decl.Events |> List.iter (fun e -> sb.AppendLine($"    {renderEvent e}") |> ignore)
    if decl.Events.Length > 0 then sb.AppendLine("") |> ignore
    // 函数在后
    decl.Functions |> List.iter (fun f -> sb.AppendLine($"    {renderFunc f}") |> ignore)
    sb.AppendLine("}") |> ignore
    sb.ToString()

// 3. 测试数据:ERC20 子集
let erc20 : InterfaceDecl =
    { Name = "IERC20"
      Events =
        [ { Name = "Transfer"
            Inputs = [("from", Address, true); ("to", Address, true); ("value", Uint256, false)] }
          { Name = "Approval"
            Inputs = [("owner", Address, true); ("spender", Address, true); ("value", Uint256, false)] } ]
      Functions =
        [ { Name = "totalSupply"; Inputs = []; Outputs = [Uint256]; StateMut = View }
          { Name = "balanceOf"; Inputs = [("account", Address)]; Outputs = [Uint256]; StateMut = View }
          { Name = "transfer"; Inputs = [("to", Address); ("amount", Uint256)]; Outputs = [Bool]; StateMut = NonPayable }
          { Name = "allowance"; Inputs = [("owner", Address); ("spender", Address)]; Outputs = [Uint256]; StateMut = View }
          { Name = "approve"; Inputs = [("spender", Address); ("amount", Uint256)]; Outputs = [Bool]; StateMut = NonPayable }
          { Name = "transferFrom"; Inputs = [("from", Address); ("to", Address); ("amount", Uint256)]; Outputs = [Bool]; StateMut = NonPayable } ] }

// 4. 生成
let outPath = "IERC20.sol"
File.WriteAllText(outPath, renderInterface erc20)
printfn $"已生成 {outPath}"

执行后得到标准 IERC20.sol,可直接通过 solc --abi IERC20.sol 验证函数选择器与 OpenZeppelin 官方一致,面试现场可当场跑通。

拓展思考

  1. 如果 ABI 里出现自定义结构体(tuple),F# 端如何保持字段名?
    可扩展 SolType 为 NamedTuple of (string * SolType) list,并在渲染时把结构体内联到接口顶部,注意 Solidity 0.8.0 以上才允许接口内嵌结构体。

  2. 如何支持泛型接口模板?
    利用 F# 的类型提供程序(Type Provider)读取链上 verified source,再实例化泛型模板,例如 interface IUniswapV3Pool<TFee>,面试时提到“TP 读取 Etherscan 反编译”可瞬间拉高段位。

  3. 生成代码的回归测试怎么做?
    在 xUnit 里启动 foundry 的 forge build --via-ir,把生成的接口与 mock 合约一起编译,再用 Warp 做 gas snapshot,确保升级前后选择器与 gas 不变,国内审计报告常要求此环节。

  4. 反向需求:把 Solidity 接口解析成 F# 的 CLR 类型,供量化程序做强类型调用,该如何设计?
    可写 F# Type Provider for ABI,实时生成调用合约的 Quotations,再编译成 LINQ Expression,对性能敏感的量化交易可省掉 Nethereum 的反射开销,面试提到“TP + Expression 树”可展示你对 .NET 生态的穿透力。