📜 [專欄新文章] Reason Why You Should Use EIP1167 Proxy Contract. (With Tutorial)
✍️ Ping Chen
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
EIP1167 minimal proxy contract is a standardized, gas-efficient way to deploy a bunch of contract clones from a factory.
1. Who may consider using EIP1167
For some DApp that are creating clones of a contract for its users, a “factory pattern” is usually introduced. Users simply interact with the factory to get a copy. For example, Gnosis Multisig Wallet has a factory. So, instead of copy-and-paste the source code to Remix, compile, key in some parameters, and deploy it by yourself, you can just ask the factory to create a wallet for you since the contract code has already been on-chain.
The problem is: we need standalone contract instances for each user, but then we’ll have many copies of the same bytecode on the blockchain, which seems redundant. Take multisig wallet as an example, different multisig wallet instances have separate addresses to receive assets and store the wallet’s owners’ addresses, but they can share the same program logic by referring to the same library. We call them ‘proxy contracts’.
One of the most famous proxy contract users is Uniswap. It also has a factory pattern to create exchanges for each ERC20 tokens. Different from Gnosis Multisig, Uniswap only has one exchange instance that contains full bytecode as the program logic, and the remainders are all proxies. So, when you go to Etherscan to check out the code, you’ll see a short bytecode, which is unlikely an implementation of an exchange.
0x3660006000376110006000366000732157a7894439191e520825fe9399ab8655e0f7085af41558576110006000f3
What it does is blindly relay every incoming transaction to the reference contract 0x2157a7894439191e520825fe9399ab8655e0f708by delegatecall.
Every proxy is a 100% replica of that contract but serving for different tokens.
The length of the creation code of Uniswap exchange implementation is 12468 bytes. A proxy contract, however, has only 46 bytes, which is much more gas efficient. So, if your DApp is in a scenario of creating copies of a contract, no matter for each user, each token, or what else, you may consider using proxy contracts to save gas.
2. Why use EIP1167
According to the proposal, EIP is a “minimal proxy contract”. It is currently the known shortest(in bytecode) and lowest gas consumption overhead implementation of proxy contract. Though most ERCs are protocols or interfaces, EIP1167 is the “best practice” of a proxy contract. It uses some EVM black magic to optimize performance.
EIP1167 not only minimizes length, but it is also literally a “minimal” proxy that does nothing but proxying. It minimizes trust. Unlike other upgradable proxy contracts that rely on the honesty of their administrator (who can change the implementation), address in EIP1167 is hardcoded in bytecode and remain unchangeable.
That brings convenience to the community.
Etherscan automatically displays code for EIP1167 proxies.
When you see an EIP1167 proxy, you can definitely regard it as the contract that it points to. For instance, if Etherscan finds a contract meets the format of EIP1167, and the reference implementation’s code has been published, it will automatically use that code for the proxy contract. Unfortunately, non-standard EIP1167 proxies like Uniswap will not benefit from this kind of network effect.
3. How to upgrade a contract to EIP1167 compatible
*Please read all the steps before use, otherwise there might have problems.
A. Build a clone factory
For Vyper, there’s a function create_with_code_of(address)that creates a proxy and returns its address. For Solidity, you may find a reference implementation here.
function createClone(address target) internal returns (address result){ bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) }}
You can either deploy the implementation contract first or deploy it with the factory’s constructor. I’ll suggest the former, so you can optimize it with higher runs.
contract WalletFactory is CloneFactory { address Template = "0xc0ffee"; function createWallet() external returns (address newWallet) { newWallet = createClone(Template); }}
B. Replace constructor with initializer
When it comes to a contract, there are two kinds of code: creation code and runtime code. Runtime code is the actual business logic stored in the contract’s code slot. Creation code, on the other hand, is runtime code plus an initialization process. When you compile a solidity source code, the output bytecode you get is creation code. And the permanent bytecode you can find on the blockchain is runtime code.
For EIP1167 proxies, we say it ‘clones’ a contract. It actually clones a contract’s runtime code. But if the contract that it is cloning has a constructor, the clone is not 100% precise. So, we need to slightly modify our implementation contract. Replace the constructor with an ‘initializer’, which is part of the permanent code but can only be called once.
// constructorconstructor(address _owner) external { owner = _owner;}// initializerfunction set(address _owner) external { require(owner == address(0)); owner = _owner;}
Mind that initializer is not a constructor, so theoretically it can be called multiple times. You need to maintain the edge case by yourself. Take the code above as an example, when the contract is initialized, the owner must never be set to 0, or anyone can modify it.
C. Don’t assign value outside a function
As mentioned, a creation code contains runtime code and initialization process. A so-called “initialization process” is not only a constructor but also all the variable assignments outside a function. If an EIP1167 proxy points to a contract that assigns value outside a function, it will again have different behavior. We need to remove them.
There are two approaches to solve this problem. The first one is to turn all the variables that need to be assigned to constant. By doing so, they are no longer a variable written in the contract’s storage, but a constant value that hardcoded everywhere it is used.
bytes32 public constant symbol = "4441490000000000000000000000000000000000000000000000000000000000";uint256 public constant decimals = 18;
Second, if you really want to assign a non-constant variable while initializing, then just add it to the initializer.
mapping(address => bool) public isOwner;uint public dailyWithdrawLimit;uint public signaturesRequired;
function set(address[] _owner, uint limit, uint required) external { require(dailyWithdrawLimit == 0 && signaturesRequired == 0); dailyWithdrawLimit = limit; signaturesRequired = required; //DO SOMETHING ELSE}
Our ultimate goal is to eliminate the difference between runtime code and creation code, so EIP1167 proxy can 100% imitate its implementation.
D. Put them all together
A proxy contract pattern splits the deployment process into two. But the factory can combine two steps into one, so users won’t feel different.
contract multisigWallet { //wallet interfaces function set(address[] owners, uint required, uint limit) external;}contract walletFactory is cloneFactory { address constant template = "0xdeadbeef"; function create(address[] owners, uint required, uint limit) external returns (address) { address wallet = createClone(template); multisigWallet(wallet).set(owners, required, limit); return wallet; }}
Since both the factory and the clone/proxy has exactly the same interface, no modification is required for all the existing DApp, webpage, and tools, just enjoy the benefit of proxy contracts!
4. Drawbacks
Though proxy contract can lower the storage fee of deploying multiple clones, it will slightly increase the gas cost of each operation in the future due to the usage of delegatecall. So, if the contract is not so long(in bytes), and you expect it’ll be called millions of times, it’ll eventually be more efficient to not use EIP1167 proxies.
In addition, proxy pattern also introduces a different attack vector to the system. For EIP1167 proxies, trust is minimized since the address they point to is hardcoded in bytecode. But, if the reference contract is not permanent, some problems may happen.
You might ever hear of parity multisig wallet hack. There are multiple proxies(not EIP1167) that refer to the same implementation. However, the wallet has a self-destruct function, which empties both the storage and the code of a contract. Unfortunately, there was a bug in Parity wallet’s access control and someone accidentally gained the ownership of the original implementation. That did not directly steal assets from other parity wallets, but then the hacker deleted the original implementation, making all the remaining wallets a shell without functionality, and lock assets in it forever.
https://cointelegraph.com/news/parity-multisig-wallet-hacked-or-how-come
Conclusion
In brief, the proxy factory pattern helps you to deploy a bunch of contract clones with a considerably lower gas cost. EIP1167 defines a bytecode format standard for minimal proxy and it is supported by Etherscan.
To upgrade a contract to EIP1167 compatible, you have to remove both constructor and variable assignment outside a function. So that runtime code will contain all business logic that proxies may need.
Here’s a use case of EIP1167 proxy contract: create adapters for ERC1155 tokens to support ERC20 interface.
pelith/erc-1155-adapter
References
https://eips.ethereum.org/EIPS/eip-1167
https://blog.openzeppelin.com/on-the-parity-wallet-multisig-hack-405a8c12e8f7/
Donation:
pingchen.eth
0xc1F9BB72216E5ecDc97e248F65E14df1fE46600a
Reason Why You Should Use EIP1167 Proxy Contract. (With Tutorial) was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌
「copy constructor」的推薦目錄:
- 關於copy constructor 在 Taipei Ethereum Meetup Facebook 的最讚貼文
- 關於copy constructor 在 Taipei Ethereum Meetup Facebook 的精選貼文
- 關於copy constructor 在 如何撰寫複製函式-c # 程式設計手冊 - Microsoft Docs 的評價
- 關於copy constructor 在 A class without a copy constructor – Arthur O'Dwyer 的評價
- 關於copy constructor 在 copy constructor and copy assignment - gists · GitHub 的評價
- 關於copy constructor 在 Disable copy constructor - Stack Overflow 的評價
- 關於copy constructor 在 Copy constructor 鏈接串列 - iT 邦幫忙 的評價
copy constructor 在 Taipei Ethereum Meetup Facebook 的精選貼文
📜 [專欄新文章] Solidity Weekly #12
✍️ mingderwang
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
functions 什麼時候用 external、private、或 internal
function 跟 (storage) state 全區域合約變數預設不同,變數宣告只有在 public 才會對外開放,讓別人看得到值;而 function 剛好相反,預設是 public。也就是說你沒刻意去宣告,它是可以被外面的程式或合約呼叫。
但如果你刻意用 external、private、或 internal 來宣告 function 的被 call 的屬性,能對最佳化得到一些好處。而 public 與 external 都會讓 function 公開;相反的 internal 與 private 的 functions 只能被合約內部叫用。
限制多寡的順序是︰ public < external < internal < private。
公開 use cases︰
比如說,如果你確定不對內公開,最好宣告為 external。external 有個好處是 call 的參數是從 CALLDATA 獲得,不需要 copy 到 memory 才能執行該 function call。所以比較省 gas,尤其是處理參數是 array 時更凸顯其效果。
但用 external,自己合約如果要調用,反而要寫 this.f() 編譯器才能接受,通常是多此一舉。而且會呼叫 CALL 指令,跟 JUMP 指令比,花更多 gas。
不公開 use cases︰
當合約自己內部的 functions 不想被外部合約或程式調用,最好是用 internal 或甚至用 private 來做限制。internal 還可以被繼承的合約來調用,而 private 就只能自己合約內使用。
它們會被用 JUMP 指令來呼叫,比較省 gas。
我們用 StackOverflow 的範例來做測試,改寫成 Test.sol 如下;
// Test.sol pragma solidity^0.4.12;
contract Test {
// spend 662 gasfunction test(uint[20] a) public pure returns (uint) { return a[10] * 2; }
// spend 317 gasfunction test2(uint[20] a) external pure returns (uint) { return a[10] * 2; }
function test3(uint[20] a) internal pure returns (uint) { return a[10] * 2; } function test4(uint[20] a) private pure returns (uint) { return a[10] * 2; }}
測試程式 (DoTest.sol) 如下︰
// DoTest.solpragma solidity ^0.4.18;
import "./Test.sol";
contract DoTest is Test {uint[20] a;uint public xx;
constructor() public { a[10]=3; } function test_1() external returns(uint) { xx = test(a); return xx; } function test_2() external returns(uint) { xx = this.test2(a); // <-- use this. return xx; } function test_3() external returns(uint) { xx = test3(a); return xx; } function test_4() external returns(uint) { xx = test4(a); // <-- compile error return xx; }}
如果你用 remix 測試,會發現 DoTest 測試繼承 Test 來的不同宣告方式的 functions,會有不同的效果。且 test3() 跟 test4() 對外是看不到的。
links 分享;
Learn X in Y minutes, where X = Solidity Ming> 雖然所用的 solidity 版本 ^0.4.19 還有點舊,但註解做得很好,值得初學者參考。
Ethernaut Lvl 12 Privacy Walkthrough: How Ethereum optimizes storage to save space and be less gassy — (Nicole Zhu) Ming > Coinmonks 的 Medium 裡還有其他很多非常精彩的文章,請自己來尋寶。
The Ethernaut by Zeppelin Ming> 一個 web3/solidity 闖關遊戲平台。
Solidity Weekly #12 was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌
copy constructor 在 A class without a copy constructor – Arthur O'Dwyer 的解答
The compiler has generated a defaulted copy constructor for A . You might try ... That copy constructor is deleted, but it's still present. ... <看更多>
copy constructor 在 copy constructor and copy assignment - gists · GitHub 的解答
#include <iostream>. class Foo {. public: Foo() {. std::cout << "default constructor" << std::endl;. } Foo(const Foo& rhs) {. std::cout << "copy ... ... <看更多>
copy constructor 在 如何撰寫複製函式-c # 程式設計手冊 - Microsoft Docs 的解答
Age; } //// Alternate copy constructor calls the instance constructor. //public Person(Person previousPerson) // : this(previousPerson. ... <看更多>