首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >abi.encodeWithSignature可以通过预计算进行优化吗?

abi.encodeWithSignature可以通过预计算进行优化吗?
EN

Ethereum用户
提问于 2021-02-03 00:18:19
回答 1查看 411关注 0票数 3

我有一个使用方法exchange的代理实现,还有一个带有以下代码的方法exchange2的委托程序:

代码语言:javascript
复制
function exchange2(int128 i, int128 j, uint256 dx, uint256 min_dy) public {
        (bool success, bytes memory result) = delegationTarget.delegatecall(
            abi.encodeWithSignature("exchange(int128,int128,uint256,uint256)", i, j, dx, min_dy)
        );
        if (!success) {
            if (result.length > 0) {
                revert(string(result));
            } else {
                revert();
            }
        }
        // pay cashback

上面这个简单的代码大约有2k的气体开销,下面是openzeppelin代理代码:

代码语言:javascript
复制
    function _delegate(address implementation) internal {
        //        // solhint-disable-next-line no-inline-assembly
        assembly {
        // Copy msg.data. We take full control of memory in this inline assembly
        // block because it will not return to Solidity code. We overwrite the
        // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

        // Call the implementation.
        // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

        // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }
    fallback () external {
        _delegate(delegationTarget);
    }

oz代码的问题是,我不知道如何从代理的exchange方法将调用委托给exchange2实现。

如果我知道abi.encodeWithSignature调用,有什么方法可以优化signature of exchange(int128,int128,uint256,uint256) - 0x3df02124调用呢?每次函数调用时,传递与参数相同的字符串听起来很浪费。

EN

回答 1

Ethereum用户

发布于 2021-02-06 01:03:52

abi.encodePacked(bytes4(keccak256(signature)),abi.encode(参数.)是对abi.encodeWithSignature的逼近

您可以在合同中将0x3df02124保存为byte4变量,并使用上述代码的调整:

代码语言:javascript
复制
bytes4 functionSig = 0x3df02124
abi.encodePacked(functionSig, abi.encode(parameters...))
票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/93068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档