Delegated Call: Why do developers fear implementing this?

Nwele UchennaNwele Uchenna
2 min read

delegate_call.png

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:

  1. The state variables in Contract(a) can be read and written.
  2. 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?

  1. Developer should understand in detail what function is been delegated.
  2. The delegate call method should be call on only addresses with code (Smart Contract).
  3. The arrangement of local variables on both contract should be identical.

Where are Delegated Calls useful?

  1. Proxy Contracts
  2. EIP-2535 Diamonds
  3. Solidity Libraries
2
Subscribe to my newsletter

Read articles from Nwele Uchenna directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nwele Uchenna
Nwele Uchenna