Eth.swift

一个轻量级的 Swift Ethereum 库。

运行测试

使用 swift test 运行测试,最好配合 xcbeautify 使用。

swift test | xcbeautify

(通过 brew install xcbeautify 安装 xcbeautify)

若要使用 EVM 调试信息进行测试

swift test -Xswiftc -DDEBUG_EVM

用法

ABI

ABI/Schema 枚举定义了 Ethereum ABI 定义,而 ABI/Value 枚举定义了一个解码后的值。你可以使用 ABI/Value/encoded 计算属性快速编码 ABI 值

let data: Data = ABI.Value.tuple1(.array(.string, [.string("hello"), .string("world")])).encoded

并使用 ABI/Schema/decode(_:) 解码值。

let schema: ABI.Schema = .tuple([.array(.string)])

switch try schema.decode(data) {
case let .tuple1(.array(_, words)):
  print(words.map { $0.asString! }.joined(separator: " and "))
default:
  throw ABI.DecodeError.invalidResponse
}

如上所述,元组通常表示为 .tuple2(.uint8(1), .uint8(2)),以便于解包。 你也可以使用辅助方法(例如 ABI/Value/asString, ABI/Value/asBigUInt, ...)解包值。

从 ABI 生成 Swift 代码

要从 ABI json 文件(例如 forge buildout/ 目录)生成 Swift 文件,请运行

swift run Geno ./out/Cool.sol/Cool.json --outDir Sources/

还建议您在生成的文件上运行 swiftformat。有关代码生成的更多信息,请参见 Geno

EVM

EVM 模块允许你在本地运行纯 EVM 代码。例如,如果你有以下 Solidity 文件

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

contract MyContract {
    function add55(uint256 x) pure external returns (uint256) {
        return 55 + x;
    }
}

那么,你可以从 MyContract.sol/MyContract.json 获取其部署的字节码,并通过 EVM/decodeCode(fromData:)EVM/runQuery(bytecode:query:withValue:) 在 EVM 中执行该函数。

let code = try! EVM.decodeCode(fromData: Hex.hex("...")) // The deployed bytecode
let result = try! EVM.runQuery(bytecode: code, query: .tuple1(.uint256(22)))
print("result=" + result.asArray![0].asBigUInt!)

兼容性测试

兼容性测试是 Solidity 测试,它会记录其结果。 然后,我们将 Eth.swift EVM 的输出与这些结果进行比较,以确保对各种真实的 Solidity 合约的兼容性。

要构建兼容性测试,请确保安装了 forge 并安装子模块 git submodule update --init --recursive,然后运行 ./Tests/Solidity/build-compliance-tests.sh。 注意:除非你正在编辑兼容性测试,否则不需要运行此操作。

编码规范

请在提交之前对所有文件使用 swiftformat。 要安装 swiftformat,请运行 brew install swiftformat