3分钟Solidity: 9.2 简单字节码合约

13 阅读2分钟

欢迎订阅专栏3分钟Solidity--智能合约--Web3区块链技术必学

如需获取本内容的最新版本,请参见 Cyfrin.io 上的简易字节码契约(代码示例)

  • runtimeCode 是部署后存储在链上的实际代码。

  • 使用内联汇编中的 create 操作码部署字节码。

  • 部署的合约没有函数接口,直接调用时会返回 255,因为运行时代码只是将 255 写入内存并返回。

  • 这种方式可以在没有 Solidity 源码的情况下部署合约。

  • 常用于 Gas 优化最小代理合约(Minimal Proxy)元编程 等场景。

  • 部署前务必验证字节码的正确性,以免浪费 Gas。

用字节码编写的合约的简单示例

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

contract Factory {
    event Log(address addr);

    // 部署一个始终返回255的合约
    function deploy() external {
        bytes memory bytecode = hex"6960ff60005260206000f3600052600a6016f3";
        address addr;
        assembly {
            // create(value, offset, size)
            addr := create(0, add(bytecode, 0x20), 0x13)
        }
        require(addr != address(0));

        emit Log(addr);
    }
}

interface IContract {
    function getValue() external view returns (uint256);
}

// https://www.evm.codes/playground
/*
运行时代码 - 返回255
60ff60005260206000f3

// 将255存储到内存中
mstore(p, v) - 将v存储在内存地址p到p+32处

PUSH1 0xff
PUSH1 0
MSTORE

// 从内存返回32字节
return(p, s) - 结束执行并从内存 p 到 p + s 返回数据

PUSH1 0x20
PUSH1 0
RETURN

创建代码 - 返回运行时代码
6960ff60005260206000f3600052600a6016f3

// 将运行时代码存储到内存中
PUSH10 0X60ff60005260206000f3
PUSH1 0
MSTORE

// 从内存偏移量22处开始返回10个字节
PUSH1 0x0a
PUSH1 0x16
RETURN
*/

Remix Lite 尝试一下