Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"contracts/ProxyLedger.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// oz imports
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// lz imports
import {OFTComposeMsgCodec} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oft/libs/OFTComposeMsgCodec.sol";
import {IOFT} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oft/interfaces/IOFT.sol";
import {VaultOCCManager} from "./lib/OCCManager.sol";
import {EvmVaultMessage, OCCLedgerMessage, LedgerToken} from "./lib/types/OCCTypes.sol";
import {LedgerPayloadTypes, PayloadDataType} from "./lib/types/LedgerTypes.sol";
/**
* @title ProxyLedger for proxy requests to ledger
* @dev proxy staking, claiming and other ledger operations from vault chains, like Ethereum, Arbitrum, etc.
*/
contract ProxyLedger is Initializable, VaultOCCManager, UUPSUpgradeable {
using OFTComposeMsgCodec for bytes;
using SafeERC20 for IERC20;
event ClaimRewardTokenTransferred(address indexed user, uint256 amount);
event WithdrawOrderTokenTransferred(address indexed user, uint256 amount);
event ClaimUsdcRevenueTransferred(address indexed user, uint256 amount);
event ClaimVestingRequestTransferred(address indexed user, uint256 amount);
function VERSION() external pure virtual returns (string memory) {
return "1.0.6";
}
/* ========== prevent initialization for implementation contracts ========== */
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/* ====== initializer ====== */
/// @notice initialize the contract
function initialize(address _oft, address _usdc, address _owner) external initializer {
orderTokenOft = _oft;
usdcAddr = _usdc;
ledgerAccessControlInit(_owner);
}
/* ====== upgradeable ====== */
/// @notice upgrade the contract
function _authorizeUpgrade(address) internal override onlyRole(DEFAULT_ADMIN_ROLE) {}
/* ====== Claim Reward ====== */
/**
* @notice construct OCCVaultMessage for claim reward operation
* @param distributionId the distribution id
* @param user the user to claim reward
* @param cumulativeAmount the cumulative amount to claim
* @param merkleProof the merkle proof
*/
function buildClaimRewardMessage(
uint32 distributionId,
address user,
uint256 cumulativeAmount,
bytes32[] memory merkleProof
) internal view returns (EvmVaultMessage memory) {
return
EvmVaultMessage({
chainedEventId: chainedEventId,
srcChainId: 0,
token: LedgerToken.PLACEHOLDER,
tokenAmount: 0,
sender: user,
payloadType: uint8(PayloadDataType.ClaimReward),
payload: abi.encode(
LedgerPayloadTypes.ClaimReward({distributionId: distributionId, cumulativeAmount: cumulativeAmount, merkleProof: merkleProof})
)
});
}
/**
* @notice claim reward from the ledger
* @param distributionId the distribution id
* @param cumulativeAmount the cumulative amount to claim
* @param merkleProof the merkle proof
*/
function claimReward(uint32 distributionId, uint256 cumulativeAmount, bytes32[] memory merkleProof) external payable whenNotPaused {
EvmVaultMessage memory message = buildClaimRewardMessage(distributionId, msg.sender, cumulativeAmount, merkleProof);
vaultSendToLedger(message);
}
/**
* @notice estimate the Layerzero fee for sending a message from vault to ledger chain in native token
* @param distributionId the distribution id
* @param user the user to claim reward
* @param cumulativeAmount the cumulative amount to claim
* @param merkleProof the merkle proof
*/
function quoteClaimReward(
uint32 distributionId,
address user,
uint256 cumulativeAmount,
bytes32[] memory merkleProof
) external view returns (uint256) {
EvmVaultMessage memory message = buildClaimRewardMessage(distributionId, user, cumulativeAmount, merkleProof);
return estimateCCFeeFromVaultToLedger(message);
}
/* ====== staking ====== */
/**
* @notice construct OCCVaultMessage for stake operation
* @param amount the amount to stake
* @param sender the sender of the stake
*/
function buildStakeOrderMessage(uint256 amount, address sender) internal view returns (EvmVaultMessage memory) {
return
EvmVaultMessage({
chainedEventId: chainedEventId,
srcChainId: 0,
token: LedgerToken.ORDER,
tokenAmount: amount,
sender: sender,
payloadType: uint8(PayloadDataType.Stake),
payload: bytes("")
});
}
/**
* @notice stake the amount to the ledger
* @param amount the amount to stake
*/
function stakeOrder(uint256 amount) external payable whenNotPaused {
EvmVaultMessage memory message = buildStakeOrderMessage(amount, msg.sender);
vaultSendToLedger(message);
}
/**
* @notice estimate the Layerzero fee for sending a message from vault to ledger chain in native token
* @param amount the amount to stake
* @param sender the sender of the stake
*/
function quoteStakeOrder(uint256 amount, address sender) external view returns (uint256) {
EvmVaultMessage memory message = buildStakeOrderMessage(amount, sender);
return estimateCCFeeFromVaultToLedger(message);
}
/* ====== Other Operations Including only Amount and User ====== */
/**
* @notice construct OCCVaultMessage for other operations
* @param amount the amount to send
* @param user the user to send
* @param payloadType the payload type
* 2: CreateOrderUnstakeRequest,
* 3: CancelOrderUnstakeRequest,
* 4: WithdrawOrder,
* 5: EsOrderUnstakeAndVest,
* 6: CancelVestingRequest,
* 7: CancelAllVestingRequests, Not supported anymore.
* 8: ClaimVestingRequest,
* 9: RedeemValor,
* 10: ClaimUsdcRevenue,
* 17: RedeemValor2,
* 18: ClaimEsOrderRevenue
*/
function buildEvmVaultMessage(uint256 amount, address user, uint8 payloadType) internal view returns (EvmVaultMessage memory) {
// require correct payloadType
require(
payloadType == uint8(PayloadDataType.CreateOrderUnstakeRequest) ||
payloadType == uint8(PayloadDataType.CancelOrderUnstakeRequest) ||
payloadType == uint8(PayloadDataType.WithdrawOrder) ||
payloadType == uint8(PayloadDataType.EsOrderUnstakeAndVest) ||
payloadType == uint8(PayloadDataType.CancelVestingRequest) ||
payloadType == uint8(PayloadDataType.ClaimVestingRequest) ||
payloadType == uint8(PayloadDataType.RedeemValor) ||
payloadType == uint8(PayloadDataType.ClaimUsdcRevenue) ||
payloadType == uint8(PayloadDataType.RedeemValor2) ||
payloadType == uint8(PayloadDataType.ClaimEsOrderRevenue),
"UnsupportedPayloadType"
);
return
EvmVaultMessage({
chainedEventId: chainedEventId,
srcChainId: 0,
token: LedgerToken.PLACEHOLDER,
tokenAmount: 0,
sender: user,
payloadType: payloadType,
payload: abi.encode(amount)
});
}
/**
* @notice send user request to the ledger
* @param amount the amount to send
* @param payloadType the payload type
*/
function sendUserRequest(uint256 amount, uint8 payloadType) external payable whenNotPaused {
EvmVaultMessage memory occMsg = buildEvmVaultMessage(amount, msg.sender, payloadType);
vaultSendToLedger(occMsg);
}
/**
* @notice estimate the Layerzero fee for sending a message from vault to ledger chain in native token
* @param amount the amount to send
* @param user the user to send
* @param payloadType the payload type
*/
function quoteSendUserRequest(uint256 amount, address user, uint8 payloadType) external view returns (uint256) {
EvmVaultMessage memory occMsg = buildEvmVaultMessage(amount, user, payloadType);
return estimateCCFeeFromVaultToLedger(occMsg);
}
/**
*
* @param _endpoint The the caller of function lzCompose() on the relayer contract, it should be the endpoint
* @param _localSender The composeMsg sender on local network, it should be the oft/adapter contract
* @param _eid The eid to identify the network from where the composeMsg sent
* @param _remoteSender The address to identiy the sender on the remote network
*/
function _authorizeComposeMsgSender(address _endpoint, address _localSender, uint32 _eid, address _remoteSender) internal view returns (bool) {
return (lzEndpoint == _endpoint && _localSender == orderTokenOft && _remoteSender == ledgerAddr && eid2ChainId[_eid] == ledgerChainId);
}
/* ====== Receive Message From Ledger ====== */
function lzCompose(
address from,
bytes32 /*guid*/,
bytes calldata _message,
address /*executor*/,
bytes calldata /*_extraData*/
) external payable whenNotPaused {
uint32 srcEid = _message.srcEid();
address remoteSender = OFTComposeMsgCodec.bytes32ToAddress(_message.composeFrom());
require(_authorizeComposeMsgSender(msg.sender, from, srcEid, remoteSender), "OrderlyBox: composeMsg sender check failed");
bytes memory _composeMsgContent = OFTComposeMsgCodec.composeMsg(_message);
OCCLedgerMessage memory message = abi.decode(_composeMsgContent, (OCCLedgerMessage));
vaultRecvFromLedger(message);
}
function vaultRecvFromLedger(OCCLedgerMessage memory message) internal {
address receiver = OFTComposeMsgCodec.bytes32ToAddress(message.receiver);
if (message.payloadType == uint8(PayloadDataType.ClaimRewardBackward)) {
// require token is order, and amount > 0
require(message.token == LedgerToken.ORDER && message.tokenAmount > 0, "InvalidClaimRewardBackward");
IERC20(IOFT(orderTokenOft).token()).safeTransfer(receiver, message.tokenAmount);
emit ClaimRewardTokenTransferred(receiver, message.tokenAmount);
} else if (message.payloadType == uint8(PayloadDataType.WithdrawOrderBackward)) {
// require token is order, and amount > 0
require(message.token == LedgerToken.ORDER && message.tokenAmount > 0, "InvalidWithdrawOrderBackward");
IERC20(IOFT(orderTokenOft).token()).safeTransfer(receiver, message.tokenAmount);
emit WithdrawOrderTokenTransferred(receiver, message.tokenAmount);
} else if (message.payloadType == uint8(PayloadDataType.ClaimVestingRequestBackward)) {
// require token is order, and amount > 0
require(message.token == LedgerToken.ORDER && message.tokenAmount > 0, "InvalidClaimVestingRequestBackward");
IERC20(IOFT(orderTokenOft).token()).safeTransfer(receiver, message.tokenAmount);
emit ClaimVestingRequestTransferred(receiver, message.tokenAmount);
} else if (message.payloadType == uint8(PayloadDataType.ClaimUsdcRevenueBackward)) {
require(message.token == LedgerToken.USDC && message.tokenAmount > 0, "InvalidClaimUsdcRevenueBackward");
IERC20(usdcAddr).safeTransfer(receiver, message.tokenAmount);
emit ClaimUsdcRevenueTransferred(receiver, message.tokenAmount);
} else {
revert("UnsupportedPayloadType");
}
}
/**
* @notice withdraw function for native token
* @param to the address to withdraw to
*/
function withdrawTo(address to) external onlyRole(DEFAULT_ADMIN_ROLE) {
payable(to).transfer(address(this).balance);
}
/// @notice fallback to receive
receive() external payable {}
}
"
},
"node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev 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:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* 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");
* }
* }
* ```
*
* TIP: 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}.
*
* CAUTION: 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.
*
* [CAUTION]
* ====
* 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 {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev 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.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev 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.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev 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.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
"
},
"node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev 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.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev 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.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev 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 ERC1967) 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 ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev 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.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: 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.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC1967-compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
"
},
"node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
"
},
"node_modules/@layerzerolabs/lz-evm-oapp-v2/contracts/oft/libs/OFTComposeMsgCodec.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library OFTComposeMsgCodec {
// Offset constants for decoding composed messages
uint8 private constant NONCE_OFFSET = 8;
uint8 private constant SRC_EID_OFFSET = 12;
uint8 private constant AMOUNT_LD_OFFSET = 44;
uint8 private constant COMPOSE_FROM_OFFSET = 76;
/**
* @dev Encodes a OFT composed message.
* @param _nonce The nonce value.
* @param _srcEid The source endpoint ID.
* @param _amountLD The amount in local decimals.
* @param _composeMsg The composed message.
* @return _msg The encoded Composed message.
*/
function encode(
uint64 _nonce,
uint32 _srcEid,
uint256 _amountLD,
bytes memory _composeMsg // 0x[composeFrom][composeMsg]
) internal pure returns (bytes memory _msg) {
_msg = abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg);
}
/**
* @dev Retrieves the nonce from the composed message.
* @param _msg The message.
* @return The nonce value.
*/
function nonce(bytes calldata _msg) internal pure returns (uint64) {
return uint64(bytes8(_msg[:NONCE_OFFSET]));
}
/**
* @dev Retrieves the source endpoint ID from the composed message.
* @param _msg The message.
* @return The source endpoint ID.
*/
function srcEid(bytes calldata _msg) internal pure returns (uint32) {
return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET]));
}
/**
* @dev Retrieves the amount in local decimals from the composed message.
* @param _msg The message.
* @return The amount in local decimals.
*/
function amountLD(bytes calldata _msg) internal pure returns (uint256) {
return uint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET]));
}
/**
* @dev Retrieves the composeFrom value from the composed message.
* @param _msg The message.
* @return The composeFrom value.
*/
function composeFrom(bytes calldata _msg) internal pure returns (bytes32) {
return bytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]);
}
/**
* @dev Retrieves the composed message.
* @param _msg The message.
* @return The composed message.
*/
function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
return _msg[COMPOSE_FROM_OFFSET:];
}
/**
* @dev Converts an address to bytes32.
* @param _addr The address to convert.
* @return The bytes32 representation of the address.
*/
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
/**
* @dev Converts bytes32 to an address.
* @param _b The bytes32 value to convert.
* @return The address representation of bytes32.
*/
function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
return address(uint160(uint256(_b)));
}
}
"
},
"node_modules/@layerzerolabs/lz-evm-oapp-v2/contracts/oft/interfaces/IOFT.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { MessagingReceipt, MessagingFee } from "../../oapp/OAppSender.sol";
/**
* @dev Struct representing token parameters for the OFT send() operation.
*/
struct SendParam {
uint32 dstEid; // Destination endpoint ID.
bytes32 to; // Recipient address.
uint256 amountLD; // Amount to send in local decimals.
uint256 minAmountLD; // Minimum amount to send in local decimals.
bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.
bytes composeMsg; // The composed message for the send() operation.
bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.
}
/**
* @dev Struct representing OFT limit information.
* @dev These amounts can change dynamically and are up the the specific oft implementation.
*/
struct OFTLimit {
uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient.
uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient.
}
/**
* @dev Struct representing OFT receipt information.
*/
struct OFTReceipt {
uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.
// @dev In non-default implementations, the amountReceivedLD COULD differ from this value.
uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.
}
/**
* @dev Struct representing OFT fee details.
* @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI.
*/
struct OFTFeeDetail {
int256 feeAmountLD; // Amount of the fee in local decimals.
string description; // Description of the fee.
}
/**
* @title IOFT
* @dev Interface for the OftChain (OFT) token.
* @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well.
* @dev This specific interface ID is '0x02e49c2c'.
*/
interface IOFT {
// Custom error messages
error InvalidLocalDecimals();
error SlippageExceeded(uint256 amountLD, uint256 minAmountLD);
// Events
event OFTSent(
bytes32 indexed guid, // GUID of the OFT message.
uint32 dstEid, // Destination Endpoint ID.
address indexed fromAddress, // Address of the sender on the src chain.
uint256 amountSentLD, // Amount of tokens sent in local decimals.
uint256 amountReceivedLD // Amount of tokens received in local decimals.
);
event OFTReceived(
bytes32 indexed guid, // GUID of the OFT message.
uint32 srcEid, // Source Endpoint ID.
address indexed toAddress, // Address of the recipient on the dst chain.
uint256 amountReceivedLD // Amount of tokens received in local decimals.
);
/**
* @notice Retrieves interfaceID and the version of the OFT.
* @return interfaceId The interface ID.
* @return version The version.
*
* @dev interfaceId: This specific interface ID is '0x02e49c2c'.
* @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
* @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
* ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
*/
function oftVersion() external view returns (bytes4 interfaceId, uint64 version);
/**
* @notice Retrieves the address of the token associated with the OFT.
* @return token The address of the ERC20 token implementation.
*/
function token() external view returns (address);
/**
* @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
* @return requiresApproval Needs approval of the underlying token implementation.
*
* @dev Allows things like wallet implementers to determine integration requirements,
* without understanding the underlying token implementation.
*/
function approvalRequired() external view returns (bool);
/**
* @notice Retrieves the shared decimals of the OFT.
* @return sharedDecimals The shared decimals of the OFT.
*/
function sharedDecimals() external view returns (uint8);
/**
* @notice Provides a quote for OFT-related operations.
* @param _sendParam The parameters for the send operation.
* @return limit The OFT limit information.
* @return oftFeeDetails The details of OFT fees.
* @return receipt The OFT receipt information.
*/
function quoteOFT(
SendParam calldata _sendParam
) external view returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory);
/**
* @notice Provides a quote for the send() operation.
* @param _sendParam The parameters for the send() operation.
* @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
* @return fee The calculated LayerZero messaging fee from the send() operation.
*
* @dev MessagingFee: LayerZero msg fee
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
*/
function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);
/**
* @notice Executes the send() operation.
* @param _sendParam The parameters for the send operation.
* @param _fee The fee information supplied by the caller.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess funds from fees etc. on the src.
* @return receipt The LayerZero messaging receipt from the send() operation.
* @return oftReceipt The OFT receipt information.
*
* @dev MessagingReceipt: LayerZero msg receipt
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function send(
SendParam calldata _sendParam,
MessagingFee calldata _fee,
address _refundAddress
) external payable returns (MessagingReceipt memory, OFTReceipt memory);
}
"
},
"contracts/lib/OCCManager.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// project imports
import {LedgerAccessControl} from "./LedgerAccessControl.sol";
import {OCCAdapterDatalayout} from "./dataLayout/OCCAdapterDatalayout.sol";
import {OCCVaultMessage, EvmVaultMessage, OCCLedgerMessage} from "./types/OCCTypes.sol";
// oz imports
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// lz imports
import {OApp, MessagingFee, Origin} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/OApp.sol";
import {MessagingReceipt} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/OAppSender.sol";
import {OptionsBuilder} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/libs/OptionsBuilder.sol";
import {IOFT, SendParam, OFTReceipt} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oft/interfaces/IOFT.sol";
import {IOAppComposer} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/interfaces/IOAppComposer.sol";
import {OFTComposeMsgCodec} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oft/libs/OFTComposeMsgCodec.sol";
/**
* @title VaultOCCManager for handle OCC message between vault and ledger
* @dev This contract is used to send OCC message from vault to ledger
*/
abstract contract VaultOCCManager is LedgerAccessControl, OCCAdapterDatalayout {
using OptionsBuilder for bytes;
using SafeERC20 for IERC20;
/// @dev chain id of the ledger chain
uint256 public ledgerChainId;
/// @dev the address of the ledger
address public ledgerAddr;
/// @dev usdc address
address public usdcAddr;
/// @dev event id tracker
uint256 public chainedEventId;
/// @dev additional fee for backward message mapping
mapping(uint8 => uint256) public payloadType2BackwardFee;
/**
* @notice set the ledger chain id and ledger address
* @param _ledgerChainId the ledger chain id
* @param _ledgerAddr the ledger address
*/
function setLedgerInfo(uint256 _ledgerChainId, address _ledgerAddr) external onlyRole(DEFAULT_ADMIN_ROLE) {
ledgerChainId = _ledgerChainId;
ledgerAddr = _ledgerAddr;
}
/**
* @notice construct OCCVaultMessage for send through Layerzero
* @param message The message to be sent.
*/
function buildOCCVaultMsg(EvmVaultMessage memory message) internal view returns (SendParam memory sendParam) {
/// set the source chain id
message.srcChainId = myChainId;
/// build options
uint8 _payloadType = message.payloadType;
uint128 _dstGas = payloadType2DstGas[_payloadType];
if (_dstGas == 0) {
_dstGas = 2000000;
}
uint128 _oftGas = defaultOftGas;
if (_oftGas == 0) {
_oftGas = 2000000;
}
bytes memory options = OptionsBuilder.newOptions().addExecutorLzReceiveOption(_oftGas, 0).addExecutorLzComposeOption(0, _dstGas, 0);
OCCVaultMessage memory occVaultMsg = OCCVaultMessage({
chainedEventId: chainedEventId,
srcChainId: message.srcChainId,
token: message.token,
tokenAmount: message.tokenAmount,
sender: OFTComposeMsgCodec.addressToBytes32(message.sender),
payloadType: message.payloadType,
payload: message.payload
});
sendParam = SendParam({
dstEid: chainId2Eid[ledgerChainId],
to: bytes32(uint256(uint160(ledgerAddr))),
amountLD: message.tokenAmount,
minAmountLD: message.tokenAmount,
extraOptions: options,
composeMsg: abi.encode(occVaultMsg),
oftCmd: bytes("")
});
}
/**
* @notice Sends a message from vault to ledger chain
* @param message The message being sent.
*/
function vaultSendToLedger(EvmVaultMessage memory message) internal {
if (message.tokenAmount > 0) {
address erc20TokenAddr = IOFT(orderTokenOft).token();
IERC20(erc20TokenAddr).safeTransferFrom(message.sender, address(this), message.tokenAmount);
if (IOFT(orderTokenOft).approvalRequired()) {
IERC20(erc20TokenAddr).approve(address(orderTokenOft), message.tokenAmount);
}
}
SendParam memory sendParam = buildOCCVaultMsg(message);
/// @dev test only
_msgPayload = sendParam.composeMsg;
_options = sendParam.extraOptions;
uint256 lzFee = msg.value - payloadType2BackwardFee[message.payloadType];
MessagingFee memory msgFee = MessagingFee(lzFee, 0);
(_msgReceipt, _oftReceipt) = IOFT(orderTokenOft).send{value: lzFee}(sendParam, msgFee, msg.sender);
chainedEventId += 1;
}
/**
* @notice estimate the Layerzero fee for sending a message from vault to ledger chain in native token
* @param message The message being sent.
*/
function estimateCCFeeFromVaultToLedger(EvmVaultMessage memory message) internal view returns (uint256) {
SendParam memory sendParam = buildOCCVaultMsg(message);
uint256 lzFee = IOFT(orderTokenOft).quoteSend(sendParam, false).nativeFee;
uint256 backwardFee = payloadType2BackwardFee[message.payloadType];
return lzFee + backwardFee;
}
/**
* @notice set payload type to backward fee
* @param payloadType the payload type
* @param backwardFee the backward fee
*/
function setPayloadType2BackwardFee(uint8 payloadType, uint256 backwardFee) external onlyRole(DEFAULT_ADMIN_ROLE) {
payloadType2BackwardFee[payloadType] = backwardFee;
}
// gap for upgradeable
uint256[48] private __gap;
}
"
},
"contracts/lib/types/OCCTypes.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
/// @dev The token types that can be transferred
enum LedgerToken {
ORDER,
ESORDER,
USDC,
PLACEHOLDER
}
struct EvmVaultMessage {
/// @dev the event id for the message, different id for different chains
uint256 chainedEventId;
/// @dev the source chain id, the sender can omit this field
uint256 srcChainId;
/// @dev the symbol of the token
LedgerToken token;
/// @dev the amount of token
uint256 tokenAmount;
/// @dev the address of the sender
address sender;
/// @dev payloadType is the type of the payload
uint8 payloadType;
/// @dev payload is the data to be sent
bytes payload;
}
struct EvmLedgerMessage {
/// @dev the destination chain id
uint256 dstChainId;
/// @dev the symbol of the token
LedgerToken token;
/// @dev the amount of token
uint256 tokenAmount;
/// @dev the address of the receiver
address receiver;
/// @dev payloadType is the type of the payload
uint8 payloadType;
/// @dev payload is the data to be sent
bytes payload;
}
struct OCCVaultMessage {
/// @dev the event id for the message, different id for different chains
uint256 chainedEventId;
/// @dev the source chain id, the sender can omit this field
uint256 srcChainId;
/// @dev the symbol of the token
LedgerToken token;
/// @dev the amount of token
uint256 tokenAmount;
/// @dev the address of the sender
bytes32 sender;
/// @dev payloadType is the type of the payload
uint8 payloadType;
/// @dev payload is the data to be sent
bytes payload;
}
struct OCCLedgerMessage {
/// @dev the destination chain id
uint256 dstChainId;
/// @dev the symbol of the token
LedgerToken token;
/// @dev the amount of token
uint256 tokenAmount;
/// @dev the address of the receiver
bytes32 receiver;
/// @dev payloadType is the type of the payload
uint8 payloadType;
/// @dev payload is the data to be sent
bytes payload;
}
"
},
"contracts/lib/types/LedgerTypes.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
import {LedgerToken} from "./OCCTypes.sol";
enum PayloadDataType {
/* ====== Payloads From vault side ====== */
ClaimReward, // 0
Stake, // 1
CreateOrderUnstakeRequest, // 2
CancelOrderUnstakeRequest, // 3
WithdrawOrder, // 4
EsOrderUnstakeAndVest, // 5
CancelVestingRequest, // 6
CancelAllVestingRequests, // 7 Not supported anymore. Do not remove for backward compatibility
ClaimVestingRequest, // 8
RedeemValor, // 9
ClaimUsdcRevenue, // 10
/* ====== Backward Payloads from ledger side ====== */
ClaimRewardBackward, // 11
WithdrawOrderBackward, // 12
ClaimVestingRequestBackward, // 13
ClaimUsdcRevenueBackward, // 14
/* ====== New Payloads ====== */
UnstakeOrderNow, // 15
ClaimRewardSolana, // 16
RedeemValor2, // 17
ClaimEsOrderRevenue // 18
}
// Suppose that in the OCCVaultMessage, the sender and chainId can be used to get the chainId and user address for all the calls
// For deposited calls like Stake, LedgerToken and amount should be filled in the OCCVaultMessage
// For calls where only the user address and chainId are needed no additional structure payload needed.
// Calls without payload: Stake, WithdrawOrder, ClaimUsdcRevenue, ClaimEsOrderRevenue
library LedgerPayloadTypes {
struct ClaimReward {
uint32 distributionId;
uint256 cumulativeAmount;
bytes32[] merkleProof;
}
struct ClaimRewardSolana {
uint32 distributionId;
uint256 cumulativeAmount;
bytes32 merkleRoot;
}
struct CreateOrderUnstakeRequest {
uint256 amount;
}
struct EsOrderUnstakeAndVest {
uint256 amount;
}
struct CancelVestingRequest {
uint256 requestId;
}
struct ClaimVestingRequest {
uint256 requestId;
}
struct RedeemValor {
uint256 amount;
}
struct UnstakeOrderNow {
uint256 amount;
}
struct RedeemValor2 {
uint256 amount;
}
}
library LedgerSignedTypes {
struct UintValueData {
bytes32 r;
bytes32 s;
uint8 v;
uint256 value;
uint64 timestamp; // timestamp in milliseconds
}
}
"
},
"node_modules/@openzeppelin/contracts/interfaces/draft-IERC1822.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: 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.
*/
function proxiableUUID() external view returns (bytes32);
}
"
},
"node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev 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.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev 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.
*
* CAUTION: 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.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
"
},
"node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issueco
Submitted on: 2025-11-01 17:56:14
Comments
Log in to comment.
No comments yet.