Michael.W基于Foundry精读Openzeppelin第66期——ProxyAdmin.sol

news2024/11/24 10:34:29

Michael.W基于Foundry精读Openzeppelin第66期——ProxyAdmin.sol

      • 0. 版本
        • 0.1 ProxyAdmin.sol
      • 1. 目标合约
      • 2. 代码精读
        • 2.1 getProxyImplementation(ITransparentUpgradeableProxy proxy)
        • 2.2 getProxyAdmin(ITransparentUpgradeableProxy proxy) && changeProxyAdmin(ITransparentUpgradeableProxy proxy, address newAdmin)
        • 2.3 upgrade(ITransparentUpgradeableProxy proxy, address implementation)
        • 2.4 upgradeAndCall(ITransparentUpgradeableProxy proxy, address implementation, bytes memory data)

0. 版本

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

0.1 ProxyAdmin.sol

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

ProxyAdmin库是指定用于做透明代理TransparentUpgradeableProxy库admin的管理员合约。

注:用一个额外合约来做透明代理合约的admin的原因及透明代理合约详解参见:https://learnblockchain.cn/article/8770

1. 目标合约

ProxyAdmin合约可直接部署。

全部foundry测试合约:

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

测试使用的物料合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/proxy/transparent/ProxyAdmin/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_;
    }
}

contract ImplementationNew is Implementation {
    // add a function
    function addI(uint i_) external payable {
        i += i_;
        emit ChangeStorageUint(i, msg.value);
    }
}

2. 代码精读

注:以下所有方法只有当本ProxyAdmin合约为透明代理合约proxy的admin时才能调用成功。

2.1 getProxyImplementation(ITransparentUpgradeableProxy proxy)

查询透明代理合约proxy背后的逻辑合约地址。

    function getProxyImplementation(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {
        // staticcall到透明代理合约proxy(calldata为0x5c60da1b),如同去调用proxy合约的implementation()方法
        (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
        // 要求调用必须成功
        require(success);
        // 将staticcall返回的bytes解码成address类型并返回
        return abi.decode(returndata, (address));
    }

foundry代码验证:

contract ProxyAdminTest is Test, IERC1967, IImplementation {
    ProxyAdmin private _testing = new ProxyAdmin();
    Implementation private _implementation1 = new Implementation();
    Implementation private _implementation2 = new Implementation();
    TransparentUpgradeableProxy private _transparentUpgradeableProxy1 = new TransparentUpgradeableProxy(
        address(_implementation1),
        address(_testing),
        abi.encodeCall(
            _implementation1.__Implementation_init,
            (1024)
        )
    );
    TransparentUpgradeableProxy private _transparentUpgradeableProxy2 = new TransparentUpgradeableProxy(
        address(_implementation2),
        address(_testing),
        abi.encodeCall(
            _implementation2.__Implementation_init,
            (2048)
        )
    );

    function test_GetProxyImplementation() external {
        assertEq(
            _testing.getProxyImplementation(
                ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1))
            ),
            address(_implementation1)
        );
        assertEq(
            _testing.getProxyImplementation(
                ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy2))
            ),
            address(_implementation2)
        );
    }
}
2.2 getProxyAdmin(ITransparentUpgradeableProxy proxy) && changeProxyAdmin(ITransparentUpgradeableProxy proxy, address newAdmin)
  • getProxyAdmin(ITransparentUpgradeableProxy proxy):查询透明代理合约proxy的admin;
  • changeProxyAdmin(ITransparentUpgradeableProxy proxy, address newAdmin):本合约的owner修改透明代理合约proxy的admin为newAdmin。
    function getProxyAdmin(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {
        // staticcall到透明代理合约proxy(calldata为f851a440),如同去调用proxy合约的admin()方法
        (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
        // 要求调用必须成功
        require(success);
        // 将staticcall返回的bytes解码成address类型并返回
        return abi.decode(returndata, (address));
    }

    function changeProxyAdmin(ITransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
        // 如同调用proxy合约的changeAdmin(address)方法
        proxy.changeAdmin(newAdmin);
    }

foundry代码验证:

contract ProxyAdminTest is Test, IERC1967, IImplementation {
    ProxyAdmin private _testing = new ProxyAdmin();
    Implementation private _implementation1 = new Implementation();
    Implementation private _implementation2 = new Implementation();
    TransparentUpgradeableProxy private _transparentUpgradeableProxy1 = new TransparentUpgradeableProxy(
        address(_implementation1),
        address(_testing),
        abi.encodeCall(
            _implementation1.__Implementation_init,
            (1024)
        )
    );
    TransparentUpgradeableProxy private _transparentUpgradeableProxy2 = new TransparentUpgradeableProxy(
        address(_implementation2),
        address(_testing),
        abi.encodeCall(
            _implementation2.__Implementation_init,
            (2048)
        )
    );

    function test_GetProxyAdminAndChangeProxyAdmin() external {
        assertEq(
            _testing.getProxyAdmin(
                ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1))
            ),
            address(_testing)
        );
        assertEq(
            _testing.getProxyAdmin(
                ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy2))
            ),
            address(_testing)
        );

        // deploy another ProxyAdmin
        ProxyAdmin newProxyAdmin = new ProxyAdmin();
        // test changeProxyAdmin(ITransparentUpgradeableProxy,address)
        vm.expectEmit(address(_transparentUpgradeableProxy1));
        emit IERC1967.AdminChanged(address(_testing), address(newProxyAdmin));

        _testing.changeProxyAdmin(ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1)), address(newProxyAdmin));

        vm.expectEmit(address(_transparentUpgradeableProxy2));
        emit IERC1967.AdminChanged(address(_testing), address(newProxyAdmin));

        _testing.changeProxyAdmin(ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy2)), address(newProxyAdmin));

        assertEq(
            newProxyAdmin.getProxyAdmin(
                ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1))
            ),
            address(newProxyAdmin)
        );
        assertEq(
            newProxyAdmin.getProxyAdmin(
                ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy2))
            ),
            address(newProxyAdmin)
        );

        // revert if not owner calls
        assertEq(newProxyAdmin.owner(), address(this));
        vm.prank(address(1));
        vm.expectRevert("Ownable: caller is not the owner");
        newProxyAdmin.changeProxyAdmin(
            ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1)),
            address(1)
        );
    }
}
2.3 upgrade(ITransparentUpgradeableProxy proxy, address implementation)

本合约的owner升级透明代理合约proxy的逻辑合约地址为implementation。

    function upgrade(ITransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
        // 如同调用proxy合约的upgradeTo(address)方法
        proxy.upgradeTo(implementation);
    }

foundry代码验证:

contract ProxyAdminTest is Test, IERC1967, IImplementation {
    ProxyAdmin private _testing = new ProxyAdmin();
    Implementation private _implementation1 = new Implementation();
    Implementation private _implementation2 = new Implementation();
    TransparentUpgradeableProxy private _transparentUpgradeableProxy1 = new TransparentUpgradeableProxy(
        address(_implementation1),
        address(_testing),
        abi.encodeCall(
            _implementation1.__Implementation_init,
            (1024)
        )
    );
    TransparentUpgradeableProxy private _transparentUpgradeableProxy2 = new TransparentUpgradeableProxy(
        address(_implementation2),
        address(_testing),
        abi.encodeCall(
            _implementation2.__Implementation_init,
            (2048)
        )
    );
    ImplementationNew private _implementationNew = new ImplementationNew();

    function test_Upgrade() external {
        // upgrade one transparent upgradeable proxy
        vm.expectEmit(address(_transparentUpgradeableProxy1));
        emit IERC1967.Upgraded(address(_implementationNew));

        _testing.upgrade(
            ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1)),
            address(_implementationNew)
        );

        // check the result of upgrade
        assertEq(
            _testing.getProxyImplementation(ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1))),
            address(_implementationNew)
        );

        ImplementationNew transparentUpgradeableProxy1AsNew = ImplementationNew(address(_transparentUpgradeableProxy1));
        assertEq(transparentUpgradeableProxy1AsNew.i(), 1024);
        vm.expectEmit(address(transparentUpgradeableProxy1AsNew));
        emit IImplementation.ChangeStorageUint(1024 + 1, 0);

        transparentUpgradeableProxy1AsNew.addI(1);
        assertEq(transparentUpgradeableProxy1AsNew.i(), 1024 + 1);

        // upgrade another transparent upgradeable proxy
        vm.expectEmit(address(_transparentUpgradeableProxy2));
        emit IERC1967.Upgraded(address(_implementationNew));

        _testing.upgrade(
            ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy2)),
            address(_implementationNew)
        );

        // check the result of upgrade
        assertEq(
            _testing.getProxyImplementation(ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy2))),
            address(_implementationNew)
        );

        ImplementationNew transparentUpgradeableProxy2AsNew = ImplementationNew(address(_transparentUpgradeableProxy2));
        assertEq(transparentUpgradeableProxy2AsNew.i(), 2048);
        vm.expectEmit(address(transparentUpgradeableProxy2AsNew));
        emit IImplementation.ChangeStorageUint(2048 + 2, 0);

        transparentUpgradeableProxy2AsNew.addI(2);
        assertEq(transparentUpgradeableProxy2AsNew.i(), 2048 + 2);

        // revert if not owner calls
        assertEq(_testing.owner(), address(this));
        vm.prank(address(1));
        vm.expectRevert("Ownable: caller is not the owner");
        _testing.upgrade(
            ITransparentUpgradeableProxy(address(transparentUpgradeableProxy1AsNew)),
            address(_implementationNew)
        );
    }
}
2.4 upgradeAndCall(ITransparentUpgradeableProxy proxy, address implementation, bytes memory data)

本合约的owner升级透明代理合约proxy的逻辑合约地址为implementation并随后以data为calldata执行一次delegatecall。

    function upgradeAndCall(
        ITransparentUpgradeableProxy proxy,
        address implementation,
        bytes memory data
    ) public payable virtual onlyOwner {
        // 如同携带本次call的全部msg.value去调用proxy合约的upgradeToAndCall(address,bytes)方法
        proxy.upgradeToAndCall{value: msg.value}(implementation, data);
    }

foundry代码验证:

contract ProxyAdminTest is Test, IERC1967, IImplementation {
    ProxyAdmin private _testing = new ProxyAdmin();
    Implementation private _implementation1 = new Implementation();
    Implementation private _implementation2 = new Implementation();
    TransparentUpgradeableProxy private _transparentUpgradeableProxy1 = new TransparentUpgradeableProxy(
        address(_implementation1),
        address(_testing),
        abi.encodeCall(
            _implementation1.__Implementation_init,
            (1024)
        )
    );
    TransparentUpgradeableProxy private _transparentUpgradeableProxy2 = new TransparentUpgradeableProxy(
        address(_implementation2),
        address(_testing),
        abi.encodeCall(
            _implementation2.__Implementation_init,
            (2048)
        )
    );
    ImplementationNew private _implementationNew = new ImplementationNew();

    function test_UpgradeAndCall() external {
        // upgrade one transparent upgradeable proxy and delegatecall the added function in new implementation
        uint ethValue = 1024;
        vm.expectEmit(address(_transparentUpgradeableProxy1));
        emit IERC1967.Upgraded(address(_implementationNew));
        vm.expectEmit(address(_transparentUpgradeableProxy1));
        emit IImplementation.ChangeStorageUint(1024 + 1, ethValue);

        _testing.upgradeAndCall{value: ethValue}(
            ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1)),
            address(_implementationNew),
            abi.encodeCall(
                _implementationNew.addI,
                (1)
            )
        );

        // check the result of upgrade
        assertEq(
            _testing.getProxyImplementation(ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1))),
            address(_implementationNew)
        );

        assertEq(ImplementationNew(address(_transparentUpgradeableProxy1)).i(), 1024 + 1);
        assertEq(address(_transparentUpgradeableProxy1).balance, ethValue);

        // upgrade another transparent upgradeable proxy and delegatecall the added function in new implementation
        vm.expectEmit(address(_transparentUpgradeableProxy2));
        emit IERC1967.Upgraded(address(_implementationNew));
        vm.expectEmit(address(_transparentUpgradeableProxy2));
        emit IImplementation.ChangeStorageUint(2048 + 2, ethValue);

        _testing.upgradeAndCall{value: ethValue}(
            ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy2)),
            address(_implementationNew),
            abi.encodeCall(
                _implementationNew.addI,
                (2)
            )
        );

        // check the result of upgrade
        assertEq(
            _testing.getProxyImplementation(ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy2))),
            address(_implementationNew)
        );

        assertEq(ImplementationNew(address(_transparentUpgradeableProxy2)).i(), 2048 + 2);
        assertEq(address(_transparentUpgradeableProxy2).balance, ethValue);

        // revert if not owner calls
        assertEq(_testing.owner(), address(this));
        address nonOwner = address(1);
        vm.deal(nonOwner, ethValue);
        vm.prank(nonOwner);
        vm.expectRevert("Ownable: caller is not the owner");

        _testing.upgradeAndCall{value: ethValue}(
            ITransparentUpgradeableProxy(address(_transparentUpgradeableProxy1)),
            address(_implementationNew),
            abi.encodeCall(
                _implementationNew.addI,
                (1)
            )
        );
    }
}

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

在这里插入图片描述

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1939113.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【计算机网络】0 课程主要内容(自顶向下方法,中科大郑烇、杨坚)(待)

1 教学目标 掌握计算机网络 基本概念 工作原理 常用技术 为将来学习、应用和研究计算机网络打下坚实基础 2 课程主要内容 1 计算机网络和互联网2 应用层3 传输层4 网络层:数据平面5 网络层:控制平面6 数据链路层和局域网7 网络安全8 无线和移动网络9 多…

C2W1.LAB.Vocabulary Creation+Candidates from String Edits

理论课:C2W1.Auto-correct 文章目录 Vocabulary CreationImports and DataPreprocessingCreate Vocabulary法1.集合法法2.词典加词频法Visualization Ungraded Exercise Candidates from String EditsImports and DataSplitsDelete Edit Ungraded Exercise 理论课&…

Linux_实现线程池

目录 1、线程池的实现逻辑 2、创建多线程 3、对线程池分配任务 3.1 任务类 3.2 发送与接收任务 结语 前言: 在Linux下实现一个线程池,线程池就是创建多个线程,然后对这些线程进行管理,并且可以发放任务给到线程池…

【springboot】中使用--WebMvcConfigurer

WebMvcConfigurer 一、页面跳转控制器step1:创建视图,resources/templates/index.htmlstep2:创建SpringMVC配置类step3:测试功能 二、数据格式化step1:创建 DeviceInfo 数据类step2:自定义 Formatterstep3: 登记自定义的 DeviceFormatterstep4: 新建 Con…

杭州外贸网站建设 最好用wordpress模板来搭建

防护服wordpress外贸网站模板 消防服、防尘服、隔热服、防化服、防静电服、电焊服wordpress外贸网站模板。 https://www.jianzhanpress.com/?p4116 工业品wordpress外贸网站模板 机械及行业设备、五金工具、安全防护、包装、钢铁、纺织皮革等工业品wordpress外贸网站模板。…

实现高效离职管理,智慧校园人事管理功能全解析

智慧校园人事管理系统中的离职管理功能,为教职工提供了一个高效、透明且合规的离职流程,同时为学校管理层提供了优化人力资源配置的有力工具。教职工可以在线轻松提交离职申请,系统随即自动记录并启动后续流程,从申请审核到工作交…

C语言 | Leetcode C语言题解之第241题为运算表达式设计优先级

题目: 题解: #define ADDITION -1 #define SUBTRACTION -2 #define MULTIPLICATION -3int* diffWaysToCompute(char * expression, int* returnSize) {int len strlen(expression);int *ops (int *)malloc(sizeof(int) * len);int opsSize 0;for (in…

任务2:python+InternStudio 关卡

任务地址 https://github.com/InternLM/Tutorial/blob/camp3/docs/L0/Python/task.md 文档 https://github.com/InternLM/Tutorial/tree/camp3/docs/L0/Python 任务 Python实现wordcount import re import collectionstext """ Got this panda plush to…

Qt Creator配置以及使用Valgrind - 检测内存泄露

Qt Creator配置以及使用Valgrind - 检测内存泄露 引言一、下载安装1.1 下载源码1.2 安装 二、配置使用2.1 Qt Creator配置2.2 使用2.3 更多详细信息可参考官方文档: 三、参考链接 引言 Valgrind是一个在Linux平台下广泛使用的开源动态分析工具,它提供了一…

ARM体系结构和接口技术(九)异常

文章目录 (一)异常模式(二)Cortex-A7核的异常处理流程分析1. 保存现场(系统自动完成)2. 恢复现场(程序员手动完成)3. 异常处理流程 (三)软中断验证异常处理函…

谷粒商城实战笔记-40-前端基础-Vue-计算属性、监听器、过滤器

文章目录 一,计算属性1,用途2,用法2.1 定义View2.2 声明计算属性 3,注意事项 二,监听器1. 使用 watch 监听属性的变化 三,过滤器1,定义局部过滤器2,定义全局过滤器3,使用…

level 6 day2-3 网络基础2---TCP编程

1.socket(三种套接字:认真看) 套接字就是在这个应用空间和内核空间的一个接口,如下图 原始套接字可以从应用层直接访问到网络层,跳过了传输层,比如在ubtan里面直接ping 一个ip地址,他没有经过TCP或者UDP的数…

如何修复 CrowdStrike 蓝屏错误 Windows 11

如果您的 PC 出现 BSoD 错误,您不是唯一一个,但这里有一个解决方法来缓解该问题。 如果您有一台运行 Windows 11(或 10)的计算机使用 CrowdStrike 的 Falcon Sensor 应用程序连接到组织,并且遇到蓝屏死机 &#xff0…

JavaScript:节流与防抖

目录 一、前言 二、节流(Throttle) 1、定义 2、使用场景 3、实现原理 4、代码示例 5、封装节流函数 三、防抖(Debounce) 1、定义 2、使用场景 3、实现原理 4、代码示例 5、封装防抖函数 四、异同点总结 一、前言 …

AI算法22-决策树算法Decision Tree | DT

目录 决策树算法概述 决策树算法背景 决策树算法简介 决策树算法核心思想 决策树算法的工作过程 特征选择 信息增益 信息增益比 决策树的生成 ID3算法 C4.5的生成算法 决策树的修剪 算法步骤 决策树算法的代码实现 决策树算法的优缺点 优点 缺点 决策树算法的…

深入解析HNSW:Faiss中的层次化可导航小世界图

层次化可导航小世界(HNSW)图是向量相似性搜索中表现最佳的索引之一。HNSW 技术以其超级快速的搜索速度和出色的召回率,在近似最近邻(ANN)搜索中表现卓越。尽管 HNSW 是近似最近邻搜索中强大且受欢迎的算法,…

Latex使用心得1

本周暑期课程大作业需要使用Latex模板,采用的是老师给的IEEE的格式。从最开始不知道Latex是什么,到摸索着把大作业的小论文排版完成,其中也有一些心得体会。写在这里记录一下,以便以后回来再看,有更多的思考沉淀。 1、…

视觉巡线小车——STM32+OpenMV(三)

目录 前言 一、OpenMV代码 二、STM32端接收数据 1.配置串口 2.接收数据并解析 总结 前言 通过视觉巡线小车——STM32OpenMV(二),已基本实现了减速电机的速度闭环控制。要使小车能够自主巡线,除了能够精准的控制速度之外&#xff0…

Java周总结7.20day

一,异常 异常 :指的是程序在运行过程中报错,然后停止运行,控制台显示错误。 注意事项:异常本身是一个类,出现异常会创建一个异常类的对象并抛出, public class DemoTest { public static void …

python—爬虫爬取电影页面实例

下面是一个简单的爬虫实例,使用Python的requests库来发送HTTP请求,并使用lxml库来解析HTML页面内容。这个爬虫的目标是抓取一个电影网站,并提取每部电影的主义部分。 首先,确保你已经安装了requests和lxml库。如果没有安装&#x…