Delegated Call: Why do developers fear implementing this?
When a contract makes a function call using delegate call it loads the function code from another contract and executes it as if it were its own code.
In the smart development space, Delegated call has become one of the most feared methods or implementation in programming smart contracts even when its implementation is necessary for the project… Developers just don’t want to implement the delegated call function.
What is a Delegated Call?
Delegated call is a method available to contracts address which give a Contract (a) the power to utilize a function from a Contract (b) using the context of Contract (a), meaning the {msg.sender}, {msg.data}, {msg.value}, {address(this)} of contract (a) would still be retained even when running a function from Contract (b).
Now if Contract(a) uses delegate call to execute a function from Contract (b) then the following two points are true:
- The state variables in Contract(a) can be read and written.
- The state variables in Contract(b) are never read or written.
EXAMPLE
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
contract B {
// NOTE: storage layout must be the same as contract A
uint public num;
address public sender;
uint public value;
function setVars(uint _num) public payable {
num = _num;
sender = msg.sender;
value = msg.value;
}
}
contract A {
uint public num;
address public sender;
uint public value;
function setVars(address _contract, uint _num) public payable {
// A's storage is set, B is not modified.
(bool success, bytes memory data) = _contract.delegatecall(
abi.encodeWithSignature("setVars(uint256)", _num)
);
}
}
EXPLANATION:
Contract B is First deployed because we would be delegating a call to it setVars function. From the explanation thus far, you should be able to denote that the variables num, sender and value in Contract B would not be manipulated despite the fact that it houses the setVars function. But instead the variables num, sender, value in Contract A would be Edited because delegated call would make uses of the Contract A context.
The fear and danger of the delegated call method come from not understanding how it works and how to use it safely.
When Should I Use Delegate Call?
- Developer should understand in detail what function is been delegated.
- The delegate call method should be call on only addresses with code (Smart Contract).
- The arrangement of local variables on both contract should be identical.
Where are Delegated Calls useful?
- Proxy Contracts
- EIP-2535 Diamonds
- Solidity Libraries