Proxies
This document is better viewed at https://docs.openzeppelin.com/contracts/api/proxy |
This is a low-level set of contracts implementing different proxy patterns with and without upgradeability. For an in-depth overview of this pattern check out the Proxy Upgrade Pattern page.
Most of the proxies below are built on an abstract base contract.
-
Proxy
: Abstract contract implementing the core delegation functionality.
In order to avoid clashes with the storage variables of the implementation contract behind a proxy, we use ERC-1967 storage slots.
-
ERC1967Utils
: Internal functions to get and set the storage slots defined in ERC-1967. -
ERC1967Proxy
: A proxy using ERC-1967 storage slots. Not upgradeable by default.
There are two alternative ways to add upgradeability to an ERC-1967 proxy. Their differences are explained below in Transparent vs UUPS Proxies.
-
TransparentUpgradeableProxy
: A proxy with a built-in immutable admin and upgrade interface. -
UUPSUpgradeable
: An upgradeability mechanism to be included in the implementation contract.
Using upgradeable proxies correctly and securely is a difficult task that requires deep knowledge of the proxy pattern, Solidity, and the EVM. Unless you want a lot of low level control, we recommend using the OpenZeppelin Upgrades Plugins for Hardhat and Foundry. |
A different family of proxies are beacon proxies. This pattern, popularized by Dharma, allows multiple proxies to be upgraded to a different implementation in a single transaction.
-
BeaconProxy
: A proxy that retrieves its implementation from a beacon contract. -
UpgradeableBeacon
: A beacon contract with a built in admin that can upgrade theBeaconProxy
pointing to it.
In this pattern, the proxy contract doesn’t hold the implementation address in storage like an ERC-1967 proxy. Instead, the address is stored in a separate beacon contract. The upgrade
operations are sent to the beacon instead of to the proxy contract, and all proxies that follow that beacon are automatically upgraded.
Outside the realm of upgradeability, proxies can also be useful to make cheap contract clones, such as those created by an on-chain factory contract that creates many instances of the same contract. These instances are designed to be both cheap to deploy, and cheap to call.
-
Clones
: A library that can deploy cheap minimal non-upgradeable proxies.
Transparent vs UUPS Proxies
The original proxies included in OpenZeppelin followed the Transparent Proxy Pattern. While this pattern is still provided, our recommendation is now shifting towards UUPS proxies, which are both lightweight and versatile. The name UUPS comes from ERC-1822, which first documented the pattern.
While both of these share the same interface for upgrades, in UUPS proxies the upgrade is handled by the implementation, and can eventually be removed. Transparent proxies, on the other hand, include the upgrade and admin logic in the proxy itself. This means TransparentUpgradeableProxy
is more expensive to deploy than what is possible with UUPS proxies.
UUPS proxies are implemented using an ERC1967Proxy
. Note that this proxy is not by itself upgradeable. It is the role of the implementation to include, alongside the contract’s logic, all the code necessary to update the implementation’s address that is stored at a specific slot in the proxy’s storage space. This is where the UUPSUpgradeable
contract comes in. Inheriting from it (and overriding the _authorizeUpgrade
function with the relevant access control mechanism) will turn your contract into a UUPS compliant implementation.
Note that since both proxies use the same storage slot for the implementation address, using a UUPS compliant implementation with a TransparentUpgradeableProxy
might allow non-admins to perform upgrade operations.
By default, the upgrade functionality included in UUPSUpgradeable
contains a security mechanism that will prevent any upgrades to a non UUPS compliant implementation. This prevents upgrades to an implementation contract that wouldn’t contain the necessary upgrade mechanism, as it would lock the upgradeability of the proxy forever. This security mechanism can be bypassed by either of:
-
Adding a flag mechanism in the implementation that will disable the upgrade function when triggered.
-
Upgrading to an implementation that features an upgrade mechanism without the additional security check, and then upgrading again to another implementation without the upgrade mechanism.
The current implementation of this security mechanism uses ERC-1822 to detect the storage slot used by the implementation. A previous implementation, now deprecated, relied on a rollback check. It is possible to upgrade from a contract using the old mechanism to a new one. The inverse is however not possible, as old implementations (before version 4.5) did not include the ERC-1822 interface.
Core
Proxy
import "@openzeppelin/contracts/proxy/Proxy.sol";
This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
instruction delegatecall
. We refer to the second contract as the implementation behind the proxy, and it has to
be specified by overriding the virtual _implementation
function.
Additionally, delegation to the implementation can be triggered manually through the _fallback
function, or to a
different contract through the _delegate
function.
The success and return data of the delegated call will be returned back to the caller of the proxy.
_delegate(address implementation)
internal
Delegates the current call to implementation
.
This function does not return to its internal call site, it will return directly to the external caller.
_implementation() → address
internal
This is a virtual function that should be overridden so it returns the address to which the fallback
function and _fallback
should delegate.
ERC-1967
ERC1967Proxy
import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an implementation address that can be changed. This address is stored in storage in the location specified by ERC-1967, so that it doesn’t conflict with the storage layout of the implementation behind the proxy.
constructor(address implementation, bytes _data)
public
Initializes the upgradeable proxy with an initial implementation specified by implementation
.
If _data
is nonempty, it’s used as data in a delegate call to implementation
. This will typically be an
encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
Requirements:
-
If
data
is empty,msg.value
must be zero.
_implementation() → address
internal
Returns the current implementation address.
To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
the eth_getStorageAt RPC call.
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
|
ERC1967Utils
import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
This library provides getters and event emitting update functions for ERC-1967 slots.
upgradeToAndCall(address newImplementation, bytes data)
internal
Performs implementation upgrade with additional setup call if data is nonempty.
This function is payable only if the setup call is performed, otherwise msg.value
is rejected
to avoid stuck value in the contract.
Emits an IERC1967.Upgraded
event.
getAdmin() → address
internal
Returns the current admin.
To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
the eth_getStorageAt RPC call.
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103
|
changeAdmin(address newAdmin)
internal
Changes the admin of the proxy.
Emits an IERC1967.AdminChanged
event.
upgradeBeaconToAndCall(address newBeacon, bytes data)
internal
Change the beacon and trigger a setup call if data is nonempty.
This function is payable only if the setup call is performed, otherwise msg.value
is rejected
to avoid stuck value in the contract.
Emits an IERC1967.BeaconUpgraded
event.
Invoking this function has no effect on an instance of BeaconProxy since v5, since
it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
efficiency.
|
ERC1967InvalidImplementation(address implementation)
error
The implementation
of the proxy is invalid.
bytes32 IMPLEMENTATION_SLOT
internal constant
Storage slot with the address of the current implementation. This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
Transparent Proxy
TransparentUpgradeableProxy
import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
This contract implements a proxy that is upgradeable through an associated ProxyAdmin
instance.
To avoid proxy selector clashing, which can potentially be used in an attack, this contract uses the transparent proxy pattern. This pattern implies two things that go hand in hand:
-
If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches the
ITransparentUpgradeableProxy.upgradeToAndCall
function exposed by the proxy itself. -
If the admin calls the proxy, it can call the
upgradeToAndCall
function but any other call won’t be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating the proxy admin cannot fallback to the target implementation.
These properties mean that the admin account can only be used for upgrading the proxy, so it’s best if it’s a
dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to
call a function from the proxy implementation. For this reason, the proxy deploys an instance of ProxyAdmin
and
allows upgrades only if they come through it. You should think of the ProxyAdmin
instance as the administrative
interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.
The real interface of this proxy is that defined in ITransparentUpgradeableProxy . This contract does not
inherit from that interface, and instead upgradeToAndCall is implicitly implemented using a custom dispatch
mechanism in _fallback . Consequently, the compiler will not produce an ABI for this contract. This is necessary to
fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
implementation.
|
This proxy does not inherit from Context deliberately. The ProxyAdmin of this contract won’t send a
meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.
|
This contract avoids unnecessary storage reads by setting the admin only during construction as an immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot is generally fine if the implementation is trusted. |
It is not recommended to extend this contract to add additional external functions. If you do so, the
compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new
function and the functions declared in ITransparentUpgradeableProxy will be resolved in favor of the new one. This
could render the upgradeToAndCall function inaccessible, preventing upgradeability and compromising transparency.
|
constructor(address _logic, address initialOwner, bytes _data)
public
Initializes an upgradeable proxy managed by an instance of a ProxyAdmin
with an initialOwner
,
backed by the implementation at _logic
, and optionally initialized with _data
as explained in
ERC1967Proxy.constructor
.
ProxyAdmin
import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";
This is an auxiliary contract meant to be assigned as the admin of a TransparentUpgradeableProxy
. For an
explanation of why you would want to use this see the documentation for TransparentUpgradeableProxy
.
upgradeAndCall(contract ITransparentUpgradeableProxy proxy, address implementation, bytes data)
public
Upgrades proxy
to implementation
and calls a function on the new implementation.
See TransparentUpgradeableProxy._dispatchUpgradeToAndCall
.
Requirements:
-
This contract must be the admin of
proxy
. -
If
data
is empty,msg.value
must be zero.
UPGRADE_INTERFACE_VERSION() → string
public
The version of the upgrade interface of the contract. If this getter is missing, both upgrade(address,address)
and upgradeAndCall(address,address,bytes)
are present, and upgrade
must be used if no function should be called,
while upgradeAndCall
will invoke the receive
function if the third argument is the empty byte string.
If the getter returns "5.0.0"
, only upgradeAndCall(address,address,bytes)
is present, and the third argument must
be the empty byte string if no function should be called, making it impossible to invoke the receive
function
during an upgrade.
Beacon
BeaconProxy
import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
This contract implements a proxy that gets the implementation address for each call from an UpgradeableBeacon
.
The beacon address can only be set once during construction, and cannot be changed afterwards. It is stored in an immutable variable to avoid unnecessary storage reads, and also in the beacon storage slot specified by ERC-1967 so that it can be accessed externally.
Since the beacon address can never be changed, you must ensure that you either control the beacon, or trust the beacon to not upgrade the implementation maliciously. |
Do not use the implementation logic to modify the beacon storage slot. Doing so would leave the proxy in an inconsistent state where the beacon storage slot does not match the beacon address. |
constructor(address beacon, bytes data)
public
Initializes the proxy with beacon
.
If data
is nonempty, it’s used as data in a delegate call to the implementation returned by the beacon. This
will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity
constructor.
Requirements:
-
beacon
must be a contract with the interfaceIBeacon
. -
If
data
is empty,msg.value
must be zero.
IBeacon
import "@openzeppelin/contracts/proxy/beacon/IBeacon.sol";
This is the interface that BeaconProxy
expects of its beacon.
implementation() → address
external
Must return an address that can be used as a delegate call target.
UpgradeableBeacon
will check that this address is a contract.
UpgradeableBeacon
import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
This contract is used in conjunction with one or more instances of BeaconProxy
to determine their
implementation contract, which is where they will delegate all function calls.
An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
constructor(address implementation_, address initialOwner)
public
Sets the address of the initial implementation, and the initial owner who can upgrade the beacon.
upgradeTo(address newImplementation)
public
Upgrades the beacon to a new implementation.
Emits an Upgraded
event.
Requirements:
-
msg.sender must be the owner of the contract.
-
newImplementation
must be a contract.
Minimal Clones
Clones
import "@openzeppelin/contracts/proxy/Clones.sol";
ERC-1167 is a standard for deploying minimal proxy contracts, also known as "clones".
To simply and cheaply clone contract functionality in an immutable way, this standard specifies a minimal bytecode implementation that delegates all calls to a known, fixed address.
The library includes functions to deploy a proxy using either create
(traditional deployment) or create2
(salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
deterministic method.
clone(address implementation) → address instance
internal
Deploys and returns the address of a clone that mimics the behaviour of implementation
.
This function uses the create opcode, which should never revert.
clone(address implementation, uint256 value) → address instance
internal
Same as clone, but with a value
parameter to send native currency
to the new contract.
Using a non-zero value at creation will require the contract using this function (e.g. a factory) to always have enough balance for new deployments. Consider exposing this function under a payable method. |
cloneDeterministic(address implementation, bytes32 salt) → address instance
internal
Deploys and returns the address of a clone that mimics the behaviour of implementation
.
This function uses the create2 opcode and a salt
to deterministically deploy
the clone. Using the same implementation
and salt
multiple time will revert, since
the clones cannot be deployed twice at the same address.
cloneDeterministic(address implementation, bytes32 salt, uint256 value) → address instance
internal
Same as cloneDeterministic, but with
a value
parameter to send native currency to the new contract.
Using a non-zero value at creation will require the contract using this function (e.g. a factory) to always have enough balance for new deployments. Consider exposing this function under a payable method. |
predictDeterministicAddress(address implementation, bytes32 salt, address deployer) → address predicted
internal
Computes the address of a clone deployed using Clones.cloneDeterministic
.
predictDeterministicAddress(address implementation, bytes32 salt) → address predicted
internal
Computes the address of a clone deployed using Clones.cloneDeterministic
.
Utils
Initializable
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
behind a proxy. Since proxied contracts do not make use of a constructor, it’s common to move constructor logic to an
external initializer function, usually called initialize
. It then becomes necessary to protect this initializer
function so it can only be called once. The initializer
modifier provided by this contract will have this effect.
The initialization functions use a version number. Once a version number is used, it is consumed and cannot be reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in case an upgrade adds a module that needs to be initialized.
For example:
contract MyToken is ERC20Upgradeable {
function initialize() initializer public {
__ERC20_init("MyToken", "MTK");
}
}
contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
function initializeV2() reinitializer(2) public {
__ERC20Permit_init("MyToken");
}
}
To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
possible by providing the encoded function call as the _data argument to ERC1967Proxy.constructor .
|
When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. |
Avoid leaving a contract uninitialized. An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
the
|
initializer()
modifier
A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
onlyInitializing
functions can be used to initialize parent contracts.
Similar to reinitializer(1)
, except that in the context of a constructor an initializer
may be invoked any
number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
production.
Emits an Initialized
event.
reinitializer(uint64 version)
modifier
A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
contract hasn’t been initialized to a greater version before. In its scope, onlyInitializing
functions can be
used to initialize parent contracts.
A reinitializer may be used after the original initialization step. This is essential to configure modules that are added through upgrades and that require initialization.
When version
is 1, this modifier is similar to initializer
, except that functions marked with reinitializer
cannot be nested. If one is invoked in the context of another, execution will revert.
Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in a contract, executing them in the right order is up to the developer or operator.
Setting the version to 2**64 - 1 will prevent any future reinitialization. |
Emits an Initialized
event.
onlyInitializing()
modifier
Modifier to protect an initialization function so that it can only be invoked by functions with the
initializer
and reinitializer
modifiers, directly or indirectly.
_checkInitializing()
internal
Reverts if the contract is not in an initializing state. See onlyInitializing
.
_disableInitializers()
internal
Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized to any version. It is recommended to use this to lock implementation contracts that are designed to be called through proxies.
Emits an Initialized
event the first time it is successfully executed.
_getInitializedVersion() → uint64
internal
Returns the highest version that has been initialized. See reinitializer
.
_isInitializing() → bool
internal
Returns true
if the contract is currently initializing. See onlyInitializing
.
UUPSUpgradeable
import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
ERC1967Proxy
, when this contract is set as the implementation behind such a proxy.
A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
UUPSUpgradeable
with a custom implementation of upgrades.
The _authorizeUpgrade
function must be overridden to include access restriction to the upgrade mechanism.
onlyProxy()
modifier
Check that the execution is being performed through a delegatecall call and that the execution context is a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to fail.
notDelegated()
modifier
Check that the execution is not being performed through a delegate call. This allows a function to be callable on the implementing contract but not through proxies.
proxiableUUID() → bytes32
external
Implementation of the ERC-1822 proxiableUUID
function. This returns the storage slot used by the
implementation. It is used to validate the implementation’s compatibility when performing an upgrade.
A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
function revert if invoked through a proxy. This is guaranteed by the notDelegated modifier.
|
upgradeToAndCall(address newImplementation, bytes data)
public
Upgrade the implementation of the proxy to newImplementation
, and subsequently execute the function call
encoded in data
.
Calls _authorizeUpgrade
.
Emits an Upgraded
event.
_checkProxy()
internal
Reverts if the execution is not performed via delegatecall or the execution context is not of a proxy with an ERC-1967 compliant implementation pointing to self. See {_onlyProxy}.
_checkNotDelegated()
internal
Reverts if the execution is performed via delegatecall.
See notDelegated
.
_authorizeUpgrade(address newImplementation)
internal
Function that should revert when msg.sender
is not authorized to upgrade the contract. Called by
upgradeToAndCall
.
Normally, this function will use an access control modifier such as Ownable.onlyOwner
.
function _authorizeUpgrade(address) internal onlyOwner {}
UPGRADE_INTERFACE_VERSION() → string
public
The version of the upgrade interface of the contract. If this getter is missing, both upgradeTo(address)
and upgradeToAndCall(address,bytes)
are present, and upgradeTo
must be used if no function should be called,
while upgradeToAndCall
will invoke the receive
function if the second argument is the empty byte string.
If the getter returns "5.0.0"
, only upgradeToAndCall(address,bytes)
is present, and the second argument must
be the empty byte string if no function should be called, making it impossible to invoke the receive
function
during an upgrade.