UUPSLegacy.sol 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  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(Address.isContract(newImplementation), "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(
  28. newImplementation,
  29. abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
  30. );
  31. rollbackTesting.value = false;
  32. // Check rollback was effective
  33. require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
  34. // Finally reset to the new implementation and log the upgrade
  35. _upgradeTo(newImplementation);
  36. }
  37. }
  38. // hooking into the old mechanism
  39. function upgradeTo(address newImplementation) public override {
  40. _upgradeToAndCallSecureLegacyV1(newImplementation, bytes(""), false);
  41. }
  42. function upgradeToAndCall(address newImplementation, bytes memory data) public payable override {
  43. _upgradeToAndCallSecureLegacyV1(newImplementation, data, false);
  44. }
  45. }