💎

Smart Contract Design Patterns

Goals

Upgradability is how a protocol can change overtime and what guarantees it makes for the future.

Composability is how easy it is to build on top of the protocol.

Upgradability

Proxies


contract SimpleProxy {
  address internal implementation;

  function fallback() external {
    implementation.delegatecall(msg.data);
  }
}
contract SomeImplementation {
	address internal implementation;
  uint256 public a;
  uint256 public b;
  function setVars(uint256 _a, uint256 _b) external {
    a = _a;
    b = _b;
  }
}

Proxies - Storage Layout

Proxies - EIP1967

contract Proxy {
  bytes32 internal constant IMPLEMENTATION_SLOT = bytes32(
		uint256(keccak256("eip1967.proxy.implementation")) - 1);

  function fallback() external {
    address implementation;
    assembly {
      implementation := sload(IMPLEMENTATION_SLOT)
    }
    implementation.delegatecall(msg.data);
  }
}
contract SomeImplementation {

  uint256 public a;
  uint256 public b;

  function setVars(uint256 _a, uint256 _b) external {
    a = _a;
    b = _b;

  }
}

Proxies - Upgrade Logic

Proxies - Diamond Pattern

Problems with Proxies

Authorization

contract Roles {
  address owner;
  mapping (address => bool) coolGuys;
  modifier onlyOwner() {
    require(msg.sender == owner );
    _;
  }
  modifier onlyCoolGuys() {
    require (coolGuys [msg. sender]);
    _;
  }
}

contract YoloSetOwner {
  address owner;
  modifier onlyOwner () {
    require(msg. sender == owner);
    _;
  }
  function setOwner(address newOwner) external onlyOwner {
    owner = newOwner;
  }
}

contract CheckedReceive {
  address owner;
  address pendingOwner;

  function setOwner(address newOwner) external {
    pendingOwner = newOwner;
  }

  function claimOwnership() external {
    require(msg.sender == pendingOwner);
    owner = pendingOwner;
    pendingOwner = address(0);
  }
}

Modularity

Modularity - Simple Composition

Modularity - Invoker

Modularity - DelegateCall

Modularity - Zora v3

Composability

Diamond Storage Proxy Pattern

Resources

https://www.youtube.com/watch?v=da52yRwWi1E&t=1750s