UUPSLegacy.sol 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.19;
  3. import "./UUPSUpgradeableMock.sol";
  4. // This contract implements the pre-4.5 UUPS upgrade function with a rollback test.
  5. // It's used to test that newer UUPS contracts are considered valid upgrades by older UUPS contracts.
  6. contract UUPSUpgradeableLegacyMock is UUPSUpgradeableMock {
  7. // Inlined from ERC1967Upgrade
  8. bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
  9. // ERC1967Upgrade._setImplementation is private so we reproduce it here.
  10. // An extra underscore prevents a name clash error.
  11. function __setImplementation(address newImplementation) private {
  12. require(newImplementation.code.length > 0, "ERC1967: new implementation is not a contract");
  13. StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
  14. }
  15. function _upgradeToAndCallSecureLegacyV1(address newImplementation, bytes memory data, bool forceCall) internal {
  16. address oldImplementation = _getImplementation();
  17. // Initial upgrade and setup call
  18. __setImplementation(newImplementation);
  19. if (data.length > 0 || forceCall) {
  20. Address.functionDelegateCall(newImplementation, data);
  21. }
  22. // Perform rollback test if not already in progress
  23. StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
  24. if (!rollbackTesting.value) {
  25. // Trigger rollback using upgradeTo from the new implementation
  26. rollbackTesting.value = true;
  27. Address.functionDelegateCall(newImplementation, abi.encodeCall(this.upgradeTo, (oldImplementation)));
  28. rollbackTesting.value = false;
  29. // Check rollback was effective
  30. require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
  31. // Finally reset to the new implementation and log the upgrade
  32. _upgradeTo(newImplementation);
  33. }
  34. }
  35. // hooking into the old mechanism
  36. function upgradeTo(address newImplementation) public override {
  37. _upgradeToAndCallSecureLegacyV1(newImplementation, bytes(""), false);
  38. }
  39. function upgradeToAndCall(address newImplementation, bytes memory data) public payable override {
  40. _upgradeToAndCallSecureLegacyV1(newImplementation, data, false);
  41. }
  42. }