UUPSLegacy.sol 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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(
  16. address newImplementation,
  17. bytes memory data,
  18. bool forceCall
  19. ) internal {
  20. address oldImplementation = _getImplementation();
  21. // Initial upgrade and setup call
  22. __setImplementation(newImplementation);
  23. if (data.length > 0 || forceCall) {
  24. Address.functionDelegateCall(newImplementation, data);
  25. }
  26. // Perform rollback test if not already in progress
  27. StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
  28. if (!rollbackTesting.value) {
  29. // Trigger rollback using upgradeTo from the new implementation
  30. rollbackTesting.value = true;
  31. Address.functionDelegateCall(
  32. newImplementation,
  33. abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
  34. );
  35. rollbackTesting.value = false;
  36. // Check rollback was effective
  37. require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
  38. // Finally reset to the new implementation and log the upgrade
  39. _upgradeTo(newImplementation);
  40. }
  41. }
  42. // hooking into the old mechanism
  43. function upgradeTo(address newImplementation) external override {
  44. _upgradeToAndCallSecureLegacyV1(newImplementation, bytes(""), false);
  45. }
  46. function upgradeToAndCall(address newImplementation, bytes memory data) external payable override {
  47. _upgradeToAndCallSecureLegacyV1(newImplementation, data, false);
  48. }
  49. }