GnosisSafeProxyFactory合约学习

GnosisSafe是以太坊区块链上最流行的多签钱包!它的最初版本叫 MultiSigWallet,现在新的钱包叫Gnosis Safe,意味着它不仅仅是钱包了。它自己的介绍为:以太坊上的最可信的数字资产管理平台(The most trusted platform to manage digital assets on Ethereum)。

所谓Factory,顾名思义,就是能够快捷创建某类合约的合约,通过合约创建合约的方式而非直接部署一个新的合约。因此GnosisSafeProxyFactory 就是用来快速创建GnosisSafeProxy的合约。

1.1 GnosisSafeProxyFactory 源码

GnosisSafeProxyFactory 的源码并不复杂,核心为 deployProxyWithNonce函数,用来创建一个GnosisSafeProxy,其它的只是一些辅助函数和包装函数而已。

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

import "./GnosisSafeProxy.sol";
import "./IProxyCreationCallback.sol";

/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
    event ProxyCreation(GnosisSafeProxy proxy, address singleton);

    /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
    /// @param singleton Address of singleton contract.
    /// @param data Payload for message call sent to new proxy contract.
    function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
        proxy = new GnosisSafeProxy(singleton);
        if (data.length > 0)
            // solhint-disable-next-line no-inline-assembly
            assembly {
                if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
                    revert(0, 0)
                }
            }
        emit ProxyCreation(proxy, singleton);
    }

    /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
    function proxyRuntimeCode() public pure returns (bytes memory) {
        return type(GnosisSafeProxy).runtimeCode;
    }

    /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
    function proxyCreationCode() public pure returns (bytes memory) {
        return type(GnosisSafeProxy).creationCode;
    }

    /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
    ///      This method is only meant as an utility to be called from other methods
    /// @param _singleton Address of singleton contract.
    /// @param initializer Payload for message call sent to new proxy contract.
    /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
    function deployProxyWithNonce(
        address _singleton,
        bytes memory initializer,
        uint256 saltNonce
    ) internal returns (GnosisSafeProxy proxy) {
        // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
        bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
        bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
        // solhint-disable-next-line no-inline-assembly
        assembly {
            proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
        }
        require(address(proxy) != address(0), "Create2 call failed");
    }

    /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
    /// @param _singleton Address of singleton contract.
    /// @param initializer Payload for message call sent to new proxy contract.
    /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
    function createProxyWithNonce(
        address _singleton,
        bytes memory initializer,
        uint256 saltNonce
    ) public returns (GnosisSafeProxy proxy) {
        proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
        if (initializer.length > 0)
            // solhint-disable-next-line no-inline-assembly
            assembly {
                if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
                    revert(0, 0)
                }
            }
        emit ProxyCreation(proxy, _singleton);
    }

    /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
    /// @param _singleton Address of singleton contract.
    /// @param initializer Payload for message call sent to new proxy contract.
    /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
    /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
    function createProxyWithCallback(
        address _singleton,
        bytes memory initializer,
        uint256 saltNonce,
        IProxyCreationCallback callback
    ) public returns (GnosisSafeProxy proxy) {
        uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
        proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
        if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
    }

    /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
    ///      This method is only meant for address calculation purpose when you use an initializer that would revert,
    ///      therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
    /// @param _singleton Address of singleton contract.
    /// @param initializer Payload for message call sent to new proxy contract.
    /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
    function calculateCreateProxyWithNonceAddress(
        address _singleton,
        bytes calldata initializer,
        uint256 saltNonce
    ) external returns (GnosisSafeProxy proxy) {
        proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
        revert(string(abi.encodePacked(proxy)));
    }
}

1.2 源码学习

我们跳过导入语句和pragma声明部分,由于本合约未继承任何合约,我们直接从函数createProxy开始学习。

  • createProxy 函数。 用来创建一个代理合约。 它使用了Solidity 的 new关键字进行了创建,同时指定构造器参数为singleton。第二个参数data一般用于创建或者升级后进行初始化,我们着重来看这个部分。

    if (data.length > 0)
      // solhint-disable-next-line no-inline-assembly
      assembly {
          if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
              revert(0, 0)
          }
      }
    

    这里if语句未使用花括号,虽然是个人风格的问题,但是还是推荐使用花括号。

    如果data的长度为0,那么data就是用来进行初始化的payload(包含了函数选择器和参数编码)。这时需要调用proxy合约进行初始化。

    这里直接调用了内嵌汇编的call函数进行proxy合约的调用,参数分别为剩余gas,proxy合约地址,发送的eth数量,内存中起始位置,调用数据的大小,output的位置 和大小。

    这里需要注意的是data的数据类型为bytes memory,为动态类型。因此它在solidity中的直接值其实代表的是包含了长度前缀的起始地址,因为长度前缀为一个word,所以add(data, 0x20) 得到了真正payload的起始地址(去除了长度前缀)。mload(data) 则是读取长度前缀的值,也就是该payload的大小。

    最后将执行的结果和0比较(0代表失败),如果失败了,revert,且无提示信息。

    函数的最后将创建的proxy地址及其实现合约地址通过事件的形式分发出去,方便客户端监听。

    这里还有一个细节,就是函数的可见性为public,通常来讲,一般为external(只要内部没有调用),这样部分数据类型更能节省gas。但是external 可见性的函数会导致其bytes类型参数datacalldata类型,也就是不存在memory中,这样还需要额外的操作将data从calldata复制到memory中,所以这里使用publicmemory反而更能节省gas

  • proxyRuntimeCode 函数,用来返回proxy合约的运行时代码,注释中提到可以用来检查proxy合约是否部署,这里暂时不是很明白检查的意义。

  • proxyCreationCode函数,用来返回proxy合约的创建时代码,注意,创建时代码运行后会得到运行时代码。部署合约时使用的是创建时代码,该代码执行后产生的是运行时代码,也就是合约的线上代码。注释中提到可以用来计算地址,这里主要是create2时使用。

  • deployProxyWithNonce 函数,用一个saltNonce来控制产生的proxy合约的地址。本函数的核心是使用了create2函数而非new来创建合约,create2中有一个可自定义的salt,从而可以控制生成的合约地址。

    根据注释,不同的initializer需要导致不行的地址,因此把它和输入参数中的saltNonce一起编码作来salt。这里,一般我们创建proxyinitializer是固定的,而通过不断改变saltNonce的值来得到不同的地址。那么这里问题来了,如果initializer_singletonsaltNonce都相同,那我们能在相同的地址部署两次么?我们晚点针对这个问题进行测试。

    这里拓展一下,为什么要使用create2呢?Solidity中有一段话:

    When creating a contract, the address of the contract is computed from the address of the creating contract and a counter that is increased with each contract creation.

    If you specify the option salt (a bytes32 value), then contract creation will use a different mechanism to come up with the address of the new contract:

    意思是,如果你直接创建合约,例如通过new或者 直接部署,生成的合约地址和创建它的地址及一个不断增加的计数器相关,例如外部账号EOA的nonce。当你定义一个salt时,它使用不同的机制来计算新合约的地址。

    create2的定义为:

    create2(v, p, n, s)
    
    create new contract with code mem[p…(p+n)) at address keccak256(0xff . this . s . keccak256(mem[p…(p+n))) and send v wei and return the new address, where 0xff is a 1 byte value, this is the current contract’s address as a 20 byte value and s is a big-endian 256-bit value; returns 0 on error
    

    我们对照实际代码:

    // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
      bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
      bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
      // solhint-disable-next-line no-inline-assembly
      assembly {
          proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
      }
      require(address(proxy) != address(0), "Create2 call failed");
    

    这里会得到 v为0(也就是不给新合约ETH),p是内存起始位置,所以为add(0x20, deploymentData),这里为什么要加add 0x20,上面也提到过,是要去除长度前缀。 当然大小就是 mload(deploymentData)了,同deployProxyWithNonce中一样,这里的salt 是将initializersaltNonce组合得到的一个值。注释中提到,哈希比直接连接便宜,这里我想是因为initializerbytes类型,不知道具体长度大小,所以连接操作不方便。而哈希之后就是固定长度的bytes32,所以操作更便宜一些。

    注意,这里keccak256(initializer)initializer的值并不是它在内存中的起始位置 ,它就是实际的bytes数据,只有在操作内存时才代表其内存地址(一般在内嵌汇编中使用)。

​ 这里可以看到最后计算的地址和本合约地址(固定的),deploymentData 及 salt 相关,而 deploymentData 又和合约的创建时代码(固定的)及 构造器参数_singleton 相关。所以最终,我们任意改变_singletoninitializer或者saltNonce的值,就可以得到一个不同的proxy地址,当然这个地址也可以线下计算出来。

​ 从上面的代码中还可以看出来,我们构造器参数其实是附在创建时代码后面的,这和不使用create2例如正常外部账号部署合约时是一致的。

​ 最后一点要注意的是,正如注释中所说,它并没有调用新创建proxy合约的initializer,因此它是功能不完整的,只是创建功能的抽象,所以它只是个内部函数,供其它函数调用 。

  • createProxyWithNonce 说曹操,曹操到。弄清楚了上面的函数,这个函数就很简单的。第一步,调用上面的内部函数创建proxy合约,第二步,如果initializer不为空,则调用proxyinitializer对应的函数进行初始化(注意并不是调用initializer函数,initializer的含义是指初始化一次。具体调用哪个函数要看initializer前8位的函数选择器。

    这里的汇编使用就很简单了,和前面的用法 一样,在操作内存相关时,记住initializer代表了包含长度前缀的payload的起始地址就可以了。

  • createProxyWithCallback函数,在上面createProxyWithNonce函数的基础上加了一个回调函数用来通知其它合约创建并初始化成功了。实际使用的场景并不多, 主要用于调用合约和回调合约不是同一个合约的场景,类似ERC20中的ApproveAndCall

  • calculateCreateProxyWithNonceAddress 函数,看注释是用来得到一个新的proxy合约的地址,它仅用于计算目的。当然我们可以线下计算,线下计算只是让这个Factory合约更完善。不过有一点却是要注意的,该函数不是一个view函数,它的结果是使用revert返回的,并不是那么容易直接获取的。并且如果直接调用,非view函数就是发送交易,哪怕是revert并未实际改写数据,也是要花费gas费用的,我们需要一点技巧来避免此项开销,就好比UniswapV3的价格查询合约Quoter一样。大家其实可以参考Uniswap V3: Quoter合约的,地址为:https://etherscan.io/address/0xb27308f9f90d607463bb33ea1bebb41c27ce5ab6#code

    当然,最好的办法是线下计算,利用上面提到的create2的定义,参考UniswapV2中Pair地址的计算方法:

    // calculates the CREATE2 address for a pair without making any external calls
    function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
        (address token0, address token1) = sortTokens(tokenA, tokenB);
        pair = address(uint(keccak256(abi.encodePacked(
                hex'ff',
                factory,
                keccak256(abi.encodePacked(token0, token1)),
                hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
            ))));
    }
    

    这里的initCode 如果使用hardhat可以通过如下方式获取:

    let UniswapV2Pair = await ethers.getContractFactory("UniswapV2Pair");
    let InitCode = ethers.utils.keccak256(UniswapV2Pair.bytecode)
    

    更为直接的是直接参考Solidity官方文档示例:

    // SPDX-License-Identifier: GPL-3.0
    pragma solidity >=0.7.0 <0.9.0;
    contract D {
        uint public x;
        constructor(uint a) {
            x = a;
        }
    }
    
    contract C {
        function createDSalted(bytes32 salt, uint arg) public {
            // This complicated expression just tells you how the address
            // can be pre-computed. It is just there for illustration.
            // You actually only need ``new D{salt: salt}(arg)``.
            address predictedAddress = address(uint160(uint(keccak256(abi.encodePacked(
                bytes1(0xff),
                address(this),
                salt,
                keccak256(abi.encodePacked(
                    type(D).creationCode,
                    arg
                ))
            )))));
    
            D d = new D{salt: salt}(arg);
            require(address(d) == predictedAddress);
        }
    }
    

    这里可以看到,使用new D{salt: salt}(arg) 可以达到和create2相同的效果,但Gnosis Safe为什么选择了create2函数呢,我想可能是使用内嵌汇编更节省gas

    在我们自己的实际应用中,使用new D{salt: salt}(arg)即可。

    这里我们可以实际测试一下,使用remix.ethereum.org在线快速编辑测试,使用相同的saltarg调用createDSalted两次。结果为:第一次会创建一个合约,第二次会出错重置(因为你不能在同一地址创建合约两次,除非原合约自杀了)。

    通过Remix我们也可以看到,合约D的x状态变量的值正是我们调用createDSaltedarg的值,这是一致的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
智慧校园的建设目标是通过数据整合、全面共享,实现校园内教学、科研、管理、服务流程的数字化、信息化、智能化和多媒体化,以提高资源利用率和管理效率,确保校园安全。 智慧校园的建设思路包括构建统一支撑平台、建立完善管理体系、大数据辅助决策和建设校园智慧环境。通过云架构的数据中心与智慧的学习、办公环境,实现日常教学活动、资源建设情况、学业水平情况的全面统计和分析,为决策提供辅助。此外,智慧校园还涵盖了多媒体教学、智慧录播、电子图书馆、VR教室等多种教学模式,以及校园网络、智慧班牌、校园广播等教务管理功能,旨在提升教学品质和管理水平。 智慧校园的详细方案设计进一步细化了教学、教务、安防和运维等多个方面的应用。例如,在智慧教学领域,通过多媒体教学、智慧录播、电子图书馆等技术,实现教学资源的共享和教学模式的创新。在智慧教务方面,校园网络、考场监控、智慧班牌等系统为校园管理提供了便捷和高效。智慧安防系统包括视频监控、一键报警、阳光厨房等,确保校园安全。智慧运维则通过综合管理平台、设备管理、能效管理和资产管理,实现校园设施的智能化管理。 智慧校园的优势和价值体现在个性化互动的智慧教学、协同高效的校园管理、无处不在的校园学习、全面感知的校园环境和轻松便捷的校园生活等方面。通过智慧校园的建设,可以促进教育资源的均衡化,提高教育质量和管理效率,同时保障校园安全和提升师生的学习体验。 总之,智慧校园解决方案通过整合现代信息技术,如云计算、大数据、物联网和人工智能,为教育行业带来了革命性的变革。它不仅提高了教育的质量和效率,还为师生创造了一个更加安全、便捷和富有智慧的学习与生活环境。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AiMateZero

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值