Source Code
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
Advanced mode: Intended for advanced users or developers and will display all Internal Transactions including zero value transfers.
Latest 25 internal transactions (View All)
Advanced mode:
| Parent Transaction Hash | Block | From | To | ||||
|---|---|---|---|---|---|---|---|
| 26838425 | 102 days ago | 0 FRAX | |||||
| 26773107 | 104 days ago | 0 FRAX | |||||
| 26752640 | 104 days ago | 0 FRAX | |||||
| 23892587 | 170 days ago | 0 FRAX | |||||
| 23608918 | 177 days ago | 0 FRAX | |||||
| 23542405 | 179 days ago | 0 FRAX | |||||
| 23372712 | 182 days ago | 0 FRAX | |||||
| 23327800 | 184 days ago | 0 FRAX | |||||
| 23286739 | 184 days ago | 0 FRAX | |||||
| 23261585 | 185 days ago | 0 FRAX | |||||
| 23261488 | 185 days ago | 0 FRAX | |||||
| 23244414 | 185 days ago | 0 FRAX | |||||
| 23244319 | 185 days ago | 0 FRAX | |||||
| 23243967 | 185 days ago | 0 FRAX | |||||
| 23217654 | 186 days ago | 0 FRAX | |||||
| 23217257 | 186 days ago | 0 FRAX | |||||
| 23098846 | 189 days ago | 0 FRAX | |||||
| 22896375 | 194 days ago | 0 FRAX | |||||
| 22690920 | 198 days ago | 0 FRAX | |||||
| 22362158 | 206 days ago | 0 FRAX | |||||
| 22246791 | 209 days ago | 0 FRAX | |||||
| 22185758 | 210 days ago | 0 FRAX | |||||
| 21708624 | 221 days ago | 0 FRAX | |||||
| 21620579 | 223 days ago | 0 FRAX | |||||
| 21454820 | 227 days ago | 0 FRAX |
Cross-Chain Transactions
Loading...
Loading
Contract Name:
InceptionRatioFeed
Compiler Version
v0.8.20+commit.a1b79de6
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "../interfaces/IInceptionRatioFeed.sol";
/// @author The InceptionLRT team
/// @title InceptionRatioFeed Contract
/// @notice Holds the up-to-date ratios for the bridged LRTs.
contract InceptionRatioFeed is
OwnableUpgradeable,
PausableUpgradeable,
IInceptionRatioFeed,
IInceptionRatioFeedErrors
{
struct HistoricalRatios {
uint64[9] historicalRatios;
uint40 lastUpdate;
}
/// @dev 100000000
uint32 public constant MAX_THRESHOLD = uint32(1e8);
address public inceptionOperator;
mapping(address => uint256) private _ratios;
mapping(address => HistoricalRatios) public historicalRatios;
/// @dev use this instead of HistoricalRatios.lastUpdate to check for 12hr ratio update timeout
mapping(address => uint256) private _ratioUpdates;
/// @dev diff between the current ratio and a new one in %(0.000001 ... 100%)
uint256 public ratioThreshold;
modifier onlyOperator() {
if (msg.sender != owner() && msg.sender != inceptionOperator)
revert OperatorUnauthorizedAccount(msg.sender);
_;
}
function initialize(address operator) external initializer {
__Ownable_init(msg.sender);
__Pausable_init();
inceptionOperator = operator;
emit OperatorUpdated(address(0), operator);
}
function updateRatioBatch(
address[] calldata addresses,
uint256[] calldata ratios
) external override whenNotPaused onlyOperator {
if (ratioThreshold == 0) revert RatioThresholdNotSet();
uint256 numOfRatios = addresses.length;
if (numOfRatios != ratios.length) revert InconsistentInputData();
for (uint256 i = 0; i < numOfRatios; ) {
address tokenAddr = addresses[i];
uint256 lastUpdate = _ratioUpdates[tokenAddr];
uint256 oldRatio = _ratios[tokenAddr];
uint256 newRatio = ratios[i];
(bool valid, string memory reason) = _checkRatioRules(
lastUpdate,
newRatio,
oldRatio
);
if (!valid) {
emit RatioNotUpdated(tokenAddr, newRatio, reason);
unchecked {
++i;
}
continue;
}
_ratios[tokenAddr] = newRatio;
emit RatioUpdated(tokenAddr, oldRatio, newRatio);
_ratioUpdates[tokenAddr] = uint40(block.timestamp);
// let's compare with the new ratio
HistoricalRatios storage hisRatio = historicalRatios[tokenAddr];
if (block.timestamp - hisRatio.lastUpdate > 1 days - 1 minutes) {
uint64 latestOffset = hisRatio.historicalRatios[0];
hisRatio.historicalRatios[
((latestOffset + 1) % 8) + 1
] = uint64(newRatio);
hisRatio.historicalRatios[0] = latestOffset + 1;
hisRatio.lastUpdate = uint40(block.timestamp);
}
unchecked {
++i;
}
}
}
function _checkRatioRules(
uint256 lastUpdated,
uint256 newRatio,
uint256 oldRatio
) internal view returns (bool valid, string memory reason) {
// initialization of the first ratio -> skip checks
if (oldRatio == 0) return (valid = true, reason);
if (block.timestamp - lastUpdated < 12 hours)
return (valid, reason = "update time range exceeds");
// new ratio should be not greater than a previous one
if (newRatio > oldRatio)
return (valid, reason = "new ratio is greater than old");
// new ratio should be in the range (oldRatio - threshold , oldRatio]
uint256 threshold = (oldRatio * ratioThreshold) / MAX_THRESHOLD;
if (newRatio < oldRatio - threshold)
return (valid, reason = "new ratio too low");
return (valid = true, reason);
}
function averagePercentageRate(
address token,
uint256 day
) external view returns (uint256) {
if (token == address(0)) revert NullParams();
if (day == 0 || day > 7) revert IncorrectDay(day);
HistoricalRatios storage hisRatio = historicalRatios[token];
uint64 latestOffset = hisRatio.historicalRatios[0];
if (latestOffset == 0) revert IncorrectToken(token);
if (latestOffset < day) revert IncorrectDay(day);
uint256 oldestRatio = hisRatio.historicalRatios[
((latestOffset - day) % 8) + 1
];
uint256 newestRatio = hisRatio.historicalRatios[
((latestOffset) % 8) + 1
];
if (oldestRatio <= newestRatio) {
return 0;
}
return
((oldestRatio - newestRatio) * 10 ** 20 * 365) /
(newestRatio * (day));
}
function getRatioFor(
address token
) external view override returns (uint256) {
return _ratios[token];
}
function repairRatioFor(address token, uint256 ratio) external onlyOwner {
if (token == address(0) || ratio == 0) revert NullParams();
uint256 oldRatio = _ratios[token];
_ratios[token] = ratio;
emit RatioUpdated(token, oldRatio, ratio);
}
function setRatioThreshold(uint256 newValue) external onlyOwner {
if (newValue >= MAX_THRESHOLD || newValue == 0)
revert NewRatioThresholdInvalid();
emit RatioThresholdChanged(ratioThreshold, newValue);
ratioThreshold = newValue;
}
function setInceptionOperator(address newOperator) external onlyOwner {
if (newOperator == address(0)) revert NullParams();
emit OperatorUpdated(inceptionOperator, newOperator);
inceptionOperator = newOperator;
}
/*///////////////////////////////
////// Pausable functions //////
/////////////////////////////*/
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// 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
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*
* _Available since v4.8.3._
*/
interface IERC1967 {
/**
* @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);
}// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../token/ERC20/extensions/IERC20Metadata.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.0;
import "../Proxy.sol";
import "./ERC1967Upgrade.sol";
/**
* @dev 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
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializing the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/IERC1967.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*/
abstract contract ERC1967Upgrade is IERC1967 {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @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 {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*/
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 {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {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 bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
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 {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev 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.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overridden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.3) (proxy/transparent/ProxyAdmin.sol)
pragma solidity ^0.8.0;
import "./TransparentUpgradeableProxy.sol";
import "../../access/Ownable.sol";
/**
* @dev 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}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(ITransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(ITransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(
ITransparentUpgradeableProxy proxy,
address implementation,
bytes memory data
) public payable virtual onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967Proxy.sol";
/**
* @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
* does not implement this interface directly, and some of its functions are implemented by an internal dispatch
* mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
* include them in the ABI so this interface must be used to interact with it.
*/
interface ITransparentUpgradeableProxy is IERC1967 {
function admin() external view returns (address);
function implementation() external view returns (address);
function changeAdmin(address) external;
function upgradeTo(address) external;
function upgradeToAndCall(address, bytes memory) external payable;
}
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, 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.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*
* NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
* inherit from that interface, and instead the admin functions are 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.
*
* WARNING: 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 admin operations inaccessible, which could prevent upgradeability. Transparency may also be compromised.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
_changeAdmin(admin_);
}
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*
* CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the
* implementation provides a function with the same selector.
*/
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
/**
* @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior
*/
function _fallback() internal virtual override {
if (msg.sender == _getAdmin()) {
bytes memory ret;
bytes4 selector = msg.sig;
if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) {
ret = _dispatchUpgradeTo();
} else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
ret = _dispatchUpgradeToAndCall();
} else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) {
ret = _dispatchChangeAdmin();
} else if (selector == ITransparentUpgradeableProxy.admin.selector) {
ret = _dispatchAdmin();
} else if (selector == ITransparentUpgradeableProxy.implementation.selector) {
ret = _dispatchImplementation();
} else {
revert("TransparentUpgradeableProxy: admin cannot fallback to proxy target");
}
assembly {
return(add(ret, 0x20), mload(ret))
}
} else {
super._fallback();
}
}
/**
* @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 _dispatchAdmin() private returns (bytes memory) {
_requireZeroValue();
address admin = _getAdmin();
return abi.encode(admin);
}
/**
* @dev Returns the current implementation.
*
* 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.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _dispatchImplementation() private returns (bytes memory) {
_requireZeroValue();
address implementation = _implementation();
return abi.encode(implementation);
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _dispatchChangeAdmin() private returns (bytes memory) {
_requireZeroValue();
address newAdmin = abi.decode(msg.data[4:], (address));
_changeAdmin(newAdmin);
return "";
}
/**
* @dev Upgrade the implementation of the proxy.
*/
function _dispatchUpgradeTo() private returns (bytes memory) {
_requireZeroValue();
address newImplementation = abi.decode(msg.data[4:], (address));
_upgradeToAndCall(newImplementation, bytes(""), false);
return "";
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*/
function _dispatchUpgradeToAndCall() private returns (bytes memory) {
(address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
_upgradeToAndCall(newImplementation, data, true);
return "";
}
/**
* @dev Returns the current admin.
*
* CAUTION: This function is deprecated. Use {ERC1967Upgrade-_getAdmin} instead.
*/
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
/**
* @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to
* emulate some proxy functions being non-payable while still allowing value to pass through.
*/
function _requireZeroValue() private {
require(msg.value == 0);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../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 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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.isContract(address(token));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./InceptionBridgeStorage.sol";
import "../interfaces/IInceptionBridge.sol";
import "../interfaces/IXERC20Lockbox.sol";
import "../lib/EthereumVerifier.sol";
import "../lib/ProofParser.sol";
import "../lib/Utils.sol";
/// @author The InceptionLRT team
/// @title The InceptionBridge contract
/// @notice Facilitates cross-chain token(asset) transfers using the burn-mint pattern.
contract InceptionBridge is
OwnableUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
InceptionBridgeStorage,
IInceptionBridge
{
using SafeERC20 for IERC20;
/// @custom:oz-upgrades-unsafe-allow constructor
/// @dev payable modifier reduces the deployment cost
constructor() payable {
_disableInitializers();
}
function initialize(
address initialOwner,
address notary
) external initializer {
__Ownable_init(initialOwner);
__Pausable_init();
__ReentrancyGuard_init();
__initInceptionBridgeStorage(notary);
}
/*//////////////////////////////
////// Deposit functions //////
////////////////////////////*/
/**
* @dev Tokens on source and destination chains are linked with independent supplies.
* Burns tokens on source chain (to later mint it on the destination chain).
* @param fromToken is one of the many supported tokens on the current chain.
* @param destinationChain is the destination chain ID.
* @param receiver of `amount` on the destination chain.
* @param amount of tokens to be transferred
*/
function deposit(
address fromToken,
uint256 destinationChain,
address receiver,
uint256 amount
) external override nonReentrant whenNotPaused {
_beforeDeposit();
_updateDepositCaps(fromToken, amount);
if (getDestination(fromToken, destinationChain) != address(0)) {
_deposit(fromToken, destinationChain, receiver, amount);
} else revert UnknownDestinationChain();
}
function _deposit(
address fromToken,
uint256 destinationChain,
address receiver,
uint256 amount
) internal {
if (_bridgeAddressByChainId[destinationChain] == address(0)) {
revert UnknownDestinationChain();
}
address sender = msg.sender;
address lockbox = xerc20TokenRegistry[fromToken];
if (lockbox == address(0)) {
_safeBurn(fromToken, sender, amount);
} else {
_depositIntoLockbox(lockbox, fromToken, sender, amount);
}
Metadata memory metaData = Metadata(
Utils.stringToBytes32(IERC20Extra(fromToken).name()),
Utils.stringToBytes32(IERC20Extra(fromToken).symbol()),
0,
address(0)
);
unchecked {
++_globalNonce;
}
emit Deposited(
destinationChain,
_bridgeAddressByChainId[destinationChain],
sender,
receiver,
fromToken,
getDestination(fromToken, destinationChain),
amount,
_globalNonce,
metaData
);
}
function _depositIntoLockbox(
address lockbox,
address fromToken,
address sender,
uint256 amount
) internal {
address xerc20 = address(IXERC20Lockbox(lockbox).XERC20());
if (xerc20 == address(0)) revert XERC20ZeroAddress();
/// deposit into the lockBox
IERC20(fromToken).safeTransferFrom(sender, address(this), amount);
IERC20(fromToken).safeApprove(lockbox, amount);
IXERC20Lockbox(lockbox).deposit(amount);
_safeBurn(xerc20, address(this), amount);
}
/*/////////////////////////////////
////// Withdrawal functions //////
///////////////////////////////*/
/// @dev Serves the authorized (signed) withdrawal request by the bridge committee.
/// @dev Mints the corresponding token to the `Deposited.receiver` address.
/// `encodedProof` represents the RLP-encoded 'Deposited' receipt.
/// @param rawReceipt is the raw deposit transaction receipt.
/// @param proofSignature is the signature of keccak256(`encodedProof`) by the operator.
function withdraw(
/* encodedProof */ bytes calldata,
bytes calldata rawReceipt,
bytes memory proofSignature
) external override nonReentrant whenNotPaused {
uint256 proofOffset;
uint256 receiptOffset;
assembly {
proofOffset := add(0x4, calldataload(4))
receiptOffset := add(0x4, calldataload(36))
}
(
EthereumVerifier.State memory state,
EthereumVerifier.DepositType depositType
) = EthereumVerifier.parseTransactionReceipt(receiptOffset);
if (state.chainId != block.chainid)
revert ReceiptWrongChain(block.chainid, state.chainId);
ProofParser.Proof memory proof = ProofParser.parseProof(proofOffset);
if (state.contractAddress == address(0))
revert InvalidContractAddress();
if (state.destinationContract != address(this))
revert WrongDestinationBridge();
if (_bridgeAddressByChainId[proof.chainId] != state.contractAddress)
revert UnknownBridge();
state.receiptHash = keccak256(rawReceipt);
proof.status = 0x01;
proof.receiptHash = state.receiptHash;
bytes32 proofHash;
assembly {
proofHash := keccak256(proof, _PROOF_LENGTH)
}
if (ECDSA.recover(proofHash, proofSignature) != notary)
revert WrongSignature();
_withdraw(state, depositType, proof, proofHash);
}
function _withdraw(
EthereumVerifier.State memory state,
EthereumVerifier.DepositType depositType,
ProofParser.Proof memory proof,
bytes32 payload
) internal {
if (_usedProofs[payload]) {
revert WithdrawalProofUsed();
}
_usedProofs[payload] = true;
if (depositType == EthereumVerifier.DepositType.TokenDeposit) {
_withdraw(state, proof);
} else revert InvalidAssetType();
}
function _withdraw(
EthereumVerifier.State memory state,
ProofParser.Proof memory proof
) internal {
if (state.fromToken == address(0)) revert InvalidFromTokenAddress();
if (getDestination(state.toToken, proof.chainId) != state.fromToken)
revert UnknownDestination();
_updateWithdrawCaps(state.toToken, state.amount);
address lockbox = xerc20TokenRegistry[state.toToken];
if (lockbox == address(0)) {
_safeMint(state.toToken, state.receiver, state.amount);
} else {
address xerc20 = address(IXERC20Lockbox(lockbox).XERC20());
if (xerc20 == address(0)) revert XERC20ZeroAddress();
_safeMint(xerc20, address(this), state.amount);
IXERC20Lockbox(lockbox).withdrawTo(state.receiver, state.amount);
}
emit Withdrawn(
state.receiptHash,
state.sender,
state.receiver,
state.fromToken,
state.toToken,
state.amount
);
}
function getDestination(
address fromToken,
uint256 destinationChain
) public view returns (address) {
return
_destinationTokens[
keccak256(
abi.encodePacked(
fromToken,
block.chainid,
_bridgeAddressByChainId[destinationChain],
destinationChain
)
)
];
}
/*//////////////////////////
////// SET functions //////
////////////////////////*/
function setNotary(address notaryAddress) external onlyOwner {
_setNotary(notaryAddress);
}
function setShortCap(
address tokenAddress,
uint256 amount
) external onlyOwner {
_setShortCap(tokenAddress, amount);
}
function setShortCapDuration(uint256 duration) external onlyOwner {
_setShortCapDuration(duration);
}
function setLongCapDuration(uint256 duration) external onlyOwner {
_setLongCapDuration(duration);
}
function setLongCap(address token, uint256 amount) external onlyOwner {
_setLongCap(token, amount);
}
function addBridge(
address bridge,
uint256 destinationChain
) external onlyOwner {
_addBridge(bridge, destinationChain);
}
function removeBridge(uint256 destinationChain) external onlyOwner {
_removeBridge(destinationChain);
}
function addDestination(
address fromToken,
uint256 destinationChain,
address toToken
) external onlyOwner {
_addDestination(fromToken, destinationChain, toToken);
}
function removeDestination(
address fromToken,
uint256 destinationChain,
address toToken
) external onlyOwner {
_removeDestination(fromToken, destinationChain, toToken);
}
function setXERC20Lockbox(
address token,
address xerc20Lockbox
) external onlyOwner {
_setXERC20Lockbox(token, xerc20Lockbox);
}
/*///////////////////////////////
////// Pausable functions //////
/////////////////////////////*/
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
/*///////////////////////////////
//////// Safe functions ////////
/////////////////////////////*/
function _safeBurn(
address token,
address account,
uint256 amount
) internal {
uint256 balanceBefore = IERC20(token).balanceOf(account);
IERC20Mintable(token).burn(account, amount);
uint256 balanceAfter = IERC20(token).balanceOf(account);
if (balanceAfter + amount != balanceBefore) {
revert BurnFailed();
}
}
function _safeMint(
address token,
address account,
uint256 amount
) internal {
uint256 balanceBefore = IERC20(token).balanceOf(account);
IERC20Mintable(token).mint(account, amount);
uint256 balanceAfter = IERC20(token).balanceOf(account);
if (balanceBefore + amount != balanceAfter) {
revert MintFailed();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
pragma abicoder v2;
import "../interfaces/IInceptionBridge.sol";
import "../interfaces/IInceptionBridgeErrors.sol";
/// @author The InceptionLRT team
/// @title The InceptionBridgeStorage contract
/// @notice Stores variables for the InceptionBridge contract and facilitates their updates.
abstract contract InceptionBridgeStorage is
IInceptionBridgeStorage,
IInceptionBridgeErrors
{
uint256 internal constant _PROOF_LENGTH = 0x100;
uint256 internal _globalNonce;
address public notary;
mapping(bytes32 => bool) internal _usedProofs;
mapping(uint256 => address) internal _bridgeAddressByChainId;
/// @dev keccak256(fromToken,fromChain,_bridgeAddressByChainId(destinationChain), destinationChain) => destinationToken
mapping(bytes32 => address) internal _destinationTokens;
uint256 public shortCapDuration;
/// @dev token => Cap per 'shortCapTime'
mapping(address => uint256) public shortCaps;
/// @dev token => (epochTime/shortCapDuration) => Current Deposits
mapping(address => mapping(uint256 => uint256)) public shortCapsDeposit;
/// @dev token => (epochTime/shortCapDuration) => Current Withdraws
mapping(address => mapping(uint256 => uint256)) public shortCapsWithdraw;
uint256 public longCapDuration;
/// @dev token => cap per 'longCapTime'
mapping(address => uint256) public longCaps;
/// @dev token => (epochTime/longCapDuration) => Current Deposits
mapping(address => mapping(uint256 => uint256)) public longCapsDeposit;
/// @dev token => (epochTime/longCapDuration) => Current Withdraws
mapping(address => mapping(uint256 => uint256)) public longCapsWithdraw;
address internal _previousSender;
uint256 internal _previousDepositBlockNum;
/// token -> lockbox
mapping(address => address) public xerc20TokenRegistry;
/// @notice WARNING: Keep it up-to-date
uint256[50 - 16] private __gap;
function __initInceptionBridgeStorage(address notaryAddress) internal {
_setNotary(notaryAddress);
_setDefaultCrosschainThreshold();
}
function _beforeDeposit() internal {
if (_previousSender != address(0) && _previousDepositBlockNum != 0) {
if (
_previousSender == tx.origin &&
_previousDepositBlockNum == block.number
) {
revert MultipleDeposits();
}
}
_previousSender = tx.origin;
_previousDepositBlockNum = block.number;
}
function _updateDepositCaps(address fromToken, uint256 amount) internal {
/// Short(default: per hour)
if (
shortCapsDeposit[fromToken][getCurrentStamp(shortCapDuration)] +
amount >
shortCaps[fromToken]
) {
revert ShortCapExceeded(
shortCaps[fromToken],
shortCapsDeposit[fromToken][getCurrentStamp(shortCapDuration)] +
amount
);
}
shortCapsDeposit[fromToken][
getCurrentStamp(shortCapDuration)
] += amount;
/// Long(default: per day)
if (
longCapsDeposit[fromToken][getCurrentStamp(longCapDuration)] +
amount >
longCaps[fromToken]
) {
revert LongCapExceeded(
longCaps[fromToken],
longCapsDeposit[fromToken][getCurrentStamp(longCapDuration)] +
amount
);
}
longCapsDeposit[fromToken][getCurrentStamp(longCapDuration)] += amount;
}
function _updateWithdrawCaps(address token, uint256 amount) internal {
/// Short(default: per hour)
if (
shortCapsWithdraw[token][getCurrentStamp(shortCapDuration)] +
amount >
shortCaps[token]
) {
revert ShortCapExceeded(
shortCaps[token],
shortCapsWithdraw[token][getCurrentStamp(shortCapDuration)] +
amount
);
}
shortCapsWithdraw[token][getCurrentStamp(shortCapDuration)] += amount;
/// Long(default: per day)
if (
longCapsWithdraw[token][getCurrentStamp(longCapDuration)] + amount >
longCaps[token]
) {
revert LongCapExceeded(
longCaps[token],
longCapsWithdraw[token][getCurrentStamp(longCapDuration)] +
amount
);
}
longCapsWithdraw[token][getCurrentStamp(longCapDuration)] += amount;
}
function _setNotary(address notaryAddress) internal {
if (notaryAddress == address(0x0)) revert NullAddress();
emit NotaryChanged(notary, notaryAddress);
notary = notaryAddress;
}
/*//////////////////////////
////// SET functions //////
////////////////////////*/
function _setShortCap(address token, uint256 newValue) internal {
if (token == address(0x0)) revert NullAddress();
uint256 prevValue = shortCaps[token];
emit ShortCapChanged(token, prevValue, newValue);
shortCaps[token] = newValue;
}
function _setShortCapDuration(uint256 newValue) internal {
emit ShortCapDurationChanged(shortCapDuration, newValue);
shortCapDuration = newValue;
}
function _setLongCapDuration(uint256 newValue) internal {
emit LongCapDurationChanged(longCapDuration, newValue);
longCapDuration = newValue;
}
function _setLongCap(address token, uint256 newValue) internal {
if (token == address(0x0)) {
revert NullAddress();
}
emit LongCapChanged(token, longCaps[token], newValue);
longCaps[token] = newValue;
}
function _setDefaultCrosschainThreshold() internal {
shortCapDuration = 1 hours;
longCapDuration = 1 days;
}
function _addBridge(address bridge, uint256 destinationChain) internal {
if (bridge == address(0x0)) {
revert NullAddress();
}
if (destinationChain == 0) {
revert InvalidChain();
}
if (_bridgeAddressByChainId[destinationChain] != address(0x00)) {
revert BridgeAlreadyAdded();
}
_bridgeAddressByChainId[destinationChain] = bridge;
emit BridgeAdded(bridge, destinationChain);
}
function _removeBridge(uint256 destinationChain) internal {
if (_bridgeAddressByChainId[destinationChain] == address(0x00)) {
revert BridgeNotExist();
}
address bridge = _bridgeAddressByChainId[destinationChain];
delete _bridgeAddressByChainId[destinationChain];
emit BridgeRemoved(bridge, destinationChain);
}
function _addDestination(
address fromToken,
uint256 destinationChain,
address toToken
) internal {
if (_bridgeAddressByChainId[destinationChain] == address(0))
revert UnknownDestinationChain();
if (fromToken == address(0) || toToken == address(0))
revert NullAddress();
bytes32 direction = keccak256(
abi.encodePacked(
fromToken,
block.chainid,
_bridgeAddressByChainId[destinationChain],
destinationChain
)
);
if (_destinationTokens[direction] != address(0))
revert DestinationAlreadyExists();
_destinationTokens[direction] = toToken;
emit DestinationAdded(fromToken, toToken, destinationChain);
}
function _removeDestination(
address fromToken,
uint256 destinationChain,
address toToken
) internal {
if (_bridgeAddressByChainId[destinationChain] == address(0))
revert UnknownDestinationChain();
bytes32 direction = keccak256(
abi.encodePacked(
fromToken,
block.chainid,
_bridgeAddressByChainId[destinationChain],
destinationChain
)
);
if (_destinationTokens[direction] != toToken)
revert UnknownDestination();
delete _destinationTokens[direction];
emit DestinationRemoved(fromToken, toToken, destinationChain);
}
function _setXERC20Lockbox(address token, address lockbox) internal {
if (address(token) == address(0) || address(lockbox) == address(0))
revert NullAddress();
if (xerc20TokenRegistry[token] != address(0))
revert XERC20LockboxAlreadyAdded();
emit XERC20LockboxAdded(token, lockbox);
xerc20TokenRegistry[token] = lockbox;
}
function getCurrentStamp(uint256 duration) public view returns (uint256) {
return (block.timestamp / duration) * duration;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "solmate/src/utils/CREATE3.sol";
import "../proxy/InitializableTransparentUpgradeableProxy.sol";
import "../interfaces/IOwnable.sol";
import "../interfaces/IFactory.sol";
/// @author The InceptionLRT team
/// @title The BridgeFactory Contract
/// @notice Facilitates the deployment of contracts via CREATE2 and CREATE3
contract BridgeFactory is IFactory {
/**
*****************************************************************************
****************************** CREATE2 FACTORY ******************************
*****************************************************************************
*/
bytes32 public bridgeSalt = "InceptionLRT Factory";
function deployCreate2(
bytes calldata creationCode
) external returns (address) {
return _deployCreate2(creationCode, msg.sender);
}
function _deployCreate2(
bytes memory bytecode,
address _sender
) internal returns (address) {
address addr = _create2(bytecode, _sender);
emit ContractCreated(addr);
return addr;
}
function _create2(
bytes memory bytecode,
address _sender
) internal returns (address) {
address payable addr;
bytes32 salt = _getSalt(_sender);
assembly {
addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return addr;
}
function getDeploymentCreate2Address(
bytes memory bytecode,
address _sender
) external view returns (address) {
bytes32 salt = _getSalt(_sender);
bytes32 rawAddress = keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
salt,
keccak256(bytecode)
)
);
return address(bytes20(rawAddress << 96));
}
function _getSalt(address _sender) internal view returns (bytes32) {
return keccak256(abi.encodePacked(bridgeSalt, _sender));
}
/**
****************************************************************************
****************************** XERC20 FACTORY ******************************
****************************************************************************
*/
/**
* @notice Deploys an XERC20 contract using CREATE3
* @dev _limits and _minters must be the same length
* @param _name The name of the token
* @param _symbol The symbol of the token
* @return _xerc20 The address of the xerc20
*/
function deployXERC20(
string memory _name,
string memory _symbol
) external returns (address _xerc20) {
_xerc20 = _deployXERC20(_name, _symbol);
emit XERC20Deployed(_xerc20);
}
/**
* @notice Deploys an XERC20Lockbox contract using CREATE3
*
* @dev When deploying a lockbox for the gas token of the chain, then, the base token needs to be address(0)
* @param _xerc20 The address of the xerc20 that you want to deploy a lockbox for
* @param _baseToken The address of the base token that you want to lock
* @param _isNative Whether or not the base token is the native (gas) token of the chain. Eg: MATIC for polygon chain
* @return _lockbox The address of the lockbox
*/
function deployLockbox(
address _xerc20,
address _baseToken,
bool _isNative
) external returns (address _lockbox) {
if (
(_baseToken == address(0) && !_isNative) ||
(_isNative && _baseToken != address(0))
) revert IXERC20Factory_BadTokenAddress();
if (IOwnable(_xerc20).owner() != msg.sender)
revert IXERC20Factory_NotOwner();
_lockbox = _deployLockbox(_xerc20, _baseToken);
emit LockboxDeployed(_lockbox);
}
/**
* @notice Deploys an XERC20 contract using CREATE3
* @dev _limits and _minters must be the same length
* @param _name The name of the token
* @param _symbol The symbol of the token
* @return _xerc20 The address of the xerc20
*/
function _deployXERC20(
string memory _name,
string memory _symbol
) internal returns (address _xerc20) {
address deployer = msg.sender;
bytes32 _salt = keccak256(abi.encodePacked(_name, _symbol, deployer));
bytes memory _creation = type(InitializableTransparentUpgradeableProxy).creationCode;
bytes memory _bytecode = abi.encodePacked(
_creation
);
_xerc20 = CREATE3.deploy(_salt, _bytecode, 0);
}
/**
* @notice Deploys an XERC20Lockbox contract using CREATE3
*
* @dev When deploying a lockbox for the gas token of the chain, then, the base token needs to be address(0)
* @param _xerc20 The address of the xerc20 that you want to deploy a lockbox for
* @param _baseToken The address of the base token that you want to lock
* @return _lockbox The address of the lockbox
*/
function _deployLockbox(
address _xerc20,
address _baseToken
) internal returns (address _lockbox) {
address deployer = msg.sender;
bytes32 _salt = keccak256(
abi.encodePacked(_xerc20, _baseToken, deployer)
);
bytes memory _bytecode = abi.encodePacked(
type(InitializableTransparentUpgradeableProxy).creationCode
);
_lockbox = CREATE3.deploy(_salt, _bytecode, 0);
}
function deployCreate3(
bytes calldata creationCode,
bytes32 _salt
) external returns (address) {
return _deployCreate3(creationCode, _salt);
}
function _deployCreate3(
bytes memory bytecode,
bytes32 _salt
) internal returns (address) {
address addr = CREATE3.deploy(_salt, bytecode, 0);
emit ContractCreated(addr);
return addr;
}
function getDeploymentCreate3XERC20Address(
string memory _name,
string memory _symbol,
address _deployer
) external view returns (address _address) {
_address = CREATE3.getDeployed(keccak256(abi.encodePacked(_name, _symbol, _deployer)));
}
function getDeploymentCreate3LockboxAddress(
address _xerc20,
address _baseToken,
address _deployer
) external view returns (address _address) {
_address = CREATE3.getDeployed(keccak256(abi.encodePacked(_xerc20, _baseToken, _deployer)));
}
function getDeploymentCreate3Address(
bytes32 _salt
) external view returns (address _address) {
_address = CREATE3.getDeployed(_salt);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IERC20Mintable {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function chargeFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
interface IERC20Pegged {
function getOrigin() external view returns (uint256, address);
}
interface IERC20Extra {
function name() external returns (string memory);
function decimals() external returns (uint8);
function symbol() external returns (string memory);
}
interface IERC20MetadataChangeable {
event NameChanged(string prevValue, string newValue);
event SymbolChanged(string prevValue, string newValue);
function changeName(bytes32) external;
function changeSymbol(bytes32) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface ICREATE2Factory {
event ContractCreated(address indexed addr);
function deployCreate2(
bytes calldata creationCode
) external returns (address);
}
interface ICREATE3Factory {
/**
* @notice Emitted when a new XERC20 is deployed
* @param _xerc20 The address of the xerc20
*/
event XERC20Deployed(address _xerc20);
/**
* @notice Emitted when a new XERC20Lockbox is deployed
* @param _lockbox The address of the lockbox
*/
event LockboxDeployed(address _lockbox);
/**
* @notice Reverts when a non-owner attempts to call
*/
error IXERC20Factory_NotOwner();
/**
* @notice Reverts when a lockbox is trying to be deployed from a malicious address
*/
error IXERC20Factory_BadTokenAddress();
/**
* @notice Reverts when a lockbox is already deployed
*/
error IXERC20Factory_LockboxAlreadyDeployed();
/**
* @notice Reverts when a the length of arrays sent is incorrect
*/
error IXERC20Factory_InvalidLength();
function deployXERC20(
string memory _name,
string memory _symbol
) external returns (address _xerc20);
function deployLockbox(
address _xerc20,
address _baseToken,
bool _isNative
) external returns (address _lockbox);
}
interface IFactory is ICREATE2Factory, ICREATE3Factory {}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./IERC20.sol";
interface IInceptionBridgeStorage {
struct Metadata {
bytes32 name;
bytes32 symbol;
uint256 originChain;
address originAddress;
}
event ShortCapChanged(
address indexed token,
uint256 prevValue,
uint256 newValue
);
event LongCapChanged(
address indexed token,
uint256 prevValue,
uint256 newValue
);
event ShortCapDurationChanged(uint256 prevValue, uint256 newValue);
event LongCapDurationChanged(uint256 prevValue, uint256 newValue);
event BridgeAdded(address indexed bridge, uint256 destinationChain);
event BridgeRemoved(address indexed bridge, uint256 destinationChain);
event DestinationAdded(
address indexed fromToken,
address indexed toToken,
uint256 toChain
);
event DestinationRemoved(
address indexed fromToken,
address indexed toToken,
uint256 toChain
);
event NotaryChanged(address indexed prevValue, address indexed newValue);
event XERC20LockboxAdded(address indexed token, address indexed lockbox);
}
interface IInceptionBridge {
event Deposited(
uint256 destinationChain,
address indexed destinationBridge,
address indexed sender,
address indexed receiver,
address fromToken,
address toToken,
uint256 amount,
uint256 nonce,
IInceptionBridgeStorage.Metadata metadata
);
event Withdrawn(
bytes32 receiptHash,
address indexed sender,
address indexed receiver,
address fromToken,
address toToken,
uint256 amount
);
function deposit(
address fromToken,
uint256 destinationChain,
address receiver,
uint256 amount
) external;
function withdraw(
bytes calldata encodedProof,
bytes calldata rawReceipt,
bytes memory receiptRootSignature
) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IInceptionBridgeErrors {
/// @dev
error ShortCapExceeded(uint256 limit, uint256 current);
/// @dev
error LongCapExceeded(uint256 limit, uint256 current);
/// @dev
error BridgeAlreadyAdded();
error BridgeNotExist();
error InvalidChain();
error MultipleDeposits();
/// @dev
error ReceiptWrongChain(uint256 required, uint256 provided);
/// @dev
error InvalidContractAddress();
error NullAddress();
/// @dev
error UnknownBridge();
/// @dev
error WrongSignature();
error WithdrawalProofUsed();
error InvalidAssetType();
error InvalidFromTokenAddress();
error UnknownDestination();
error WrongDestinationBridge();
error XERC20LockboxAlreadyAdded();
error XERC20ZeroAddress();
/// @notice non-existing-bridge
error UnknownDestinationChain();
error DestinationAlreadyExists();
error BurnFailed();
error MintFailed();
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IInceptionRatioFeedErrors {
error OperatorUnauthorizedAccount(address account);
error InconsistentInputData();
error NullParams();
error RatioThresholdNotSet();
error NewRatioThresholdInvalid();
error IncorrectDay(uint256 day);
error IncorrectToken(address token);
}
interface IInceptionRatioFeed {
event OperatorUpdated(address prevValue, address newValue);
event RatioUpdated(
address indexed tokenAddress,
uint256 prevValue,
uint256 newValue
);
event RatioNotUpdated(
address indexed tokenAddress,
uint256 failedRatio,
string reason
);
event RatioThresholdChanged(uint256 prevValue, uint256 newValue);
function updateRatioBatch(
address[] calldata addresses,
uint256[] calldata ratios
) external;
function getRatioFor(address) external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IOwnable {
function owner() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @notice Rate Provider interface
interface IRateProvider {
function getRate() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IERC20Errors {
/**
* @notice Reverts when a user with too low of a limit tries to call mint/burn
*/
error IXERC20_NotHighEnoughLimits();
/**
* @notice Reverts when caller sets too small _limit
*/
error IXERC20_WrongBridgeLimit();
}
interface IXERC20 is IERC20Errors {
/**
* @notice Contains the full minting and burning data for a particular bridge
*
* @param minterParams The minting parameters for the bridge
* @param burnerParams The burning parameters for the bridge
*/
struct Bridge {
BridgeParameters minterParams;
BridgeParameters burnerParams;
}
/**
* @notice Emits when a lockbox is set
*
* @param _lockbox The address of the lockbox
*/
event LockboxSet(address _lockbox);
/**
* @notice Emits when a limit is set
*
* @param _mintingLimit The updated minting limit we are setting to the bridge
* @param _burningLimit The updated burning limit we are setting to the bridge
* @param _bridge The address of the bridge we are setting the limit too
*/
event BridgeLimitsSet(
uint256 _mintingLimit,
uint256 _burningLimit,
address indexed _bridge
);
/**
* @notice Contains the mint or burn parameters for a bridge
*
* @param timestamp The timestamp of the last mint/burn
* @param ratePerSecond The rate per second of the bridge
* @param maxLimit The max limit of the bridge
* @param currentLimit The current limit of the bridge
*/
struct BridgeParameters {
uint256 timestamp;
uint256 ratePerSecond;
uint256 maxLimit;
uint256 currentLimit;
}
/**
* @notice Sets the lockbox address
*
* @param _lockbox The address of the lockbox
*/
function setLockbox(address _lockbox) external;
/**
* @notice Updates the limits of any bridge
* @dev Can only be called by the owner
* @param _mintingLimit The updated minting limit we are setting to the bridge
* @param _burningLimit The updated burning limit we are setting to the bridge
* @param _bridge The address of the bridge we are setting the limits too
*/
function setBridgeLimits(
address _bridge,
uint256 _mintingLimit,
uint256 _burningLimit
) external;
/**
* @notice Returns the max limit of a minter
*
* @param _minter The minter we are viewing the limits of
* @return _limit The limit the minter has
*/
function mintingMaxLimitOf(
address _minter
) external view returns (uint256 _limit);
/**
* @notice Returns the max limit of a bridge
*
* @param _bridge the bridge we are viewing the limits of
* @return _limit The limit the bridge has
*/
function burningMaxLimitOf(
address _bridge
) external view returns (uint256 _limit);
/**
* @notice Returns the current limit of a minter
*
* @param _minter The minter we are viewing the limits of
* @return _limit The limit the minter has
*/
function mintingCurrentLimitOf(
address _minter
) external view returns (uint256 _limit);
/**
* @notice Returns the current limit of a bridge
*
* @param _bridge the bridge we are viewing the limits of
* @return _limit The limit the bridge has
*/
function burningCurrentLimitOf(
address _bridge
) external view returns (uint256 _limit);
/**
* @notice Mints tokens for a user
* @dev Can only be called by a minter
* @param _user The address of the user who needs tokens minted
* @param _amount The amount of tokens being minted
*/
function mint(address _user, uint256 _amount) external;
/**
* @notice Burns tokens for a user
* @dev Can only be called by a minter
* @param _user The address of the user who needs tokens burned
* @param _amount The amount of tokens being burned
*/
function burn(address _user, uint256 _amount) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "./IXERC20.sol";
interface IXERC20LockboxErrors {
/// @notice Reverts when a user tries to deposit native tokens on a non-native lockbox
error IXERC20Lockbox_NotNative();
/// @notice Reverts when a user tries to deposit non-native tokens on a native lockbox
error IXERC20Lockbox_Native();
/// @notice Reverts when a user tries to withdraw and the call fails
error IXERC20Lockbox_WithdrawFailed();
/// @notice Reverts when a user tries to withdraw to the XERC20Lockbox itself
error IXERC20Lockbox_WrongReceiver();
}
interface IXERC20Lockbox is IXERC20LockboxErrors {
/**
* @notice Emitted when tokens are deposited into the lockbox
*
* @param _sender The address of the user who deposited
* @param _amount The amount of tokens deposited
*/
event Deposit(address _sender, uint256 _amount);
/**
* @notice Emitted when tokens are withdrawn from the lockbox
*
* @param _sender The address of the user who withdrew
* @param _amount The amount of tokens withdrawn
*/
event Withdraw(address _sender, uint256 _amount);
function XERC20() external view returns (IXERC20 xerc20);
function ERC20() external view returns (IERC20 erc20);
/**
* @notice Deposit ERC20 tokens into the lockbox
*
* @param _amount The amount of tokens to deposit
*/
function deposit(uint256 _amount) external;
/**
* @notice Deposit ERC20 tokens into the lockbox, and send the XERC20 to a user
*
* @param _user The user to send the XERC20 to
* @param _amount The amount of tokens to deposit
*/
function depositTo(address _user, uint256 _amount) external;
/**
* @notice Deposit the native asset into the lockbox, and send the XERC20 to a user
*
* @param _user The user to send the XERC20 to
*/
function depositNativeTo(address _user) external payable;
/**
* @notice Withdraw ERC20 tokens from the lockbox
*
* @param _amount The amount of tokens to withdraw
*/
function withdraw(uint256 _amount) external;
/**
* @notice Withdraw ERC20 tokens from the lockbox
*
* @param _user The user to withdraw to
* @param _amount The amount of tokens to withdraw
*/
function withdrawTo(address _user, uint256 _amount) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library CallDataRLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
function beginIteration(
uint256 listOffset
) internal pure returns (uint256 iter) {
return listOffset + _payloadOffset(listOffset);
}
function next(uint256 iter) internal pure returns (uint256 nextIter) {
return iter + itemLength(iter);
}
function payloadLen(
uint256 ptr,
uint256 len
) internal pure returns (uint256) {
return len - _payloadOffset(ptr);
}
function receiver(uint256 ptr) internal pure returns (address) {
return address(uint160(toUint(ptr, 21)));
}
function toUint(uint256 ptr, uint256 len) internal pure returns (uint256) {
require(len > 0 && len <= 33);
uint256 offset = _payloadOffset(ptr);
uint256 numLen = len - offset;
uint256 result;
assembly {
result := calldataload(add(ptr, offset))
// cut off redundant bytes
result := shr(mul(8, sub(32, numLen)), result)
}
return result;
}
function toUintStrict(uint256 ptr) internal pure returns (uint256) {
// one byte prefix
uint256 result;
assembly {
result := calldataload(add(ptr, 1))
}
return result;
}
function rawDataPtr(uint256 ptr) internal pure returns (uint256) {
return ptr + _payloadOffset(ptr);
}
/// @return entire rlp item byte length
function itemLength(uint256 callDataPtr) internal pure returns (uint256) {
uint256 itemLen;
uint256 byte0;
assembly {
byte0 := byte(0, calldataload(callDataPtr))
}
if (byte0 < STRING_SHORT_START) itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
callDataPtr := add(callDataPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := shr(
mul(8, sub(32, byteLen)),
calldataload(callDataPtr)
)
itemLen := add(dataLen, add(byteLen, 1))
}
} else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
} else {
assembly {
let byteLen := sub(byte0, 0xf7)
callDataPtr := add(callDataPtr, 1)
let dataLen := shr(
mul(8, sub(32, byteLen)),
calldataload(callDataPtr)
)
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
/// @return number of bytes until the data
function _payloadOffset(
uint256 callDataPtr
) private pure returns (uint256) {
uint256 byte0;
assembly {
byte0 := byte(0, calldataload(callDataPtr))
}
if (byte0 < STRING_SHORT_START) return 0;
else if (
byte0 < STRING_LONG_START ||
(byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)
) return 1;
else if (byte0 < LIST_SHORT_START)
return byte0 - (STRING_LONG_START - 1) + 1;
else return byte0 - (LIST_LONG_START - 1) + 1;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./CallDataRLPReader.sol";
import "./Utils.sol";
import "../interfaces/IInceptionBridge.sol";
library EthereumVerifier {
bytes32 constant TOPIC_DEPOSITED =
keccak256(
"Deposited(uint256,address,address,address,address,address,uint256,uint256,(bytes32,bytes32,uint256,address))"
);
enum DepositType {
None,
TokenDeposit
}
struct State {
bytes32 receiptHash;
address contractAddress;
address destinationContract;
uint256 chainId;
address sender;
address receiver;
address fromToken;
address toToken;
uint256 amount;
uint256 nonce;
// metadata fields (we can't use Metadata struct here because of Solidity struct memory layout)
bytes32 symbol;
bytes32 name;
uint256 originChain;
address originToken;
}
function getMetadata(
State memory state
) internal pure returns (IInceptionBridgeStorage.Metadata memory) {
IInceptionBridgeStorage.Metadata memory metadata;
assembly {
metadata := add(state, 0x120)
}
return metadata;
}
function parseTransactionReceipt(
uint256 receiptOffset
) internal pure returns (State memory state, DepositType depositType) {
uint256 iter = CallDataRLPReader.beginIteration(receiptOffset + 0x20);
{
/* postStateOrStatus - we must ensure that tx is not reverted */
uint256 statusOffset = iter;
iter = CallDataRLPReader.next(iter);
require(
CallDataRLPReader.payloadLen(
statusOffset,
iter - statusOffset
) == 1,
"EthereumVerifier: tx is reverted"
);
}
/* skip cumulativeGasUsed */
iter = CallDataRLPReader.next(iter);
/* logs - we need to find our logs */
uint256 logs = iter;
iter = CallDataRLPReader.next(iter);
uint256 logsIter = CallDataRLPReader.beginIteration(logs);
for (; logsIter < iter; ) {
uint256 log = logsIter;
logsIter = CallDataRLPReader.next(logsIter);
/* make sure there is only one peg-in event in logs */
DepositType logType = _decodeReceiptLogs(state, log);
if (logType != DepositType.None) {
require(
depositType == DepositType.None,
"EthereumVerifier: multiple logs"
);
depositType = logType;
}
}
/* don't allow to process if peg-in type is unknown */
require(
depositType != DepositType.None,
"EthereumVerifier: missing logs"
);
return (state, depositType);
}
function _decodeReceiptLogs(
State memory state,
uint256 log
) internal pure returns (DepositType depositType) {
uint256 logIter = CallDataRLPReader.beginIteration(log);
address contractAddress;
{
/* parse smart contract address */
uint256 addressOffset = logIter;
logIter = CallDataRLPReader.next(logIter);
contractAddress = CallDataRLPReader.receiver(addressOffset);
}
/* topics */
bytes32 mainTopic;
address destinationContract;
address sender;
address receiver;
{
uint256 topicsIter = logIter;
logIter = CallDataRLPReader.next(logIter);
// Must be 4 topics RLP encoded: event signature, destinationContract, sender, receiver
// Each topic RLP encoded is 33 bytes (0xa0[32 bytes data])
// Total payload: 132 bytes. Since it's list with total size bigger than 55 bytes we need 2 bytes prefix (0xf863)
// So total size of RLP encoded topics array must be 134
if (CallDataRLPReader.itemLength(topicsIter) != 134) {
return DepositType.None;
}
topicsIter = CallDataRLPReader.beginIteration(topicsIter);
mainTopic = bytes32(CallDataRLPReader.toUintStrict(topicsIter));
topicsIter = CallDataRLPReader.next(topicsIter);
destinationContract = address(
bytes20(uint160(CallDataRLPReader.toUintStrict(topicsIter)))
);
topicsIter = CallDataRLPReader.next(topicsIter);
sender = address(
bytes20(uint160(CallDataRLPReader.toUintStrict(topicsIter)))
);
topicsIter = CallDataRLPReader.next(topicsIter);
receiver = address(
bytes20(uint160(CallDataRLPReader.toUintStrict(topicsIter)))
);
topicsIter = CallDataRLPReader.next(topicsIter);
require(topicsIter == logIter); // safety check that iteration is finished
}
uint256 ptr = CallDataRLPReader.rawDataPtr(logIter);
logIter = CallDataRLPReader.next(logIter);
uint256 len = logIter - ptr;
{
// parse logs based on topic type and check that event data has correct length
uint256 expectedLen;
if (mainTopic == TOPIC_DEPOSITED) {
expectedLen = 0x120;
depositType = DepositType.TokenDeposit;
} else {
return DepositType.None;
}
if (len != expectedLen) {
return DepositType.None;
}
}
{
// read chain id separately and verify that contract that emitted event is relevant
uint256 chainId;
assembly {
chainId := calldataload(ptr)
}
// if (chainId != Utils.currentChain()) return DepositType.None;
// All checks are passed after this point, no errors allowed and we can modify state
state.chainId = chainId;
ptr += 0x20;
len -= 0x20;
}
{
uint256 structOffset;
assembly {
// skip 6 fields: receiptHash, destinationContract, contractAddress, chainId, sender, receiver
structOffset := add(state, 0xc0)
calldatacopy(structOffset, ptr, len)
}
}
state.destinationContract = destinationContract;
state.contractAddress = contractAddress;
state.sender = sender;
state.receiver = receiver;
return depositType;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./CallDataRLPReader.sol";
import "./Utils.sol";
library ProofParser {
// Proof is message format signed by the protocol. It contains somewhat redundant information, so only part
// of the proof could be passed into the contract and other part can be inferred from transaction receipt
struct Proof {
uint256 chainId;
uint256 status;
bytes32 transactionHash;
uint256 blockNumber;
bytes32 blockHash;
uint256 transactionIndex;
bytes32 receiptHash;
uint256 transferAmount;
}
function parseProof(
uint256 proofOffset
) internal pure returns (Proof memory) {
Proof memory proof;
uint256 dataOffset = proofOffset + 0x20;
assembly {
calldatacopy(proof, dataOffset, 0x20) // 1 field (chainId)
dataOffset := add(dataOffset, 0x40)
calldatacopy(add(proof, 0x40), dataOffset, 0x80) // 4 fields * 0x20 = 0x80
dataOffset := add(dataOffset, 0xa0)
calldatacopy(add(proof, 0xe0), dataOffset, 0x20) // transferAmount
}
return proof;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library Utils {
function currentChain() internal view returns (uint256) {
uint256 chain;
assembly {
chain := chainid()
}
return chain;
}
function stringToBytes32(
string memory source
) internal pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function saturatingMultiply(
uint256 a,
uint256 b
) internal pure returns (uint256) {
unchecked {
if (a == 0) return 0;
uint256 c = a * b;
if (c / a != b) return type(uint256).max;
return c;
}
}
function saturatingAdd(
uint256 a,
uint256 b
) internal pure returns (uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return type(uint256).max;
return c;
}
}
// Preconditions:
// 1. a may be arbitrary (up to 2 ** 256 - 1)
// 2. b * c < 2 ** 256
// Returned value: min(floor((a * b) / c), 2 ** 256 - 1)
function multiplyAndDivideFloor(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (uint256) {
return
saturatingAdd(
saturatingMultiply(a / c, b),
((a % c) * b) / c // can't fail because of assumption 2.
);
}
// Preconditions:
// 1. a may be arbitrary (up to 2 ** 256 - 1)
// 2. b * c < 2 ** 256
// Returned value: min(ceil((a * b) / c), 2 ** 256 - 1)
function multiplyAndDivideCeil(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (uint256) {
return
saturatingAdd(
saturatingMultiply(a / c, b),
((a % c) * b + (c - 1)) / c // can't fail because of assumption 2.
);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/proxy/Proxy.sol";
import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol";
/// @dev The original OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol), but
/// constructor() was removed
contract InitializableERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Returns the current implementation address.
*/
function _implementation()
internal
view
virtual
override
returns (address impl)
{
return ERC1967Upgrade._getImplementation();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";
import "./InitializableERC1967Proxy.sol";
contract InceptionProxyAdmin is ProxyAdmin {}
/// @dev The original OpenZeppelin Contracts (last updated v4.9.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
/// with replacement constructor by initializer
contract InitializableTransparentUpgradeableProxy is InitializableERC1967Proxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param admin_ Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract
*/
function initialize(
address _logic,
address admin_,
bytes memory _data
) external payable {
require(
_implementation() == address(0),
"implementation has already been set"
);
_upgradeToAndCall(_logic, _data, false);
_changeAdmin(admin_);
}
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*
* CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the
* implementation provides a function with the same selector.
*/
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
/**
* @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior
*/
function _fallback() internal virtual override {
if (msg.sender == _getAdmin()) {
bytes memory ret;
bytes4 selector = msg.sig;
if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) {
ret = _dispatchUpgradeTo();
} else if (
selector ==
ITransparentUpgradeableProxy.upgradeToAndCall.selector
) {
ret = _dispatchUpgradeToAndCall();
} else if (
selector == ITransparentUpgradeableProxy.changeAdmin.selector
) {
ret = _dispatchChangeAdmin();
} else if (
selector == ITransparentUpgradeableProxy.admin.selector
) {
ret = _dispatchAdmin();
} else if (
selector == ITransparentUpgradeableProxy.implementation.selector
) {
ret = _dispatchImplementation();
} else {
revert(
"TransparentUpgradeableProxy: admin cannot fallback to proxy target"
);
}
assembly {
return(add(ret, 0x20), mload(ret))
}
} else {
super._fallback();
}
}
/**
* @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 _dispatchAdmin() private returns (bytes memory) {
_requireZeroValue();
address admin = _getAdmin();
return abi.encode(admin);
}
/**
* @dev Returns the current implementation.
*
* 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.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _dispatchImplementation() private returns (bytes memory) {
_requireZeroValue();
address implementation = _implementation();
return abi.encode(implementation);
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _dispatchChangeAdmin() private returns (bytes memory) {
_requireZeroValue();
address newAdmin = abi.decode(msg.data[4:], (address));
_changeAdmin(newAdmin);
return "";
}
/**
* @dev Upgrade the implementation of the proxy.
*/
function _dispatchUpgradeTo() private returns (bytes memory) {
_requireZeroValue();
address newImplementation = abi.decode(msg.data[4:], (address));
_upgradeToAndCall(newImplementation, bytes(""), false);
return "";
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*/
function _dispatchUpgradeToAndCall() private returns (bytes memory) {
(address newImplementation, bytes memory data) = abi.decode(
msg.data[4:],
(address, bytes)
);
_upgradeToAndCall(newImplementation, data, true);
return "";
}
/**
* @dev Returns the current admin.
*
* CAUTION: This function is deprecated. Use {ERC1967Upgrade-_getAdmin} instead.
*/
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
/**
* @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to
* emulate some proxy functions being non-payable while still allowing value to pass through.
*/
function _requireZeroValue() private {
require(msg.value == 0, "zero value is required");
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "../interfaces/IRateProvider.sol";
import "../interfaces/IInceptionRatioFeed.sol";
/// @author The InceptionLRT team
/// @title The InceptionRateProvider contract
/// @notice Inheritable standard rate provider interface.
abstract contract InceptionRateProvider is IRateProvider {
using SafeMath for uint256;
IInceptionRatioFeed public ratioFeed;
address internal _asset;
constructor(address ratioFeedAddress, address assetAddress) payable {
ratioFeed = IInceptionRatioFeed(ratioFeedAddress);
_asset = assetAddress;
}
function getRate() external view override returns (uint256) {
return
safeFloorMultiplyAndDivide(
1e18,
1e18,
ratioFeed.getRatioFor(_asset)
);
}
function safeFloorMultiplyAndDivide(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (uint256) {
uint256 remainder = a.mod(c);
uint256 result = a.div(c);
bool safe;
(safe, result) = result.tryMul(b);
if (!safe) {
return
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
(safe, result) = result.tryAdd(remainder.mul(b).div(c));
if (!safe) {
return
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
return result;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../InceptionRateProvider.sol";
/// @author The InceptionLRT team
/// @title The InETHRateProvider contract
/// @notice The InceptionRateProvider is used to build a rate provider for inETH LRT.
contract InETHRateProvider is InceptionRateProvider {
constructor(
address ratioFeedAddress,
address assetAddress
) payable InceptionRateProvider(ratioFeedAddress, assetAddress) {}
function inETH() external view returns (address) {
return _asset;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../InceptionRateProvider.sol";
/// @author The InceptionLRT team
/// @title The InstETHRateProvider contract
/// @notice The InceptionRateProvider is used to build a rate provider for instETH LRT.
contract InstETHRateProvider is InceptionRateProvider {
constructor(
address ratioFeedAddress,
address assetAddress
) payable InceptionRateProvider(ratioFeedAddress, assetAddress) {}
function instETH() external view returns (address) {
return _asset;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";
contract ERC20Mintable is ERC20 {
constructor(
string memory name_,
string memory symbol_
) payable ERC20(name_, symbol_) {}
function mint(address usr, uint wad) external {
_mint(usr, wad);
}
function burn(address usr, uint wad) external {
_burn(usr, wad);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "../interfaces/IInceptionBridge.sol";
contract MultipleDepositor {
IInceptionBridge internal _bridge;
constructor(IInceptionBridge bridge) {
_bridge = bridge;
}
function deposit(
address fromToken,
uint256 destinationChain,
address receiver,
uint256 amount,
uint256 numOfDeposits
) external {
IERC20(fromToken).transferFrom(
msg.sender,
address(this),
numOfDeposits * amount
);
IERC20(fromToken).approve(address(_bridge), numOfDeposits * amount);
for (uint256 i = 0; i < numOfDeposits; i++) {
_bridge.deposit(fromToken, destinationChain, receiver, amount);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {ERC20Upgradeable} from "openzeppelin-4-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "openzeppelin-4-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol";
import "openzeppelin-4-upgradeable/access/OwnableUpgradeable.sol";
import "openzeppelin-4-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IXERC20.sol";
contract XERC20 is
Initializable,
ERC20Upgradeable,
OwnableUpgradeable,
ERC20PermitUpgradeable,
IXERC20
{
/**
* @notice The duration it takes for the limits to fully replenish
*/
uint256 private constant _DURATION = 1 days;
/**
* @notice The address of the factory which deployed this contract
*/
address public FACTORY;
/**
* @notice The address of the lockbox contract
*/
address public lockbox;
/**
* @notice Maps bridge address to bridge configurations
*/
mapping(address => Bridge) public bridges;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() payable {
//_do();
}
/**
* @param _name The name of the token
* @param _symbol The symbol of the token
* @param _factory The factory which deployed this contract
*/
function initialize(
string memory _name,
string memory _symbol,
address _factory
) external initializer {
__ERC20_init(_name, _symbol);
__Ownable_init();
__ERC20Permit_init(_name);
FACTORY = _factory;
}
/**
* @notice Mints tokens for a user
* @dev Can only be called by a bridge
* @param _user The address of the user who needs tokens minted
* @param _amount The amount of tokens being minted
*/
function mint(address _user, uint256 _amount) external {
_mintWithCaller(msg.sender, _user, _amount);
}
/**
* @notice Burns tokens for a user
* @dev Can only be called by a bridge
* @param _user The address of the user who needs tokens burned
* @param _amount The amount of tokens being burned
*/
function burn(address _user, uint256 _amount) external {
_burnWithCaller(msg.sender, _user, _amount);
}
/**
* @notice Sets the lockbox address
* @param _lockbox The address of the lockbox
*/
function setLockbox(address _lockbox) external onlyOwner {
lockbox = _lockbox;
emit LockboxSet(_lockbox);
}
/**
* @notice Updates the limits of any bridge
* @dev Can only be called by the owner
* @param _mintingLimit The updated minting limit we are setting to the bridge
* @param _burningLimit The updated burning limit we are setting to the bridge
* @param _bridge The address of the bridge we are setting the limits too
*/
function setBridgeLimits(
address _bridge,
uint256 _mintingLimit,
uint256 _burningLimit
) external onlyOwner {
_changeMinterLimit(_bridge, _mintingLimit);
_changeBurnerLimit(_bridge, _burningLimit);
emit BridgeLimitsSet(_mintingLimit, _burningLimit, _bridge);
}
/**
* @notice Returns the max limit of a bridge
* @param _bridge the bridge we are viewing the limits of
* @return _limit The limit the bridge has
*/
function mintingMaxLimitOf(
address _bridge
) external view returns (uint256 _limit) {
_limit = bridges[_bridge].minterParams.maxLimit;
}
/**
* @notice Returns the max limit of a bridge
* @param _bridge the bridge we are viewing the limits of
* @return _limit The limit the bridge has
*/
function burningMaxLimitOf(
address _bridge
) external view returns (uint256 _limit) {
_limit = bridges[_bridge].burnerParams.maxLimit;
}
/**
* @notice Returns the current limit of a bridge
* @param _bridge the bridge we are viewing the limits of
* @return _limit The limit the bridge has
*/
function mintingCurrentLimitOf(
address _bridge
) public view returns (uint256 _limit) {
_limit = _getCurrentLimit(
bridges[_bridge].minterParams.currentLimit,
bridges[_bridge].minterParams.maxLimit,
bridges[_bridge].minterParams.timestamp,
bridges[_bridge].minterParams.ratePerSecond
);
}
/**
* @notice Returns the current limit of a bridge
* @param _bridge the bridge we are viewing the limits of
* @return _limit The limit the bridge has
*/
function burningCurrentLimitOf(
address _bridge
) public view returns (uint256 _limit) {
_limit = _getCurrentLimit(
bridges[_bridge].burnerParams.currentLimit,
bridges[_bridge].burnerParams.maxLimit,
bridges[_bridge].burnerParams.timestamp,
bridges[_bridge].burnerParams.ratePerSecond
);
}
/**
* @notice Uses the limit of any bridge
* @param _bridge The address of the bridge who is being changed
* @param _change The change in the limit
*/
function _useMinterLimits(address _bridge, uint256 _change) internal {
uint256 _currentLimit = mintingCurrentLimitOf(_bridge);
bridges[_bridge].minterParams.timestamp = block.timestamp;
bridges[_bridge].minterParams.currentLimit = _currentLimit - _change;
}
/**
* @notice Uses the limit of any bridge
* @param _bridge The address of the bridge who is being changed
* @param _change The change in the limit
*/
function _useBurnerLimits(address _bridge, uint256 _change) internal {
uint256 _currentLimit = burningCurrentLimitOf(_bridge);
bridges[_bridge].burnerParams.timestamp = block.timestamp;
bridges[_bridge].burnerParams.currentLimit = _currentLimit - _change;
}
/**
* @notice Updates the limit of any bridge
* @dev Can only be called by the owner
* @param _bridge The address of the bridge we are setting the limit too
* @param _limit The updated limit we are setting to the bridge
*/
function _changeMinterLimit(address _bridge, uint256 _limit) internal {
if (_limit < _DURATION && _limit > 0) revert IXERC20_WrongBridgeLimit();
uint256 _oldLimit = bridges[_bridge].minterParams.maxLimit;
uint256 _currentLimit = mintingCurrentLimitOf(_bridge);
bridges[_bridge].minterParams.maxLimit = _limit;
bridges[_bridge].minterParams.currentLimit = _calculateNewCurrentLimit(
_limit,
_oldLimit,
_currentLimit
);
bridges[_bridge].minterParams.ratePerSecond = _limit / _DURATION;
bridges[_bridge].minterParams.timestamp = block.timestamp;
}
/**
* @notice Updates the limit of any bridge
* @dev Can only be called by the owner
* @param _bridge The address of the bridge we are setting the limit too
* @param _limit The updated limit we are setting to the bridge
*/
function _changeBurnerLimit(address _bridge, uint256 _limit) internal {
if (_limit < _DURATION && _limit > 0) revert IXERC20_WrongBridgeLimit();
uint256 _oldLimit = bridges[_bridge].burnerParams.maxLimit;
uint256 _currentLimit = burningCurrentLimitOf(_bridge);
bridges[_bridge].burnerParams.maxLimit = _limit;
bridges[_bridge].burnerParams.currentLimit = _calculateNewCurrentLimit(
_limit,
_oldLimit,
_currentLimit
);
bridges[_bridge].burnerParams.ratePerSecond = _limit / _DURATION;
bridges[_bridge].burnerParams.timestamp = block.timestamp;
}
/**
* @param _limit The new limit
* @param _oldLimit The old limit
* @param _currentLimit The current limit
* @return _newCurrentLimit The new current limit
*/
function _calculateNewCurrentLimit(
uint256 _limit,
uint256 _oldLimit,
uint256 _currentLimit
) internal pure returns (uint256 _newCurrentLimit) {
uint256 _difference;
if (_oldLimit > _limit) {
_difference = _oldLimit - _limit;
_newCurrentLimit = _currentLimit > _difference
? _currentLimit - _difference
: 0;
} else {
_difference = _limit - _oldLimit;
_newCurrentLimit = _currentLimit + _difference;
}
}
/**
* @param _currentLimit The current limit
* @param _maxLimit The max limit
* @param _timestamp The timestamp of the last update
* @param _ratePerSecond The rate per second
* @return _limit The current limit
*/
function _getCurrentLimit(
uint256 _currentLimit,
uint256 _maxLimit,
uint256 _timestamp,
uint256 _ratePerSecond
) internal view returns (uint256 _limit) {
_limit = _currentLimit;
if (_limit == _maxLimit) {
return _limit;
} else if (_timestamp + _DURATION <= block.timestamp) {
_limit = _maxLimit;
} else if (_timestamp + _DURATION > block.timestamp) {
uint256 _timePassed = block.timestamp - _timestamp;
uint256 _calculatedLimit = _limit + (_timePassed * _ratePerSecond);
_limit = _calculatedLimit > _maxLimit
? _maxLimit
: _calculatedLimit;
}
}
/**
* @param _caller The caller address
* @param _user The user address
* @param _amount The amount to burn
*/
function _burnWithCaller(
address _caller,
address _user,
uint256 _amount
) internal {
if (_caller != lockbox) {
uint256 _currentLimit = burningCurrentLimitOf(_caller);
if (_currentLimit < _amount) revert IXERC20_NotHighEnoughLimits();
_useBurnerLimits(_caller, _amount);
}
_burn(_user, _amount);
}
/**
* @param _caller The caller address
* @param _user The user address
* @param _amount The amount to mint
*/
function _mintWithCaller(
address _caller,
address _user,
uint256 _amount
) internal {
if (_caller != lockbox) {
uint256 _currentLimit = mintingCurrentLimitOf(_caller);
if (_currentLimit < _amount) revert IXERC20_NotHighEnoughLimits();
_useMinterLimits(_caller, _amount);
}
_mint(_user, _amount);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IXERC20Lockbox.sol";
import "../interfaces/IXERC20.sol";
contract XERC20Lockbox is IXERC20Lockbox, Initializable {
using SafeERC20 for IERC20;
using SafeCast for uint256;
/**
* @notice The XERC20 token of this contract
*/
IXERC20 public XERC20;
/**
* @notice The ERC20 token of this contract
*/
IERC20 public ERC20;
/**
* @notice Whether the ERC20 token is the native gas token of this chain
*/
bool public IS_NATIVE;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() payable {
_disableInitializers();
}
/**
* @param _xerc20 The address of the XERC20 contract
* @param _erc20 The address of the ERC20 contract
* @param _isNative Whether the ERC20 token is the native gas token of this chain or not
*/
function initialize(
address _xerc20,
address _erc20,
bool _isNative
) external initializer {
XERC20 = IXERC20(_xerc20);
ERC20 = IERC20(_erc20);
IS_NATIVE = _isNative;
}
/**
* @notice Deposit native tokens into the lockbox
*/
function depositNative() public payable {
if (!IS_NATIVE) revert IXERC20Lockbox_NotNative();
_deposit(msg.sender, msg.value);
}
/**
* @notice Deposit ERC20 tokens into the lockbox
* @param _amount The amount of tokens to deposit
*/
function deposit(uint256 _amount) external {
if (IS_NATIVE) revert IXERC20Lockbox_Native();
_deposit(msg.sender, _amount);
}
/**
* @notice Deposit ERC20 tokens into the lockbox, and send the XERC20 to a user
* @param _to The user to send the XERC20 to
* @param _amount The amount of tokens to deposit
*/
function depositTo(address _to, uint256 _amount) external {
if (IS_NATIVE) revert IXERC20Lockbox_Native();
_deposit(_to, _amount);
}
/**
* @notice Deposit the native asset into the lockbox, and send the XERC20 to a user
* @param _to The user to send the XERC20 to
*/
function depositNativeTo(address _to) external payable {
if (!IS_NATIVE) revert IXERC20Lockbox_NotNative();
_deposit(_to, msg.value);
}
/**
* @notice Withdraw ERC20 tokens from the lockbox
* @param _amount The amount of tokens to withdraw
*/
function withdraw(uint256 _amount) external {
_withdraw(msg.sender, _amount);
}
/**
* @notice Withdraw tokens from the lockbox
* @param _to The user to withdraw to
* @param _amount The amount of tokens to withdraw
*/
function withdrawTo(address _to, uint256 _amount) external {
_withdraw(_to, _amount);
}
/**
* @notice Withdraw tokens from the lockbox
* @param _to The user to withdraw to
* @param _amount The amount of tokens to withdraw
*/
function _withdraw(address _to, uint256 _amount) internal {
if (_to == address(this)) revert IXERC20Lockbox_WrongReceiver();
XERC20.burn(msg.sender, _amount);
if (IS_NATIVE) {
(bool _success, ) = payable(_to).call{value: _amount}("");
if (!_success) revert IXERC20Lockbox_WithdrawFailed();
} else {
ERC20.safeTransfer(_to, _amount);
}
emit Withdraw(_to, _amount);
}
/**
* @notice Deposit tokens into the lockbox
* @param _to The address to send the XERC20 to
* @param _amount The amount of tokens to deposit
*/
function _deposit(address _to, uint256 _amount) internal {
if (_to == address(this)) revert IXERC20Lockbox_WrongReceiver();
if (!IS_NATIVE)
ERC20.safeTransferFrom(msg.sender, address(this), _amount);
XERC20.mint(_to, _amount);
emit Deposit(_to, _amount);
}
/**
* @notice Fallback function to deposit native tokens
*/
receive() external payable {
depositNative();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @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.
*
* 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 initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../utils/CountersUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
/**
* This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Library for converting between addresses and bytes32 values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Bytes32AddressLib.sol)
library Bytes32AddressLib {
function fromLast20Bytes(bytes32 bytesValue) internal pure returns (address) {
return address(uint160(uint256(bytesValue)));
}
function fillLast12Bytes(address addressValue) internal pure returns (bytes32) {
return bytes32(bytes20(addressValue));
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {Bytes32AddressLib} from "./Bytes32AddressLib.sol";
/// @notice Deploy to deterministic addresses without an initcode factor.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/CREATE3.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/create3/blob/master/contracts/Create3.sol)
library CREATE3 {
using Bytes32AddressLib for bytes32;
//--------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//--------------------------------------------------------------------------------//
// 0x36 | 0x36 | CALLDATASIZE | size //
// 0x3d | 0x3d | RETURNDATASIZE | 0 size //
// 0x3d | 0x3d | RETURNDATASIZE | 0 0 size //
// 0x37 | 0x37 | CALLDATACOPY | //
// 0x36 | 0x36 | CALLDATASIZE | size //
// 0x3d | 0x3d | RETURNDATASIZE | 0 size //
// 0x34 | 0x34 | CALLVALUE | value 0 size //
// 0xf0 | 0xf0 | CREATE | newContract //
//--------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//--------------------------------------------------------------------------------//
// 0x67 | 0x67XXXXXXXXXXXXXXXX | PUSH8 bytecode | bytecode //
// 0x3d | 0x3d | RETURNDATASIZE | 0 bytecode //
// 0x52 | 0x52 | MSTORE | //
// 0x60 | 0x6008 | PUSH1 08 | 8 //
// 0x60 | 0x6018 | PUSH1 18 | 24 8 //
// 0xf3 | 0xf3 | RETURN | //
//--------------------------------------------------------------------------------//
bytes internal constant PROXY_BYTECODE = hex"67_36_3d_3d_37_36_3d_34_f0_3d_52_60_08_60_18_f3";
bytes32 internal constant PROXY_BYTECODE_HASH = keccak256(PROXY_BYTECODE);
function deploy(
bytes32 salt,
bytes memory creationCode,
uint256 value
) internal returns (address deployed) {
bytes memory proxyChildBytecode = PROXY_BYTECODE;
address proxy;
/// @solidity memory-safe-assembly
assembly {
// Deploy a new contract with our pre-made bytecode via CREATE2.
// We start 32 bytes into the code to avoid copying the byte length.
proxy := create2(0, add(proxyChildBytecode, 32), mload(proxyChildBytecode), salt)
}
require(proxy != address(0), "DEPLOYMENT_FAILED");
deployed = getDeployed(salt);
(bool success, ) = proxy.call{value: value}(creationCode);
require(success && deployed.code.length != 0, "INITIALIZATION_FAILED");
}
function getDeployed(bytes32 salt) internal view returns (address) {
address proxy = keccak256(
abi.encodePacked(
// Prefix:
bytes1(0xFF),
// Creator:
address(this),
// Salt:
salt,
// Bytecode hash:
PROXY_BYTECODE_HASH
)
).fromLast20Bytes();
return
keccak256(
abi.encodePacked(
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01)
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex)
hex"d6_94",
proxy,
hex"01" // Nonce of the proxy contract (1)
)
).fromLast20Bytes();
}
}{
"optimizer": {
"enabled": true,
"runs": 200
},
"evmVersion": "paris",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"InconsistentInputData","type":"error"},{"inputs":[{"internalType":"uint256","name":"day","type":"uint256"}],"name":"IncorrectDay","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"IncorrectToken","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NewRatioThresholdInvalid","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"NullParams","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OperatorUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"RatioThresholdNotSet","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"prevValue","type":"address"},{"indexed":false,"internalType":"address","name":"newValue","type":"address"}],"name":"OperatorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"failedRatio","type":"uint256"},{"indexed":false,"internalType":"string","name":"reason","type":"string"}],"name":"RatioNotUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"prevValue","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newValue","type":"uint256"}],"name":"RatioThresholdChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"prevValue","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newValue","type":"uint256"}],"name":"RatioUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"MAX_THRESHOLD","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"day","type":"uint256"}],"name":"averagePercentageRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getRatioFor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"historicalRatios","outputs":[{"internalType":"uint40","name":"lastUpdate","type":"uint40"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"inceptionOperator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ratioThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"ratio","type":"uint256"}],"name":"repairRatioFor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOperator","type":"address"}],"name":"setInceptionOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newValue","type":"uint256"}],"name":"setRatioThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"addresses","type":"address[]"},{"internalType":"uint256[]","name":"ratios","type":"uint256[]"}],"name":"updateRatioBatch","outputs":[],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
608060405234801561001057600080fd5b50611179806100206000396000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c8063715018a6116100a2578063b037d56a11610071578063b037d56a1461021e578063b148122414610231578063c4d66de814610244578063ec653c4b14610257578063f2fde38b1461029757600080fd5b8063715018a6146101dd5780638456cb59146101e55780638da5cb5b146101ed578063a1f1d48d146101f557600080fd5b80633be19c03116100de5780633be19c031461017e5780633f4ba83a146101875780635c975abb1461018f5780636878324b146101b257600080fd5b806308af5431146101105780632364753a146101355780632acaaff41461014a5780632ef86a1f1461016b575b600080fd5b61011b6305f5e10081565b60405163ffffffff90911681526020015b60405180910390f35b610148610143366004610ea2565b6102aa565b005b61015d610158366004610ed7565b610322565b60405190815260200161012c565b610148610179366004610ed7565b610519565b61015d60045481565b6101486105b2565b6000805160206111248339815191525460ff16604051901515815260200161012c565b6000546101c5906001600160a01b031681565b6040516001600160a01b03909116815260200161012c565b6101486105c4565b6101486105d6565b6101c56105e6565b61015d610203366004610f01565b6001600160a01b031660009081526001602052604090205490565b61014861022c366004610f6e565b610614565b61014861023f366004610f01565b61090c565b610148610252366004610f01565b6109a4565b610281610265366004610f01565b60026020526000908152604090206003015464ffffffffff1681565b60405164ffffffffff909116815260200161012c565b6101486102a5366004610f01565b610b10565b6102b2610b4e565b6305f5e100811015806102c3575080155b156102e15760405163b70d743f60e01b815260040160405180910390fd5b60045460408051918252602082018390527f661e4cadf2d36ec16a59d60dcfeebe23f9be2aec99852725798a4be99790840e910160405180910390a1600455565b60006001600160a01b03831661034b5760405163a22b4cd760e01b815260040160405180910390fd5b8115806103585750600782115b1561037e57604051632924c02560e21b8152600481018390526024015b60405180910390fd5b6001600160a01b0383166000908152600260205260408120805490916001600160401b03909116908190036103d157604051633dafde0760e01b81526001600160a01b0386166004820152602401610375565b83816001600160401b031610156103fe57604051632924c02560e21b815260048101859052602401610375565b6000826008610416876001600160401b038616611005565b610420919061102e565b61042b906001611042565b6009811061043b5761043b610fd9565b60048104909101546001600160401b036008600390931683026101000a909104169150600090849061046d9085611055565b61047890600161107b565b6001600160401b03166009811061049157610491610fd9565b600491828204019190066008029054906101000a90046001600160401b03166001600160401b031690508082116104cf576000945050505050610513565b6104d986826110a2565b6104e38284611005565b6104f69068056bc75e2d631000006110a2565b6105029061016d6110a2565b61050c91906110b9565b9450505050505b92915050565b610521610b4e565b6001600160a01b0382161580610535575080155b156105535760405163a22b4cd760e01b815260040160405180910390fd5b6001600160a01b038216600081815260016020908152604091829020805490859055825181815291820185905292917f4c5c23b4efbfea6d16c8453f565e165a02a22cda9a8dc7aac0a66f91d2304da6910160405180910390a2505050565b6105ba610b4e565b6105c2610b80565b565b6105cc610b4e565b6105c26000610be0565b6105de610b4e565b6105c2610c51565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300546001600160a01b031690565b61061c610c9a565b6106246105e6565b6001600160a01b0316336001600160a01b03161415801561065057506000546001600160a01b03163314155b1561067057604051630642623160e11b8152336004820152602401610375565b60045460000361069357604051633c70047d60e01b815260040160405180910390fd5b828181146106b4576040516327ce0ee760e21b815260040160405180910390fd5b60005b818110156109045760008686838181106106d3576106d3610fd9565b90506020020160208101906106e89190610f01565b6001600160a01b0381166000908152600360209081526040808320546001909252822054929350919087878681811061072357610723610fd9565b90506020020135905060008061073a858486610ccb565b915091508161079757856001600160a01b03167f2471a7627ad27128888e46dfc72f5d674c7156d6e99c969a675492a558a0b0e0848360405161077e9291906110cd565b60405180910390a28660010196505050505050506106b7565b6001600160a01b03861660008181526001602090815260409182902086905581518781529081018690527f4c5c23b4efbfea6d16c8453f565e165a02a22cda9a8dc7aac0a66f91d2304da6910160405180910390a26001600160a01b038616600090815260036020818152604080842064ffffffffff42818116909255600290935293209182015491926201514492610831921690611005565b11156108f25780546001600160401b03168482600861085184600161107b565b61085b9190611055565b61086690600161107b565b6001600160401b03166009811061087f5761087f610fd9565b600491828204019190066008026101000a8154816001600160401b0302191690836001600160401b031602179055508060016108bb919061107b565b825467ffffffffffffffff19166001600160401b03919091161782555060038101805464ffffffffff19164264ffffffffff161790555b876001019750505050505050506106b7565b505050505050565b610914610b4e565b6001600160a01b03811661093b5760405163a22b4cd760e01b815260040160405180910390fd5b600054604080516001600160a01b03928316815291831660208301527ffbe5b6cbafb274f445d7fed869dc77a838d8243a22c460de156560e8857cad03910160405180910390a1600080546001600160a01b0319166001600160a01b0392909216919091179055565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff1615906001600160401b03166000811580156109e95750825b90506000826001600160401b03166001148015610a055750303b155b905081158015610a13575080155b15610a315760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315610a5b57845460ff60401b1916600160401b1785555b610a6433610ddf565b610a6c610df0565b600080546001600160a01b0319166001600160a01b03881690811782556040805192835260208301919091527ffbe5b6cbafb274f445d7fed869dc77a838d8243a22c460de156560e8857cad03910160405180910390a1831561090457845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a1505050505050565b610b18610b4e565b6001600160a01b038116610b4257604051631e4fbdf760e01b815260006004820152602401610375565b610b4b81610be0565b50565b33610b576105e6565b6001600160a01b0316146105c25760405163118cdaa760e01b8152336004820152602401610375565b610b88610e00565b600080516020611124833981519152805460ff191681557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a150565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930080546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3505050565b610c59610c9a565b600080516020611124833981519152805460ff191660011781557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25833610bc2565b6000805160206111248339815191525460ff16156105c25760405163d93c066560e01b815260040160405180910390fd5b6000606082600003610ce05760019150610dd7565b61a8c0610ced8642611005565b1015610d2d575060408051808201909152601981527f7570646174652074696d652072616e67652065786365656473000000000000006020820152610dd7565b82841115610d6f575060408051808201909152601d81527f6e657720726174696f2069732067726561746572207468616e206f6c640000006020820152610dd7565b6004546000906305f5e10090610d8590866110a2565b610d8f91906110b9565b9050610d9b8185611005565b851015610dd15750506040805180820190915260118152706e657720726174696f20746f6f206c6f7760781b6020820152610dd7565b60019250505b935093915050565b610de7610e30565b610b4b81610e79565b610df8610e30565b6105c2610e81565b6000805160206111248339815191525460ff166105c257604051638dfc202b60e01b815260040160405180910390fd5b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff166105c257604051631afcd79f60e31b815260040160405180910390fd5b610b18610e30565b610e89610e30565b600080516020611124833981519152805460ff19169055565b600060208284031215610eb457600080fd5b5035919050565b80356001600160a01b0381168114610ed257600080fd5b919050565b60008060408385031215610eea57600080fd5b610ef383610ebb565b946020939093013593505050565b600060208284031215610f1357600080fd5b610f1c82610ebb565b9392505050565b60008083601f840112610f3557600080fd5b5081356001600160401b03811115610f4c57600080fd5b6020830191508360208260051b8501011115610f6757600080fd5b9250929050565b60008060008060408587031215610f8457600080fd5b84356001600160401b0380821115610f9b57600080fd5b610fa788838901610f23565b90965094506020870135915080821115610fc057600080fd5b50610fcd87828801610f23565b95989497509550505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8181038181111561051357610513610fef565b634e487b7160e01b600052601260045260246000fd5b60008261103d5761103d611018565b500690565b8082018082111561051357610513610fef565b60006001600160401b038084168061106f5761106f611018565b92169190910692915050565b6001600160401b0381811683821601908082111561109b5761109b610fef565b5092915050565b808202811582820484141761051357610513610fef565b6000826110c8576110c8611018565b500490565b82815260006020604081840152835180604085015260005b81811015611101578581018301518582016060015282016110e5565b506000606082860101526060601f19601f83011685010192505050939250505056fecd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300a264697066735822122006a3e4d66713f14f8bb034057a5dafa7173ba2215f3f1a7f8871138f19c2880f64736f6c63430008140033
Deployed Bytecode
0x608060405234801561001057600080fd5b506004361061010b5760003560e01c8063715018a6116100a2578063b037d56a11610071578063b037d56a1461021e578063b148122414610231578063c4d66de814610244578063ec653c4b14610257578063f2fde38b1461029757600080fd5b8063715018a6146101dd5780638456cb59146101e55780638da5cb5b146101ed578063a1f1d48d146101f557600080fd5b80633be19c03116100de5780633be19c031461017e5780633f4ba83a146101875780635c975abb1461018f5780636878324b146101b257600080fd5b806308af5431146101105780632364753a146101355780632acaaff41461014a5780632ef86a1f1461016b575b600080fd5b61011b6305f5e10081565b60405163ffffffff90911681526020015b60405180910390f35b610148610143366004610ea2565b6102aa565b005b61015d610158366004610ed7565b610322565b60405190815260200161012c565b610148610179366004610ed7565b610519565b61015d60045481565b6101486105b2565b6000805160206111248339815191525460ff16604051901515815260200161012c565b6000546101c5906001600160a01b031681565b6040516001600160a01b03909116815260200161012c565b6101486105c4565b6101486105d6565b6101c56105e6565b61015d610203366004610f01565b6001600160a01b031660009081526001602052604090205490565b61014861022c366004610f6e565b610614565b61014861023f366004610f01565b61090c565b610148610252366004610f01565b6109a4565b610281610265366004610f01565b60026020526000908152604090206003015464ffffffffff1681565b60405164ffffffffff909116815260200161012c565b6101486102a5366004610f01565b610b10565b6102b2610b4e565b6305f5e100811015806102c3575080155b156102e15760405163b70d743f60e01b815260040160405180910390fd5b60045460408051918252602082018390527f661e4cadf2d36ec16a59d60dcfeebe23f9be2aec99852725798a4be99790840e910160405180910390a1600455565b60006001600160a01b03831661034b5760405163a22b4cd760e01b815260040160405180910390fd5b8115806103585750600782115b1561037e57604051632924c02560e21b8152600481018390526024015b60405180910390fd5b6001600160a01b0383166000908152600260205260408120805490916001600160401b03909116908190036103d157604051633dafde0760e01b81526001600160a01b0386166004820152602401610375565b83816001600160401b031610156103fe57604051632924c02560e21b815260048101859052602401610375565b6000826008610416876001600160401b038616611005565b610420919061102e565b61042b906001611042565b6009811061043b5761043b610fd9565b60048104909101546001600160401b036008600390931683026101000a909104169150600090849061046d9085611055565b61047890600161107b565b6001600160401b03166009811061049157610491610fd9565b600491828204019190066008029054906101000a90046001600160401b03166001600160401b031690508082116104cf576000945050505050610513565b6104d986826110a2565b6104e38284611005565b6104f69068056bc75e2d631000006110a2565b6105029061016d6110a2565b61050c91906110b9565b9450505050505b92915050565b610521610b4e565b6001600160a01b0382161580610535575080155b156105535760405163a22b4cd760e01b815260040160405180910390fd5b6001600160a01b038216600081815260016020908152604091829020805490859055825181815291820185905292917f4c5c23b4efbfea6d16c8453f565e165a02a22cda9a8dc7aac0a66f91d2304da6910160405180910390a2505050565b6105ba610b4e565b6105c2610b80565b565b6105cc610b4e565b6105c26000610be0565b6105de610b4e565b6105c2610c51565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300546001600160a01b031690565b61061c610c9a565b6106246105e6565b6001600160a01b0316336001600160a01b03161415801561065057506000546001600160a01b03163314155b1561067057604051630642623160e11b8152336004820152602401610375565b60045460000361069357604051633c70047d60e01b815260040160405180910390fd5b828181146106b4576040516327ce0ee760e21b815260040160405180910390fd5b60005b818110156109045760008686838181106106d3576106d3610fd9565b90506020020160208101906106e89190610f01565b6001600160a01b0381166000908152600360209081526040808320546001909252822054929350919087878681811061072357610723610fd9565b90506020020135905060008061073a858486610ccb565b915091508161079757856001600160a01b03167f2471a7627ad27128888e46dfc72f5d674c7156d6e99c969a675492a558a0b0e0848360405161077e9291906110cd565b60405180910390a28660010196505050505050506106b7565b6001600160a01b03861660008181526001602090815260409182902086905581518781529081018690527f4c5c23b4efbfea6d16c8453f565e165a02a22cda9a8dc7aac0a66f91d2304da6910160405180910390a26001600160a01b038616600090815260036020818152604080842064ffffffffff42818116909255600290935293209182015491926201514492610831921690611005565b11156108f25780546001600160401b03168482600861085184600161107b565b61085b9190611055565b61086690600161107b565b6001600160401b03166009811061087f5761087f610fd9565b600491828204019190066008026101000a8154816001600160401b0302191690836001600160401b031602179055508060016108bb919061107b565b825467ffffffffffffffff19166001600160401b03919091161782555060038101805464ffffffffff19164264ffffffffff161790555b876001019750505050505050506106b7565b505050505050565b610914610b4e565b6001600160a01b03811661093b5760405163a22b4cd760e01b815260040160405180910390fd5b600054604080516001600160a01b03928316815291831660208301527ffbe5b6cbafb274f445d7fed869dc77a838d8243a22c460de156560e8857cad03910160405180910390a1600080546001600160a01b0319166001600160a01b0392909216919091179055565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff1615906001600160401b03166000811580156109e95750825b90506000826001600160401b03166001148015610a055750303b155b905081158015610a13575080155b15610a315760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315610a5b57845460ff60401b1916600160401b1785555b610a6433610ddf565b610a6c610df0565b600080546001600160a01b0319166001600160a01b03881690811782556040805192835260208301919091527ffbe5b6cbafb274f445d7fed869dc77a838d8243a22c460de156560e8857cad03910160405180910390a1831561090457845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a1505050505050565b610b18610b4e565b6001600160a01b038116610b4257604051631e4fbdf760e01b815260006004820152602401610375565b610b4b81610be0565b50565b33610b576105e6565b6001600160a01b0316146105c25760405163118cdaa760e01b8152336004820152602401610375565b610b88610e00565b600080516020611124833981519152805460ff191681557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a150565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930080546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3505050565b610c59610c9a565b600080516020611124833981519152805460ff191660011781557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25833610bc2565b6000805160206111248339815191525460ff16156105c25760405163d93c066560e01b815260040160405180910390fd5b6000606082600003610ce05760019150610dd7565b61a8c0610ced8642611005565b1015610d2d575060408051808201909152601981527f7570646174652074696d652072616e67652065786365656473000000000000006020820152610dd7565b82841115610d6f575060408051808201909152601d81527f6e657720726174696f2069732067726561746572207468616e206f6c640000006020820152610dd7565b6004546000906305f5e10090610d8590866110a2565b610d8f91906110b9565b9050610d9b8185611005565b851015610dd15750506040805180820190915260118152706e657720726174696f20746f6f206c6f7760781b6020820152610dd7565b60019250505b935093915050565b610de7610e30565b610b4b81610e79565b610df8610e30565b6105c2610e81565b6000805160206111248339815191525460ff166105c257604051638dfc202b60e01b815260040160405180910390fd5b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff166105c257604051631afcd79f60e31b815260040160405180910390fd5b610b18610e30565b610e89610e30565b600080516020611124833981519152805460ff19169055565b600060208284031215610eb457600080fd5b5035919050565b80356001600160a01b0381168114610ed257600080fd5b919050565b60008060408385031215610eea57600080fd5b610ef383610ebb565b946020939093013593505050565b600060208284031215610f1357600080fd5b610f1c82610ebb565b9392505050565b60008083601f840112610f3557600080fd5b5081356001600160401b03811115610f4c57600080fd5b6020830191508360208260051b8501011115610f6757600080fd5b9250929050565b60008060008060408587031215610f8457600080fd5b84356001600160401b0380821115610f9b57600080fd5b610fa788838901610f23565b90965094506020870135915080821115610fc057600080fd5b50610fcd87828801610f23565b95989497509550505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8181038181111561051357610513610fef565b634e487b7160e01b600052601260045260246000fd5b60008261103d5761103d611018565b500690565b8082018082111561051357610513610fef565b60006001600160401b038084168061106f5761106f611018565b92169190910692915050565b6001600160401b0381811683821601908082111561109b5761109b610fef565b5092915050565b808202811582820484141761051357610513610fef565b6000826110c8576110c8611018565b500490565b82815260006020604081840152835180604085015260005b81811015611101578581018301518582016060015282016110e5565b506000606082860101526060601f19601f83011685010192505050939250505056fecd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300a264697066735822122006a3e4d66713f14f8bb034057a5dafa7173ba2215f3f1a7f8871138f19c2880f64736f6c63430008140033
Deployed Bytecode Sourcemap
394:5866:53:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;658:50;;704:3;658:50;;;;;188:10:71;176:23;;;158:42;;146:2;131:18;658:50:53;;;;;;;;5489:272;;;;;;:::i;:::-;;:::i;:::-;;4181:886;;;;;;:::i;:::-;;:::i;:::-;;;979:25:71;;;967:2;952:18;4181:886:53;833:177:71;5208:275:53;;;;;;:::i;:::-;;:::i;1108:29::-;;;;;;6193:65;;;:::i;2692:145:3:-;-1:-1:-1;;;;;;;;;;;2821:9:3;;;2692:145;;1180:14:71;;1173:22;1155:41;;1143:2;1128:18;2692:145:3;1015:187:71;715:32:53;;;;;-1:-1:-1;;;;;715:32:53;;;;;;-1:-1:-1;;;;;1371:32:71;;;1353:51;;1341:2;1326:18;715:32:53;1207:203:71;3155:101:0;;;:::i;6126:61:53:-;;;:::i;2441:144:0:-;;;:::i;5073:129:53:-;;;;;;:::i;:::-;-1:-1:-1;;;;;5181:14:53;5155:7;5181:14;;;:7;:14;;;;;;;5073:129;1548:1743;;;;;;:::i;:::-;;:::i;5767:241::-;;;;;;:::i;:::-;;:::i;1322:220::-;;;;;;:::i;:::-;;:::i;803:60::-;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;2930:12:71;2918:25;;;2900:44;;2888:2;2873:18;803:60:53;2756:194:71;3405:215:0;;;;;;:::i;:::-;;:::i;5489:272:53:-;2334:13:0;:11;:13::i;:::-;704:3:53::1;5567:25:::0;::::1;;::::0;:42:::1;;-1:-1:-1::0;5596:13:53;;5567:42:::1;5563:93;;;5630:26;;-1:-1:-1::0;;;5630:26:53::1;;;;;;;;;;;5563:93;5694:14;::::0;5672:47:::1;::::0;;3129:25:71;;;3185:2;3170:18;;3163:34;;;5672:47:53::1;::::0;3102:18:71;5672:47:53::1;;;;;;;5729:14;:25:::0;5489:272::o;4181:886::-;4285:7;-1:-1:-1;;;;;4308:19:53;;4304:44;;4336:12;;-1:-1:-1;;;4336:12:53;;;;;;;;;;;4304:44;4362:8;;;:19;;;4380:1;4374:3;:7;4362:19;4358:49;;;4390:17;;-1:-1:-1;;;4390:17:53;;;;;979:25:71;;;952:18;;4390:17:53;;;;;;;;4358:49;-1:-1:-1;;;;;4454:23:53;;4418:33;4454:23;;;:16;:23;;;;;4509:28;;4454:23;;-1:-1:-1;;;;;4509:28:53;;;;4551:17;;;4547:51;;4577:21;;-1:-1:-1;;;4577:21:53;;-1:-1:-1;;;;;1371:32:71;;4577:21:53;;;1353:51:71;1326:18;;4577:21:53;1207:203:71;4547:51:53;4627:3;4612:12;-1:-1:-1;;;;;4612:18:53;;4608:48;;;4639:17;;-1:-1:-1;;;4639:17:53;;;;;979:25:71;;;952:18;;4639:17:53;833:177:71;4608:48:53;4667:19;4689:8;4752:1;4730:18;4745:3;-1:-1:-1;;;;;4730:18:53;;;:::i;:::-;4729:24;;;;:::i;:::-;4728:30;;4757:1;4728:30;:::i;:::-;4689:79;;;;;;;:::i;:::-;;;;;;;;-1:-1:-1;;;;;4689:79:53;;;;;;;;;;;;;;-1:-1:-1;4778:19:53;;4800:8;;4840:18;;4841:12;4840:18;:::i;:::-;4839:24;;4862:1;4839:24;:::i;:::-;-1:-1:-1;;;;;4800:73:53;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;4800:73:53;-1:-1:-1;;;;;4778:95:53;;;4903:11;4888;:26;4884:65;;4937:1;4930:8;;;;;;;;4884:65;5040:19;5055:3;5040:11;:19;:::i;:::-;4980:25;4994:11;4980;:25;:::i;:::-;4979:38;;5009:8;4979:38;:::i;:::-;:44;;5020:3;4979:44;:::i;:::-;4978:82;;;;:::i;:::-;4959:101;;;;;;4181:886;;;;;:::o;5208:275::-;2334:13:0;:11;:13::i;:::-;-1:-1:-1;;;;;5295:19:53;::::1;::::0;;:33:::1;;-1:-1:-1::0;5318:10:53;;5295:33:::1;5291:58;;;5337:12;;-1:-1:-1::0;;;5337:12:53::1;;;;;;;;;;;5291:58;-1:-1:-1::0;;;;;5379:14:53;::::1;5360:16;5379:14:::0;;;:7:::1;:14;::::0;;;;;;;;;;5403:22;;;;5440:36;;3129:25:71;;;3170:18;;;3163:34;;;5379:14:53;;5440:36:::1;::::0;3102:18:71;5440:36:53::1;;;;;;;5281:202;5208:275:::0;;:::o;6193:65::-;2334:13:0;:11;:13::i;:::-;6241:10:53::1;:8;:10::i;:::-;6193:65::o:0;3155:101:0:-;2334:13;:11;:13::i;:::-;3219:30:::1;3246:1;3219:18;:30::i;6126:61:53:-:0;2334:13:0;:11;:13::i;:::-;6172:8:53::1;:6;:8::i;2441:144:0:-:0;1313:22;2570:8;-1:-1:-1;;;;;2570:8:0;;2441:144::o;1548:1743:53:-;2316:19:3;:17;:19::i;:::-;1196:7:53::1;:5;:7::i;:::-;-1:-1:-1::0;;;;;1182:21:53::1;:10;-1:-1:-1::0;;;;;1182:21:53::1;;;:56;;;;-1:-1:-1::0;1221:17:53::1;::::0;-1:-1:-1;;;;;1221:17:53::1;1207:10;:31;;1182:56;1178:120;;;1259:39;::::0;-1:-1:-1;;;1259:39:53;;1287:10:::1;1259:39;::::0;::::1;1353:51:71::0;1326:18;;1259:39:53::1;1207:203:71::0;1178:120:53::1;1712:14:::2;;1730:1;1712:19:::0;1708:54:::2;;1740:22;;-1:-1:-1::0;;;1740:22:53::2;;;;;;;;;;;1708:54;1795:9:::0;1825:28;;::::2;1821:64;;1862:23;;-1:-1:-1::0;;;1862:23:53::2;;;;;;;;;;;1821:64;1901:9;1896:1389;1920:11;1916:1;:15;1896:1389;;;1949:17;1969:9;;1979:1;1969:12;;;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1::0;;;;;2016:24:53;::::2;1995:18;2016:24:::0;;;:13:::2;:24;::::0;;;;;;;;2073:7:::2;:18:::0;;;;;;1949:32;;-1:-1:-1;2016:24:53;2073:18;2124:6;;2131:1;2124:9;;::::2;;;;;:::i;:::-;;;;;;;2105:28;;2149:10;2161:20:::0;2185:110:::2;2219:10;2247:8;2273;2185:16;:110::i;:::-;2148:147;;;;2315:5;2310:191;;2361:9;-1:-1:-1::0;;;;;2345:44:53::2;;2372:8;2382:6;2345:44;;;;;;;:::i;:::-;;;;;;;;2439:3;;;;;2478:8;;;;;;1896:1389;;2310:191;-1:-1:-1::0;;;;;2515:18:53;::::2;;::::0;;;:7:::2;:18;::::0;;;;;;;;:29;;;2563:43;;3129:25:71;;;3170:18;;;3163:34;;;2563:43:53::2;::::0;3102:18:71;2563:43:53::2;;;;;;;-1:-1:-1::0;;;;;2621:24:53;::::2;;::::0;;;:13:::2;:24;::::0;;;;;;;:50:::2;2655:15;2621:50:::0;;::::2;::::0;;;2770:16:::2;:27:::0;;;;;2833:19;;::::2;::::0;2770:27;;2855:18:::2;::::0;2815:37:::2;::::0;2833:19:::2;::::0;2815:37:::2;:::i;:::-;:58;2811:405;;;2915:28:::0;;-1:-1:-1;;;;;2915:28:53::2;3064:8:::0;2915;:28:::2;3010:16;2915:28:::0;;3010:16:::2;:::i;:::-;3009:22;;;;:::i;:::-;3008:28;::::0;3035:1:::2;3008:28;:::i;:::-;-1:-1:-1::0;;;;;2961:93:53::2;;;;;;;;:::i;:::-;;;;;;;;;;;;:112;;;;;-1:-1:-1::0;;;;;2961:112:53::2;;;;;-1:-1:-1::0;;;;;2961:112:53::2;;;;;;3122:12;3137:1;3122:16;;;;:::i;:::-;3091:47:::0;;-1:-1:-1;;3091:47:53::2;-1:-1:-1::0;;;;;3091:47:53;;;::::2;;::::0;;-1:-1:-1;3091:28:53;3156:19;::::2;:45:::0;;-1:-1:-1;;3156:45:53::2;3185:15;3156:45;;;::::0;;2811:405:::2;3257:3;;;;;1935:1350;;;;;;;1896:1389;;;;1698:1593;1548:1743:::0;;;;:::o;5767:241::-;2334:13:0;:11;:13::i;:::-;-1:-1:-1;;;;;5851:25:53;::::1;5847:50;;5885:12;;-1:-1:-1::0;;;5885:12:53::1;;;;;;;;;;;5847:50;5929:17;::::0;5913:47:::1;::::0;;-1:-1:-1;;;;;5929:17:53;;::::1;5499:34:71::0;;5569:15;;;5564:2;5549:18;;5542:43;5913:47:53::1;::::0;5434:18:71;5913:47:53::1;;;;;;;5970:17;:31:::0;;-1:-1:-1;;;;;;5970:31:53::1;-1:-1:-1::0;;;;;5970:31:53;;;::::1;::::0;;;::::1;::::0;;5767:241::o;1322:220::-;8870:21:1;4302:15;;-1:-1:-1;;;4302:15:1;;;;4301:16;;-1:-1:-1;;;;;4348:14:1;4158:30;4726:16;;:34;;;;;4746:14;4726:34;4706:54;;4770:17;4790:11;-1:-1:-1;;;;;4790:16:1;4805:1;4790:16;:50;;;;-1:-1:-1;4818:4:1;4810:25;:30;4790:50;4770:70;;4856:12;4855:13;:30;;;;;4873:12;4872:13;4855:30;4851:91;;;4908:23;;-1:-1:-1;;;4908:23:1;;;;;;;;;;;4851:91;4951:18;;-1:-1:-1;;4951:18:1;4968:1;4951:18;;;4979:67;;;;5013:22;;-1:-1:-1;;;;5013:22:1;-1:-1:-1;;;5013:22:1;;;4979:67;1391:26:53::1;1406:10;1391:14;:26::i;:::-;1427:17;:15;:17::i;:::-;1455;:28:::0;;-1:-1:-1;;;;;;1455:28:53::1;-1:-1:-1::0;;;;;1455:28:53;::::1;::::0;;::::1;::::0;;1498:37:::1;::::0;;5499:34:71;;;5564:2;5549:18;;5542:43;;;;1498:37:53::1;::::0;5434:18:71;1498:37:53::1;;;;;;;5070:14:1::0;5066:101;;;5100:23;;-1:-1:-1;;;;5100:23:1;;;5142:14;;-1:-1:-1;5749:50:71;;5142:14:1;;5737:2:71;5722:18;5142:14:1;;;;;;;4092:1081;;;;;1322:220:53;:::o;3405:215:0:-;2334:13;:11;:13::i;:::-;-1:-1:-1;;;;;3489:22:0;::::1;3485:91;;3534:31;::::0;-1:-1:-1;;;3534:31:0;;3562:1:::1;3534:31;::::0;::::1;1353:51:71::0;1326:18;;3534:31:0::1;1207:203:71::0;3485:91:0::1;3585:28;3604:8;3585:18;:28::i;:::-;3405:215:::0;:::o;2658:162::-;966:10:2;2717:7:0;:5;:7::i;:::-;-1:-1:-1;;;;;2717:23:0;;2713:101;;2763:40;;-1:-1:-1;;;2763:40:0;;966:10:2;2763:40:0;;;1353:51:71;1326:18;;2763:40:0;1207:203:71;3674:178:3;2563:16;:14;:16::i;:::-;-1:-1:-1;;;;;;;;;;;3791:17:3;;-1:-1:-1;;3791:17:3::1;::::0;;3823:22:::1;966:10:2::0;3832:12:3::1;3823:22;::::0;-1:-1:-1;;;;;1371:32:71;;;1353:51;;1341:2;1326:18;3823:22:3::1;;;;;;;3722:130;3674:178::o:0;3774:248:0:-;1313:22;3923:8;;-1:-1:-1;;;;;;3941:19:0;;-1:-1:-1;;;;;3941:19:0;;;;;;;;3975:40;;3923:8;;;;;3975:40;;3847:24;;3975:40;3837:185;;3774:248;:::o;3366:176:3:-;2316:19;:17;:19::i;:::-;-1:-1:-1;;;;;;;;;;;3484:16:3;;-1:-1:-1;;3484:16:3::1;3496:4;3484:16;::::0;;3515:20:::1;966:10:2::0;3522:12:3::1;887:96:2::0;2905:128:3;-1:-1:-1;;;;;;;;;;;2821:9:3;;;2966:61;;;3001:15;;-1:-1:-1;;;3001:15:3;;;;;;;;;;;3297:878:53;3433:10;3445:20;3541:8;3553:1;3541:13;3537:48;;3572:4;3564:12;;3556:29;;3537:48;3632:8;3600:29;3618:11;3600:15;:29;:::i;:::-;:40;3596:110;;;-1:-1:-1;3669:36:53;;;;;;;;;;;;;;;;;3654:52;;3596:110;3795:8;3784;:19;3780:93;;;-1:-1:-1;3832:40:53;;;;;;;;;;;;;;;;;3817:56;;3780:93;3994:14;;3962:17;;704:3;;3983:25;;:8;:25;:::i;:::-;3982:43;;;;:::i;:::-;3962:63;-1:-1:-1;4050:20:53;3962:63;4050:8;:20;:::i;:::-;4039:8;:31;4035:93;;;-1:-1:-1;;4099:28:53;;;;;;;;;;;;-1:-1:-1;;;4099:28:53;;;;4084:44;;4035:93;4155:4;4147:12;;4139:29;3297:878;;;;;;;:::o;1847:127:0:-;6931:20:1;:18;:20::i;:::-;1929:38:0::1;1954:12;1929:24;:38::i;1836:97:3:-:0;6931:20:1;:18;:20::i;:::-;1899:27:3::1;:25;:27::i;3105:126::-:0;-1:-1:-1;;;;;;;;;;;2821:9:3;;;3163:62;;3199:15;;-1:-1:-1;;;3199:15:3;;;;;;;;;;;7084:141:1;8870:21;8560:40;-1:-1:-1;;;8560:40:1;;;;7146:73;;7191:17;;-1:-1:-1;;;7191:17:1;;;;;;;;;;;1980:235:0;6931:20:1;:18;:20::i;1939:156:3:-;6931:20:1;:18;:20::i;:::-;-1:-1:-1;;;;;;;;;;;2071:17:3;;-1:-1:-1;;2071:17:3::1;::::0;;1939:156::o;211:180:71:-;270:6;323:2;311:9;302:7;298:23;294:32;291:52;;;339:1;336;329:12;291:52;-1:-1:-1;362:23:71;;211:180;-1:-1:-1;211:180:71:o;396:173::-;464:20;;-1:-1:-1;;;;;513:31:71;;503:42;;493:70;;559:1;556;549:12;493:70;396:173;;;:::o;574:254::-;642:6;650;703:2;691:9;682:7;678:23;674:32;671:52;;;719:1;716;709:12;671:52;742:29;761:9;742:29;:::i;:::-;732:39;818:2;803:18;;;;790:32;;-1:-1:-1;;;574:254:71:o;1415:186::-;1474:6;1527:2;1515:9;1506:7;1502:23;1498:32;1495:52;;;1543:1;1540;1533:12;1495:52;1566:29;1585:9;1566:29;:::i;:::-;1556:39;1415:186;-1:-1:-1;;;1415:186:71:o;1606:367::-;1669:8;1679:6;1733:3;1726:4;1718:6;1714:17;1710:27;1700:55;;1751:1;1748;1741:12;1700:55;-1:-1:-1;1774:20:71;;-1:-1:-1;;;;;1806:30:71;;1803:50;;;1849:1;1846;1839:12;1803:50;1886:4;1878:6;1874:17;1862:29;;1946:3;1939:4;1929:6;1926:1;1922:14;1914:6;1910:27;1906:38;1903:47;1900:67;;;1963:1;1960;1953:12;1900:67;1606:367;;;;;:::o;1978:773::-;2100:6;2108;2116;2124;2177:2;2165:9;2156:7;2152:23;2148:32;2145:52;;;2193:1;2190;2183:12;2145:52;2233:9;2220:23;-1:-1:-1;;;;;2303:2:71;2295:6;2292:14;2289:34;;;2319:1;2316;2309:12;2289:34;2358:70;2420:7;2411:6;2400:9;2396:22;2358:70;:::i;:::-;2447:8;;-1:-1:-1;2332:96:71;-1:-1:-1;2535:2:71;2520:18;;2507:32;;-1:-1:-1;2551:16:71;;;2548:36;;;2580:1;2577;2570:12;2548:36;;2619:72;2683:7;2672:8;2661:9;2657:24;2619:72;:::i;:::-;1978:773;;;;-1:-1:-1;2710:8:71;-1:-1:-1;;;;1978:773:71:o;3208:127::-;3269:10;3264:3;3260:20;3257:1;3250:31;3300:4;3297:1;3290:15;3324:4;3321:1;3314:15;3340:127;3401:10;3396:3;3392:20;3389:1;3382:31;3432:4;3429:1;3422:15;3456:4;3453:1;3446:15;3472:128;3539:9;;;3560:11;;;3557:37;;;3574:18;;:::i;3605:127::-;3666:10;3661:3;3657:20;3654:1;3647:31;3697:4;3694:1;3687:15;3721:4;3718:1;3711:15;3737:112;3769:1;3795;3785:35;;3800:18;;:::i;:::-;-1:-1:-1;3834:9:71;;3737:112::o;3854:125::-;3919:9;;;3940:10;;;3937:36;;;3953:18;;:::i;3984:191::-;4015:1;-1:-1:-1;;;;;4086:2:71;4083:1;4079:10;4108:3;4098:37;;4115:18;;:::i;:::-;4153:10;;4149:20;;;;;3984:191;-1:-1:-1;;3984:191:71:o;4180:180::-;-1:-1:-1;;;;;4285:10:71;;;4297;;;4281:27;;4320:11;;;4317:37;;;4334:18;;:::i;:::-;4317:37;4180:180;;;;:::o;4365:168::-;4438:9;;;4469;;4486:15;;;4480:22;;4466:37;4456:71;;4507:18;;:::i;4538:120::-;4578:1;4604;4594:35;;4609:18;;:::i;:::-;-1:-1:-1;4643:9:71;;4538:120::o;4663:619::-;4840:6;4829:9;4822:25;4803:4;4866:2;4904;4899;4888:9;4884:18;4877:30;4936:6;4930:13;4979:6;4974:2;4963:9;4959:18;4952:34;5004:1;5014:140;5028:6;5025:1;5022:13;5014:140;;;5123:14;;;5119:23;;5113:30;5089:17;;;5108:2;5085:26;5078:66;5043:10;;5014:140;;;5018:3;5203:1;5198:2;5189:6;5178:9;5174:22;5170:31;5163:42;5273:2;5266;5262:7;5257:2;5249:6;5245:15;5241:29;5230:9;5226:45;5222:54;5214:62;;;;4663:619;;;;;:::o
Swarm Source
ipfs://06a3e4d66713f14f8bb034057a5dafa7173ba2215f3f1a7f8871138f19c2880f
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in FRAX
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.