自学内容网 自学内容网

Michael.W基于Foundry精读Openzeppelin第67期——BeaconProxy.sol

0. 版本

[openzeppelin]:v4.8.3,[forge-std]:v1.5.6

0.1 BeaconProxy.sol

Github: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.3/contracts/proxy/beacon/BeaconProxy.sol

BeaconProxy库是信标代理合约的实现。与ERC1967Proxy和TransparentUpgradeableProxy两种代理合约不同,信标代理合约背后的逻辑合约地址并不是存储在代理合约内,而是存储于信标合约中。信标代理合约自身只存储信标合约的地址(基于ERC1967标准),这样就可以实现了多代理合约对一逻辑合约的信标代理模式。

注:

1. 目标合约

继承BeaconProxy合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/src/proxy/beacon/BeaconProxy/MockBeaconProxy.sol

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

import "openzeppelin-contracts/contracts/proxy/beacon/BeaconProxy.sol";

contract MockBeaconProxy is BeaconProxy {

    constructor(address beacon_, bytes memory data) payable
    BeaconProxy(beacon_, data)
    {}

    function beacon() external view returns (address) {
        return _beacon();
    }

    function implementation() external view returns (address) {
        return _implementation();
    }

    // deprecated
    function setBeacon(address beacon_, bytes memory data) external payable {
        _setBeacon(beacon_, data);
    }
}

全部foundry测试合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/proxy/beacon/BeaconProxy/BeaconProxy.t.sol

测试使用的物料合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/proxy/beacon/BeaconProxy/Beacon.sol

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

import "openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol";

contract Beacon is IBeacon {
    address public implementation;

    constructor(address newImplementation){
        implementation = newImplementation;
    }
}

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/proxy/beacon/BeaconProxy/Implementation.sol

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

interface IImplementation {
    event ChangeStorageUint(uint, uint);
}

contract Implementation is IImplementation {
    // storage
    uint public i;

    function __Implementation_init(uint i_) external {
        i = i_;
    }

    function addI(uint i_) external payable {
        i += i_;
        emit ChangeStorageUint(i, msg.value);
    }
}

2. 代码精读

2.1 constructor(address beacon, bytes memory data)

设置信标合约地址为beacon。如果data不为空,则随后以data为calldata执行一次delegatecall到存储在beacon中的逻辑合约地址上。

注:信标合约beacon必须实现IBeacon接口且beacon地址与其内部存储的逻辑合约地址必须是合约地址,否则revert。

    constructor(address beacon, bytes memory data) payable {
        // 调用ERC1967Upgrade._upgradeBeaconToAndCall()来设置信标合约地址。如果data不为空,则随后以data为calldata执行一次delegatecall到存储在信标合约中的逻辑合约地址上
        // 注:ERC1967Upgrade._upgradeBeaconToAndCall()详解参见:https://learnblockchain.cn/article/8581
        _upgradeBeaconToAndCall(beacon, data, false);
    }

foundry代码验证:

contract BeaconProxyTest is Test, IERC1967, IImplementation {
    Implementation private _implementation = new Implementation();
    Beacon private _beacon = new Beacon(address(_implementation));
    MockBeaconProxy private _testing = new MockBeaconProxy(
        address(_beacon),
        abi.encodeCall(
            _implementation.__Implementation_init,
            (1024)
        )
    );

    function test_ConstructorWithEmptyData() external {
        vm.expectEmit();
        emit IERC1967.BeaconUpgraded(address(_beacon));

        _testing = new MockBeaconProxy(address(_beacon), "");
        assertEq(Implementation(address(_testing)).i(), 0);

        // revert if beacon is not an contract
        vm.expectRevert("ERC1967: new beacon is not a contract");
        new MockBeaconProxy(address(1024), "");

        // revert if implementation is not an contract
        _beacon = new Beacon(address(1024));
        vm.expectRevert("ERC1967: beacon implementation is not a contract");
        new MockBeaconProxy(address(_beacon), "");

        // revert if beacon isn't an IBeacon contract
        vm.expectRevert();
        new MockBeaconProxy(address(this), "");
    }

    function test_ConstructorWithData() external {
        uint ethValue = 1024;
        bytes memory data = abi.encodeCall(
            _implementation.addI,
            (2048)
        );

        vm.expectEmit();
        emit IERC1967.BeaconUpgraded(address(_beacon));
        vm.expectEmit();
        emit IImplementation.ChangeStorageUint(2048, ethValue);

        _testing = new MockBeaconProxy{value: ethValue}(
            address(_beacon),
            data
        );
        assertEq(Implementation(address(_testing)).i(), 2048);
        assertEq(address(_testing).balance, ethValue);

        // revert if beacon is not an contract
        vm.expectRevert("ERC1967: new beacon is not a contract");
        new MockBeaconProxy{value: ethValue}(
            address(1024),
            data
        );

        // revert if implementation is not an contract
        _beacon = new Beacon(address(1024));
        vm.expectRevert("ERC1967: beacon implementation is not a contract");
        new MockBeaconProxy{value: ethValue}(
            address(_beacon),
            data
        );

        // revert if beacon isn't an IBeacon contract
        vm.expectRevert();
        new MockBeaconProxy{value: ethValue}(
            address(this),
            data
        );
    }
}
2.2 _beacon() internal

返回当前的信标合约地址。

    function _beacon() internal view virtual returns (address) {
        // 调用ERC1967Upgrade._getBeacon()来返回信标合约地址
        // 注:ERC1967Upgrade._getBeacon()详解参见:https://learnblockchain.cn/article/8581
        return _getBeacon();
    }

foundry代码验证:

contract BeaconProxyTest is Test {
    Implementation private _implementation = new Implementation();
    Beacon private _beacon = new Beacon(address(_implementation));
    MockBeaconProxy private _testing = new MockBeaconProxy(
        address(_beacon),
        abi.encodeCall(
            _implementation.__Implementation_init,
            (1024)
        )
    );

    function test_Beacon() external {
        assertEq(_testing.beacon(), address(_beacon));
    }
}
2.3 _implementation() internal

重写Proxy._implementation()方法,返回当前代理合约背后的存储在信标合约中的逻辑合约地址。在Proxy的fallback处理中会将对本合约的全部call都delegatecall到_implementation()返回的地址上。

注:Proxy._implementation()及其fallback处理详解参见:https://learnblockchain.cn/article/8469

    function _implementation() internal view virtual override returns (address) {
        // 调用信标合约的implementation()方法获得逻辑合约地址
        return IBeacon(_getBeacon()).implementation();
    }

foundry代码验证:

contract BeaconProxyTest is Test {
    Implementation private _implementation = new Implementation();
    Beacon private _beacon = new Beacon(address(_implementation));
    MockBeaconProxy private _testing = new MockBeaconProxy(
        address(_beacon),
        abi.encodeCall(
            _implementation.__Implementation_init,
            (1024)
        )
    );

    function test_Implementation() external {
        assertEq(_testing.implementation(), _beacon.implementation());
        assertEq(_testing.implementation(), address(_implementation));
    }
}
2.4 _setBeacon(address beacon, bytes memory data) internal

更换信标合约地址为beacon。如果data不为空,则随后以data为calldata执行一次delegatecall到存储在beacon中的逻辑合约地址上。

该方法目前已弃用。因为对于信标代理合约而言,其信标合约地址往往是固定不变的。想要升级更换逻辑合约,往往是在信标合约中进行升级操作。

注:信标合约beacon必须实现IBeacon接口且beacon地址与其内部存储的逻辑合约地址必须是合约地址,否则revert。

    function _setBeacon(address beacon, bytes memory data) internal virtual {
        // 调用ERC1967Upgrade._upgradeBeaconToAndCall()来设置信标合约地址。如果data不为空,则随后以data为calldata执行一次delegatecall到存储在信标合约中的逻辑合约地址上
        // 注:ERC1967Upgrade._upgradeBeaconToAndCall()详解参见:https://learnblockchain.cn/article/8581
        _upgradeBeaconToAndCall(beacon, data, false);
    }

foundry代码验证:

contract BeaconProxyTest is Test, IERC1967, IImplementation {
    Implementation private _implementation = new Implementation();
    Beacon private _beacon = new Beacon(address(_implementation));
    MockBeaconProxy private _testing = new MockBeaconProxy(
        address(_beacon),
        abi.encodeCall(
            _implementation.__Implementation_init,
            (1024)
        )
    );

    function test_SetBeacon() external {
        Implementation proxyAsImplementation = Implementation(address(_testing));
        assertEq(proxyAsImplementation.i(), 1024);

        Implementation newImplementation = new Implementation();
        Beacon newBeacon = new Beacon(address(newImplementation));

        // case 1: with empty data
        vm.expectEmit(address(_testing));
        emit IERC1967.BeaconUpgraded(address(newBeacon));

        _testing.setBeacon(address(newBeacon), "");
        // check
        assertEq(proxyAsImplementation.i(), 1024);
        assertEq(_testing.beacon(), address(newBeacon));
        assertEq(_testing.implementation(), newBeacon.implementation());
        assertEq(_testing.implementation(), address(newImplementation));

        // case 2: with data
        uint ethValue = 1024;
        assertEq(address(_testing).balance, 0);

        vm.expectEmit(address(_testing));
        emit IERC1967.BeaconUpgraded(address(_beacon));
        vm.expectEmit(address(_testing));
        emit IImplementation.ChangeStorageUint(1024 + 2048, ethValue);

        _testing.setBeacon{value: ethValue}(
            address(_beacon),
            abi.encodeCall(
                _implementation.addI,
                (2048)
            )
        );
        // check
        assertEq(proxyAsImplementation.i(), 1024 + 2048);
        assertEq(_testing.beacon(), address(_beacon));
        assertEq(_testing.implementation(), _beacon.implementation());
        assertEq(_testing.implementation(), address(_implementation));
        assertEq(address(_testing).balance, ethValue);

        // case 3: revert if beacon is not an contract
        vm.expectRevert("ERC1967: new beacon is not a contract");
        _testing.setBeacon(
            address(1024),
            ""
        );

        // case 4: revert if implementation is not an contract
        newBeacon = new Beacon(address(1024));
        vm.expectRevert("ERC1967: beacon implementation is not a contract");
        _testing.setBeacon(
            address(newBeacon),
            ""
        );

        // case 5: revert if beacon isn't an IBeacon contract
        vm.expectRevert();
        _testing.setBeacon(
            address(this),
            ""
        );
    }
}

ps:
本人热爱图灵,热爱中本聪,热爱V神。
以下是我个人的公众号,如果有技术问题可以关注我的公众号来跟我交流。
同时我也会在这个公众号上每周更新我的原创文章,喜欢的小伙伴或者老伙计可以支持一下!
如果需要转发,麻烦注明作者。十分感谢!

在这里插入图片描述

公众号名称:后现代泼痞浪漫主义奠基人


原文地址:https://blog.csdn.net/michael_wgy_/article/details/140641121

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!