Overview
S Balance
S Value
$0.00More Info
Private Name Tags
ContractCreator
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 5 internal transactions
Parent Transaction Hash | Block | From | To | |||
---|---|---|---|---|---|---|
7408285 | 11 days ago | Contract Creation | 0 S | |||
7408285 | 11 days ago | Contract Creation | 0 S | |||
7408285 | 11 days ago | Contract Creation | 0 S | |||
7408285 | 11 days ago | Contract Creation | 0 S | |||
7408285 | 11 days ago | Contract Creation | 0 S |
Loading...
Loading
Contract Name:
AaveV3PeripheryBatch
Compiler Version
v0.8.22+commit.4fc1097e
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import {AaveV3TreasuryProcedure} from '../../../contracts/procedures/AaveV3TreasuryProcedure.sol'; import {AaveV3OracleProcedure} from '../../../contracts/procedures/AaveV3OracleProcedure.sol'; import {AaveV3IncentiveProcedure} from '../../../contracts/procedures/AaveV3IncentiveProcedure.sol'; import {AaveV3DefaultRateStrategyProcedure} from '../../../contracts/procedures/AaveV3DefaultRateStrategyProcedure.sol'; import {Ownable} from '../../../../contracts/dependencies/openzeppelin/contracts/Ownable.sol'; import '../../../interfaces/IMarketReportTypes.sol'; import {IRewardsController} from '../../../../contracts/rewards/interfaces/IRewardsController.sol'; import {RevenueSplitter} from '../../../../contracts/treasury/RevenueSplitter.sol'; contract AaveV3PeripheryBatch is AaveV3TreasuryProcedure, AaveV3OracleProcedure, AaveV3IncentiveProcedure { PeripheryReport internal _report; constructor( address poolAdmin, MarketConfig memory config, address poolAddressesProvider, address setupBatch ) { _report.aaveOracle = _deployAaveOracle(config.oracleDecimals, poolAddressesProvider); if (config.treasury == address(0)) { TreasuryReport memory treasuryReport = _deployAaveV3Treasury(poolAdmin, config.salt); _report.treasury = treasuryReport.treasury; _report.treasuryImplementation = treasuryReport.treasuryImplementation; } else { _report.treasury = config.treasury; } if ( config.treasuryPartner != address(0) && config.treasurySplitPercent > 0 && config.treasurySplitPercent < 100_00 ) { _report.revenueSplitter = address( new RevenueSplitter(_report.treasury, config.treasuryPartner, config.treasurySplitPercent) ); } if (config.incentivesProxy == address(0)) { (_report.emissionManager, _report.rewardsControllerImplementation) = _deployIncentives( setupBatch ); } else { _report.emissionManager = IRewardsController(config.incentivesProxy).getEmissionManager(); } } function getPeripheryReport() external view returns (PeripheryReport memory) { return _report; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol) pragma solidity ^0.8.20; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ```solidity * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ```solidity * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules} * to enforce additional security measures for this role. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable { struct RoleData { mapping(address account => bool) hasRole; bytes32 adminRole; } bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl struct AccessControlStorage { mapping(bytes32 role => RoleData) _roles; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800; function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) { assembly { $.slot := AccessControlStorageLocation } } /** * @dev Modifier that checks that an account has a specific role. Reverts * with an {AccessControlUnauthorizedAccount} error including the required role. */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); return $._roles[role].hasRole[account]; } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()` * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier. */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account` * is missing `role`. */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert AccessControlUnauthorizedAccount(account, role); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) { AccessControlStorage storage $ = _getAccessControlStorage(); return $._roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `callerConfirmation`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address callerConfirmation) public virtual { if (callerConfirmation != _msgSender()) { revert AccessControlBadConfirmation(); } _revokeRole(role, callerConfirmation); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { AccessControlStorage storage $ = _getAccessControlStorage(); bytes32 previousAdminRole = getRoleAdmin(role); $._roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); if (!hasRole(role, account)) { $._roles[role].hasRole[account] = true; emit RoleGranted(role, account, _msgSender()); return true; } else { return false; } } /** * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); if (hasRole(role, account)) { $._roles[role].hasRole[account] = false; emit RoleRevoked(role, account, _msgSender()); return true; } else { return false; } } }
// 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.1.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 EIP-1153 (transient storage) is available on the chain you're deploying at, * consider using {ReentrancyGuardTransient} instead. * * 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 v5.1.0) (utils/introspection/ERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` */ abstract contract ERC165Upgradeable is Initializable, IERC165 { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol) pragma solidity ^0.8.20; /** * @dev External interface of AccessControl declared to support ERC-165 detection. */ interface IAccessControl { /** * @dev The `account` is missing a role. */ error AccessControlUnauthorizedAccount(address account, bytes32 neededRole); /** * @dev The caller of a function is not the expected one. * * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}. */ error AccessControlBadConfirmation(); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role). * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `callerConfirmation`. */ function renounceRole(bytes32 role, address callerConfirmation) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {Context} from "../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. * * 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 Ownable is Context { address private _owner; /** * @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. */ constructor(address initialOwner) { 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) { 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 { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC165} from "./IERC165.sol"; /** * @title IERC1363 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363]. * * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction. */ interface IERC1363 is IERC20, IERC165 { /* * Note: the ERC-165 identifier for this interface is 0xb0202a11. * 0xb0202a11 === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^ * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @dev Moves a `value` amount of tokens from the caller's account to `to` * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from the caller's account to `to` * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @param data Additional data with no specified format, sent in call to `to`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param from The address which you want to send tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferFromAndCall(address from, address to, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param from The address which you want to send tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @param data Additional data with no specified format, sent in call to `to`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @param data Additional data with no specified format, sent in call to `spender`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol) pragma solidity ^0.8.20; /** * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. */ 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 (last updated v5.0.0) (interfaces/IERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Proxy.sol) pragma solidity ^0.8.20; import {Proxy} from "../Proxy.sol"; import {ERC1967Utils} from "./ERC1967Utils.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[ERC-1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`. * * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor. * * Requirements: * * - If `data` is empty, `msg.value` must be zero. */ constructor(address implementation, bytes memory _data) payable { ERC1967Utils.upgradeToAndCall(implementation, _data); } /** * @dev Returns the current implementation address. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function _implementation() internal view virtual override returns (address) { return ERC1967Utils.getImplementation(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol) pragma solidity ^0.8.21; import {IBeacon} from "../beacon/IBeacon.sol"; import {IERC1967} from "../../interfaces/IERC1967.sol"; import {Address} from "../../utils/Address.sol"; import {StorageSlot} from "../../utils/StorageSlot.sol"; /** * @dev This library provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots. */ library ERC1967Utils { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev The `implementation` of the proxy is invalid. */ error ERC1967InvalidImplementation(address implementation); /** * @dev The `admin` of the proxy is invalid. */ error ERC1967InvalidAdmin(address admin); /** * @dev The `beacon` of the proxy is invalid. */ error ERC1967InvalidBeacon(address beacon); /** * @dev An upgrade function sees `msg.value > 0` that may be lost. */ error ERC1967NonPayable(); /** * @dev Returns the current implementation address. */ function getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the ERC-1967 implementation slot. */ function _setImplementation(address newImplementation) private { if (newImplementation.code.length == 0) { revert ERC1967InvalidImplementation(newImplementation); } StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Performs implementation upgrade with additional setup call if data is nonempty. * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected * to avoid stuck value in the contract. * * Emits an {IERC1967-Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) internal { _setImplementation(newImplementation); emit IERC1967.Upgraded(newImplementation); if (data.length > 0) { Address.functionDelegateCall(newImplementation, data); } else { _checkNonPayable(); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(ADMIN_SLOT).value; } /** * @dev Stores a new address in the ERC-1967 admin slot. */ function _setAdmin(address newAdmin) private { if (newAdmin == address(0)) { revert ERC1967InvalidAdmin(address(0)); } StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {IERC1967-AdminChanged} event. */ function changeAdmin(address newAdmin) internal { emit IERC1967.AdminChanged(getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Returns the current beacon. */ function getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(BEACON_SLOT).value; } /** * @dev Stores a new beacon in the ERC-1967 beacon slot. */ function _setBeacon(address newBeacon) private { if (newBeacon.code.length == 0) { revert ERC1967InvalidBeacon(newBeacon); } StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon; address beaconImplementation = IBeacon(newBeacon).implementation(); if (beaconImplementation.code.length == 0) { revert ERC1967InvalidImplementation(beaconImplementation); } } /** * @dev Change the beacon and trigger a setup call if data is nonempty. * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected * to avoid stuck value in the contract. * * Emits an {IERC1967-BeaconUpgraded} event. * * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for * efficiency. */ function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal { _setBeacon(newBeacon); emit IERC1967.BeaconUpgraded(newBeacon); if (data.length > 0) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } else { _checkNonPayable(); } } /** * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract * if an upgrade doesn't perform an initialization call. */ function _checkNonPayable() private { if (msg.value > 0) { revert ERC1967NonPayable(); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol) pragma solidity ^0.8.20; /** * @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 { _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(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.20; /** * @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. * * {UpgradeableBeacon} will check that this address is a contract. */ function implementation() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (proxy/transparent/ProxyAdmin.sol) pragma solidity ^0.8.20; import {ITransparentUpgradeableProxy} from "./TransparentUpgradeableProxy.sol"; import {Ownable} from "../../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 The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address,address)` * and `upgradeAndCall(address,address,bytes)` are present, and `upgrade` must be used if no function should be called, * while `upgradeAndCall` will invoke the `receive` function if the third argument is the empty byte string. * If the getter returns `"5.0.0"`, only `upgradeAndCall(address,address,bytes)` is present, and the third argument must * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function * during an upgrade. */ string public constant UPGRADE_INTERFACE_VERSION = "5.0.0"; /** * @dev Sets the initial owner who can perform upgrades. */ constructor(address initialOwner) Ownable(initialOwner) {} /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. * - If `data` is empty, `msg.value` must be zero. */ 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 v5.1.0) (proxy/transparent/TransparentUpgradeableProxy.sol) pragma solidity ^0.8.20; import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol"; import {ERC1967Proxy} from "../ERC1967/ERC1967Proxy.sol"; import {IERC1967} from "../../interfaces/IERC1967.sol"; import {ProxyAdmin} from "./ProxyAdmin.sol"; /** * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy} * does not implement this interface directly, and its upgradeability mechanism is 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 { /// @dev See {UUPSUpgradeable-upgradeToAndCall} function upgradeToAndCall(address newImplementation, bytes calldata data) external payable; } /** * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance. * * 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 the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself. * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating * the proxy admin cannot fallback to the target implementation. * * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership. * * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the * implementation. * * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract. * * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot * is generally fine if the implementation is trusted. * * 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 `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency. */ contract TransparentUpgradeableProxy is ERC1967Proxy { // An immutable address for the admin to avoid unnecessary SLOADs before each call // at the expense of removing the ability to change the admin once it's set. // This is acceptable if the admin is always a ProxyAdmin instance or similar contract // with its own ability to transfer the permissions to another account. address private immutable _admin; /** * @dev The proxy caller is the current admin, and can't fallback to the proxy target. */ error ProxyDeniedAdminAccess(); /** * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`, * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in * {ERC1967Proxy-constructor}. */ constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) { _admin = address(new ProxyAdmin(initialOwner)); // Set the storage value and emit an event for ERC-1967 compatibility ERC1967Utils.changeAdmin(_proxyAdmin()); } /** * @dev Returns the admin of this proxy. */ function _proxyAdmin() internal view virtual returns (address) { return _admin; } /** * @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 == _proxyAdmin()) { if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) { revert ProxyDeniedAdminAccess(); } else { _dispatchUpgradeToAndCall(); } } else { super._fallback(); } } /** * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}. * * Requirements: * * - If `data` is empty, `msg.value` must be zero. */ function _dispatchUpgradeToAndCall() private { (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes)); ERC1967Utils.upgradeToAndCall(newImplementation, data); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-20 standard as defined in the ERC. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` 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 value) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; import {IERC1363} from "../../../interfaces/IERC1363.sol"; import {Address} from "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC-20 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 { /** * @dev An operation with an ERC-20 token failed. */ error SafeERC20FailedOperation(address token); /** * @dev Indicates a failed `decreaseAllowance` request. */ error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value))); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. * * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); forceApprove(token, spender, oldAllowance + value); } /** * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no * value, non-reverting calls are assumed to be successful. * * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal { unchecked { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance < requestedDecrease) { revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); } forceApprove(token, spender, currentAllowance - requestedDecrease); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval * to be set to zero before setting it to a non-zero value, such as USDT. * * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being * set here. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); _callOptionalReturn(token, approvalCall); } } /** * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * Reverts if the returned value is other than `true`. */ function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { if (to.code.length == 0) { safeTransfer(token, to, value); } else if (!token.transferAndCall(to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * Reverts if the returned value is other than `true`. */ function transferFromAndCallRelaxed( IERC1363 token, address from, address to, uint256 value, bytes memory data ) internal { if (to.code.length == 0) { safeTransferFrom(token, from, to, value); } else if (!token.transferFromAndCall(from, to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}. * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall} * once without retrying, and relies on the returned value to be true. * * Reverts if the returned value is other than `true`. */ function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { if (to.code.length == 0) { forceApprove(token, to, value); } else if (!token.approveAndCall(to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements. */ function _callOptionalReturn(IERC20 token, bytes memory data) private { uint256 returnSize; uint256 returnValue; assembly ("memory-safe") { let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20) // bubble errors if iszero(success) { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize()) revert(ptr, returndatasize()) } returnSize := returndatasize() returnValue := mload(0) } if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { bool success; uint256 returnSize; uint256 returnValue; assembly ("memory-safe") { success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20) returnSize := returndatasize() returnValue := mload(0) } return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol) pragma solidity ^0.8.20; import {Errors} from "./Errors.sol"; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev There's no code at `target` (it is not a contract). */ error AddressEmptyCode(address target); /** * @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) { revert Errors.InsufficientBalance(address(this).balance, amount); } (bool success, ) = recipient.call{value: amount}(""); if (!success) { revert Errors.FailedCall(); } } /** * @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 or custom error, it is bubbled * up by this function (like regular Solidity function calls). However, if * the call reverted with no returned reason, this function reverts with a * {Errors.FailedCall} error. * * 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. */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0); } /** * @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`. */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { if (address(this).balance < value) { revert Errors.InsufficientBalance(address(this).balance, value); } (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case * of an unsuccessful call. */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata ) internal view returns (bytes memory) { if (!success) { _revert(returndata); } else { // only check if target is a contract if the call was successful and the return data is empty // otherwise we already know that it was a contract if (returndata.length == 0 && target.code.length == 0) { revert AddressEmptyCode(target); } return returndata; } } /** * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the * revert reason or with a default {Errors.FailedCall} error. */ function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) { if (!success) { _revert(returndata); } else { return returndata; } } /** * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}. */ function _revert(bytes memory returndata) 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 assembly ("memory-safe") { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert Errors.FailedCall(); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; /** * @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 v5.1.0) (utils/Errors.sol) pragma solidity ^0.8.20; /** * @dev Collection of common custom errors used in multiple contracts * * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library. * It is recommended to avoid relying on the error API for critical functionality. * * _Available since v5.1._ */ library Errors { /** * @dev The ETH balance of the account is not enough to perform the operation. */ error InsufficientBalance(uint256 balance, uint256 needed); /** * @dev A call to an address target failed. The target may have reverted. */ error FailedCall(); /** * @dev The deployment failed. */ error FailedDeployment(); /** * @dev A necessary precompile is missing. */ error MissingPrecompile(address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. pragma solidity ^0.8.20; /** * @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 ERC-1967 implementation slot: * ```solidity * contract ERC1967 { * // Define the slot. Alternatively, use the SlotDerivation library to derive the slot. * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(newImplementation.code.length > 0); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * TIP: Consider using this library along with {SlotDerivation}. */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct Int256Slot { int256 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) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Int256Slot` with member `value` located at `slot`. */ function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { assembly ("memory-safe") { 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) { assembly ("memory-safe") { r.slot := store.slot } } /** * @dev Returns a `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { assembly ("memory-safe") { 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) { assembly ("memory-safe") { r.slot := store.slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[ERC]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // Chainlink Contracts v0.8 pragma solidity ^0.8.0; interface AggregatorInterface { function decimals() external view returns (uint8); function description() external view returns (string memory); function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); }
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.10; import {IERC20} from '../../openzeppelin/contracts/IERC20.sol'; /// @title Gnosis Protocol v2 Safe ERC20 Transfer Library /// @author Gnosis Developers /// @dev Gas-efficient version of Openzeppelin's SafeERC20 contract. library GPv2SafeERC20 { /// @dev Wrapper around a call to the ERC20 function `transfer` that reverts /// also when the token returns `false`. function safeTransfer(IERC20 token, address to, uint256 value) internal { bytes4 selector_ = token.transfer.selector; // solhint-disable-next-line no-inline-assembly assembly { let freeMemoryPointer := mload(0x40) mstore(freeMemoryPointer, selector_) mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(freeMemoryPointer, 36), value) if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } require(getLastTransferResult(token), 'GPv2: failed transfer'); } /// @dev Wrapper around a call to the ERC20 function `transferFrom` that /// reverts also when the token returns `false`. function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { bytes4 selector_ = token.transferFrom.selector; // solhint-disable-next-line no-inline-assembly assembly { let freeMemoryPointer := mload(0x40) mstore(freeMemoryPointer, selector_) mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(freeMemoryPointer, 68), value) if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } require(getLastTransferResult(token), 'GPv2: failed transferFrom'); } /// @dev Verifies that the last return was a successful `transfer*` call. /// This is done by checking that the return data is either empty, or /// is a valid ABI encoded boolean. function getLastTransferResult(IERC20 token) private view returns (bool success) { // NOTE: Inspecting previous return data requires assembly. Note that // we write the return data to memory 0 in the case where the return // data size is 32, this is OK since the first 64 bytes of memory are // reserved by Solidy as a scratch space that can be used within // assembly blocks. // <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html> // solhint-disable-next-line no-inline-assembly assembly { /// @dev Revert with an ABI encoded Solidity error with a message /// that fits into 32-bytes. /// /// An ABI encoded Solidity error has the following memory layout: /// /// ------------+---------------------------------- /// byte range | value /// ------------+---------------------------------- /// 0x00..0x04 | selector("Error(string)") /// 0x04..0x24 | string offset (always 0x20) /// 0x24..0x44 | string length /// 0x44..0x64 | string value, padded to 32-bytes function revertWithMessage(length, message) { mstore(0x00, '\x08\xc3\x79\xa0') mstore(0x04, 0x20) mstore(0x24, length) mstore(0x44, message) revert(0x00, 0x64) } switch returndatasize() // Non-standard ERC20 transfer without return. case 0 { // NOTE: When the return data size is 0, verify that there // is code at the address. This is done in order to maintain // compatibility with Solidity calling conventions. // <https://docs.soliditylang.org/en/v0.7.6/control-structures.html#external-function-calls> if iszero(extcodesize(token)) { revertWithMessage(20, 'GPv2: not a contract') } success := 1 } // Standard ERC20 transfer returning boolean success value. case 32 { returndatacopy(0, 0, returndatasize()) // NOTE: For ABI encoding v1, any non-zero value is accepted // as `true` for a boolean. In order to stay compatible with // OpenZeppelin's `SafeERC20` library which is known to work // with the existing ERC20 implementation we care about, // make sure we return success for any non-zero return value // from the `transfer*` call. success := iszero(iszero(mload(0))) } default { revertWithMessage(31, 'GPv2: malformed transfer result') } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @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 ReentrancyGuard { // 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; uint256 private _status; constructor() { _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() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, 'ReentrancyGuard: reentrant call'); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev As we use the guard with the proxy we need to init it with the empty value */ function _initGuard() internal { _status = _NOT_ENTERED; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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 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) { require(isContract(target), 'Address: delegate call to non-contract'); (bool success, bytes memory returndata) = target.delegatecall(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 pragma solidity ^0.8.10; /* * @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 GSN 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 payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, 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 pragma solidity ^0.8.10; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import './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. */ 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() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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 { emit OwnershipTransferred(_owner, address(0)); _owner = 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'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) pragma solidity ^0.8.10; /** * @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 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 */ 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 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 */ 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 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 */ 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 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 */ 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 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 */ 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 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 */ 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. */ 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. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, 'SafeCast: value must be positive'); return uint256(value); } /** * @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) { require( value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits" ); return int128(value); } /** * @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) { require( value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits" ); return int64(value); } /** * @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) { require( value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits" ); return int32(value); } /** * @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) { require( value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits" ); return int16(value); } /** * @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) { require( value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits" ); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ 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 v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import './IERC20.sol'; import './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; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } 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)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } 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'); uint256 newAllowance = oldAllowance - value; _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } } /** * @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'); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library SafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { require((z = x + y) >= x); } } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { require((z = x - y) <= x); } } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @param message The error msg /// @return z The difference of x and y function sub(uint256 x, uint256 y, string memory message) internal pure returns (uint256 z) { unchecked { require((z = x - y) <= x, message); } } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { require(x == 0 || (z = x * y) / x == y); } } /// @notice Returns x / y, reverts if overflows - no specific check, solidity reverts on division by 0 /// @param x The numerator /// @param y The denominator /// @return z The product of x and y function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {DataTypes} from '../../protocol/libraries/types/DataTypes.sol'; import {FlashLoanSimpleReceiverBase} from '../../misc/flashloan/base/FlashLoanSimpleReceiverBase.sol'; import {GPv2SafeERC20} from '../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {IERC20WithPermit} from '../../interfaces/IERC20WithPermit.sol'; import {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; /** * @title BaseParaSwapAdapter * @notice Utility functions for adapters using ParaSwap * @author Jason Raymond Bell */ abstract contract BaseParaSwapAdapter is FlashLoanSimpleReceiverBase, Ownable { using SafeMath for uint256; using GPv2SafeERC20 for IERC20; using GPv2SafeERC20 for IERC20Detailed; using GPv2SafeERC20 for IERC20WithPermit; struct PermitSignature { uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } // Max slippage percent allowed uint256 public constant MAX_SLIPPAGE_PERCENT = 3000; // 30% IPriceOracleGetter public immutable ORACLE; event Swapped( address indexed fromAsset, address indexed toAsset, uint256 fromAmount, uint256 receivedAmount ); event Bought( address indexed fromAsset, address indexed toAsset, uint256 amountSold, uint256 receivedAmount ); constructor( IPoolAddressesProvider addressesProvider ) FlashLoanSimpleReceiverBase(addressesProvider) { ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle()); } /** * @dev Get the price of the asset from the oracle denominated in eth * @param asset address * @return eth price for the asset */ function _getPrice(address asset) internal view returns (uint256) { return ORACLE.getAssetPrice(asset); } /** * @dev Get the decimals of an asset * @return number of decimals of the asset */ function _getDecimals(IERC20Detailed asset) internal view returns (uint8) { uint8 decimals = asset.decimals(); // Ensure 10**decimals won't overflow a uint256 require(decimals <= 77, 'TOO_MANY_DECIMALS_ON_TOKEN'); return decimals; } function _pullATokenAndWithdraw( address reserve, address user, uint256 amount, PermitSignature memory permitSignature ) internal { IERC20WithPermit reserveAToken = IERC20WithPermit(POOL.getReserveAToken(reserve)); _pullATokenAndWithdraw(reserve, reserveAToken, user, amount, permitSignature); } /** * @dev Pull the ATokens from the user * @param reserve address of the asset * @param reserveAToken address of the aToken of the reserve * @param user address * @param amount of tokens to be transferred to the contract * @param permitSignature struct containing the permit signature */ function _pullATokenAndWithdraw( address reserve, IERC20WithPermit reserveAToken, address user, uint256 amount, PermitSignature memory permitSignature ) internal { // If deadline is set to zero, assume there is no signature for permit if (permitSignature.deadline != 0) { reserveAToken.permit( user, address(this), permitSignature.amount, permitSignature.deadline, permitSignature.v, permitSignature.r, permitSignature.s ); } // transfer from user to adapter reserveAToken.safeTransferFrom(user, address(this), amount); // withdraw reserve require(POOL.withdraw(reserve, amount, address(this)) == amount, 'UNEXPECTED_AMOUNT_WITHDRAWN'); } /** * @dev Emergency rescue for token stucked on this contract, as failsafe mechanism * - Funds should never remain in this contract more time than during transactions * - Only callable by the owner */ function rescueTokens(IERC20 token) external onlyOwner { token.safeTransfer(owner(), token.balanceOf(address(this))); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {PercentageMath} from '../../protocol/libraries/math/PercentageMath.sol'; import {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol'; import {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol'; import {BaseParaSwapAdapter} from './BaseParaSwapAdapter.sol'; /** * @title BaseParaSwapBuyAdapter * @notice Implements the logic for buying tokens on ParaSwap */ abstract contract BaseParaSwapBuyAdapter is BaseParaSwapAdapter { using PercentageMath for uint256; using SafeMath for uint256; using SafeERC20 for IERC20Detailed; IParaSwapAugustusRegistry public immutable AUGUSTUS_REGISTRY; constructor( IPoolAddressesProvider addressesProvider, IParaSwapAugustusRegistry augustusRegistry ) BaseParaSwapAdapter(addressesProvider) { // Do something on Augustus registry to check the right contract was passed require(!augustusRegistry.isValidAugustus(address(0)), 'Not a valid Augustus address'); AUGUSTUS_REGISTRY = augustusRegistry; } /** * @dev Swaps a token for another using ParaSwap * @param toAmountOffset Offset of toAmount in Augustus calldata if it should be overwritten, otherwise 0 * @param paraswapData Data for Paraswap Adapter * @param assetToSwapFrom Address of the asset to be swapped from * @param assetToSwapTo Address of the asset to be swapped to * @param maxAmountToSwap Max amount to be swapped * @param amountToReceive Amount to be received from the swap * @return amountSold The amount sold during the swap * @return amountBought The amount bought during the swap */ function _buyOnParaSwap( uint256 toAmountOffset, bytes memory paraswapData, IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive ) internal returns (uint256 amountSold, uint256 amountBought) { (bytes memory buyCalldata, IParaSwapAugustus augustus) = abi.decode( paraswapData, (bytes, IParaSwapAugustus) ); require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS'); { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom)); uint256 toAssetPrice = _getPrice(address(assetToSwapTo)); uint256 expectedMaxAmountToSwap = amountToReceive .mul(toAssetPrice.mul(10 ** fromAssetDecimals)) .div(fromAssetPrice.mul(10 ** toAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT)); require(maxAmountToSwap <= expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); } uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this)); require(balanceBeforeAssetFrom >= maxAmountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP'); uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this)); address tokenTransferProxy = augustus.getTokenTransferProxy(); assetToSwapFrom.safeApprove(tokenTransferProxy, maxAmountToSwap); if (toAmountOffset != 0) { // Ensure 256 bit (32 bytes) toAmountOffset value is within bounds of the // calldata, not overlapping with the first 4 bytes (function selector). require( toAmountOffset >= 4 && toAmountOffset <= buyCalldata.length.sub(32), 'TO_AMOUNT_OFFSET_OUT_OF_RANGE' ); // Overwrite the toAmount with the correct amount for the buy. // In memory, buyCalldata consists of a 256 bit length field, followed by // the actual bytes data, that is why 32 is added to the byte offset. assembly { mstore(add(buyCalldata, add(toAmountOffset, 32)), amountToReceive) } } (bool success, ) = address(augustus).call(buyCalldata); if (!success) { // Copy revert reason from call assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } // Reset allowance assetToSwapFrom.safeApprove(tokenTransferProxy, 0); uint256 balanceAfterAssetFrom = assetToSwapFrom.balanceOf(address(this)); amountSold = balanceBeforeAssetFrom - balanceAfterAssetFrom; require(amountSold <= maxAmountToSwap, 'WRONG_BALANCE_AFTER_SWAP'); amountBought = assetToSwapTo.balanceOf(address(this)).sub(balanceBeforeAssetTo); require(amountBought >= amountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED'); emit Bought(address(assetToSwapFrom), address(assetToSwapTo), amountSold, amountBought); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {PercentageMath} from '../../protocol/libraries/math/PercentageMath.sol'; import {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol'; import {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol'; import {BaseParaSwapAdapter} from './BaseParaSwapAdapter.sol'; /** * @title BaseParaSwapSellAdapter * @notice Implements the logic for selling tokens on ParaSwap * @author Jason Raymond Bell */ abstract contract BaseParaSwapSellAdapter is BaseParaSwapAdapter { using PercentageMath for uint256; using SafeMath for uint256; using SafeERC20 for IERC20Detailed; IParaSwapAugustusRegistry public immutable AUGUSTUS_REGISTRY; constructor( IPoolAddressesProvider addressesProvider, IParaSwapAugustusRegistry augustusRegistry ) BaseParaSwapAdapter(addressesProvider) { // Do something on Augustus registry to check the right contract was passed require(!augustusRegistry.isValidAugustus(address(0))); AUGUSTUS_REGISTRY = augustusRegistry; } /** * @dev Swaps a token for another using ParaSwap * @param fromAmountOffset Offset of fromAmount in Augustus calldata if it should be overwritten, otherwise 0 * @param swapCalldata Calldata for ParaSwap's AugustusSwapper contract * @param augustus Address of ParaSwap's AugustusSwapper contract * @param assetToSwapFrom Address of the asset to be swapped from * @param assetToSwapTo Address of the asset to be swapped to * @param amountToSwap Amount to be swapped * @param minAmountToReceive Minimum amount to be received from the swap * @return amountReceived The amount received from the swap */ function _sellOnParaSwap( uint256 fromAmountOffset, bytes memory swapCalldata, IParaSwapAugustus augustus, IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 amountToSwap, uint256 minAmountToReceive ) internal returns (uint256 amountReceived) { require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS'); { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom)); uint256 toAssetPrice = _getPrice(address(assetToSwapTo)); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10 ** toAssetDecimals)) .div(toAssetPrice.mul(10 ** fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR - MAX_SLIPPAGE_PERCENT); require(expectedMinAmountOut <= minAmountToReceive, 'MIN_AMOUNT_EXCEEDS_MAX_SLIPPAGE'); } uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this)); require(balanceBeforeAssetFrom >= amountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP'); uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this)); address tokenTransferProxy = augustus.getTokenTransferProxy(); assetToSwapFrom.safeApprove(tokenTransferProxy, 0); assetToSwapFrom.safeApprove(tokenTransferProxy, amountToSwap); if (fromAmountOffset != 0) { // Ensure 256 bit (32 bytes) fromAmount value is within bounds of the // calldata, not overlapping with the first 4 bytes (function selector). require( fromAmountOffset >= 4 && fromAmountOffset <= swapCalldata.length.sub(32), 'FROM_AMOUNT_OFFSET_OUT_OF_RANGE' ); // Overwrite the fromAmount with the correct amount for the swap. // In memory, swapCalldata consists of a 256 bit length field, followed by // the actual bytes data, that is why 32 is added to the byte offset. assembly { mstore(add(swapCalldata, add(fromAmountOffset, 32)), amountToSwap) } } (bool success, ) = address(augustus).call(swapCalldata); if (!success) { // Copy revert reason from call assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } require( assetToSwapFrom.balanceOf(address(this)) == balanceBeforeAssetFrom - amountToSwap, 'WRONG_BALANCE_AFTER_SWAP' ); amountReceived = assetToSwapTo.balanceOf(address(this)).sub(balanceBeforeAssetTo); require(amountReceived >= minAmountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED'); emit Swapped(address(assetToSwapFrom), address(assetToSwapTo), amountToSwap, amountReceived); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {IERC20WithPermit} from '../../interfaces/IERC20WithPermit.sol'; import {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {BaseParaSwapSellAdapter} from './BaseParaSwapSellAdapter.sol'; import {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol'; import {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol'; import {ReentrancyGuard} from '../../dependencies/openzeppelin/ReentrancyGuard.sol'; /** * @title ParaSwapLiquiditySwapAdapter * @notice Adapter to swap liquidity using ParaSwap. * @author Jason Raymond Bell */ contract ParaSwapLiquiditySwapAdapter is BaseParaSwapSellAdapter, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20Detailed; constructor( IPoolAddressesProvider addressesProvider, IParaSwapAugustusRegistry augustusRegistry, address owner ) BaseParaSwapSellAdapter(addressesProvider, augustusRegistry) { transferOwnership(owner); } /** * @dev Swaps the received reserve amount from the flash loan into the asset specified in the params. * The received funds from the swap are then deposited into the protocol on behalf of the user. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and repay the flash loan. * @param asset The address of the flash-borrowed asset * @param amount The amount of the flash-borrowed asset * @param premium The fee of the flash-borrowed asset * @param initiator The address of the flashloan initiator * @param params The byte-encoded params passed when initiating the flashloan * @return True if the execution of the operation succeeds, false otherwise * address assetToSwapTo Address of the underlying asset to be swapped to and deposited * uint256 minAmountToReceive Min amount to be received from the swap * uint256 swapAllBalanceOffset Set to offset of fromAmount in Augustus calldata if wanting to swap all balance, otherwise 0 * bytes swapCalldata Calldata for ParaSwap's AugustusSwapper contract * address augustus Address of ParaSwap's AugustusSwapper contract * PermitSignature permitParams Struct containing the permit signatures, set to all zeroes if not used */ function executeOperation( address asset, uint256 amount, uint256 premium, address initiator, bytes calldata params ) external override nonReentrant returns (bool) { require(msg.sender == address(POOL), 'CALLER_MUST_BE_POOL'); uint256 flashLoanAmount = amount; uint256 premiumLocal = premium; address initiatorLocal = initiator; IERC20Detailed assetToSwapFrom = IERC20Detailed(asset); ( IERC20Detailed assetToSwapTo, uint256 minAmountToReceive, uint256 swapAllBalanceOffset, bytes memory swapCalldata, IParaSwapAugustus augustus, PermitSignature memory permitParams ) = abi.decode( params, (IERC20Detailed, uint256, uint256, bytes, IParaSwapAugustus, PermitSignature) ); _swapLiquidity( swapAllBalanceOffset, swapCalldata, augustus, permitParams, flashLoanAmount, premiumLocal, initiatorLocal, assetToSwapFrom, assetToSwapTo, minAmountToReceive ); return true; } /** * @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using a flash loan. * This method can be used when the temporary transfer of the collateral asset to this contract does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and perform the swap. * @param assetToSwapFrom Address of the underlying asset to be swapped from * @param assetToSwapTo Address of the underlying asset to be swapped to and deposited * @param amountToSwap Amount to be swapped, or maximum amount when swapping all balance * @param minAmountToReceive Minimum amount to be received from the swap * @param swapAllBalanceOffset Set to offset of fromAmount in Augustus calldata if wanting to swap all balance, otherwise 0 * @param swapCalldata Calldata for ParaSwap's AugustusSwapper contract * @param augustus Address of ParaSwap's AugustusSwapper contract * @param permitParams Struct containing the permit signatures, set to all zeroes if not used */ function swapAndDeposit( IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 amountToSwap, uint256 minAmountToReceive, uint256 swapAllBalanceOffset, bytes calldata swapCalldata, IParaSwapAugustus augustus, PermitSignature calldata permitParams ) external nonReentrant { IERC20WithPermit aToken = IERC20WithPermit(POOL.getReserveAToken(address(assetToSwapFrom))); if (swapAllBalanceOffset != 0) { uint256 balance = aToken.balanceOf(msg.sender); require(balance <= amountToSwap, 'INSUFFICIENT_AMOUNT_TO_SWAP'); amountToSwap = balance; } _pullATokenAndWithdraw( address(assetToSwapFrom), aToken, msg.sender, amountToSwap, permitParams ); uint256 amountReceived = _sellOnParaSwap( swapAllBalanceOffset, swapCalldata, augustus, assetToSwapFrom, assetToSwapTo, amountToSwap, minAmountToReceive ); assetToSwapTo.safeApprove(address(POOL), 0); assetToSwapTo.safeApprove(address(POOL), amountReceived); POOL.deposit(address(assetToSwapTo), amountReceived, msg.sender, 0); } /** * @dev Swaps an amount of an asset to another and deposits the funds on behalf of the initiator. * @param swapAllBalanceOffset Set to offset of fromAmount in Augustus calldata if wanting to swap all balance, otherwise 0 * @param swapCalldata Calldata for ParaSwap's AugustusSwapper contract * @param augustus Address of ParaSwap's AugustusSwapper contract * @param permitParams Struct containing the permit signatures, set to all zeroes if not used * @param flashLoanAmount Amount of the flash loan i.e. maximum amount to swap * @param premium Fee of the flash loan * @param initiator Account that initiated the flash loan * @param assetToSwapFrom Address of the underyling asset to be swapped from * @param assetToSwapTo Address of the underlying asset to be swapped to and deposited * @param minAmountToReceive Min amount to be received from the swap */ function _swapLiquidity( uint256 swapAllBalanceOffset, bytes memory swapCalldata, IParaSwapAugustus augustus, PermitSignature memory permitParams, uint256 flashLoanAmount, uint256 premium, address initiator, IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 minAmountToReceive ) internal { IERC20WithPermit aToken = IERC20WithPermit(POOL.getReserveAToken(address(assetToSwapFrom))); uint256 amountToSwap = flashLoanAmount; uint256 balance = aToken.balanceOf(initiator); if (swapAllBalanceOffset != 0) { uint256 balanceToSwap = balance.sub(premium); require(balanceToSwap <= amountToSwap, 'INSUFFICIENT_AMOUNT_TO_SWAP'); amountToSwap = balanceToSwap; } else { require(balance >= amountToSwap.add(premium), 'INSUFFICIENT_ATOKEN_BALANCE'); } uint256 amountReceived = _sellOnParaSwap( swapAllBalanceOffset, swapCalldata, augustus, assetToSwapFrom, assetToSwapTo, amountToSwap, minAmountToReceive ); assetToSwapTo.safeApprove(address(POOL), 0); assetToSwapTo.safeApprove(address(POOL), amountReceived); POOL.deposit(address(assetToSwapTo), amountReceived, initiator, 0); _pullATokenAndWithdraw( address(assetToSwapFrom), aToken, initiator, amountToSwap.add(premium), permitParams ); // Repay flash loan assetToSwapFrom.safeApprove(address(POOL), 0); assetToSwapFrom.safeApprove(address(POOL), flashLoanAmount.add(premium)); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {DataTypes} from '../../protocol/libraries/types/DataTypes.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20WithPermit} from '../../interfaces/IERC20WithPermit.sol'; import {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {BaseParaSwapBuyAdapter} from './BaseParaSwapBuyAdapter.sol'; import {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol'; import {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol'; import {ReentrancyGuard} from '../../dependencies/openzeppelin/ReentrancyGuard.sol'; /** * @title ParaSwapRepayAdapter * @notice ParaSwap Adapter to perform a repay of a debt with collateral. * @author Aave **/ contract ParaSwapRepayAdapter is BaseParaSwapBuyAdapter, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; struct RepayParams { address collateralAsset; uint256 collateralAmount; uint256 rateMode; PermitSignature permitSignature; bool useEthPath; } constructor( IPoolAddressesProvider addressesProvider, IParaSwapAugustusRegistry augustusRegistry, address owner ) BaseParaSwapBuyAdapter(addressesProvider, augustusRegistry) { transferOwnership(owner); } /** * @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls * the collateral from the user and swaps it to the debt asset to repay the flash loan. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it * and repay the flash loan. * Supports only one asset on the flash loan. * @param asset The address of the flash-borrowed asset * @param amount The amount of the flash-borrowed asset * @param premium The fee of the flash-borrowed asset * @param initiator The address of the flashloan initiator * @param params The byte-encoded params passed when initiating the flashloan * @return True if the execution of the operation succeeds, false otherwise * IERC20Detailed debtAsset Address of the debt asset * uint256 debtAmount Amount of debt to be repaid * uint256 rateMode Rate modes of the debt to be repaid * uint256 deadline Deadline for the permit signature * uint256 debtRateMode Rate mode of the debt to be repaid * bytes paraswapData Paraswap Data * * bytes buyCallData Call data for augustus * * IParaSwapAugustus augustus Address of Augustus Swapper * PermitSignature permitParams Struct containing the permit signatures, set to all zeroes if not used */ function executeOperation( address asset, uint256 amount, uint256 premium, address initiator, bytes calldata params ) external override nonReentrant returns (bool) { require(msg.sender == address(POOL), 'CALLER_MUST_BE_POOL'); uint256 collateralAmount = amount; address initiatorLocal = initiator; IERC20Detailed collateralAsset = IERC20Detailed(asset); _swapAndRepay(params, premium, initiatorLocal, collateralAsset, collateralAmount); return true; } /** * @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user * without using flash loans. This method can be used when the temporary transfer of the collateral asset to this * contract does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset * @param collateralAsset Address of asset to be swapped * @param debtAsset Address of debt asset * @param collateralAmount max Amount of the collateral to be swapped * @param debtRepayAmount Amount of the debt to be repaid, or maximum amount when repaying entire debt * @param debtRateMode Rate mode of the debt to be repaid * @param buyAllBalanceOffset Set to offset of toAmount in Augustus calldata if wanting to pay entire debt, otherwise 0 * @param paraswapData Data for Paraswap Adapter * @param permitSignature struct containing the permit signature */ function swapAndRepay( IERC20Detailed collateralAsset, IERC20Detailed debtAsset, uint256 collateralAmount, uint256 debtRepayAmount, uint256 debtRateMode, uint256 buyAllBalanceOffset, bytes calldata paraswapData, PermitSignature calldata permitSignature ) external nonReentrant { debtRepayAmount = getDebtRepayAmount( debtAsset, debtRateMode, buyAllBalanceOffset, debtRepayAmount, msg.sender ); // Pull aTokens from user _pullATokenAndWithdraw(address(collateralAsset), msg.sender, collateralAmount, permitSignature); //buy debt asset using collateral asset (uint256 amountSold, uint256 amountBought) = _buyOnParaSwap( buyAllBalanceOffset, paraswapData, collateralAsset, debtAsset, collateralAmount, debtRepayAmount ); uint256 collateralBalanceLeft = collateralAmount - amountSold; //deposit collateral back in the pool, if left after the swap(buy) if (collateralBalanceLeft > 0) { IERC20(collateralAsset).safeApprove(address(POOL), collateralBalanceLeft); POOL.deposit(address(collateralAsset), collateralBalanceLeft, msg.sender, 0); IERC20(collateralAsset).safeApprove(address(POOL), 0); } // Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix IERC20(debtAsset).safeApprove(address(POOL), debtRepayAmount); POOL.repay(address(debtAsset), debtRepayAmount, debtRateMode, msg.sender); IERC20(debtAsset).safeApprove(address(POOL), 0); { //transfer excess of debtAsset back to the user, if any uint256 debtAssetExcess = amountBought - debtRepayAmount; if (debtAssetExcess > 0) { IERC20(debtAsset).safeTransfer(msg.sender, debtAssetExcess); } } } /** * @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan * @param premium Fee of the flash loan * @param initiator Address of the user * @param collateralAsset Address of token to be swapped * @param collateralAmount Amount of the reserve to be swapped(flash loan amount) */ function _swapAndRepay( bytes calldata params, uint256 premium, address initiator, IERC20Detailed collateralAsset, uint256 collateralAmount ) private { ( IERC20Detailed debtAsset, uint256 debtRepayAmount, uint256 buyAllBalanceOffset, uint256 rateMode, bytes memory paraswapData, PermitSignature memory permitSignature ) = abi.decode(params, (IERC20Detailed, uint256, uint256, uint256, bytes, PermitSignature)); debtRepayAmount = getDebtRepayAmount( debtAsset, rateMode, buyAllBalanceOffset, debtRepayAmount, initiator ); (uint256 amountSold, uint256 amountBought) = _buyOnParaSwap( buyAllBalanceOffset, paraswapData, collateralAsset, debtAsset, collateralAmount, debtRepayAmount ); // Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(POOL), debtRepayAmount); POOL.repay(address(debtAsset), debtRepayAmount, rateMode, initiator); IERC20(debtAsset).safeApprove(address(POOL), 0); uint256 neededForFlashLoanRepay = amountSold.add(premium); // Pull aTokens from user _pullATokenAndWithdraw( address(collateralAsset), initiator, neededForFlashLoanRepay, permitSignature ); { //transfer excess of debtAsset back to the user, if any uint256 debtAssetExcess = amountBought - debtRepayAmount; if (debtAssetExcess > 0) { IERC20(debtAsset).safeTransfer(initiator, debtAssetExcess); } } // Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(collateralAsset).safeApprove(address(POOL), 0); IERC20(collateralAsset).safeApprove(address(POOL), collateralAmount.add(premium)); } function getDebtRepayAmount( IERC20Detailed debtAsset, uint256 rateMode, uint256 buyAllBalanceOffset, uint256 debtRepayAmount, address initiator ) private view returns (uint256) { require( DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE, 'INVALID_RATE_MODE' ); address variableDebtTokenAddress = POOL.getReserveVariableDebtToken(address(debtAsset)); uint256 currentDebt = IERC20(variableDebtTokenAddress).balanceOf(initiator); if (buyAllBalanceOffset != 0) { require(currentDebt <= debtRepayAmount, 'INSUFFICIENT_AMOUNT_TO_REPAY'); debtRepayAmount = currentDebt; } else { require(debtRepayAmount <= currentDebt, 'INVALID_DEBT_REPAY_AMOUNT'); } return debtRepayAmount; } }
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.10; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {IERC20WithPermit} from '../../interfaces/IERC20WithPermit.sol'; import {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol'; import {BaseParaSwapSellAdapter} from './BaseParaSwapSellAdapter.sol'; import {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol'; import {ReentrancyGuard} from '../../dependencies/openzeppelin/ReentrancyGuard.sol'; contract ParaSwapWithdrawSwapAdapter is BaseParaSwapSellAdapter, ReentrancyGuard { using SafeERC20 for IERC20Detailed; constructor( IPoolAddressesProvider addressesProvider, IParaSwapAugustusRegistry augustusRegistry, address owner ) BaseParaSwapSellAdapter(addressesProvider, augustusRegistry) { transferOwnership(owner); } function executeOperation( address, uint256, uint256, address, bytes calldata ) external override nonReentrant returns (bool) { revert('NOT_SUPPORTED'); } /** * @dev Swaps an amount of an asset to another after a withdraw and transfers the new asset to the user. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and perform the swap. * @param assetToSwapFrom Address of the underlying asset to be swapped from * @param assetToSwapTo Address of the underlying asset to be swapped to * @param amountToSwap Amount to be swapped, or maximum amount when swapping all balance * @param minAmountToReceive Minimum amount to be received from the swap * @param swapAllBalanceOffset Set to offset of fromAmount in Augustus calldata if wanting to swap all balance, otherwise 0 * @param swapCalldata Calldata for ParaSwap's AugustusSwapper contract * @param augustus Address of ParaSwap's AugustusSwapper contract * @param permitParams Struct containing the permit signatures, set to all zeroes if not used */ function withdrawAndSwap( IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 amountToSwap, uint256 minAmountToReceive, uint256 swapAllBalanceOffset, bytes calldata swapCalldata, IParaSwapAugustus augustus, PermitSignature calldata permitParams ) external nonReentrant { IERC20WithPermit aToken = IERC20WithPermit(POOL.getReserveAToken(address(assetToSwapFrom))); if (swapAllBalanceOffset != 0) { uint256 balance = aToken.balanceOf(msg.sender); require(balance <= amountToSwap, 'INSUFFICIENT_AMOUNT_TO_SWAP'); amountToSwap = balance; } _pullATokenAndWithdraw( address(assetToSwapFrom), aToken, msg.sender, amountToSwap, permitParams ); uint256 amountReceived = _sellOnParaSwap( swapAllBalanceOffset, swapCalldata, augustus, assetToSwapFrom, assetToSwapTo, amountToSwap, minAmountToReceive ); assetToSwapTo.safeTransfer(msg.sender, amountReceived); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IParaSwapAugustus { function getTokenTransferProxy() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IParaSwapAugustusRegistry { function isValidAugustus(address augustus) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {IPoolAddressesProvider} from '../interfaces/IPoolAddressesProvider.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IPool} from '../interfaces/IPool.sol'; import {IPoolDataProvider} from '../interfaces/IPoolDataProvider.sol'; /** * @title AaveProtocolDataProvider * @author Aave * @notice Peripheral contract to collect and pre-process information from the Pool. */ contract AaveProtocolDataProvider is IPoolDataProvider { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using WadRayMath for uint256; address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2; address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @inheritdoc IPoolDataProvider IPoolAddressesProvider public immutable ADDRESSES_PROVIDER; /** * @notice Constructor * @param addressesProvider The address of the PoolAddressesProvider contract */ constructor(IPoolAddressesProvider addressesProvider) { ADDRESSES_PROVIDER = addressesProvider; } /// @inheritdoc IPoolDataProvider function getAllReservesTokens() external view override returns (TokenData[] memory) { IPool pool = IPool(ADDRESSES_PROVIDER.getPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory reservesTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { if (reserves[i] == MKR) { reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]}); continue; } if (reserves[i] == ETH) { reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]}); continue; } reservesTokens[i] = TokenData({ symbol: IERC20Detailed(reserves[i]).symbol(), tokenAddress: reserves[i] }); } return reservesTokens; } /// @inheritdoc IPoolDataProvider function getAllATokens() external view override returns (TokenData[] memory) { IPool pool = IPool(ADDRESSES_PROVIDER.getPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory aTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { address aTokenAddress = pool.getReserveAToken(reserves[i]); aTokens[i] = TokenData({ symbol: IERC20Detailed(aTokenAddress).symbol(), tokenAddress: aTokenAddress }); } return aTokens; } /// @inheritdoc IPoolDataProvider function getReserveConfigurationData( address asset ) external view override returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ) { DataTypes.ReserveConfigurationMap memory configuration = IPool(ADDRESSES_PROVIDER.getPool()) .getConfiguration(asset); (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration .getParams(); (isActive, isFrozen, borrowingEnabled, ) = configuration.getFlags(); // @notice all stable debt related parameters deprecated in v3.2.0 stableBorrowRateEnabled = false; usageAsCollateralEnabled = liquidationThreshold != 0; } /// @inheritdoc IPoolDataProvider function getReserveCaps( address asset ) external view override returns (uint256 borrowCap, uint256 supplyCap) { (borrowCap, supplyCap) = IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getCaps(); } /// @inheritdoc IPoolDataProvider function getPaused(address asset) external view override returns (bool isPaused) { (, , , isPaused) = IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getFlags(); } /// @inheritdoc IPoolDataProvider function getSiloedBorrowing(address asset) external view override returns (bool) { return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getSiloedBorrowing(); } /// @inheritdoc IPoolDataProvider function getLiquidationProtocolFee(address asset) external view override returns (uint256) { return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getLiquidationProtocolFee(); } /// @inheritdoc IPoolDataProvider function getUnbackedMintCap(address asset) external view override returns (uint256) { return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getUnbackedMintCap(); } /// @inheritdoc IPoolDataProvider function getDebtCeiling(address asset) external view override returns (uint256) { return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getDebtCeiling(); } /// @inheritdoc IPoolDataProvider function getDebtCeilingDecimals() external pure override returns (uint256) { return ReserveConfiguration.DEBT_CEILING_DECIMALS; } /// @inheritdoc IPoolDataProvider function getReserveData( address asset ) external view override returns ( uint256 unbacked, uint256 accruedToTreasuryScaled, uint256 totalAToken, uint256, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256, uint256, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ) { DataTypes.ReserveDataLegacy memory reserve = IPool(ADDRESSES_PROVIDER.getPool()).getReserveData( asset ); // @notice all stable debt related parameters deprecated in v3.2.0 return ( reserve.unbacked, reserve.accruedToTreasury, IERC20Detailed(reserve.aTokenAddress).totalSupply(), 0, IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(), reserve.currentLiquidityRate, reserve.currentVariableBorrowRate, 0, 0, reserve.liquidityIndex, reserve.variableBorrowIndex, reserve.lastUpdateTimestamp ); } /// @inheritdoc IPoolDataProvider function getATokenTotalSupply(address asset) external view override returns (uint256) { address aTokenAddress = IPool(ADDRESSES_PROVIDER.getPool()).getReserveAToken(asset); return IERC20Detailed(aTokenAddress).totalSupply(); } /// @inheritdoc IPoolDataProvider function getTotalDebt(address asset) external view override returns (uint256) { address variableDebtTokenAddress = IPool(ADDRESSES_PROVIDER.getPool()) .getReserveVariableDebtToken(asset); return IERC20Detailed(variableDebtTokenAddress).totalSupply(); } /// @inheritdoc IPoolDataProvider function getUserReserveData( address asset, address user ) external view override returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ) { DataTypes.ReserveDataLegacy memory reserve = IPool(ADDRESSES_PROVIDER.getPool()).getReserveData( asset ); DataTypes.UserConfigurationMap memory userConfig = IPool(ADDRESSES_PROVIDER.getPool()) .getUserConfiguration(user); currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user); currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user); // @notice all stable debt related parameters deprecated in v3.2.0 currentStableDebt = principalStableDebt = stableBorrowRate = stableRateLastUpdated = 0; scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id); } /// @inheritdoc IPoolDataProvider function getReserveTokensAddresses( address asset ) external view override returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ) { IPool pool = IPool(ADDRESSES_PROVIDER.getPool()); // @notice all stable debt related parameters deprecated in v3.2.0 return (pool.getReserveAToken(asset), address(0), pool.getReserveVariableDebtToken(asset)); } /// @inheritdoc IPoolDataProvider function getInterestRateStrategyAddress( address asset ) external view override returns (address irStrategyAddress) { DataTypes.ReserveDataLegacy memory reserve = IPool(ADDRESSES_PROVIDER.getPool()).getReserveData( asset ); return (reserve.interestRateStrategyAddress); } /// @inheritdoc IPoolDataProvider function getFlashLoanEnabled(address asset) external view override returns (bool) { DataTypes.ReserveConfigurationMap memory configuration = IPool(ADDRESSES_PROVIDER.getPool()) .getConfiguration(asset); return configuration.getFlashLoanEnabled(); } /// @inheritdoc IPoolDataProvider function getIsVirtualAccActive(address asset) external view override returns (bool) { DataTypes.ReserveConfigurationMap memory configuration = IPool(ADDRESSES_PROVIDER.getPool()) .getConfiguration(asset); return configuration.getIsVirtualAccActive(); } /// @inheritdoc IPoolDataProvider function getVirtualUnderlyingBalance(address asset) external view override returns (uint256) { return IPool(ADDRESSES_PROVIDER.getPool()).getVirtualUnderlyingBalance(asset); } /// @inheritdoc IPoolDataProvider function getReserveDeficit(address asset) external view override returns (uint256) { return IPool(ADDRESSES_PROVIDER.getPool()).getReserveDeficit(asset); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {SafeCast} from '../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IPool} from '../interfaces/IPool.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title L2Encoder * @author Aave * @notice Helper contract to encode calldata, used to optimize calldata size in L2Pool for transaction cost reduction * only indented to help generate calldata for uses/frontends. */ contract L2Encoder { using SafeCast for uint256; IPool public immutable POOL; /** * @dev Constructor. * @param pool The address of the Pool contract */ constructor(IPool pool) { POOL = pool; } /** * @notice Encodes supply parameters from standard input to compact representation of 1 bytes32 * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf * @param asset The address of the underlying asset to supply * @param amount The amount to be supplied * @param referralCode referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @return compact representation of supply parameters */ function encodeSupplyParams( address asset, uint256 amount, uint16 referralCode ) external view returns (bytes32) { DataTypes.ReserveDataLegacy memory data = POOL.getReserveData(asset); uint16 assetId = data.id; uint128 shortenedAmount = amount.toUint128(); bytes32 res; assembly { res := add(assetId, add(shl(16, shortenedAmount), shl(144, referralCode))) } return res; } /** * @notice Encodes supplyWithPermit parameters from standard input to compact representation of 3 bytes32 * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf * @param asset The address of the underlying asset to supply * @param amount The amount to be supplied * @param referralCode referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param deadline The deadline timestamp that the permit is valid * @param permitV The V parameter of ERC712 permit sig * @param permitR The R parameter of ERC712 permit sig * @param permitS The S parameter of ERC712 permit sig * @return compact representation of supplyWithPermit parameters * @return The R parameter of ERC712 permit sig * @return The S parameter of ERC712 permit sig */ function encodeSupplyWithPermitParams( address asset, uint256 amount, uint16 referralCode, uint256 deadline, uint8 permitV, bytes32 permitR, bytes32 permitS ) external view returns (bytes32, bytes32, bytes32) { DataTypes.ReserveDataLegacy memory data = POOL.getReserveData(asset); uint16 assetId = data.id; uint128 shortenedAmount = amount.toUint128(); uint32 shortenedDeadline = deadline.toUint32(); bytes32 res; assembly { res := add( assetId, add( shl(16, shortenedAmount), add(shl(144, referralCode), add(shl(160, shortenedDeadline), shl(192, permitV))) ) ) } return (res, permitR, permitS); } /** * @notice Encodes withdraw parameters from standard input to compact representation of 1 bytes32 * @dev Without a to parameter as the compact calls to L2Pool will use msg.sender as to * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * @return compact representation of withdraw parameters */ function encodeWithdrawParams(address asset, uint256 amount) external view returns (bytes32) { DataTypes.ReserveDataLegacy memory data = POOL.getReserveData(asset); uint16 assetId = data.id; uint128 shortenedAmount = amount == type(uint256).max ? type(uint128).max : amount.toUint128(); bytes32 res; assembly { res := add(assetId, shl(16, shortenedAmount)) } return res; } /** * @notice Encodes borrow parameters from standard input to compact representation of 1 bytes32 * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 2 for Variable, 1 is deprecated (changed on v3.2.0) * @param referralCode The code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @return compact representation of withdraw parameters */ function encodeBorrowParams( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode ) external view returns (bytes32) { DataTypes.ReserveDataLegacy memory data = POOL.getReserveData(asset); uint16 assetId = data.id; uint128 shortenedAmount = amount.toUint128(); uint8 shortenedInterestRateMode = interestRateMode.toUint8(); bytes32 res; assembly { res := add( assetId, add( shl(16, shortenedAmount), add(shl(144, shortenedInterestRateMode), shl(152, referralCode)) ) ) } return res; } /** * @notice Encodes repay parameters from standard input to compact representation of 1 bytes32 * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `interestRateMode` * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 2 for Variable, 1 is deprecated (changed on v3.2.0) * @return compact representation of repay parameters */ function encodeRepayParams( address asset, uint256 amount, uint256 interestRateMode ) public view returns (bytes32) { DataTypes.ReserveDataLegacy memory data = POOL.getReserveData(asset); uint16 assetId = data.id; uint128 shortenedAmount = amount == type(uint256).max ? type(uint128).max : amount.toUint128(); uint8 shortenedInterestRateMode = interestRateMode.toUint8(); bytes32 res; assembly { res := add(assetId, add(shl(16, shortenedAmount), shl(144, shortenedInterestRateMode))) } return res; } /** * @notice Encodes repayWithPermit parameters from standard input to compact representation of 3 bytes32 * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 2 for Variable, 1 is deprecated (changed on v3.2.0) * @param deadline The deadline timestamp that the permit is valid * @param permitV The V parameter of ERC712 permit sig * @param permitR The R parameter of ERC712 permit sig * @param permitS The S parameter of ERC712 permit sig * @return compact representation of repayWithPermit parameters * @return The R parameter of ERC712 permit sig * @return The S parameter of ERC712 permit sig */ function encodeRepayWithPermitParams( address asset, uint256 amount, uint256 interestRateMode, uint256 deadline, uint8 permitV, bytes32 permitR, bytes32 permitS ) external view returns (bytes32, bytes32, bytes32) { DataTypes.ReserveDataLegacy memory data = POOL.getReserveData(asset); uint16 assetId = data.id; uint128 shortenedAmount = amount == type(uint256).max ? type(uint128).max : amount.toUint128(); uint8 shortenedInterestRateMode = interestRateMode.toUint8(); uint32 shortenedDeadline = deadline.toUint32(); bytes32 res; assembly { res := add( assetId, add( shl(16, shortenedAmount), add( shl(144, shortenedInterestRateMode), add(shl(152, shortenedDeadline), shl(184, permitV)) ) ) ) } return (res, permitR, permitS); } /** * @notice Encodes repay with aToken parameters from standard input to compact representation of 1 bytes32 * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 2 for Variable, 1 is deprecated (changed on v3.2.0) * @return compact representation of repay with aToken parameters */ function encodeRepayWithATokensParams( address asset, uint256 amount, uint256 interestRateMode ) external view returns (bytes32) { return encodeRepayParams(asset, amount, interestRateMode); } /** * @notice Encodes set user use reserve as collateral parameters from standard input to compact representation of 1 bytes32 * @param asset The address of the underlying asset borrowed * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise * @return compact representation of set user use reserve as collateral parameters */ function encodeSetUserUseReserveAsCollateral( address asset, bool useAsCollateral ) external view returns (bytes32) { DataTypes.ReserveDataLegacy memory data = POOL.getReserveData(asset); uint16 assetId = data.id; bytes32 res; assembly { res := add(assetId, shl(16, useAsCollateral)) } return res; } /** * @notice Encodes liquidation call parameters from standard input to compact representation of 2 bytes32 * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly * @return First half ot compact representation of liquidation call parameters * @return Second half ot compact representation of liquidation call parameters */ function encodeLiquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external view returns (bytes32, bytes32) { DataTypes.ReserveDataLegacy memory collateralData = POOL.getReserveData(collateralAsset); uint16 collateralAssetId = collateralData.id; DataTypes.ReserveDataLegacy memory debtData = POOL.getReserveData(debtAsset); uint16 debtAssetId = debtData.id; uint128 shortenedDebtToCover = debtToCover == type(uint256).max ? type(uint128).max : debtToCover.toUint128(); bytes32 res1; bytes32 res2; assembly { res1 := add(add(collateralAssetId, shl(16, debtAssetId)), shl(32, user)) res2 := add(shortenedDebtToCover, shl(128, receiveAToken)) } return (res1, res2); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {IPoolAddressesProvider} from '../interfaces/IPoolAddressesProvider.sol'; import {IPool} from '../interfaces/IPool.sol'; import {IncentivizedERC20} from '../protocol/tokenization/base/IncentivizedERC20.sol'; import {UserConfiguration} from '../../contracts/protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {IRewardsController} from '../rewards/interfaces/IRewardsController.sol'; import {AggregatorInterface} from '../dependencies/chainlink/AggregatorInterface.sol'; import {IUiIncentiveDataProviderV3} from './interfaces/IUiIncentiveDataProviderV3.sol'; contract UiIncentiveDataProviderV3 is IUiIncentiveDataProviderV3 { using UserConfiguration for DataTypes.UserConfigurationMap; function getFullReservesIncentiveData( IPoolAddressesProvider provider, address user ) external view override returns (AggregatedReserveIncentiveData[] memory, UserReserveIncentiveData[] memory) { return (_getReservesIncentivesData(provider), _getUserReservesIncentivesData(provider, user)); } function getReservesIncentivesData( IPoolAddressesProvider provider ) external view override returns (AggregatedReserveIncentiveData[] memory) { return _getReservesIncentivesData(provider); } function _getReservesIncentivesData( IPoolAddressesProvider provider ) private view returns (AggregatedReserveIncentiveData[] memory) { IPool pool = IPool(provider.getPool()); address[] memory reserves = pool.getReservesList(); AggregatedReserveIncentiveData[] memory reservesIncentiveData = new AggregatedReserveIncentiveData[](reserves.length); // Iterate through the reserves to get all the information from the (a/s/v) Tokens for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveIncentiveData memory reserveIncentiveData = reservesIncentiveData[i]; reserveIncentiveData.underlyingAsset = reserves[i]; DataTypes.ReserveDataLegacy memory baseData = pool.getReserveData(reserves[i]); // Get aTokens rewards information IRewardsController aTokenIncentiveController = IRewardsController( address(IncentivizedERC20(baseData.aTokenAddress).getIncentivesController()) ); RewardInfo[] memory aRewardsInformation; if (address(aTokenIncentiveController) != address(0)) { address[] memory aTokenRewardAddresses = aTokenIncentiveController.getRewardsByAsset( baseData.aTokenAddress ); aRewardsInformation = new RewardInfo[](aTokenRewardAddresses.length); for (uint256 j = 0; j < aTokenRewardAddresses.length; ++j) { RewardInfo memory rewardInformation; rewardInformation.rewardTokenAddress = aTokenRewardAddresses[j]; ( rewardInformation.tokenIncentivesIndex, rewardInformation.emissionPerSecond, rewardInformation.incentivesLastUpdateTimestamp, rewardInformation.emissionEndTimestamp ) = aTokenIncentiveController.getRewardsData( baseData.aTokenAddress, rewardInformation.rewardTokenAddress ); rewardInformation.precision = aTokenIncentiveController.getAssetDecimals( baseData.aTokenAddress ); rewardInformation.rewardTokenDecimals = IERC20Detailed( rewardInformation.rewardTokenAddress ).decimals(); rewardInformation.rewardTokenSymbol = IERC20Detailed(rewardInformation.rewardTokenAddress) .symbol(); // Get price of reward token from Chainlink Proxy Oracle rewardInformation.rewardOracleAddress = aTokenIncentiveController.getRewardOracle( rewardInformation.rewardTokenAddress ); rewardInformation.priceFeedDecimals = AggregatorInterface( rewardInformation.rewardOracleAddress ).decimals(); rewardInformation.rewardPriceFeed = AggregatorInterface( rewardInformation.rewardOracleAddress ).latestAnswer(); aRewardsInformation[j] = rewardInformation; } } reserveIncentiveData.aIncentiveData = IncentiveData( baseData.aTokenAddress, address(aTokenIncentiveController), aRewardsInformation ); // Get vTokens rewards information IRewardsController vTokenIncentiveController = IRewardsController( address(IncentivizedERC20(baseData.variableDebtTokenAddress).getIncentivesController()) ); RewardInfo[] memory vRewardsInformation; if (address(vTokenIncentiveController) != address(0)) { address[] memory vTokenRewardAddresses = vTokenIncentiveController.getRewardsByAsset( baseData.variableDebtTokenAddress ); vRewardsInformation = new RewardInfo[](vTokenRewardAddresses.length); for (uint256 j = 0; j < vTokenRewardAddresses.length; ++j) { RewardInfo memory rewardInformation; rewardInformation.rewardTokenAddress = vTokenRewardAddresses[j]; ( rewardInformation.tokenIncentivesIndex, rewardInformation.emissionPerSecond, rewardInformation.incentivesLastUpdateTimestamp, rewardInformation.emissionEndTimestamp ) = vTokenIncentiveController.getRewardsData( baseData.variableDebtTokenAddress, rewardInformation.rewardTokenAddress ); rewardInformation.precision = vTokenIncentiveController.getAssetDecimals( baseData.variableDebtTokenAddress ); rewardInformation.rewardTokenDecimals = IERC20Detailed( rewardInformation.rewardTokenAddress ).decimals(); rewardInformation.rewardTokenSymbol = IERC20Detailed(rewardInformation.rewardTokenAddress) .symbol(); // Get price of reward token from Chainlink Proxy Oracle rewardInformation.rewardOracleAddress = vTokenIncentiveController.getRewardOracle( rewardInformation.rewardTokenAddress ); rewardInformation.priceFeedDecimals = AggregatorInterface( rewardInformation.rewardOracleAddress ).decimals(); rewardInformation.rewardPriceFeed = AggregatorInterface( rewardInformation.rewardOracleAddress ).latestAnswer(); vRewardsInformation[j] = rewardInformation; } } reserveIncentiveData.vIncentiveData = IncentiveData( baseData.variableDebtTokenAddress, address(vTokenIncentiveController), vRewardsInformation ); } return (reservesIncentiveData); } function getUserReservesIncentivesData( IPoolAddressesProvider provider, address user ) external view override returns (UserReserveIncentiveData[] memory) { return _getUserReservesIncentivesData(provider, user); } function _getUserReservesIncentivesData( IPoolAddressesProvider provider, address user ) private view returns (UserReserveIncentiveData[] memory) { IPool pool = IPool(provider.getPool()); address[] memory reserves = pool.getReservesList(); UserReserveIncentiveData[] memory userReservesIncentivesData = new UserReserveIncentiveData[]( user != address(0) ? reserves.length : 0 ); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveDataLegacy memory baseData = pool.getReserveData(reserves[i]); // user reserve data userReservesIncentivesData[i].underlyingAsset = reserves[i]; IRewardsController aTokenIncentiveController = IRewardsController( address(IncentivizedERC20(baseData.aTokenAddress).getIncentivesController()) ); if (address(aTokenIncentiveController) != address(0)) { // get all rewards information from the asset address[] memory aTokenRewardAddresses = aTokenIncentiveController.getRewardsByAsset( baseData.aTokenAddress ); UserRewardInfo[] memory aUserRewardsInformation = new UserRewardInfo[]( aTokenRewardAddresses.length ); for (uint256 j = 0; j < aTokenRewardAddresses.length; ++j) { UserRewardInfo memory userRewardInformation; userRewardInformation.rewardTokenAddress = aTokenRewardAddresses[j]; userRewardInformation.tokenIncentivesUserIndex = aTokenIncentiveController .getUserAssetIndex( user, baseData.aTokenAddress, userRewardInformation.rewardTokenAddress ); userRewardInformation.userUnclaimedRewards = aTokenIncentiveController .getUserAccruedRewards(user, userRewardInformation.rewardTokenAddress); userRewardInformation.rewardTokenDecimals = IERC20Detailed( userRewardInformation.rewardTokenAddress ).decimals(); userRewardInformation.rewardTokenSymbol = IERC20Detailed( userRewardInformation.rewardTokenAddress ).symbol(); // Get price of reward token from Chainlink Proxy Oracle userRewardInformation.rewardOracleAddress = aTokenIncentiveController.getRewardOracle( userRewardInformation.rewardTokenAddress ); userRewardInformation.priceFeedDecimals = AggregatorInterface( userRewardInformation.rewardOracleAddress ).decimals(); userRewardInformation.rewardPriceFeed = AggregatorInterface( userRewardInformation.rewardOracleAddress ).latestAnswer(); aUserRewardsInformation[j] = userRewardInformation; } userReservesIncentivesData[i].aTokenIncentivesUserData = UserIncentiveData( baseData.aTokenAddress, address(aTokenIncentiveController), aUserRewardsInformation ); } // variable debt token IRewardsController vTokenIncentiveController = IRewardsController( address(IncentivizedERC20(baseData.variableDebtTokenAddress).getIncentivesController()) ); if (address(vTokenIncentiveController) != address(0)) { // get all rewards information from the asset address[] memory vTokenRewardAddresses = vTokenIncentiveController.getRewardsByAsset( baseData.variableDebtTokenAddress ); UserRewardInfo[] memory vUserRewardsInformation = new UserRewardInfo[]( vTokenRewardAddresses.length ); for (uint256 j = 0; j < vTokenRewardAddresses.length; ++j) { UserRewardInfo memory userRewardInformation; userRewardInformation.rewardTokenAddress = vTokenRewardAddresses[j]; userRewardInformation.tokenIncentivesUserIndex = vTokenIncentiveController .getUserAssetIndex( user, baseData.variableDebtTokenAddress, userRewardInformation.rewardTokenAddress ); userRewardInformation.userUnclaimedRewards = vTokenIncentiveController .getUserAccruedRewards(user, userRewardInformation.rewardTokenAddress); userRewardInformation.rewardTokenDecimals = IERC20Detailed( userRewardInformation.rewardTokenAddress ).decimals(); userRewardInformation.rewardTokenSymbol = IERC20Detailed( userRewardInformation.rewardTokenAddress ).symbol(); // Get price of reward token from Chainlink Proxy Oracle userRewardInformation.rewardOracleAddress = vTokenIncentiveController.getRewardOracle( userRewardInformation.rewardTokenAddress ); userRewardInformation.priceFeedDecimals = AggregatorInterface( userRewardInformation.rewardOracleAddress ).decimals(); userRewardInformation.rewardPriceFeed = AggregatorInterface( userRewardInformation.rewardOracleAddress ).latestAnswer(); vUserRewardsInformation[j] = userRewardInformation; } userReservesIncentivesData[i].vTokenIncentivesUserData = UserIncentiveData( baseData.variableDebtTokenAddress, address(aTokenIncentiveController), vUserRewardsInformation ); } } return (userReservesIncentivesData); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {IPoolAddressesProvider} from '../interfaces/IPoolAddressesProvider.sol'; import {IPool} from '../interfaces/IPool.sol'; import {IAaveOracle} from '../interfaces/IAaveOracle.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IDefaultInterestRateStrategyV2} from '../interfaces/IDefaultInterestRateStrategyV2.sol'; import {AaveProtocolDataProvider} from './AaveProtocolDataProvider.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {AggregatorInterface} from '../dependencies/chainlink/AggregatorInterface.sol'; import {IERC20DetailedBytes} from './interfaces/IERC20DetailedBytes.sol'; import {IUiPoolDataProviderV3} from './interfaces/IUiPoolDataProviderV3.sol'; contract UiPoolDataProviderV3 is IUiPoolDataProviderV3 { using WadRayMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; AggregatorInterface public immutable networkBaseTokenPriceInUsdProxyAggregator; AggregatorInterface public immutable marketReferenceCurrencyPriceInUsdProxyAggregator; uint256 public constant ETH_CURRENCY_UNIT = 1 ether; address public constant MKR_ADDRESS = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2; constructor( AggregatorInterface _networkBaseTokenPriceInUsdProxyAggregator, AggregatorInterface _marketReferenceCurrencyPriceInUsdProxyAggregator ) { networkBaseTokenPriceInUsdProxyAggregator = _networkBaseTokenPriceInUsdProxyAggregator; marketReferenceCurrencyPriceInUsdProxyAggregator = _marketReferenceCurrencyPriceInUsdProxyAggregator; } function getReservesList( IPoolAddressesProvider provider ) external view override returns (address[] memory) { IPool pool = IPool(provider.getPool()); return pool.getReservesList(); } function getReservesData( IPoolAddressesProvider provider ) external view override returns (AggregatedReserveData[] memory, BaseCurrencyInfo memory) { IAaveOracle oracle = IAaveOracle(provider.getPriceOracle()); IPool pool = IPool(provider.getPool()); AaveProtocolDataProvider poolDataProvider = AaveProtocolDataProvider( provider.getPoolDataProvider() ); address[] memory reserves = pool.getReservesList(); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveDataLegacy memory baseData = pool.getReserveData( reserveData.underlyingAsset ); //the liquidity index. Expressed in ray reserveData.liquidityIndex = baseData.liquidityIndex; //variable borrow index. Expressed in ray reserveData.variableBorrowIndex = baseData.variableBorrowIndex; //the current supply rate. Expressed in ray reserveData.liquidityRate = baseData.currentLiquidityRate; //the current variable borrow rate. Expressed in ray reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; //address of the interest rate strategy reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInMarketReferenceCurrency = oracle.getAssetPrice( reserveData.underlyingAsset ); reserveData.priceOracle = oracle.getSourceOfAsset(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // Due we take the symbol from underlying token we need a special case for $MKR as symbol() returns bytes32 if (address(reserveData.underlyingAsset) == address(MKR_ADDRESS)) { bytes32 symbol = IERC20DetailedBytes(reserveData.underlyingAsset).symbol(); bytes32 name = IERC20DetailedBytes(reserveData.underlyingAsset).name(); reserveData.symbol = bytes32ToString(symbol); reserveData.name = bytes32ToString(name); } else { reserveData.symbol = IERC20Detailed(reserveData.underlyingAsset).symbol(); reserveData.name = IERC20Detailed(reserveData.underlyingAsset).name(); } //stores the reserve configuration DataTypes.ReserveConfigurationMap memory reserveConfigurationMap = baseData.configuration; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = reserveConfigurationMap.getParams(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.isPaused ) = reserveConfigurationMap.getFlags(); // interest rates try IDefaultInterestRateStrategyV2(reserveData.interestRateStrategyAddress).getInterestRateData( reserveData.underlyingAsset ) returns (IDefaultInterestRateStrategyV2.InterestRateDataRay memory res) { reserveData.baseVariableBorrowRate = res.baseVariableBorrowRate; reserveData.variableRateSlope1 = res.variableRateSlope1; reserveData.variableRateSlope2 = res.variableRateSlope2; reserveData.optimalUsageRatio = res.optimalUsageRatio; } catch {} // v3 only reserveData.deficit = uint128(pool.getReserveDeficit(reserveData.underlyingAsset)); reserveData.debtCeiling = reserveConfigurationMap.getDebtCeiling(); reserveData.debtCeilingDecimals = poolDataProvider.getDebtCeilingDecimals(); (reserveData.borrowCap, reserveData.supplyCap) = reserveConfigurationMap.getCaps(); try poolDataProvider.getFlashLoanEnabled(reserveData.underlyingAsset) returns ( bool flashLoanEnabled ) { reserveData.flashLoanEnabled = flashLoanEnabled; } catch (bytes memory) { reserveData.flashLoanEnabled = true; } reserveData.isSiloedBorrowing = reserveConfigurationMap.getSiloedBorrowing(); reserveData.unbacked = baseData.unbacked; reserveData.isolationModeTotalDebt = baseData.isolationModeTotalDebt; reserveData.accruedToTreasury = baseData.accruedToTreasury; reserveData.borrowableInIsolation = reserveConfigurationMap.getBorrowableInIsolation(); try poolDataProvider.getIsVirtualAccActive(reserveData.underlyingAsset) returns ( bool virtualAccActive ) { reserveData.virtualAccActive = virtualAccActive; } catch (bytes memory) { reserveData.virtualAccActive = false; } try pool.getVirtualUnderlyingBalance(reserveData.underlyingAsset) returns ( uint128 virtualUnderlyingBalance ) { reserveData.virtualUnderlyingBalance = virtualUnderlyingBalance; } catch (bytes memory) { reserveData.virtualUnderlyingBalance = 0; } } BaseCurrencyInfo memory baseCurrencyInfo; baseCurrencyInfo.networkBaseTokenPriceInUsd = networkBaseTokenPriceInUsdProxyAggregator .latestAnswer(); baseCurrencyInfo.networkBaseTokenPriceDecimals = networkBaseTokenPriceInUsdProxyAggregator .decimals(); try oracle.BASE_CURRENCY_UNIT() returns (uint256 baseCurrencyUnit) { baseCurrencyInfo.marketReferenceCurrencyUnit = baseCurrencyUnit; baseCurrencyInfo.marketReferenceCurrencyPriceInUsd = int256(baseCurrencyUnit); } catch (bytes memory /*lowLevelData*/) { baseCurrencyInfo.marketReferenceCurrencyUnit = ETH_CURRENCY_UNIT; baseCurrencyInfo .marketReferenceCurrencyPriceInUsd = marketReferenceCurrencyPriceInUsdProxyAggregator .latestAnswer(); } return (reservesData, baseCurrencyInfo); } /// @inheritdoc IUiPoolDataProviderV3 function getEModes(IPoolAddressesProvider provider) external view returns (Emode[] memory) { IPool pool = IPool(provider.getPool()); Emode[] memory tempCategories = new Emode[](256); uint8 eModesFound = 0; uint8 missCounter = 0; for (uint8 i = 1; i < 256; i++) { DataTypes.CollateralConfig memory cfg = pool.getEModeCategoryCollateralConfig(i); if (cfg.liquidationThreshold != 0) { tempCategories[eModesFound] = Emode({ eMode: DataTypes.EModeCategory({ ltv: cfg.ltv, liquidationThreshold: cfg.liquidationThreshold, liquidationBonus: cfg.liquidationBonus, label: pool.getEModeCategoryLabel(i), collateralBitmap: pool.getEModeCategoryCollateralBitmap(i), borrowableBitmap: pool.getEModeCategoryBorrowableBitmap(i) }), id: i }); ++eModesFound; missCounter = 0; } else { ++missCounter; } // assumes there will never be a gap > 2 when setting eModes if (missCounter > 2) break; } Emode[] memory categories = new Emode[](eModesFound); for (uint8 i = 0; i < eModesFound; i++) { categories[i] = tempCategories[i]; } return categories; } function getUserReservesData( IPoolAddressesProvider provider, address user ) external view override returns (UserReserveData[] memory, uint8) { IPool pool = IPool(provider.getPool()); address[] memory reserves = pool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = pool.getUserConfiguration(user); uint8 userEmodeCategoryId = uint8(pool.getUserEMode(user)); UserReserveData[] memory userReservesData = new UserReserveData[]( user != address(0) ? reserves.length : 0 ); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveDataLegacy memory baseData = pool.getReserveData(reserves[i]); // user reserve data userReservesData[i].underlyingAsset = reserves[i]; userReservesData[i].scaledATokenBalance = IAToken(baseData.aTokenAddress).scaledBalanceOf( user ); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( baseData.variableDebtTokenAddress ).scaledBalanceOf(user); } } return (userReservesData, userEmodeCategoryId); } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while (i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {Address} from '../dependencies/openzeppelin/contracts/Address.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IPoolAddressesProvider} from '../interfaces/IPoolAddressesProvider.sol'; import {IPool} from '../interfaces/IPool.sol'; import {GPv2SafeERC20} from '../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title WalletBalanceProvider contract * @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol * @notice Implements a logic of getting multiple tokens balance for one user address * @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls * towards the blockchain from the Aave backend. **/ contract WalletBalanceProvider { using Address for address payable; using Address for address; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** @dev Fallback function, don't accept any ETH **/ receive() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), '22'); } /** @dev Check the token balance of a wallet in a token contract Returns the balance of the token for user. Avoids possible errors: - return 0 on non-contract address **/ function balanceOf(address user, address token) public view returns (uint256) { if (token == MOCK_ETH_ADDRESS) { return user.balance; // ETH balance // check if token is actually a contract } else if (token.isContract()) { return IERC20(token).balanceOf(user); } revert('INVALID_TOKEN'); } /** * @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances * @param users The list of users * @param tokens The list of tokens * @return And array with the concatenation of, for each user, his/her balances **/ function batchBalanceOf( address[] calldata users, address[] calldata tokens ) external view returns (uint256[] memory) { uint256[] memory balances = new uint256[](users.length * tokens.length); for (uint256 i = 0; i < users.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]); } } return balances; } /** @dev provides balances of user wallet for all reserves available on the pool */ function getUserWalletBalances( address provider, address user ) external view returns (address[] memory, uint256[] memory) { IPool pool = IPool(IPoolAddressesProvider(provider).getPool()); address[] memory reserves = pool.getReservesList(); address[] memory reservesWithEth = new address[](reserves.length + 1); for (uint256 i = 0; i < reserves.length; i++) { reservesWithEth[i] = reserves[i]; } reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS; uint256[] memory balances = new uint256[](reservesWithEth.length); for (uint256 j = 0; j < reserves.length; j++) { DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration( reservesWithEth[j] ); (bool isActive, , , ) = configuration.getFlags(); if (!isActive) { balances[j] = 0; continue; } balances[j] = balanceOf(user, reservesWithEth[j]); } balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS); return (reservesWithEth, balances); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; interface IERC20DetailedBytes is IERC20 { function name() external view returns (bytes32); function symbol() external view returns (bytes32); function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol'; interface IUiIncentiveDataProviderV3 { struct AggregatedReserveIncentiveData { address underlyingAsset; IncentiveData aIncentiveData; IncentiveData vIncentiveData; } struct IncentiveData { address tokenAddress; address incentiveControllerAddress; RewardInfo[] rewardsTokenInformation; } struct RewardInfo { string rewardTokenSymbol; address rewardTokenAddress; address rewardOracleAddress; uint256 emissionPerSecond; uint256 incentivesLastUpdateTimestamp; uint256 tokenIncentivesIndex; uint256 emissionEndTimestamp; int256 rewardPriceFeed; uint8 rewardTokenDecimals; uint8 precision; uint8 priceFeedDecimals; } struct UserReserveIncentiveData { address underlyingAsset; UserIncentiveData aTokenIncentivesUserData; UserIncentiveData vTokenIncentivesUserData; } struct UserIncentiveData { address tokenAddress; address incentiveControllerAddress; UserRewardInfo[] userRewardsInformation; } struct UserRewardInfo { string rewardTokenSymbol; address rewardOracleAddress; address rewardTokenAddress; uint256 userUnclaimedRewards; uint256 tokenIncentivesUserIndex; int256 rewardPriceFeed; uint8 priceFeedDecimals; uint8 rewardTokenDecimals; } function getReservesIncentivesData( IPoolAddressesProvider provider ) external view returns (AggregatedReserveIncentiveData[] memory); function getUserReservesIncentivesData( IPoolAddressesProvider provider, address user ) external view returns (UserReserveIncentiveData[] memory); // generic method with full data function getFullReservesIncentiveData( IPoolAddressesProvider provider, address user ) external view returns (AggregatedReserveIncentiveData[] memory, UserReserveIncentiveData[] memory); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol'; import {DataTypes} from '../../protocol/libraries/types/DataTypes.sol'; interface IUiPoolDataProviderV3 { struct AggregatedReserveData { address underlyingAsset; string name; string symbol; uint256 decimals; uint256 baseLTVasCollateral; uint256 reserveLiquidationThreshold; uint256 reserveLiquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool isActive; bool isFrozen; // base data uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; // uint256 availableLiquidity; uint256 totalScaledVariableDebt; uint256 priceInMarketReferenceCurrency; address priceOracle; uint256 variableRateSlope1; uint256 variableRateSlope2; uint256 baseVariableBorrowRate; uint256 optimalUsageRatio; // v3 only bool isPaused; bool isSiloedBorrowing; uint128 accruedToTreasury; uint128 unbacked; uint128 isolationModeTotalDebt; bool flashLoanEnabled; // uint256 debtCeiling; uint256 debtCeilingDecimals; uint256 borrowCap; uint256 supplyCap; bool borrowableInIsolation; // v3.1 bool virtualAccActive; uint128 virtualUnderlyingBalance; // v3.3 uint128 deficit; } struct UserReserveData { address underlyingAsset; uint256 scaledATokenBalance; bool usageAsCollateralEnabledOnUser; uint256 scaledVariableDebt; } struct BaseCurrencyInfo { uint256 marketReferenceCurrencyUnit; int256 marketReferenceCurrencyPriceInUsd; int256 networkBaseTokenPriceInUsd; uint8 networkBaseTokenPriceDecimals; } struct Emode { uint8 id; DataTypes.EModeCategory eMode; } function getReservesList( IPoolAddressesProvider provider ) external view returns (address[] memory); function getReservesData( IPoolAddressesProvider provider ) external view returns (AggregatedReserveData[] memory, BaseCurrencyInfo memory); function getUserReservesData( IPoolAddressesProvider provider, address user ) external view returns (UserReserveData[] memory, uint8); /** * @dev Iterates the eModes mapping and returns all eModes found * @notice The method assumes for id gaps <= 2 within the eMode definitions * @return an array of eModes that were found in the eMode mapping */ function getEModes(IPoolAddressesProvider provider) external view returns (Emode[] memory); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); function transferFrom(address src, address dst, uint256 wad) external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {IWETH} from '../interfaces/IWETH.sol'; import {IPool} from '../../interfaces/IPool.sol'; interface IWrappedTokenGatewayV3 { function WETH() external view returns (IWETH); function POOL() external view returns (IPool); function depositETH(address pool, address onBehalfOf, uint16 referralCode) external payable; function withdrawETH(address pool, uint256 amount, address onBehalfOf) external; function repayETH(address pool, uint256 amount, address onBehalfOf) external payable; function borrowETH(address pool, uint256 amount, uint16 referralCode) external; function withdrawETHWithPermit( address pool, uint256 amount, address to, uint256 deadline, uint8 permitV, bytes32 permitR, bytes32 permitS ) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IPoolAddressesProvider} from './IPoolAddressesProvider.sol'; /** * @title IACLManager * @author Aave * @notice Defines the basic interface for the ACL Manager */ interface IACLManager { /** * @notice Returns the contract address of the PoolAddressesProvider * @return The address of the PoolAddressesProvider */ function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider); /** * @notice Returns the identifier of the PoolAdmin role * @return The id of the PoolAdmin role */ function POOL_ADMIN_ROLE() external view returns (bytes32); /** * @notice Returns the identifier of the EmergencyAdmin role * @return The id of the EmergencyAdmin role */ function EMERGENCY_ADMIN_ROLE() external view returns (bytes32); /** * @notice Returns the identifier of the RiskAdmin role * @return The id of the RiskAdmin role */ function RISK_ADMIN_ROLE() external view returns (bytes32); /** * @notice Returns the identifier of the FlashBorrower role * @return The id of the FlashBorrower role */ function FLASH_BORROWER_ROLE() external view returns (bytes32); /** * @notice Returns the identifier of the Bridge role * @return The id of the Bridge role */ function BRIDGE_ROLE() external view returns (bytes32); /** * @notice Returns the identifier of the AssetListingAdmin role * @return The id of the AssetListingAdmin role */ function ASSET_LISTING_ADMIN_ROLE() external view returns (bytes32); /** * @notice Set the role as admin of a specific role. * @dev By default the admin role for all roles is `DEFAULT_ADMIN_ROLE`. * @param role The role to be managed by the admin role * @param adminRole The admin role */ function setRoleAdmin(bytes32 role, bytes32 adminRole) external; /** * @notice Adds a new admin as PoolAdmin * @param admin The address of the new admin */ function addPoolAdmin(address admin) external; /** * @notice Removes an admin as PoolAdmin * @param admin The address of the admin to remove */ function removePoolAdmin(address admin) external; /** * @notice Returns true if the address is PoolAdmin, false otherwise * @param admin The address to check * @return True if the given address is PoolAdmin, false otherwise */ function isPoolAdmin(address admin) external view returns (bool); /** * @notice Adds a new admin as EmergencyAdmin * @param admin The address of the new admin */ function addEmergencyAdmin(address admin) external; /** * @notice Removes an admin as EmergencyAdmin * @param admin The address of the admin to remove */ function removeEmergencyAdmin(address admin) external; /** * @notice Returns true if the address is EmergencyAdmin, false otherwise * @param admin The address to check * @return True if the given address is EmergencyAdmin, false otherwise */ function isEmergencyAdmin(address admin) external view returns (bool); /** * @notice Adds a new admin as RiskAdmin * @param admin The address of the new admin */ function addRiskAdmin(address admin) external; /** * @notice Removes an admin as RiskAdmin * @param admin The address of the admin to remove */ function removeRiskAdmin(address admin) external; /** * @notice Returns true if the address is RiskAdmin, false otherwise * @param admin The address to check * @return True if the given address is RiskAdmin, false otherwise */ function isRiskAdmin(address admin) external view returns (bool); /** * @notice Adds a new address as FlashBorrower * @param borrower The address of the new FlashBorrower */ function addFlashBorrower(address borrower) external; /** * @notice Removes an address as FlashBorrower * @param borrower The address of the FlashBorrower to remove */ function removeFlashBorrower(address borrower) external; /** * @notice Returns true if the address is FlashBorrower, false otherwise * @param borrower The address to check * @return True if the given address is FlashBorrower, false otherwise */ function isFlashBorrower(address borrower) external view returns (bool); /** * @notice Adds a new address as Bridge * @param bridge The address of the new Bridge */ function addBridge(address bridge) external; /** * @notice Removes an address as Bridge * @param bridge The address of the bridge to remove */ function removeBridge(address bridge) external; /** * @notice Returns true if the address is Bridge, false otherwise * @param bridge The address to check * @return True if the given address is Bridge, false otherwise */ function isBridge(address bridge) external view returns (bool); /** * @notice Adds a new admin as AssetListingAdmin * @param admin The address of the new admin */ function addAssetListingAdmin(address admin) external; /** * @notice Removes an admin as AssetListingAdmin * @param admin The address of the admin to remove */ function removeAssetListingAdmin(address admin) external; /** * @notice Returns true if the address is AssetListingAdmin, false otherwise * @param admin The address to check * @return True if the given address is AssetListingAdmin, false otherwise */ function isAssetListingAdmin(address admin) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableAToken} from './IInitializableAToken.sol'; /** * @title IAToken * @author Aave * @notice Defines the basic interface for an AToken. */ interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The scaled amount being transferred * @param index The next liquidity index of the reserve */ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @notice Mints `amount` aTokens to `user` * @param caller The address performing the mint * @param onBehalfOf The address of the user that will receive the minted aTokens * @param amount The amount of tokens getting minted * @param index The next liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address caller, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @notice Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @dev In some instances, the mint event could be emitted from a burn transaction * if the amount to burn is less than the interest that the user accrued * @param from The address from which the aTokens will be burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The next liquidity index of the reserve */ function burn(address from, address receiverOfUnderlying, uint256 amount, uint256 index) external; /** * @notice Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The next liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @notice Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred */ function transferOnLiquidation(address from, address to, uint256 value) external; /** * @notice Transfers the underlying asset to `target`. * @dev Used by the Pool to transfer assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the underlying * @param amount The amount getting transferred */ function transferUnderlyingTo(address target, uint256 amount) external; /** * @notice Handles the underlying received by the aToken after the transfer has been completed. * @dev The default implementation is empty as with standard ERC20 tokens, nothing needs to be done after the * transfer is concluded. However in the future there may be aTokens that allow for example to stake the underlying * to receive LM rewards. In that case, `handleRepayment()` would perform the staking of the underlying asset. * @param user The user executing the repayment * @param onBehalfOf The address of the user who will get his debt reduced/removed * @param amount The amount getting repaid */ function handleRepayment(address user, address onBehalfOf, uint256 amount) external; /** * @notice Allow passing a signed message to approve spending * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) * @return The address of the underlying asset */ function UNDERLYING_ASSET_ADDRESS() external view returns (address); /** * @notice Returns the address of the Aave treasury, receiving the fees on this aToken. * @return Address of the Aave treasury */ function RESERVE_TREASURY_ADDRESS() external view returns (address); /** * @notice Get the domain separator for the token * @dev Return cached value if chainId matches cache, otherwise recomputes separator * @return The domain separator of the token at current chain */ function DOMAIN_SEPARATOR() external view returns (bytes32); /** * @notice Returns the nonce for owner. * @param owner The address of the owner * @return The nonce of the owner */ function nonces(address owner) external view returns (uint256); /** * @notice Rescue and transfer tokens locked in this contract * @param token The address of the token * @param to The address of the recipient * @param amount The amount of token to transfer */ function rescueTokens(address token, address to, uint256 amount) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title IAaveIncentivesController * @author Aave * @notice Defines the basic interface for an Aave Incentives Controller. * @dev It only contains one single function, needed as a hook on aToken and debtToken transfers. */ interface IAaveIncentivesController { /** * @dev Called by the corresponding asset on transfer hook in order to update the rewards distribution. * @dev The units of `totalSupply` and `userBalance` should be the same. * @param user The address of the user whose asset balance has changed * @param totalSupply The total supply of the asset prior to user balance change * @param userBalance The previous user balance prior to balance change */ function handleAction(address user, uint256 totalSupply, uint256 userBalance) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IPriceOracleGetter} from './IPriceOracleGetter.sol'; import {IPoolAddressesProvider} from './IPoolAddressesProvider.sol'; /** * @title IAaveOracle * @author Aave * @notice Defines the basic interface for the Aave Oracle */ interface IAaveOracle is IPriceOracleGetter { /** * @dev Emitted after the base currency is set * @param baseCurrency The base currency of used for price quotes * @param baseCurrencyUnit The unit of the base currency */ event BaseCurrencySet(address indexed baseCurrency, uint256 baseCurrencyUnit); /** * @dev Emitted after the price source of an asset is updated * @param asset The address of the asset * @param source The price source of the asset */ event AssetSourceUpdated(address indexed asset, address indexed source); /** * @dev Emitted after the address of fallback oracle is updated * @param fallbackOracle The address of the fallback oracle */ event FallbackOracleUpdated(address indexed fallbackOracle); /** * @notice Returns the PoolAddressesProvider * @return The address of the PoolAddressesProvider contract */ function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider); /** * @notice Sets or replaces price sources of assets * @param assets The addresses of the assets * @param sources The addresses of the price sources */ function setAssetSources(address[] calldata assets, address[] calldata sources) external; /** * @notice Sets the fallback oracle * @param fallbackOracle The address of the fallback oracle */ function setFallbackOracle(address fallbackOracle) external; /** * @notice Returns a list of prices from a list of assets addresses * @param assets The list of assets addresses * @return The prices of the given assets */ function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory); /** * @notice Returns the address of the source for an asset address * @param asset The address of the asset * @return The address of the source */ function getSourceOfAsset(address asset) external view returns (address); /** * @notice Returns the address of the fallback oracle * @return The address of the fallback oracle */ function getFallbackOracle() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IReserveInterestRateStrategy} from './IReserveInterestRateStrategy.sol'; import {IPoolAddressesProvider} from './IPoolAddressesProvider.sol'; /** * @title IDefaultInterestRateStrategyV2 * @author BGD Labs * @notice Interface of the default interest rate strategy used by the Aave protocol */ interface IDefaultInterestRateStrategyV2 is IReserveInterestRateStrategy { /** * @notice Holds the interest rate data for a given reserve * * @dev Since values are in bps, they are multiplied by 1e23 in order to become rays with 27 decimals. This * in turn means that the maximum supported interest rate is 4294967295 (2**32-1) bps or 42949672.95%. * * @param optimalUsageRatio The optimal usage ratio, in bps * @param baseVariableBorrowRate The base variable borrow rate, in bps * @param variableRateSlope1 The slope of the variable interest curve, before hitting the optimal ratio, in bps * @param variableRateSlope2 The slope of the variable interest curve, after hitting the optimal ratio, in bps */ struct InterestRateData { uint16 optimalUsageRatio; uint32 baseVariableBorrowRate; uint32 variableRateSlope1; uint32 variableRateSlope2; } /** * @notice The interest rate data, where all values are in ray (fixed-point 27 decimal numbers) for a given reserve, * used in in-memory calculations. * * @param optimalUsageRatio The optimal usage ratio * @param baseVariableBorrowRate The base variable borrow rate * @param variableRateSlope1 The slope of the variable interest curve, before hitting the optimal ratio * @param variableRateSlope2 The slope of the variable interest curve, after hitting the optimal ratio */ struct InterestRateDataRay { uint256 optimalUsageRatio; uint256 baseVariableBorrowRate; uint256 variableRateSlope1; uint256 variableRateSlope2; } /** * @notice emitted when new interest rate data is set in a reserve * * @param reserve address of the reserve that has new interest rate data set * @param optimalUsageRatio The optimal usage ratio, in bps * @param baseVariableBorrowRate The base variable borrow rate, in bps * @param variableRateSlope1 The slope of the variable interest curve, before hitting the optimal ratio, in bps * @param variableRateSlope2 The slope of the variable interest curve, after hitting the optimal ratio, in bps */ event RateDataUpdate( address indexed reserve, uint256 optimalUsageRatio, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2 ); /** * @notice Returns the address of the PoolAddressesProvider * @return The address of the PoolAddressesProvider contract */ function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider); /** * @notice Returns the maximum value achievable for variable borrow rate, in bps * @return The maximum rate */ function MAX_BORROW_RATE() external view returns (uint256); /** * @notice Returns the minimum optimal point, in bps * @return The optimal point */ function MIN_OPTIMAL_POINT() external view returns (uint256); /** * @notice Returns the maximum optimal point, in bps * @return The optimal point */ function MAX_OPTIMAL_POINT() external view returns (uint256); /** * notice Returns the full InterestRateData object for the given reserve, in ray * * @param reserve The reserve to get the data of * * @return The InterestRateDataRay object for the given reserve */ function getInterestRateData(address reserve) external view returns (InterestRateDataRay memory); /** * notice Returns the full InterestRateDataRay object for the given reserve, in bps * * @param reserve The reserve to get the data of * * @return The InterestRateData object for the given reserve */ function getInterestRateDataBps(address reserve) external view returns (InterestRateData memory); /** * @notice Returns the optimal usage rate for the given reserve in ray * * @param reserve The reserve to get the optimal usage rate of * * @return The optimal usage rate is the level of borrow / collateral at which the borrow rate */ function getOptimalUsageRatio(address reserve) external view returns (uint256); /** * @notice Returns the variable rate slope below optimal usage ratio in ray * @dev It's the variable rate when usage ratio > 0 and <= OPTIMAL_USAGE_RATIO * * @param reserve The reserve to get the variable rate slope 1 of * * @return The variable rate slope */ function getVariableRateSlope1(address reserve) external view returns (uint256); /** * @notice Returns the variable rate slope above optimal usage ratio in ray * @dev It's the variable rate when usage ratio > OPTIMAL_USAGE_RATIO * * @param reserve The reserve to get the variable rate slope 2 of * * @return The variable rate slope */ function getVariableRateSlope2(address reserve) external view returns (uint256); /** * @notice Returns the base variable borrow rate, in ray * * @param reserve The reserve to get the base variable borrow rate of * * @return The base variable borrow rate */ function getBaseVariableBorrowRate(address reserve) external view returns (uint256); /** * @notice Returns the maximum variable borrow rate, in ray * * @param reserve The reserve to get the maximum variable borrow rate of * * @return The maximum variable borrow rate */ function getMaxVariableBorrowRate(address reserve) external view returns (uint256); /** * @notice Sets interest rate data for an Aave rate strategy * @param reserve The reserve to update * @param rateData The reserve interest rate data to apply to the given reserve * Being specific to this custom implementation, with custom struct type, * overloading the function on the generic interface */ function setInterestRateParams(address reserve, InterestRateData calldata rateData) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; /** * @title IERC20WithPermit * @author Aave * @notice Interface for the permit function (EIP-2612) */ interface IERC20WithPermit is IERC20 { /** * @notice Allow passing a signed message to approve spending * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; import {IPool} from './IPool.sol'; /** * @title IInitializableAToken * @author Aave * @notice Interface for the initialize function on AToken */ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals The decimals of the underlying * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken * @param params A set of encoded parameters for additional initialization */ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @notice Initializes the aToken * @param pool The pool contract that is initializing this contract * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken * @param params A set of encoded parameters for additional initialization */ function initialize( IPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; import {IPool} from './IPool.sol'; /** * @title IInitializableDebtToken * @author Aave * @notice Interface for the initialize function common between debt tokens */ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals The decimals of the debt token * @param debtTokenName The name of the debt token * @param debtTokenSymbol The symbol of the debt token * @param params A set of encoded parameters for additional initialization */ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @notice Initializes the debt token. * @param pool The pool contract that is initializing this contract * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token * @param params A set of encoded parameters for additional initialization */ function initialize( IPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IPoolAddressesProvider} from './IPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title IPool * @author Aave * @notice Defines the basic interface for an Aave Pool. */ interface IPool { /** * @dev Emitted on mintUnbacked() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the supply * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens * @param amount The amount of supplied assets * @param referralCode The referral code used */ event MintUnbacked( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referralCode ); /** * @dev Emitted on backUnbacked() * @param reserve The address of the underlying asset of the reserve * @param backer The address paying for the backing * @param amount The amount added as backing * @param fee The amount paid in fees */ event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee); /** * @dev Emitted on supply() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the supply * @param onBehalfOf The beneficiary of the supply, receiving the aTokens * @param amount The amount supplied * @param referralCode The referral code used */ event Supply( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referralCode ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlying asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to The address that will receive the underlying * @param amount The amount to be withdrawn */ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param interestRateMode The rate mode: 2 for Variable, 1 is deprecated (changed on v3.2.0) * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray * @param referralCode The referral code used */ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, DataTypes.InterestRateMode interestRateMode, uint256 borrowRate, uint16 indexed referralCode ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly */ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount, bool useATokens ); /** * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets * @param asset The address of the underlying asset of the reserve * @param totalDebt The total isolation mode debt for the reserve */ event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt); /** * @dev Emitted when the user selects a certain asset category for eMode * @param user The address of the user * @param categoryId The category id */ event UserEModeSet(address indexed user, uint8 categoryId); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral */ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral */ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param interestRateMode The flashloan mode: 0 for regular flashloan, * 1 for Stable (Deprecated on v3.2.0), 2 for Variable * @param premium The fee flash borrowed * @param referralCode The referral code used */ event FlashLoan( address indexed target, address initiator, address indexed asset, uint256 amount, DataTypes.InterestRateMode interestRateMode, uint256 premium, uint16 indexed referralCode ); /** * @dev Emitted when a borrower is liquidated. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liquidator * @param liquidator The address of the liquidator * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly */ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The next liquidity rate * @param stableBorrowRate The next stable borrow rate @note deprecated on v3.2.0 * @param variableBorrowRate The next variable borrow rate * @param liquidityIndex The next liquidity index * @param variableBorrowIndex The next variable borrow index */ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Emitted when the deficit of a reserve is covered. * @param reserve The address of the underlying asset of the reserve * @param caller The caller that triggered the DeficitCovered event * @param amountCovered The amount of deficit covered */ event DeficitCovered(address indexed reserve, address caller, uint256 amountCovered); /** * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest. * @param reserve The address of the reserve * @param amountMinted The amount minted to the treasury */ event MintedToTreasury(address indexed reserve, uint256 amountMinted); /** * @dev Emitted when deficit is realized on a liquidation. * @param user The user address where the bad debt will be burned * @param debtAsset The address of the underlying borrowed asset to be burned * @param amountCreated The amount of deficit created */ event DeficitCreated(address indexed user, address indexed debtAsset, uint256 amountCreated); /** * @notice Mints an `amount` of aTokens to the `onBehalfOf` * @param asset The address of the underlying asset to mint * @param amount The amount to mint * @param onBehalfOf The address that will receive the aTokens * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man */ function mintUnbacked( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @notice Back the current unbacked underlying with `amount` and pay `fee`. * @param asset The address of the underlying asset to back * @param amount The amount to back * @param fee The amount paid in fees * @return The backed amount */ function backUnbacked(address asset, uint256 amount, uint256 fee) external returns (uint256); /** * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User supplies 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to supply * @param amount The amount to be supplied * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man */ function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external; /** * @notice Supply with transfer approval of asset to be supplied done via permit function * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713 * @param asset The address of the underlying asset to supply * @param amount The amount to be supplied * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param deadline The deadline timestamp that the permit is valid * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param permitV The V parameter of ERC712 permit sig * @param permitR The R parameter of ERC712 permit sig * @param permitS The S parameter of ERC712 permit sig */ function supplyWithPermit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode, uint256 deadline, uint8 permitV, bytes32 permitR, bytes32 permitS ) external; /** * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to The address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn */ function withdraw(address asset, uint256 amount, address to) external returns (uint256); /** * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already supplied enough collateral, or he was given enough allowance by a credit delegator on the VariableDebtToken * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 variable debt tokens * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode 2 for Variable, 1 is deprecated on v3.2.0 * @param referralCode The code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance */ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param interestRateMode 2 for Variable, 1 is deprecated on v3.2.0 * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid */ function repay( address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf ) external returns (uint256); /** * @notice Repay with transfer approval of asset to be repaid done via permit function * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713 * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param interestRateMode 2 for Variable, 1 is deprecated on v3.2.0 * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @param deadline The deadline timestamp that the permit is valid * @param permitV The V parameter of ERC712 permit sig * @param permitR The R parameter of ERC712 permit sig * @param permitS The S parameter of ERC712 permit sig * @return The final amount repaid */ function repayWithPermit( address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf, uint256 deadline, uint8 permitV, bytes32 permitR, bytes32 permitS ) external returns (uint256); /** * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the * equivalent debt tokens * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable debt tokens * @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken * balance is not enough to cover the whole debt * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param interestRateMode DEPRECATED in v3.2.0 * @return The final amount repaid */ function repayWithATokens( address asset, uint256 amount, uint256 interestRateMode ) external returns (uint256); /** * @notice Allows suppliers to enable/disable a specific supplied asset as collateral * @param asset The address of the underlying asset supplied * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise */ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly */ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @notice Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept * into consideration. For further details please visit https://docs.aave.com/developers/ * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts of the assets being flash-borrowed * @param interestRateModes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Deprecated on v3.2.0 * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using 2 on `modes` * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode The code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man */ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata interestRateModes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @notice Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept * into consideration. For further details please visit https://docs.aave.com/developers/ * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface * @param asset The address of the asset being flash-borrowed * @param amount The amount of the asset being flash-borrowed * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode The code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man */ function flashLoanSimple( address receiverAddress, address asset, uint256 amount, bytes calldata params, uint16 referralCode ) external; /** * @notice Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed * @return totalDebtBase The total debt of the user in the base currency used by the price feed * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed * @return currentLiquidationThreshold The liquidation threshold of the user * @return ltv The loan to value of The user * @return healthFactor The current health factor of the user */ function getUserAccountData( address user ) external view returns ( uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); /** * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an * interest rate strategy * @dev Only callable by the PoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param aTokenAddress The address of the aToken that will be assigned to the reserve * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve * @param interestRateStrategyAddress The address of the interest rate strategy contract */ function initReserve( address asset, address aTokenAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; /** * @notice Drop a reserve * @dev Only callable by the PoolConfigurator contract * @dev Does not reset eMode flags, which must be considered when reusing the same reserve id for a different reserve. * @param asset The address of the underlying asset of the reserve */ function dropReserve(address asset) external; /** * @notice Updates the address of the interest rate strategy contract * @dev Only callable by the PoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The address of the interest rate strategy contract */ function setReserveInterestRateStrategyAddress( address asset, address rateStrategyAddress ) external; /** * @notice Accumulates interest to all indexes of the reserve * @dev Only callable by the PoolConfigurator contract * @dev To be used when required by the configurator, for example when updating interest rates strategy data * @param asset The address of the underlying asset of the reserve */ function syncIndexesState(address asset) external; /** * @notice Updates interest rates on the reserve data * @dev Only callable by the PoolConfigurator contract * @dev To be used when required by the configurator, for example when updating interest rates strategy data * @param asset The address of the underlying asset of the reserve */ function syncRatesState(address asset) external; /** * @notice Sets the configuration bitmap of the reserve as a whole * @dev Only callable by the PoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param configuration The new configuration bitmap */ function setConfiguration( address asset, DataTypes.ReserveConfigurationMap calldata configuration ) external; /** * @notice Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve */ function getConfiguration( address asset ) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @notice Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user */ function getUserConfiguration( address user ) external view returns (DataTypes.UserConfigurationMap memory); /** * @notice Returns the normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @notice Returns the normalized variable debt per unit of asset * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a * "dynamic" variable index based on time, current stored index and virtual rate at the current * moment (approx. a borrower would get if opening a position). This means that is always used in * combination with variable debt supply/balances. * If using this function externally, consider that is possible to have an increasing normalized * variable debt that is not equivalent to how the variable debt index would be updated in storage * (e.g. only updates with non-zero variable debt supply) * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @notice Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state and configuration data of the reserve */ function getReserveData(address asset) external view returns (DataTypes.ReserveDataLegacy memory); /** * @notice Returns the virtual underlying balance of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve virtual underlying balance */ function getVirtualUnderlyingBalance(address asset) external view returns (uint128); /** * @notice Validates and finalizes an aToken transfer * @dev Only callable by the overlying aToken of the `asset` * @param asset The address of the underlying asset of the aToken * @param from The user from which the aTokens are transferred * @param to The user receiving the aTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The aToken balance of the `from` user before the transfer * @param balanceToBefore The aToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external; /** * @notice Returns the list of the underlying assets of all the initialized reserves * @dev It does not include dropped reserves * @return The addresses of the underlying assets of the initialized reserves */ function getReservesList() external view returns (address[] memory); /** * @notice Returns the number of initialized reserves * @dev It includes dropped reserves * @return The count */ function getReservesCount() external view returns (uint256); /** * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct * @param id The id of the reserve as stored in the DataTypes.ReserveData struct * @return The address of the reserve associated with id */ function getReserveAddressById(uint16 id) external view returns (address); /** * @notice Returns the PoolAddressesProvider connected to this contract * @return The address of the PoolAddressesProvider */ function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider); /** * @notice Updates the protocol fee on the bridging * @param bridgeProtocolFee The part of the premium sent to the protocol treasury */ function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external; /** * @notice Updates flash loan premiums. Flash loan premium consists of two parts: * - A part is sent to aToken holders as extra, one time accumulated interest * - A part is collected by the protocol treasury * @dev The total premium is calculated on the total borrowed amount * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal` * @dev Only callable by the PoolConfigurator contract * @param flashLoanPremiumTotal The total premium, expressed in bps * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps */ function updateFlashloanPremiums( uint128 flashLoanPremiumTotal, uint128 flashLoanPremiumToProtocol ) external; /** * @notice Configures a new or alters an existing collateral configuration of an eMode. * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category. * The category 0 is reserved as it's the default for volatile assets * @param id The id of the category * @param config The configuration of the category */ function configureEModeCategory( uint8 id, DataTypes.EModeCategoryBaseConfiguration memory config ) external; /** * @notice Replaces the current eMode collateralBitmap. * @param id The id of the category * @param collateralBitmap The collateralBitmap of the category */ function configureEModeCategoryCollateralBitmap(uint8 id, uint128 collateralBitmap) external; /** * @notice Replaces the current eMode borrowableBitmap. * @param id The id of the category * @param borrowableBitmap The borrowableBitmap of the category */ function configureEModeCategoryBorrowableBitmap(uint8 id, uint128 borrowableBitmap) external; /** * @notice Returns the data of an eMode category * @dev DEPRECATED use independent getters instead * @param id The id of the category * @return The configuration data of the category */ function getEModeCategoryData( uint8 id ) external view returns (DataTypes.EModeCategoryLegacy memory); /** * @notice Returns the label of an eMode category * @param id The id of the category * @return The label of the category */ function getEModeCategoryLabel(uint8 id) external view returns (string memory); /** * @notice Returns the collateral config of an eMode category * @param id The id of the category * @return The ltv,lt,lb of the category */ function getEModeCategoryCollateralConfig( uint8 id ) external view returns (DataTypes.CollateralConfig memory); /** * @notice Returns the collateralBitmap of an eMode category * @param id The id of the category * @return The collateralBitmap of the category */ function getEModeCategoryCollateralBitmap(uint8 id) external view returns (uint128); /** * @notice Returns the borrowableBitmap of an eMode category * @param id The id of the category * @return The borrowableBitmap of the category */ function getEModeCategoryBorrowableBitmap(uint8 id) external view returns (uint128); /** * @notice Allows a user to use the protocol in eMode * @param categoryId The id of the category */ function setUserEMode(uint8 categoryId) external; /** * @notice Returns the eMode the user is using * @param user The address of the user * @return The eMode id */ function getUserEMode(address user) external view returns (uint256); /** * @notice Resets the isolation mode total debt of the given asset to zero * @dev It requires the given asset has zero debt ceiling * @param asset The address of the underlying asset to reset the isolationModeTotalDebt */ function resetIsolationModeTotalDebt(address asset) external; /** * @notice Sets the liquidation grace period of the given asset * @dev To enable a liquidation grace period, a timestamp in the future should be set, * To disable a liquidation grace period, any timestamp in the past works, like 0 * @param asset The address of the underlying asset to set the liquidationGracePeriod * @param until Timestamp when the liquidation grace period will end **/ function setLiquidationGracePeriod(address asset, uint40 until) external; /** * @notice Returns the liquidation grace period of the given asset * @param asset The address of the underlying asset * @return Timestamp when the liquidation grace period will end **/ function getLiquidationGracePeriod(address asset) external view returns (uint40); /** * @notice Returns the total fee on flash loans * @return The total fee on flashloans */ function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128); /** * @notice Returns the part of the bridge fees sent to protocol * @return The bridge fee sent to the protocol treasury */ function BRIDGE_PROTOCOL_FEE() external view returns (uint256); /** * @notice Returns the part of the flashloan fees sent to protocol * @return The flashloan fee sent to the protocol treasury */ function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128); /** * @notice Returns the maximum number of reserves supported to be listed in this Pool * @return The maximum number of reserves supported */ function MAX_NUMBER_RESERVES() external view returns (uint16); /** * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens * @param assets The list of reserves for which the minting needs to be executed */ function mintToTreasury(address[] calldata assets) external; /** * @notice Rescue and transfer tokens locked in this contract * @param token The address of the token * @param to The address of the recipient * @param amount The amount of token to transfer */ function rescueTokens(address token, address to, uint256 amount) external; /** * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User supplies 100 USDC and gets in return 100 aUSDC * @dev Deprecated: Use the `supply` function instead * @param asset The address of the underlying asset to supply * @param amount The amount to be supplied * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man */ function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external; /** * @notice It covers the deficit of a specified reserve by burning: * - the equivalent aToken `amount` for assets with virtual accounting enabled * - the equivalent `amount` of underlying for assets with virtual accounting disabled (e.g. GHO) * @dev The deficit of a reserve can occur due to situations where borrowed assets are not repaid, leading to bad debt. * @param asset The address of the underlying asset to cover the deficit. * @param amount The amount to be covered, in aToken or underlying on non-virtual accounted assets */ function eliminateReserveDeficit(address asset, uint256 amount) external; /** * @notice Returns the current deficit of a reserve. * @param asset The address of the underlying asset of the reserve * @return The current deficit of the reserve */ function getReserveDeficit(address asset) external view returns (uint256); /** * @notice Returns the aToken address of a reserve. * @param asset The address of the underlying asset of the reserve * @return The address of the aToken */ function getReserveAToken(address asset) external view returns (address); /** * @notice Returns the variableDebtToken address of a reserve. * @param asset The address of the underlying asset of the reserve * @return The address of the variableDebtToken */ function getReserveVariableDebtToken(address asset) external view returns (address); /** * @notice Gets the address of the external FlashLoanLogic */ function getFlashLoanLogic() external view returns (address); /** * @notice Gets the address of the external BorrowLogic */ function getBorrowLogic() external view returns (address); /** * @notice Gets the address of the external BridgeLogic */ function getBridgeLogic() external view returns (address); /** * @notice Gets the address of the external EModeLogic */ function getEModeLogic() external view returns (address); /** * @notice Gets the address of the external LiquidationLogic */ function getLiquidationLogic() external view returns (address); /** * @notice Gets the address of the external PoolLogic */ function getPoolLogic() external view returns (address); /** * @notice Gets the address of the external SupplyLogic */ function getSupplyLogic() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title IPoolAddressesProvider * @author Aave * @notice Defines the basic interface for a Pool Addresses Provider. */ interface IPoolAddressesProvider { /** * @dev Emitted when the market identifier is updated. * @param oldMarketId The old id of the market * @param newMarketId The new id of the market */ event MarketIdSet(string indexed oldMarketId, string indexed newMarketId); /** * @dev Emitted when the pool is updated. * @param oldAddress The old address of the Pool * @param newAddress The new address of the Pool */ event PoolUpdated(address indexed oldAddress, address indexed newAddress); /** * @dev Emitted when the pool configurator is updated. * @param oldAddress The old address of the PoolConfigurator * @param newAddress The new address of the PoolConfigurator */ event PoolConfiguratorUpdated(address indexed oldAddress, address indexed newAddress); /** * @dev Emitted when the price oracle is updated. * @param oldAddress The old address of the PriceOracle * @param newAddress The new address of the PriceOracle */ event PriceOracleUpdated(address indexed oldAddress, address indexed newAddress); /** * @dev Emitted when the ACL manager is updated. * @param oldAddress The old address of the ACLManager * @param newAddress The new address of the ACLManager */ event ACLManagerUpdated(address indexed oldAddress, address indexed newAddress); /** * @dev Emitted when the ACL admin is updated. * @param oldAddress The old address of the ACLAdmin * @param newAddress The new address of the ACLAdmin */ event ACLAdminUpdated(address indexed oldAddress, address indexed newAddress); /** * @dev Emitted when the price oracle sentinel is updated. * @param oldAddress The old address of the PriceOracleSentinel * @param newAddress The new address of the PriceOracleSentinel */ event PriceOracleSentinelUpdated(address indexed oldAddress, address indexed newAddress); /** * @dev Emitted when the pool data provider is updated. * @param oldAddress The old address of the PoolDataProvider * @param newAddress The new address of the PoolDataProvider */ event PoolDataProviderUpdated(address indexed oldAddress, address indexed newAddress); /** * @dev Emitted when a new proxy is created. * @param id The identifier of the proxy * @param proxyAddress The address of the created proxy contract * @param implementationAddress The address of the implementation contract */ event ProxyCreated( bytes32 indexed id, address indexed proxyAddress, address indexed implementationAddress ); /** * @dev Emitted when a new non-proxied contract address is registered. * @param id The identifier of the contract * @param oldAddress The address of the old contract * @param newAddress The address of the new contract */ event AddressSet(bytes32 indexed id, address indexed oldAddress, address indexed newAddress); /** * @dev Emitted when the implementation of the proxy registered with id is updated * @param id The identifier of the contract * @param proxyAddress The address of the proxy contract * @param oldImplementationAddress The address of the old implementation contract * @param newImplementationAddress The address of the new implementation contract */ event AddressSetAsProxy( bytes32 indexed id, address indexed proxyAddress, address oldImplementationAddress, address indexed newImplementationAddress ); /** * @notice Returns the id of the Aave market to which this contract points to. * @return The market id */ function getMarketId() external view returns (string memory); /** * @notice Associates an id with a specific PoolAddressesProvider. * @dev This can be used to create an onchain registry of PoolAddressesProviders to * identify and validate multiple Aave markets. * @param newMarketId The market id */ function setMarketId(string calldata newMarketId) external; /** * @notice Returns an address by its identifier. * @dev The returned address might be an EOA or a contract, potentially proxied * @dev It returns ZERO if there is no registered address with the given id * @param id The id * @return The address of the registered for the specified id */ function getAddress(bytes32 id) external view returns (address); /** * @notice General function to update the implementation of a proxy registered with * certain `id`. If there is no proxy registered, it will instantiate one and * set as implementation the `newImplementationAddress`. * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit * setter function, in order to avoid unexpected consequences * @param id The id * @param newImplementationAddress The address of the new implementation */ function setAddressAsProxy(bytes32 id, address newImplementationAddress) external; /** * @notice Sets an address for an id replacing the address saved in the addresses map. * @dev IMPORTANT Use this function carefully, as it will do a hard replacement * @param id The id * @param newAddress The address to set */ function setAddress(bytes32 id, address newAddress) external; /** * @notice Returns the address of the Pool proxy. * @return The Pool proxy address */ function getPool() external view returns (address); /** * @notice Updates the implementation of the Pool, or creates a proxy * setting the new `pool` implementation when the function is called for the first time. * @param newPoolImpl The new Pool implementation */ function setPoolImpl(address newPoolImpl) external; /** * @notice Returns the address of the PoolConfigurator proxy. * @return The PoolConfigurator proxy address */ function getPoolConfigurator() external view returns (address); /** * @notice Updates the implementation of the PoolConfigurator, or creates a proxy * setting the new `PoolConfigurator` implementation when the function is called for the first time. * @param newPoolConfiguratorImpl The new PoolConfigurator implementation */ function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external; /** * @notice Returns the address of the price oracle. * @return The address of the PriceOracle */ function getPriceOracle() external view returns (address); /** * @notice Updates the address of the price oracle. * @param newPriceOracle The address of the new PriceOracle */ function setPriceOracle(address newPriceOracle) external; /** * @notice Returns the address of the ACL manager. * @return The address of the ACLManager */ function getACLManager() external view returns (address); /** * @notice Updates the address of the ACL manager. * @param newAclManager The address of the new ACLManager */ function setACLManager(address newAclManager) external; /** * @notice Returns the address of the ACL admin. * @return The address of the ACL admin */ function getACLAdmin() external view returns (address); /** * @notice Updates the address of the ACL admin. * @param newAclAdmin The address of the new ACL admin */ function setACLAdmin(address newAclAdmin) external; /** * @notice Returns the address of the price oracle sentinel. * @return The address of the PriceOracleSentinel */ function getPriceOracleSentinel() external view returns (address); /** * @notice Updates the address of the price oracle sentinel. * @param newPriceOracleSentinel The address of the new PriceOracleSentinel */ function setPriceOracleSentinel(address newPriceOracleSentinel) external; /** * @notice Returns the address of the data provider. * @return The address of the DataProvider */ function getPoolDataProvider() external view returns (address); /** * @notice Updates the address of the data provider. * @param newDataProvider The address of the new DataProvider */ function setPoolDataProvider(address newDataProvider) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title IPoolAddressesProviderRegistry * @author Aave * @notice Defines the basic interface for an Aave Pool Addresses Provider Registry. */ interface IPoolAddressesProviderRegistry { /** * @dev Emitted when a new AddressesProvider is registered. * @param addressesProvider The address of the registered PoolAddressesProvider * @param id The id of the registered PoolAddressesProvider */ event AddressesProviderRegistered(address indexed addressesProvider, uint256 indexed id); /** * @dev Emitted when an AddressesProvider is unregistered. * @param addressesProvider The address of the unregistered PoolAddressesProvider * @param id The id of the unregistered PoolAddressesProvider */ event AddressesProviderUnregistered(address indexed addressesProvider, uint256 indexed id); /** * @notice Returns the list of registered addresses providers * @return The list of addresses providers */ function getAddressesProvidersList() external view returns (address[] memory); /** * @notice Returns the id of a registered PoolAddressesProvider * @param addressesProvider The address of the PoolAddressesProvider * @return The id of the PoolAddressesProvider or 0 if is not registered */ function getAddressesProviderIdByAddress( address addressesProvider ) external view returns (uint256); /** * @notice Returns the address of a registered PoolAddressesProvider * @param id The id of the market * @return The address of the PoolAddressesProvider with the given id or zero address if it is not registered */ function getAddressesProviderAddressById(uint256 id) external view returns (address); /** * @notice Registers an addresses provider * @dev The PoolAddressesProvider must not already be registered in the registry * @dev The id must not be used by an already registered PoolAddressesProvider * @param provider The address of the new PoolAddressesProvider * @param id The id for the new PoolAddressesProvider, referring to the market it belongs to */ function registerAddressesProvider(address provider, uint256 id) external; /** * @notice Removes an addresses provider from the list of registered addresses providers * @param provider The PoolAddressesProvider address */ function unregisterAddressesProvider(address provider) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ConfiguratorInputTypes} from '../protocol/libraries/types/ConfiguratorInputTypes.sol'; import {IDefaultInterestRateStrategyV2} from './IDefaultInterestRateStrategyV2.sol'; /** * @title IPoolConfigurator * @author Aave * @notice Defines the basic interface for a Pool configurator. */ interface IPoolConfigurator { /** * @dev Emitted when a reserve is initialized. * @param asset The address of the underlying asset of the reserve * @param aToken The address of the associated aToken contract * @param stableDebtToken, DEPRECATED in v3.2.0 * @param variableDebtToken The address of the associated variable rate debt token * @param interestRateStrategyAddress The address of the interest rate strategy for the reserve */ event ReserveInitialized( address indexed asset, address indexed aToken, address stableDebtToken, address variableDebtToken, address interestRateStrategyAddress ); /** * @dev Emitted when borrowing is enabled or disabled on a reserve. * @param asset The address of the underlying asset of the reserve * @param enabled True if borrowing is enabled, false otherwise */ event ReserveBorrowing(address indexed asset, bool enabled); /** * @dev Emitted when flashloans are enabled or disabled on a reserve. * @param asset The address of the underlying asset of the reserve * @param enabled True if flashloans are enabled, false otherwise */ event ReserveFlashLoaning(address indexed asset, bool enabled); /** * @dev Emitted when the ltv is set for the frozen asset. * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral */ event PendingLtvChanged(address indexed asset, uint256 ltv); /** * @dev Emitted when the collateralization risk parameters for the specified asset are updated. * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset */ event CollateralConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Emitted when a reserve is activated or deactivated * @param asset The address of the underlying asset of the reserve * @param active True if reserve is active, false otherwise */ event ReserveActive(address indexed asset, bool active); /** * @dev Emitted when a reserve is frozen or unfrozen * @param asset The address of the underlying asset of the reserve * @param frozen True if reserve is frozen, false otherwise */ event ReserveFrozen(address indexed asset, bool frozen); /** * @dev Emitted when a reserve is paused or unpaused * @param asset The address of the underlying asset of the reserve * @param paused True if reserve is paused, false otherwise */ event ReservePaused(address indexed asset, bool paused); /** * @dev Emitted when a reserve is dropped. * @param asset The address of the underlying asset of the reserve */ event ReserveDropped(address indexed asset); /** * @dev Emitted when a reserve factor is updated. * @param asset The address of the underlying asset of the reserve * @param oldReserveFactor The old reserve factor, expressed in bps * @param newReserveFactor The new reserve factor, expressed in bps */ event ReserveFactorChanged( address indexed asset, uint256 oldReserveFactor, uint256 newReserveFactor ); /** * @dev Emitted when the borrow cap of a reserve is updated. * @param asset The address of the underlying asset of the reserve * @param oldBorrowCap The old borrow cap * @param newBorrowCap The new borrow cap */ event BorrowCapChanged(address indexed asset, uint256 oldBorrowCap, uint256 newBorrowCap); /** * @dev Emitted when the supply cap of a reserve is updated. * @param asset The address of the underlying asset of the reserve * @param oldSupplyCap The old supply cap * @param newSupplyCap The new supply cap */ event SupplyCapChanged(address indexed asset, uint256 oldSupplyCap, uint256 newSupplyCap); /** * @dev Emitted when the liquidation protocol fee of a reserve is updated. * @param asset The address of the underlying asset of the reserve * @param oldFee The old liquidation protocol fee, expressed in bps * @param newFee The new liquidation protocol fee, expressed in bps */ event LiquidationProtocolFeeChanged(address indexed asset, uint256 oldFee, uint256 newFee); /** * @dev Emitted when the liquidation grace period is updated. * @param asset The address of the underlying asset of the reserve * @param gracePeriodUntil Timestamp until when liquidations will not be allowed post-unpause */ event LiquidationGracePeriodChanged(address indexed asset, uint40 gracePeriodUntil); /** * @dev Emitted when the liquidation grace period is disabled. * @param asset The address of the underlying asset of the reserve */ event LiquidationGracePeriodDisabled(address indexed asset); /** * @dev Emitted when the unbacked mint cap of a reserve is updated. * @param asset The address of the underlying asset of the reserve * @param oldUnbackedMintCap The old unbacked mint cap * @param newUnbackedMintCap The new unbacked mint cap */ event UnbackedMintCapChanged( address indexed asset, uint256 oldUnbackedMintCap, uint256 newUnbackedMintCap ); /** * @dev Emitted when an collateral configuration of an asset in an eMode is changed. * @param asset The address of the underlying asset of the reserve * @param categoryId The eMode category * @param collateral True if the asset is enabled as collateral in the eMode, false otherwise. */ event AssetCollateralInEModeChanged(address indexed asset, uint8 categoryId, bool collateral); /** * @dev Emitted when the borrowable configuration of an asset in an eMode changed. * @param asset The address of the underlying asset of the reserve * @param categoryId The eMode category * @param borrowable True if the asset is enabled as borrowable in the eMode, false otherwise. */ event AssetBorrowableInEModeChanged(address indexed asset, uint8 categoryId, bool borrowable); /** * @dev Emitted when a new eMode category is added or an existing category is altered. * @param categoryId The new eMode category id * @param ltv The ltv for the asset category in eMode * @param liquidationThreshold The liquidationThreshold for the asset category in eMode * @param liquidationBonus The liquidationBonus for the asset category in eMode * @param oracle DEPRECATED in v3.2.0 * @param label A human readable identifier for the category */ event EModeCategoryAdded( uint8 indexed categoryId, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address oracle, string label ); /** * @dev Emitted when a reserve interest strategy contract is updated. * @param asset The address of the underlying asset of the reserve * @param oldStrategy The address of the old interest strategy contract * @param newStrategy The address of the new interest strategy contract */ event ReserveInterestRateStrategyChanged( address indexed asset, address oldStrategy, address newStrategy ); /** * @dev Emitted when the data of a reserve interest strategy contract is updated. * @param asset The address of the underlying asset of the reserve * @param data abi encoded data */ event ReserveInterestRateDataChanged(address indexed asset, address indexed strategy, bytes data); /** * @dev Emitted when an aToken implementation is upgraded. * @param asset The address of the underlying asset of the reserve * @param proxy The aToken proxy address * @param implementation The new aToken implementation */ event ATokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a variable debt token is upgraded. * @param asset The address of the underlying asset of the reserve * @param proxy The variable debt token proxy address * @param implementation The new aToken implementation */ event VariableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the debt ceiling of an asset is set. * @param asset The address of the underlying asset of the reserve * @param oldDebtCeiling The old debt ceiling * @param newDebtCeiling The new debt ceiling */ event DebtCeilingChanged(address indexed asset, uint256 oldDebtCeiling, uint256 newDebtCeiling); /** * @dev Emitted when the the siloed borrowing state for an asset is changed. * @param asset The address of the underlying asset of the reserve * @param oldState The old siloed borrowing state * @param newState The new siloed borrowing state */ event SiloedBorrowingChanged(address indexed asset, bool oldState, bool newState); /** * @dev Emitted when the bridge protocol fee is updated. * @param oldBridgeProtocolFee The old protocol fee, expressed in bps * @param newBridgeProtocolFee The new protocol fee, expressed in bps */ event BridgeProtocolFeeUpdated(uint256 oldBridgeProtocolFee, uint256 newBridgeProtocolFee); /** * @dev Emitted when the total premium on flashloans is updated. * @param oldFlashloanPremiumTotal The old premium, expressed in bps * @param newFlashloanPremiumTotal The new premium, expressed in bps */ event FlashloanPremiumTotalUpdated( uint128 oldFlashloanPremiumTotal, uint128 newFlashloanPremiumTotal ); /** * @dev Emitted when the part of the premium that goes to protocol is updated. * @param oldFlashloanPremiumToProtocol The old premium, expressed in bps * @param newFlashloanPremiumToProtocol The new premium, expressed in bps */ event FlashloanPremiumToProtocolUpdated( uint128 oldFlashloanPremiumToProtocol, uint128 newFlashloanPremiumToProtocol ); /** * @dev Emitted when the reserve is set as borrowable/non borrowable in isolation mode. * @param asset The address of the underlying asset of the reserve * @param borrowable True if the reserve is borrowable in isolation, false otherwise */ event BorrowableInIsolationChanged(address asset, bool borrowable); /** * @notice Initializes multiple reserves. * @dev param useVirtualBalance of the input struct should be true for all normal assets and should be false * only in special cases (ex. GHO) where an asset is minted instead of supplied. * @param input The array of initialization parameters */ function initReserves(ConfiguratorInputTypes.InitReserveInput[] calldata input) external; /** * @dev Updates the aToken implementation for the reserve. * @param input The aToken update parameters */ function updateAToken(ConfiguratorInputTypes.UpdateATokenInput calldata input) external; /** * @notice Updates the variable debt token implementation for the asset. * @param input The variableDebtToken update parameters */ function updateVariableDebtToken( ConfiguratorInputTypes.UpdateDebtTokenInput calldata input ) external; /** * @notice Configures borrowing on a reserve. * @param asset The address of the underlying asset of the reserve * @param enabled True if borrowing needs to be enabled, false otherwise */ function setReserveBorrowing(address asset, bool enabled) external; /** * @notice Configures the reserve collateralization parameters. * @dev All the values are expressed in bps. A value of 10000, results in 100.00% * @dev The `liquidationBonus` is always above 100%. A value of 105% means the liquidator will receive a 5% bonus * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset */ function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) external; /** * @notice Enable or disable flashloans on a reserve * @param asset The address of the underlying asset of the reserve * @param enabled True if flashloans need to be enabled, false otherwise */ function setReserveFlashLoaning(address asset, bool enabled) external; /** * @notice Activate or deactivate a reserve * @param asset The address of the underlying asset of the reserve * @param active True if the reserve needs to be active, false otherwise */ function setReserveActive(address asset, bool active) external; /** * @notice Freeze or unfreeze a reserve. A frozen reserve doesn't allow any new supply, borrow * or rate swap but allows repayments, liquidations, rate rebalances and withdrawals. * @param asset The address of the underlying asset of the reserve * @param freeze True if the reserve needs to be frozen, false otherwise */ function setReserveFreeze(address asset, bool freeze) external; /** * @notice Sets the borrowable in isolation flag for the reserve. * @dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the * borrowed amount will be accumulated in the isolated collateral's total debt exposure * @dev Only assets of the same family (e.g. USD stablecoins) should be borrowable in isolation mode to keep * consistency in the debt ceiling calculations * @param asset The address of the underlying asset of the reserve * @param borrowable True if the asset should be borrowable in isolation, false otherwise */ function setBorrowableInIsolation(address asset, bool borrowable) external; /** * @notice Pauses a reserve. A paused reserve does not allow any interaction (supply, borrow, repay, * swap interest rate, liquidate, atoken transfers). * @param asset The address of the underlying asset of the reserve * @param paused True if pausing the reserve, false if unpausing * @param gracePeriod Count of seconds after unpause during which liquidations will not be available * - Only applicable whenever unpausing (`paused` as false) * - Passing 0 means no grace period * - Capped to maximum MAX_GRACE_PERIOD */ function setReservePause(address asset, bool paused, uint40 gracePeriod) external; /** * @notice Pauses a reserve. A paused reserve does not allow any interaction (supply, borrow, repay, * swap interest rate, liquidate, atoken transfers). * @dev Version with no grace period * @param asset The address of the underlying asset of the reserve * @param paused True if pausing the reserve, false if unpausing */ function setReservePause(address asset, bool paused) external; /** * @notice Disables liquidation grace period for the asset. The liquidation grace period is set in the past * so that liquidations are allowed for the asset. * @param asset The address of the underlying asset of the reserve */ function disableLiquidationGracePeriod(address asset) external; /** * @notice Updates the reserve factor of a reserve. * @param asset The address of the underlying asset of the reserve * @param newReserveFactor The new reserve factor of the reserve */ function setReserveFactor(address asset, uint256 newReserveFactor) external; /** * @notice Sets the interest rate strategy of a reserve. * @param asset The address of the underlying asset of the reserve * @param newRateStrategyAddress The address of the new interest strategy contract * @param rateData bytes-encoded rate data. In this format in order to allow the rate strategy contract * to de-structure custom data */ function setReserveInterestRateStrategyAddress( address asset, address newRateStrategyAddress, bytes calldata rateData ) external; /** * @notice Sets interest rate data for a reserve * @param asset The address of the underlying asset of the reserve * @param rateData bytes-encoded rate data. In this format in order to allow the rate strategy contract * to de-structure custom data */ function setReserveInterestRateData(address asset, bytes calldata rateData) external; /** * @notice Pauses or unpauses all the protocol reserves. In the paused state all the protocol interactions * are suspended. * @param paused True if protocol needs to be paused, false otherwise * @param gracePeriod Count of seconds after unpause during which liquidations will not be available * - Only applicable whenever unpausing (`paused` as false) * - Passing 0 means no grace period * - Capped to maximum MAX_GRACE_PERIOD */ function setPoolPause(bool paused, uint40 gracePeriod) external; /** * @notice Pauses or unpauses all the protocol reserves. In the paused state all the protocol interactions * are suspended. * @dev Version with no grace period * @param paused True if protocol needs to be paused, false otherwise */ function setPoolPause(bool paused) external; /** * @notice Updates the borrow cap of a reserve. * @param asset The address of the underlying asset of the reserve * @param newBorrowCap The new borrow cap of the reserve */ function setBorrowCap(address asset, uint256 newBorrowCap) external; /** * @notice Updates the supply cap of a reserve. * @param asset The address of the underlying asset of the reserve * @param newSupplyCap The new supply cap of the reserve */ function setSupplyCap(address asset, uint256 newSupplyCap) external; /** * @notice Updates the liquidation protocol fee of reserve. * @param asset The address of the underlying asset of the reserve * @param newFee The new liquidation protocol fee of the reserve, expressed in bps */ function setLiquidationProtocolFee(address asset, uint256 newFee) external; /** * @notice Updates the unbacked mint cap of reserve. * @param asset The address of the underlying asset of the reserve * @param newUnbackedMintCap The new unbacked mint cap of the reserve */ function setUnbackedMintCap(address asset, uint256 newUnbackedMintCap) external; /** * @notice Enables/disables an asset to be borrowable in a selected eMode. * - eMode.borrowable always has less priority then reserve.borrowable * @param asset The address of the underlying asset of the reserve * @param categoryId The eMode categoryId * @param borrowable True if the asset should be borrowable in the given eMode category, false otherwise. */ function setAssetBorrowableInEMode(address asset, uint8 categoryId, bool borrowable) external; /** * @notice Enables/disables an asset to be collateral in a selected eMode. * @param asset The address of the underlying asset of the reserve * @param categoryId The eMode categoryId * @param collateral True if the asset should be collateral in the given eMode category, false otherwise. */ function setAssetCollateralInEMode(address asset, uint8 categoryId, bool collateral) external; /** * @notice Adds a new efficiency mode (eMode) category or alters a existing one. * @param categoryId The id of the category to be configured * @param ltv The ltv associated with the category * @param liquidationThreshold The liquidation threshold associated with the category * @param liquidationBonus The liquidation bonus associated with the category * @param label A label identifying the category */ function setEModeCategory( uint8 categoryId, uint16 ltv, uint16 liquidationThreshold, uint16 liquidationBonus, string calldata label ) external; /** * @notice Drops a reserve entirely. * @param asset The address of the reserve to drop */ function dropReserve(address asset) external; /** * @notice Updates the bridge fee collected by the protocol reserves. * @param newBridgeProtocolFee The part of the fee sent to the protocol treasury, expressed in bps */ function updateBridgeProtocolFee(uint256 newBridgeProtocolFee) external; /** * @notice Updates the total flash loan premium. * Total flash loan premium consists of two parts: * - A part is sent to aToken holders as extra balance * - A part is collected by the protocol reserves * @dev Expressed in bps * @dev The premium is calculated on the total amount borrowed * @param newFlashloanPremiumTotal The total flashloan premium */ function updateFlashloanPremiumTotal(uint128 newFlashloanPremiumTotal) external; /** * @notice Updates the flash loan premium collected by protocol reserves * @dev Expressed in bps * @dev The premium to protocol is calculated on the total flashloan premium * @param newFlashloanPremiumToProtocol The part of the flashloan premium sent to the protocol treasury */ function updateFlashloanPremiumToProtocol(uint128 newFlashloanPremiumToProtocol) external; /** * @notice Sets the debt ceiling for an asset. * @param newDebtCeiling The new debt ceiling */ function setDebtCeiling(address asset, uint256 newDebtCeiling) external; /** * @notice Sets siloed borrowing for an asset * @param siloed The new siloed borrowing state */ function setSiloedBorrowing(address asset, bool siloed) external; /** * @notice Gets pending ltv value * @param asset The new siloed borrowing state */ function getPendingLtv(address asset) external view returns (uint256); /** * @notice Gets the address of the external ConfiguratorLogic */ function getConfiguratorLogic() external view returns (address); /** * @notice Gets the maximum liquidations grace period allowed, in seconds */ function MAX_GRACE_PERIOD() external view returns (uint40); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IPoolAddressesProvider} from './IPoolAddressesProvider.sol'; /** * @title IPoolDataProvider * @author Aave * @notice Defines the basic interface of a PoolDataProvider */ interface IPoolDataProvider { struct TokenData { string symbol; address tokenAddress; } /** * @notice Returns the address for the PoolAddressesProvider contract. * @return The address for the PoolAddressesProvider contract */ function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider); /** * @notice Returns the list of the existing reserves in the pool. * @dev Handling MKR and ETH in a different way since they do not have standard `symbol` functions. * @return The list of reserves, pairs of symbols and addresses */ function getAllReservesTokens() external view returns (TokenData[] memory); /** * @notice Returns the list of the existing ATokens in the pool. * @return The list of ATokens, pairs of symbols and addresses */ function getAllATokens() external view returns (TokenData[] memory); /** * @notice Returns the configuration data of the reserve * @dev Not returning borrow and supply caps for compatibility, nor pause flag * @param asset The address of the underlying asset of the reserve * @return decimals The number of decimals of the reserve * @return ltv The ltv of the reserve * @return liquidationThreshold The liquidationThreshold of the reserve * @return liquidationBonus The liquidationBonus of the reserve * @return reserveFactor The reserveFactor of the reserve * @return usageAsCollateralEnabled True if the usage as collateral is enabled, false otherwise * @return borrowingEnabled True if borrowing is enabled, false otherwise * @return stableBorrowRateEnabled True if stable rate borrowing is enabled, false otherwise * @return isActive True if it is active, false otherwise * @return isFrozen True if it is frozen, false otherwise */ function getReserveConfigurationData( address asset ) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); /** * @notice Returns the caps parameters of the reserve * @param asset The address of the underlying asset of the reserve * @return borrowCap The borrow cap of the reserve * @return supplyCap The supply cap of the reserve */ function getReserveCaps( address asset ) external view returns (uint256 borrowCap, uint256 supplyCap); /** * @notice Returns if the pool is paused * @param asset The address of the underlying asset of the reserve * @return isPaused True if the pool is paused, false otherwise */ function getPaused(address asset) external view returns (bool isPaused); /** * @notice Returns the siloed borrowing flag * @param asset The address of the underlying asset of the reserve * @return True if the asset is siloed for borrowing */ function getSiloedBorrowing(address asset) external view returns (bool); /** * @notice Returns the protocol fee on the liquidation bonus * @param asset The address of the underlying asset of the reserve * @return The protocol fee on liquidation */ function getLiquidationProtocolFee(address asset) external view returns (uint256); /** * @notice Returns the unbacked mint cap of the reserve * @param asset The address of the underlying asset of the reserve * @return The unbacked mint cap of the reserve */ function getUnbackedMintCap(address asset) external view returns (uint256); /** * @notice Returns the debt ceiling of the reserve * @param asset The address of the underlying asset of the reserve * @return The debt ceiling of the reserve */ function getDebtCeiling(address asset) external view returns (uint256); /** * @notice Returns the debt ceiling decimals * @return The debt ceiling decimals */ function getDebtCeilingDecimals() external pure returns (uint256); /** * @notice Returns the reserve data * @param asset The address of the underlying asset of the reserve * @return unbacked The amount of unbacked tokens * @return accruedToTreasuryScaled The scaled amount of tokens accrued to treasury that is to be minted * @return totalAToken The total supply of the aToken * @return totalStableDebt The total stable debt of the reserve * @return totalVariableDebt The total variable debt of the reserve * @return liquidityRate The liquidity rate of the reserve * @return variableBorrowRate The variable borrow rate of the reserve * @return stableBorrowRate The stable borrow rate of the reserve * @return averageStableBorrowRate The average stable borrow rate of the reserve * @return liquidityIndex The liquidity index of the reserve * @return variableBorrowIndex The variable borrow index of the reserve * @return lastUpdateTimestamp The timestamp of the last update of the reserve */ function getReserveData( address asset ) external view returns ( uint256 unbacked, uint256 accruedToTreasuryScaled, uint256 totalAToken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); /** * @notice Returns the total supply of aTokens for a given asset * @param asset The address of the underlying asset of the reserve * @return The total supply of the aToken */ function getATokenTotalSupply(address asset) external view returns (uint256); /** * @notice Returns the total debt for a given asset * @param asset The address of the underlying asset of the reserve * @return The total debt for asset */ function getTotalDebt(address asset) external view returns (uint256); /** * @notice Returns the user data in a reserve * @param asset The address of the underlying asset of the reserve * @param user The address of the user * @return currentATokenBalance The current AToken balance of the user * @return currentStableDebt The current stable debt of the user * @return currentVariableDebt The current variable debt of the user * @return principalStableDebt The principal stable debt of the user * @return scaledVariableDebt The scaled variable debt of the user * @return stableBorrowRate The stable borrow rate of the user * @return liquidityRate The liquidity rate of the reserve * @return stableRateLastUpdated The timestamp of the last update of the user stable rate * @return usageAsCollateralEnabled True if the user is using the asset as collateral, false * otherwise */ function getUserReserveData( address asset, address user ) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); /** * @notice Returns the token addresses of the reserve * @param asset The address of the underlying asset of the reserve * @return aTokenAddress The AToken address of the reserve * @return stableDebtTokenAddress DEPRECATED in v3.2.0 * @return variableDebtTokenAddress The VariableDebtToken address of the reserve */ function getReserveTokensAddresses( address asset ) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); /** * @notice Returns the address of the Interest Rate strategy * @param asset The address of the underlying asset of the reserve * @return irStrategyAddress The address of the Interest Rate strategy */ function getInterestRateStrategyAddress( address asset ) external view returns (address irStrategyAddress); /** * @notice Returns whether the reserve has FlashLoans enabled or disabled * @param asset The address of the underlying asset of the reserve * @return True if FlashLoans are enabled, false otherwise */ function getFlashLoanEnabled(address asset) external view returns (bool); /** * @notice Returns whether virtual accounting is enabled/not for a reserve * @param asset The address of the underlying asset of the reserve * @return True if active, false otherwise */ function getIsVirtualAccActive(address asset) external view returns (bool); /** * @notice Returns the virtual underlying balance of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve virtual underlying balance */ function getVirtualUnderlyingBalance(address asset) external view returns (uint256); /** * @notice Returns the deficit of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve deficit */ function getReserveDeficit(address asset) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title IPriceOracleGetter * @author Aave * @notice Interface for the Aave price oracle. */ interface IPriceOracleGetter { /** * @notice Returns the base currency address * @dev Address 0x0 is reserved for USD as base currency. * @return Returns the base currency address. */ function BASE_CURRENCY() external view returns (address); /** * @notice Returns the base currency unit * @dev 1 ether for ETH, 1e8 for USD. * @return Returns the base currency unit. */ function BASE_CURRENCY_UNIT() external view returns (uint256); /** * @notice Returns the asset price in the base currency * @param asset The address of the asset * @return The price of the asset */ function getAssetPrice(address asset) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title IReserveInterestRateStrategy * @author BGD Labs * @notice Basic interface for any rate strategy used by the Aave protocol */ interface IReserveInterestRateStrategy { /** * @notice Sets interest rate data for an Aave rate strategy * @param reserve The reserve to update * @param rateData The abi encoded reserve interest rate data to apply to the given reserve * Abstracted this way as rate strategies can be custom */ function setInterestRateParams(address reserve, bytes calldata rateData) external; /** * @notice Calculates the interest rates depending on the reserve's state and configurations * @param params The parameters needed to calculate interest rates * @return liquidityRate The liquidity rate expressed in ray * @return variableBorrowRate The variable borrow rate expressed in ray */ function calculateInterestRates( DataTypes.CalculateInterestRatesParams memory params ) external view returns (uint256, uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title IScaledBalanceToken * @author Aave * @notice Defines the basic interface for a scaled-balance token. */ interface IScaledBalanceToken { /** * @dev Emitted after the mint action * @param caller The address performing the mint * @param onBehalfOf The address of the user that will receive the minted tokens * @param value The scaled-up amount being minted (based on user entered amount and balance increase from interest) * @param balanceIncrease The increase in scaled-up balance since the last action of 'onBehalfOf' * @param index The next liquidity index of the reserve */ event Mint( address indexed caller, address indexed onBehalfOf, uint256 value, uint256 balanceIncrease, uint256 index ); /** * @dev Emitted after the burn action * @dev If the burn function does not involve a transfer of the underlying asset, the target defaults to zero address * @param from The address from which the tokens will be burned * @param target The address that will receive the underlying, if any * @param value The scaled-up amount being burned (user entered amount - balance increase from interest) * @param balanceIncrease The increase in scaled-up balance since the last action of 'from' * @param index The next liquidity index of the reserve */ event Burn( address indexed from, address indexed target, uint256 value, uint256 balanceIncrease, uint256 index ); /** * @notice Returns the scaled balance of the user. * @dev The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index * at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user */ function scaledBalanceOf(address user) external view returns (uint256); /** * @notice Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled total supply */ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @notice Returns the scaled total supply of the scaled balance token. Represents sum(debt/index) * @return The scaled total supply */ function scaledTotalSupply() external view returns (uint256); /** * @notice Returns last index interest was accrued to the user's balance * @param user The address of the user * @return The last index interest was accrued to the user's balance, expressed in ray */ function getPreviousIndex(address user) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. */ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @notice Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return True if the previous balance of the user is 0, false otherwise * @return The scaled total debt of the reserve */ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool, uint256); /** * @notice Burns user variable debt * @dev In some instances, a burn transaction will emit a mint event * if the amount to burn is less than the interest that the user accrued * @param from The address from which the debt will be burned * @param amount The amount getting burned * @param index The variable debt index of the reserve * @return The scaled total debt of the reserve */ function burn(address from, uint256 amount, uint256 index) external returns (uint256); /** * @notice Returns the address of the underlying asset of this debtToken (E.g. WETH for variableDebtWETH) * @return The address of the underlying asset */ function UNDERLYING_ASSET_ADDRESS() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {AggregatorInterface} from '../dependencies/chainlink/AggregatorInterface.sol'; import {Errors} from '../protocol/libraries/helpers/Errors.sol'; import {IACLManager} from '../interfaces/IACLManager.sol'; import {IPoolAddressesProvider} from '../interfaces/IPoolAddressesProvider.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAaveOracle} from '../interfaces/IAaveOracle.sol'; /** * @title AaveOracle * @author Aave * @notice Contract to get asset prices, manage price sources and update the fallback oracle * - Use of Chainlink Aggregators as first source of price * - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallback oracle * - Owned by the Aave governance */ contract AaveOracle is IAaveOracle { IPoolAddressesProvider public immutable ADDRESSES_PROVIDER; // Map of asset price sources (asset => priceSource) mapping(address => AggregatorInterface) private assetsSources; IPriceOracleGetter private _fallbackOracle; address public immutable override BASE_CURRENCY; uint256 public immutable override BASE_CURRENCY_UNIT; /** * @dev Only asset listing or pool admin can call functions marked by this modifier. */ modifier onlyAssetListingOrPoolAdmins() { _onlyAssetListingOrPoolAdmins(); _; } /** * @notice Constructor * @param provider The address of the new PoolAddressesProvider * @param assets The addresses of the assets * @param sources The address of the source of each asset * @param fallbackOracle The address of the fallback oracle to use if the data of an * aggregator is not consistent * @param baseCurrency The base currency used for the price quotes. If USD is used, base currency is 0x0 * @param baseCurrencyUnit The unit of the base currency */ constructor( IPoolAddressesProvider provider, address[] memory assets, address[] memory sources, address fallbackOracle, address baseCurrency, uint256 baseCurrencyUnit ) { ADDRESSES_PROVIDER = provider; _setFallbackOracle(fallbackOracle); _setAssetsSources(assets, sources); BASE_CURRENCY = baseCurrency; BASE_CURRENCY_UNIT = baseCurrencyUnit; emit BaseCurrencySet(baseCurrency, baseCurrencyUnit); } /// @inheritdoc IAaveOracle function setAssetSources( address[] calldata assets, address[] calldata sources ) external override onlyAssetListingOrPoolAdmins { _setAssetsSources(assets, sources); } /// @inheritdoc IAaveOracle function setFallbackOracle( address fallbackOracle ) external override onlyAssetListingOrPoolAdmins { _setFallbackOracle(fallbackOracle); } /** * @notice Internal function to set the sources for each asset * @param assets The addresses of the assets * @param sources The address of the source of each asset */ function _setAssetsSources(address[] memory assets, address[] memory sources) internal { require(assets.length == sources.length, Errors.INCONSISTENT_PARAMS_LENGTH); for (uint256 i = 0; i < assets.length; i++) { assetsSources[assets[i]] = AggregatorInterface(sources[i]); emit AssetSourceUpdated(assets[i], sources[i]); } } /** * @notice Internal function to set the fallback oracle * @param fallbackOracle The address of the fallback oracle */ function _setFallbackOracle(address fallbackOracle) internal { _fallbackOracle = IPriceOracleGetter(fallbackOracle); emit FallbackOracleUpdated(fallbackOracle); } /// @inheritdoc IPriceOracleGetter function getAssetPrice(address asset) public view override returns (uint256) { AggregatorInterface source = assetsSources[asset]; if (asset == BASE_CURRENCY) { return BASE_CURRENCY_UNIT; } else if (address(source) == address(0)) { return _fallbackOracle.getAssetPrice(asset); } else { int256 price = source.latestAnswer(); if (price > 0) { return uint256(price); } else { return _fallbackOracle.getAssetPrice(asset); } } } /// @inheritdoc IAaveOracle function getAssetsPrices( address[] calldata assets ) external view override returns (uint256[] memory) { uint256[] memory prices = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { prices[i] = getAssetPrice(assets[i]); } return prices; } /// @inheritdoc IAaveOracle function getSourceOfAsset(address asset) external view override returns (address) { return address(assetsSources[asset]); } /// @inheritdoc IAaveOracle function getFallbackOracle() external view returns (address) { return address(_fallbackOracle); } function _onlyAssetListingOrPoolAdmins() internal view { IACLManager aclManager = IACLManager(ADDRESSES_PROVIDER.getACLManager()); require( aclManager.isAssetListingAdmin(msg.sender) || aclManager.isPoolAdmin(msg.sender), Errors.CALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {Errors} from '../protocol/libraries/helpers/Errors.sol'; import {IDefaultInterestRateStrategyV2} from '../interfaces/IDefaultInterestRateStrategyV2.sol'; import {IReserveInterestRateStrategy} from '../interfaces/IReserveInterestRateStrategy.sol'; import {IPoolAddressesProvider} from '../interfaces/IPoolAddressesProvider.sol'; /** * @title DefaultReserveInterestRateStrategyV2 contract * @author BGD Labs * @notice Default interest rate strategy used by the Aave protocol * @dev Strategies are pool-specific: each contract CAN'T be used across different Aave pools * due to the caching of the PoolAddressesProvider and the usage of underlying addresses as * index of the _interestRateData */ contract DefaultReserveInterestRateStrategyV2 is IDefaultInterestRateStrategyV2 { using WadRayMath for uint256; using PercentageMath for uint256; struct CalcInterestRatesLocalVars { uint256 availableLiquidity; uint256 currentVariableBorrowRate; uint256 currentLiquidityRate; uint256 borrowUsageRatio; uint256 supplyUsageRatio; uint256 availableLiquidityPlusDebt; } /// @inheritdoc IDefaultInterestRateStrategyV2 IPoolAddressesProvider public immutable ADDRESSES_PROVIDER; /// @inheritdoc IDefaultInterestRateStrategyV2 uint256 public constant MAX_BORROW_RATE = 1000_00; /// @inheritdoc IDefaultInterestRateStrategyV2 uint256 public constant MIN_OPTIMAL_POINT = 1_00; /// @inheritdoc IDefaultInterestRateStrategyV2 uint256 public constant MAX_OPTIMAL_POINT = 99_00; /// @dev Map of reserves address and their interest rate data (reserveAddress => interestRateData) mapping(address => InterestRateData) internal _interestRateData; modifier onlyPoolConfigurator() { require( msg.sender == ADDRESSES_PROVIDER.getPoolConfigurator(), Errors.CALLER_NOT_POOL_CONFIGURATOR ); _; } /** * @dev Constructor. * @param provider The address of the PoolAddressesProvider of the associated Aave pool */ constructor(address provider) { require(provider != address(0), Errors.INVALID_ADDRESSES_PROVIDER); ADDRESSES_PROVIDER = IPoolAddressesProvider(provider); } /// @inheritdoc IReserveInterestRateStrategy function setInterestRateParams( address reserve, bytes calldata rateData ) external onlyPoolConfigurator { _setInterestRateParams(reserve, abi.decode(rateData, (InterestRateData))); } /// @inheritdoc IDefaultInterestRateStrategyV2 function setInterestRateParams( address reserve, InterestRateData calldata rateData ) external onlyPoolConfigurator { _setInterestRateParams(reserve, rateData); } /// @inheritdoc IDefaultInterestRateStrategyV2 function getInterestRateData(address reserve) external view returns (InterestRateDataRay memory) { return _rayifyRateData(_interestRateData[reserve]); } /// @inheritdoc IDefaultInterestRateStrategyV2 function getInterestRateDataBps(address reserve) external view returns (InterestRateData memory) { return _interestRateData[reserve]; } /// @inheritdoc IDefaultInterestRateStrategyV2 function getOptimalUsageRatio(address reserve) external view returns (uint256) { return _bpsToRay(uint256(_interestRateData[reserve].optimalUsageRatio)); } /// @inheritdoc IDefaultInterestRateStrategyV2 function getVariableRateSlope1(address reserve) external view returns (uint256) { return _bpsToRay(uint256(_interestRateData[reserve].variableRateSlope1)); } /// @inheritdoc IDefaultInterestRateStrategyV2 function getVariableRateSlope2(address reserve) external view returns (uint256) { return _bpsToRay(uint256(_interestRateData[reserve].variableRateSlope2)); } /// @inheritdoc IDefaultInterestRateStrategyV2 function getBaseVariableBorrowRate(address reserve) external view override returns (uint256) { return _bpsToRay(uint256(_interestRateData[reserve].baseVariableBorrowRate)); } /// @inheritdoc IDefaultInterestRateStrategyV2 function getMaxVariableBorrowRate(address reserve) external view override returns (uint256) { return _bpsToRay( uint256( _interestRateData[reserve].baseVariableBorrowRate + _interestRateData[reserve].variableRateSlope1 + _interestRateData[reserve].variableRateSlope2 ) ); } /// @inheritdoc IReserveInterestRateStrategy function calculateInterestRates( DataTypes.CalculateInterestRatesParams memory params ) external view virtual override returns (uint256, uint256) { InterestRateDataRay memory rateData = _rayifyRateData(_interestRateData[params.reserve]); // @note This is a short circuit to allow mintable assets (ex. GHO), which by definition cannot be supplied // and thus do not use virtual underlying balances. if (!params.usingVirtualBalance) { return (0, rateData.baseVariableBorrowRate); } CalcInterestRatesLocalVars memory vars; vars.currentLiquidityRate = 0; vars.currentVariableBorrowRate = rateData.baseVariableBorrowRate; if (params.totalDebt != 0) { vars.availableLiquidity = params.virtualUnderlyingBalance + params.liquidityAdded - params.liquidityTaken; vars.availableLiquidityPlusDebt = vars.availableLiquidity + params.totalDebt; vars.borrowUsageRatio = params.totalDebt.rayDiv(vars.availableLiquidityPlusDebt); vars.supplyUsageRatio = params.totalDebt.rayDiv( vars.availableLiquidityPlusDebt + params.unbacked ); } else { return (0, vars.currentVariableBorrowRate); } if (vars.borrowUsageRatio > rateData.optimalUsageRatio) { uint256 excessBorrowUsageRatio = (vars.borrowUsageRatio - rateData.optimalUsageRatio).rayDiv( WadRayMath.RAY - rateData.optimalUsageRatio ); vars.currentVariableBorrowRate += rateData.variableRateSlope1 + rateData.variableRateSlope2.rayMul(excessBorrowUsageRatio); } else { vars.currentVariableBorrowRate += rateData .variableRateSlope1 .rayMul(vars.borrowUsageRatio) .rayDiv(rateData.optimalUsageRatio); } vars.currentLiquidityRate = vars .currentVariableBorrowRate .rayMul(vars.supplyUsageRatio) .percentMul(PercentageMath.PERCENTAGE_FACTOR - params.reserveFactor); return (vars.currentLiquidityRate, vars.currentVariableBorrowRate); } /** * @dev Doing validations and data update for an asset * @param reserve address of the underlying asset of the reserve * @param rateData Encoded reserve interest rate data to apply */ function _setInterestRateParams(address reserve, InterestRateData memory rateData) internal { require(reserve != address(0), Errors.ZERO_ADDRESS_NOT_VALID); require( rateData.optimalUsageRatio <= MAX_OPTIMAL_POINT && rateData.optimalUsageRatio >= MIN_OPTIMAL_POINT, Errors.INVALID_OPTIMAL_USAGE_RATIO ); require( rateData.variableRateSlope1 <= rateData.variableRateSlope2, Errors.SLOPE_2_MUST_BE_GTE_SLOPE_1 ); // The maximum rate should not be above certain threshold require( uint256(rateData.baseVariableBorrowRate) + uint256(rateData.variableRateSlope1) + uint256(rateData.variableRateSlope2) <= MAX_BORROW_RATE, Errors.INVALID_MAX_RATE ); _interestRateData[reserve] = rateData; emit RateDataUpdate( reserve, rateData.optimalUsageRatio, rateData.baseVariableBorrowRate, rateData.variableRateSlope1, rateData.variableRateSlope2 ); } /** * @dev Transforms an InterestRateData struct to an InterestRateDataRay struct by multiplying all values * by 1e23, turning them into ray values * * @param data The InterestRateData struct to transform * * @return The resulting InterestRateDataRay struct */ function _rayifyRateData( InterestRateData memory data ) internal pure returns (InterestRateDataRay memory) { return InterestRateDataRay({ optimalUsageRatio: _bpsToRay(uint256(data.optimalUsageRatio)), baseVariableBorrowRate: _bpsToRay(uint256(data.baseVariableBorrowRate)), variableRateSlope1: _bpsToRay(uint256(data.variableRateSlope1)), variableRateSlope2: _bpsToRay(uint256(data.variableRateSlope2)) }); } // @dev helper function added here, as generally the protocol doesn't use bps function _bpsToRay(uint256 n) internal pure returns (uint256) { return n * 1e23; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * @notice Helper contract to implement initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * @dev WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @notice Returns the revision number of the contract * @dev Needs to be defined in the inherited class as a constant. * @return The revision number */ function getRevision() internal pure virtual returns (uint256); /** * @notice Returns true if and only if the function is running in the constructor * @return True if the function is running in the constructor */ function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {IFlashLoanSimpleReceiver} from '../interfaces/IFlashLoanSimpleReceiver.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IPool} from '../../../interfaces/IPool.sol'; /** * @title FlashLoanSimpleReceiverBase * @author Aave * @notice Base contract to develop a flashloan-receiver contract. */ abstract contract FlashLoanSimpleReceiverBase is IFlashLoanSimpleReceiver { IPoolAddressesProvider public immutable override ADDRESSES_PROVIDER; IPool public immutable override POOL; constructor(IPoolAddressesProvider provider) { ADDRESSES_PROVIDER = provider; POOL = IPool(provider.getPool()); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IPool} from '../../../interfaces/IPool.sol'; /** * @title IFlashLoanSimpleReceiver * @author Aave * @notice Defines the basic interface of a flashloan-receiver contract. * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract */ interface IFlashLoanSimpleReceiver { /** * @notice Executes an operation after receiving the flash-borrowed asset * @dev Ensure that the contract can return the debt + premium, e.g., has * enough funds to repay and has approved the Pool to pull the total amount * @param asset The address of the flash-borrowed asset * @param amount The amount of the flash-borrowed asset * @param premium The fee of the flash-borrowed asset * @param initiator The address of the flashloan initiator * @param params The byte-encoded params passed when initiating the flashloan * @return True if the execution of the operation succeeds, false otherwise */ function executeOperation( address asset, uint256 amount, uint256 premium, address initiator, bytes calldata params ) external returns (bool); function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider); function POOL() external view returns (IPool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 internal constant LTV_MASK = 0x000000000000000000000000000000000000000000000000000000000000FFFF; // prettier-ignore uint256 internal constant LIQUIDATION_THRESHOLD_MASK = 0x00000000000000000000000000000000000000000000000000000000FFFF0000; // prettier-ignore uint256 internal constant LIQUIDATION_BONUS_MASK = 0x0000000000000000000000000000000000000000000000000000FFFF00000000; // prettier-ignore uint256 internal constant DECIMALS_MASK = 0x00000000000000000000000000000000000000000000000000FF000000000000; // prettier-ignore uint256 internal constant ACTIVE_MASK = 0x0000000000000000000000000000000000000000000000000100000000000000; // prettier-ignore uint256 internal constant FROZEN_MASK = 0x0000000000000000000000000000000000000000000000000200000000000000; // prettier-ignore uint256 internal constant BORROWING_MASK = 0x0000000000000000000000000000000000000000000000000400000000000000; // prettier-ignore // @notice there is an unoccupied hole of 1 bit at position 59 from pre 3.2 stableBorrowRateEnabled uint256 internal constant PAUSED_MASK = 0x0000000000000000000000000000000000000000000000001000000000000000; // prettier-ignore uint256 internal constant BORROWABLE_IN_ISOLATION_MASK = 0x0000000000000000000000000000000000000000000000002000000000000000; // prettier-ignore uint256 internal constant SILOED_BORROWING_MASK = 0x0000000000000000000000000000000000000000000000004000000000000000; // prettier-ignore uint256 internal constant FLASHLOAN_ENABLED_MASK = 0x0000000000000000000000000000000000000000000000008000000000000000; // prettier-ignore uint256 internal constant RESERVE_FACTOR_MASK = 0x00000000000000000000000000000000000000000000FFFF0000000000000000; // prettier-ignore uint256 internal constant BORROW_CAP_MASK = 0x00000000000000000000000000000000000FFFFFFFFF00000000000000000000; // prettier-ignore uint256 internal constant SUPPLY_CAP_MASK = 0x00000000000000000000000000FFFFFFFFF00000000000000000000000000000; // prettier-ignore uint256 internal constant LIQUIDATION_PROTOCOL_FEE_MASK = 0x0000000000000000000000FFFF00000000000000000000000000000000000000; // prettier-ignore //@notice there is an unoccupied hole of 8 bits from 168 to 176 left from pre 3.2 eModeCategory uint256 internal constant UNBACKED_MINT_CAP_MASK = 0x00000000000FFFFFFFFF00000000000000000000000000000000000000000000; // prettier-ignore uint256 internal constant DEBT_CEILING_MASK = 0x0FFFFFFFFFF00000000000000000000000000000000000000000000000000000; // prettier-ignore uint256 internal constant VIRTUAL_ACC_ACTIVE_MASK = 0x1000000000000000000000000000000000000000000000000000000000000000; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 internal constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 internal constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 internal constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 internal constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 internal constant IS_FROZEN_START_BIT_POSITION = 57; uint256 internal constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 internal constant IS_PAUSED_START_BIT_POSITION = 60; uint256 internal constant BORROWABLE_IN_ISOLATION_START_BIT_POSITION = 61; uint256 internal constant SILOED_BORROWING_START_BIT_POSITION = 62; uint256 internal constant FLASHLOAN_ENABLED_START_BIT_POSITION = 63; uint256 internal constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 internal constant BORROW_CAP_START_BIT_POSITION = 80; uint256 internal constant SUPPLY_CAP_START_BIT_POSITION = 116; uint256 internal constant LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION = 152; //@notice there is an unoccupied hole of 8 bits from 168 to 176 left from pre 3.2 eModeCategory uint256 internal constant UNBACKED_MINT_CAP_START_BIT_POSITION = 176; uint256 internal constant DEBT_CEILING_START_BIT_POSITION = 212; uint256 internal constant VIRTUAL_ACC_START_BIT_POSITION = 252; uint256 internal constant MAX_VALID_LTV = 65535; uint256 internal constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 internal constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 internal constant MAX_VALID_DECIMALS = 255; uint256 internal constant MAX_VALID_RESERVE_FACTOR = 65535; uint256 internal constant MAX_VALID_BORROW_CAP = 68719476735; uint256 internal constant MAX_VALID_SUPPLY_CAP = 68719476735; uint256 internal constant MAX_VALID_LIQUIDATION_PROTOCOL_FEE = 65535; uint256 internal constant MAX_VALID_UNBACKED_MINT_CAP = 68719476735; uint256 internal constant MAX_VALID_DEBT_CEILING = 1099511627775; uint256 public constant DEBT_CEILING_DECIMALS = 2; uint16 public constant MAX_RESERVES_COUNT = 128; /** * @notice Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv The new ltv */ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.INVALID_LTV); self.data = (self.data & ~LTV_MASK) | ltv; } /** * @notice Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value */ function getLtv(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) { return self.data & LTV_MASK; } /** * @notice Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold */ function setLiquidationThreshold( DataTypes.ReserveConfigurationMap memory self, uint256 threshold ) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.INVALID_LIQ_THRESHOLD); self.data = (self.data & ~LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @notice Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold */ function getLiquidationThreshold( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256) { return (self.data & LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @notice Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus */ function setLiquidationBonus( DataTypes.ReserveConfigurationMap memory self, uint256 bonus ) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.INVALID_LIQ_BONUS); self.data = (self.data & ~LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @notice Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus */ function getLiquidationBonus( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256) { return (self.data & LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @notice Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals */ function setDecimals( DataTypes.ReserveConfigurationMap memory self, uint256 decimals ) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.INVALID_DECIMALS); self.data = (self.data & ~DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @notice Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset */ function getDecimals( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256) { return (self.data & DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @notice Sets the active state of the reserve * @param self The reserve configuration * @param active The active state */ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ~ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @notice Gets the active state of the reserve * @param self The reserve configuration * @return The active state */ function getActive(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) { return (self.data & ACTIVE_MASK) != 0; } /** * @notice Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state */ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & ~FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @notice Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state */ function getFrozen(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) { return (self.data & FROZEN_MASK) != 0; } /** * @notice Sets the paused state of the reserve * @param self The reserve configuration * @param paused The paused state */ function setPaused(DataTypes.ReserveConfigurationMap memory self, bool paused) internal pure { self.data = (self.data & ~PAUSED_MASK) | (uint256(paused ? 1 : 0) << IS_PAUSED_START_BIT_POSITION); } /** * @notice Gets the paused state of the reserve * @param self The reserve configuration * @return The paused state */ function getPaused(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) { return (self.data & PAUSED_MASK) != 0; } /** * @notice Sets the borrowable in isolation flag for the reserve. * @dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the borrowed * amount will be accumulated in the isolated collateral's total debt exposure. * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep * consistency in the debt ceiling calculations. * @param self The reserve configuration * @param borrowable True if the asset is borrowable */ function setBorrowableInIsolation( DataTypes.ReserveConfigurationMap memory self, bool borrowable ) internal pure { self.data = (self.data & ~BORROWABLE_IN_ISOLATION_MASK) | (uint256(borrowable ? 1 : 0) << BORROWABLE_IN_ISOLATION_START_BIT_POSITION); } /** * @notice Gets the borrowable in isolation flag for the reserve. * @dev If the returned flag is true, the asset is borrowable against isolated collateral. Assets borrowed with * isolated collateral is accounted for in the isolated collateral's total debt exposure. * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep * consistency in the debt ceiling calculations. * @param self The reserve configuration * @return The borrowable in isolation flag */ function getBorrowableInIsolation( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (bool) { return (self.data & BORROWABLE_IN_ISOLATION_MASK) != 0; } /** * @notice Sets the siloed borrowing flag for the reserve. * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset. * @param self The reserve configuration * @param siloed True if the asset is siloed */ function setSiloedBorrowing( DataTypes.ReserveConfigurationMap memory self, bool siloed ) internal pure { self.data = (self.data & ~SILOED_BORROWING_MASK) | (uint256(siloed ? 1 : 0) << SILOED_BORROWING_START_BIT_POSITION); } /** * @notice Gets the siloed borrowing flag for the reserve. * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset. * @param self The reserve configuration * @return The siloed borrowing flag */ function getSiloedBorrowing( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (bool) { return (self.data & SILOED_BORROWING_MASK) != 0; } /** * @notice Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise */ function setBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self, bool enabled ) internal pure { self.data = (self.data & ~BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @notice Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state */ function getBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (bool) { return (self.data & BORROWING_MASK) != 0; } /** * @notice Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor */ function setReserveFactor( DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor ) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.INVALID_RESERVE_FACTOR); self.data = (self.data & ~RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @notice Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor */ function getReserveFactor( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256) { return (self.data & RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @notice Sets the borrow cap of the reserve * @param self The reserve configuration * @param borrowCap The borrow cap */ function setBorrowCap( DataTypes.ReserveConfigurationMap memory self, uint256 borrowCap ) internal pure { require(borrowCap <= MAX_VALID_BORROW_CAP, Errors.INVALID_BORROW_CAP); self.data = (self.data & ~BORROW_CAP_MASK) | (borrowCap << BORROW_CAP_START_BIT_POSITION); } /** * @notice Gets the borrow cap of the reserve * @param self The reserve configuration * @return The borrow cap */ function getBorrowCap( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256) { return (self.data & BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION; } /** * @notice Sets the supply cap of the reserve * @param self The reserve configuration * @param supplyCap The supply cap */ function setSupplyCap( DataTypes.ReserveConfigurationMap memory self, uint256 supplyCap ) internal pure { require(supplyCap <= MAX_VALID_SUPPLY_CAP, Errors.INVALID_SUPPLY_CAP); self.data = (self.data & ~SUPPLY_CAP_MASK) | (supplyCap << SUPPLY_CAP_START_BIT_POSITION); } /** * @notice Gets the supply cap of the reserve * @param self The reserve configuration * @return The supply cap */ function getSupplyCap( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256) { return (self.data & SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION; } /** * @notice Sets the debt ceiling in isolation mode for the asset * @param self The reserve configuration * @param ceiling The maximum debt ceiling for the asset */ function setDebtCeiling( DataTypes.ReserveConfigurationMap memory self, uint256 ceiling ) internal pure { require(ceiling <= MAX_VALID_DEBT_CEILING, Errors.INVALID_DEBT_CEILING); self.data = (self.data & ~DEBT_CEILING_MASK) | (ceiling << DEBT_CEILING_START_BIT_POSITION); } /** * @notice Gets the debt ceiling for the asset if the asset is in isolation mode * @param self The reserve configuration * @return The debt ceiling (0 = isolation mode disabled) */ function getDebtCeiling( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256) { return (self.data & DEBT_CEILING_MASK) >> DEBT_CEILING_START_BIT_POSITION; } /** * @notice Sets the liquidation protocol fee of the reserve * @param self The reserve configuration * @param liquidationProtocolFee The liquidation protocol fee */ function setLiquidationProtocolFee( DataTypes.ReserveConfigurationMap memory self, uint256 liquidationProtocolFee ) internal pure { require( liquidationProtocolFee <= MAX_VALID_LIQUIDATION_PROTOCOL_FEE, Errors.INVALID_LIQUIDATION_PROTOCOL_FEE ); self.data = (self.data & ~LIQUIDATION_PROTOCOL_FEE_MASK) | (liquidationProtocolFee << LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION); } /** * @dev Gets the liquidation protocol fee * @param self The reserve configuration * @return The liquidation protocol fee */ function getLiquidationProtocolFee( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256) { return (self.data & LIQUIDATION_PROTOCOL_FEE_MASK) >> LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION; } /** * @notice Sets the unbacked mint cap of the reserve * @param self The reserve configuration * @param unbackedMintCap The unbacked mint cap */ function setUnbackedMintCap( DataTypes.ReserveConfigurationMap memory self, uint256 unbackedMintCap ) internal pure { require(unbackedMintCap <= MAX_VALID_UNBACKED_MINT_CAP, Errors.INVALID_UNBACKED_MINT_CAP); self.data = (self.data & ~UNBACKED_MINT_CAP_MASK) | (unbackedMintCap << UNBACKED_MINT_CAP_START_BIT_POSITION); } /** * @dev Gets the unbacked mint cap of the reserve * @param self The reserve configuration * @return The unbacked mint cap */ function getUnbackedMintCap( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256) { return (self.data & UNBACKED_MINT_CAP_MASK) >> UNBACKED_MINT_CAP_START_BIT_POSITION; } /** * @notice Sets the flashloanable flag for the reserve * @param self The reserve configuration * @param flashLoanEnabled True if the asset is flashloanable, false otherwise */ function setFlashLoanEnabled( DataTypes.ReserveConfigurationMap memory self, bool flashLoanEnabled ) internal pure { self.data = (self.data & ~FLASHLOAN_ENABLED_MASK) | (uint256(flashLoanEnabled ? 1 : 0) << FLASHLOAN_ENABLED_START_BIT_POSITION); } /** * @notice Gets the flashloanable flag for the reserve * @param self The reserve configuration * @return The flashloanable flag */ function getFlashLoanEnabled( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (bool) { return (self.data & FLASHLOAN_ENABLED_MASK) != 0; } /** * @notice Sets the virtual account active/not state of the reserve * @param self The reserve configuration * @param active The active state */ function setVirtualAccActive( DataTypes.ReserveConfigurationMap memory self, bool active ) internal pure { self.data = (self.data & ~VIRTUAL_ACC_ACTIVE_MASK) | (uint256(active ? 1 : 0) << VIRTUAL_ACC_START_BIT_POSITION); } /** * @notice Gets the virtual account active/not state of the reserve * @dev The state should be true for all normal assets and should be false * Virtual accounting being disabled means that the asset: * - is GHO * - can never be supplied * - the interest rate strategy is not influenced by the virtual balance * @param self The reserve configuration * @return The active state */ function getIsVirtualAccActive( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (bool) { return (self.data & VIRTUAL_ACC_ACTIVE_MASK) != 0; } /** * @notice Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flag representing active * @return The state flag representing frozen * @return The state flag representing borrowing enabled * @return The state flag representing paused */ function getFlags( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (bool, bool, bool, bool) { uint256 dataLocal = self.data; return ( (dataLocal & ACTIVE_MASK) != 0, (dataLocal & FROZEN_MASK) != 0, (dataLocal & BORROWING_MASK) != 0, (dataLocal & PAUSED_MASK) != 0 ); } /** * @notice Gets the configuration parameters of the reserve from storage * @param self The reserve configuration * @return The state param representing ltv * @return The state param representing liquidation threshold * @return The state param representing liquidation bonus * @return The state param representing reserve decimals * @return The state param representing reserve factor */ function getParams( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256, uint256, uint256, uint256, uint256) { uint256 dataLocal = self.data; return ( dataLocal & LTV_MASK, (dataLocal & LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @notice Gets the caps parameters of the reserve from storage * @param self The reserve configuration * @return The state param representing borrow cap * @return The state param representing supply cap. */ function getCaps( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256, uint256) { uint256 dataLocal = self.data; return ( (dataLocal & BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION, (dataLocal & SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveConfiguration} from './ReserveConfiguration.sol'; /** * @title UserConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the user configuration */ library UserConfiguration { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555; uint256 internal constant COLLATERAL_MASK = 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA; /** * @notice Sets if the user is borrowing the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param borrowing True if the user is borrowing the reserve, false otherwise */ function setBorrowing( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing ) internal { unchecked { require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX); uint256 bit = 1 << (reserveIndex << 1); if (borrowing) { self.data |= bit; } else { self.data &= ~bit; } } } /** * @notice Sets if the user is using as collateral the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param usingAsCollateral True if the user is using the reserve as collateral, false otherwise */ function setUsingAsCollateral( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool usingAsCollateral ) internal { unchecked { require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX); uint256 bit = 1 << ((reserveIndex << 1) + 1); if (usingAsCollateral) { self.data |= bit; } else { self.data &= ~bit; } } } /** * @notice Returns if a user has been using the reserve for borrowing or as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise */ function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { unchecked { require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX); return (self.data >> (reserveIndex << 1)) & 3 != 0; } } /** * @notice Validate a user has been using the reserve for borrowing * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing, false otherwise */ function isBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { unchecked { require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX); return (self.data >> (reserveIndex << 1)) & 1 != 0; } } /** * @notice Validate a user has been using the reserve as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve as collateral, false otherwise */ function isUsingAsCollateral( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { unchecked { require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX); return (self.data >> ((reserveIndex << 1) + 1)) & 1 != 0; } } /** * @notice Checks if a user has been supplying only one reserve as collateral * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0 * @param self The configuration object * @return True if the user has been supplying as collateral one reserve, false otherwise */ function isUsingAsCollateralOne( DataTypes.UserConfigurationMap memory self ) internal pure returns (bool) { uint256 collateralData = self.data & COLLATERAL_MASK; return collateralData != 0 && (collateralData & (collateralData - 1) == 0); } /** * @notice Checks if a user has been supplying any reserve as collateral * @param self The configuration object * @return True if the user has been supplying as collateral any reserve, false otherwise */ function isUsingAsCollateralAny( DataTypes.UserConfigurationMap memory self ) internal pure returns (bool) { return self.data & COLLATERAL_MASK != 0; } /** * @notice Checks if a user has been borrowing only one asset * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0 * @param self The configuration object * @return True if the user has been supplying as collateral one reserve, false otherwise */ function isBorrowingOne(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { uint256 borrowingData = self.data & BORROWING_MASK; return borrowingData != 0 && (borrowingData & (borrowingData - 1) == 0); } /** * @notice Checks if a user has been borrowing from any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise */ function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data & BORROWING_MASK != 0; } /** * @notice Checks if a user has not been using any reserve for borrowing or supply * @param self The configuration object * @return True if the user has not been borrowing or supplying any reserve, false otherwise */ function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; } /** * @notice Returns the Isolation Mode state of the user * @param self The configuration object * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @return True if the user is in isolation mode, false otherwise * @return The address of the only asset used as collateral * @return The debt ceiling of the reserve */ function getIsolationModeState( DataTypes.UserConfigurationMap memory self, mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList ) internal view returns (bool, address, uint256) { if (isUsingAsCollateralOne(self)) { uint256 assetId = _getFirstAssetIdByMask(self, COLLATERAL_MASK); address assetAddress = reservesList[assetId]; uint256 ceiling = reservesData[assetAddress].configuration.getDebtCeiling(); if (ceiling != 0) { return (true, assetAddress, ceiling); } } return (false, address(0), 0); } /** * @notice Returns the siloed borrowing state for the user * @param self The configuration object * @param reservesData The data of all the reserves * @param reservesList The reserve list * @return True if the user has borrowed a siloed asset, false otherwise * @return The address of the only borrowed asset */ function getSiloedBorrowingState( DataTypes.UserConfigurationMap memory self, mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList ) internal view returns (bool, address) { if (isBorrowingOne(self)) { uint256 assetId = _getFirstAssetIdByMask(self, BORROWING_MASK); address assetAddress = reservesList[assetId]; if (reservesData[assetAddress].configuration.getSiloedBorrowing()) { return (true, assetAddress); } } return (false, address(0)); } /** * @notice Returns the address of the first asset flagged in the bitmap given the corresponding bitmask * @param self The configuration object * @return The index of the first asset flagged in the bitmap once the corresponding mask is applied */ function _getFirstAssetIdByMask( DataTypes.UserConfigurationMap memory self, uint256 mask ) internal pure returns (uint256) { unchecked { uint256 bitmapData = self.data & mask; uint256 firstAssetPosition = bitmapData & ~(bitmapData - 1); uint256 id; while ((firstAssetPosition >>= 2) != 0) { id += 1; } return id; } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol */ library Errors { string public constant CALLER_NOT_POOL_ADMIN = '1'; // 'The caller of the function is not a pool admin' string public constant CALLER_NOT_EMERGENCY_ADMIN = '2'; // 'The caller of the function is not an emergency admin' string public constant CALLER_NOT_POOL_OR_EMERGENCY_ADMIN = '3'; // 'The caller of the function is not a pool or emergency admin' string public constant CALLER_NOT_RISK_OR_POOL_ADMIN = '4'; // 'The caller of the function is not a risk or pool admin' string public constant CALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN = '5'; // 'The caller of the function is not an asset listing or pool admin' string public constant CALLER_NOT_BRIDGE = '6'; // 'The caller of the function is not a bridge' string public constant ADDRESSES_PROVIDER_NOT_REGISTERED = '7'; // 'Pool addresses provider is not registered' string public constant INVALID_ADDRESSES_PROVIDER_ID = '8'; // 'Invalid id for the pool addresses provider' string public constant NOT_CONTRACT = '9'; // 'Address is not a contract' string public constant CALLER_NOT_POOL_CONFIGURATOR = '10'; // 'The caller of the function is not the pool configurator' string public constant CALLER_NOT_ATOKEN = '11'; // 'The caller of the function is not an AToken' string public constant INVALID_ADDRESSES_PROVIDER = '12'; // 'The address of the pool addresses provider is invalid' string public constant INVALID_FLASHLOAN_EXECUTOR_RETURN = '13'; // 'Invalid return value of the flashloan executor function' string public constant RESERVE_ALREADY_ADDED = '14'; // 'Reserve has already been added to reserve list' string public constant NO_MORE_RESERVES_ALLOWED = '15'; // 'Maximum amount of reserves in the pool reached' string public constant EMODE_CATEGORY_RESERVED = '16'; // 'Zero eMode category is reserved for volatile heterogeneous assets' string public constant INVALID_EMODE_CATEGORY_ASSIGNMENT = '17'; // 'Invalid eMode category assignment to asset' string public constant RESERVE_LIQUIDITY_NOT_ZERO = '18'; // 'The liquidity of the reserve needs to be 0' string public constant FLASHLOAN_PREMIUM_INVALID = '19'; // 'Invalid flashloan premium' string public constant INVALID_RESERVE_PARAMS = '20'; // 'Invalid risk parameters for the reserve' string public constant INVALID_EMODE_CATEGORY_PARAMS = '21'; // 'Invalid risk parameters for the eMode category' string public constant BRIDGE_PROTOCOL_FEE_INVALID = '22'; // 'Invalid bridge protocol fee' string public constant CALLER_MUST_BE_POOL = '23'; // 'The caller of this function must be a pool' string public constant INVALID_MINT_AMOUNT = '24'; // 'Invalid amount to mint' string public constant INVALID_BURN_AMOUNT = '25'; // 'Invalid amount to burn' string public constant INVALID_AMOUNT = '26'; // 'Amount must be greater than 0' string public constant RESERVE_INACTIVE = '27'; // 'Action requires an active reserve' string public constant RESERVE_FROZEN = '28'; // 'Action cannot be performed because the reserve is frozen' string public constant RESERVE_PAUSED = '29'; // 'Action cannot be performed because the reserve is paused' string public constant BORROWING_NOT_ENABLED = '30'; // 'Borrowing is not enabled' string public constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = '32'; // 'User cannot withdraw more than the available balance' string public constant INVALID_INTEREST_RATE_MODE_SELECTED = '33'; // 'Invalid interest rate mode selected' string public constant COLLATERAL_BALANCE_IS_ZERO = '34'; // 'The collateral balance is 0' string public constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '35'; // 'Health factor is lesser than the liquidation threshold' string public constant COLLATERAL_CANNOT_COVER_NEW_BORROW = '36'; // 'There is not enough collateral to cover a new borrow' string public constant COLLATERAL_SAME_AS_BORROWING_CURRENCY = '37'; // 'Collateral is (mostly) the same currency that is being borrowed' string public constant NO_DEBT_OF_SELECTED_TYPE = '39'; // 'For repayment of a specific type of debt, the user needs to have debt that type' string public constant NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '40'; // 'To repay on behalf of a user an explicit amount to repay is needed' string public constant NO_OUTSTANDING_VARIABLE_DEBT = '42'; // 'User does not have outstanding variable rate debt on this reserve' string public constant UNDERLYING_BALANCE_ZERO = '43'; // 'The underlying balance needs to be greater than 0' string public constant INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '44'; // 'Interest rate rebalance conditions were not met' string public constant HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '45'; // 'Health factor is not below the threshold' string public constant COLLATERAL_CANNOT_BE_LIQUIDATED = '46'; // 'The collateral chosen cannot be liquidated' string public constant SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '47'; // 'User did not borrow the specified currency' string public constant INCONSISTENT_FLASHLOAN_PARAMS = '49'; // 'Inconsistent flashloan parameters' string public constant BORROW_CAP_EXCEEDED = '50'; // 'Borrow cap is exceeded' string public constant SUPPLY_CAP_EXCEEDED = '51'; // 'Supply cap is exceeded' string public constant UNBACKED_MINT_CAP_EXCEEDED = '52'; // 'Unbacked mint cap is exceeded' string public constant DEBT_CEILING_EXCEEDED = '53'; // 'Debt ceiling is exceeded' string public constant UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO = '54'; // 'Claimable rights over underlying not zero (aToken supply or accruedToTreasury)' string public constant VARIABLE_DEBT_SUPPLY_NOT_ZERO = '56'; // 'Variable debt supply is not zero' string public constant LTV_VALIDATION_FAILED = '57'; // 'Ltv validation failed' string public constant INCONSISTENT_EMODE_CATEGORY = '58'; // 'Inconsistent eMode category' string public constant PRICE_ORACLE_SENTINEL_CHECK_FAILED = '59'; // 'Price oracle sentinel validation failed' string public constant ASSET_NOT_BORROWABLE_IN_ISOLATION = '60'; // 'Asset is not borrowable in isolation mode' string public constant RESERVE_ALREADY_INITIALIZED = '61'; // 'Reserve has already been initialized' string public constant USER_IN_ISOLATION_MODE_OR_LTV_ZERO = '62'; // 'User is in isolation mode or ltv is zero' string public constant INVALID_LTV = '63'; // 'Invalid ltv parameter for the reserve' string public constant INVALID_LIQ_THRESHOLD = '64'; // 'Invalid liquidity threshold parameter for the reserve' string public constant INVALID_LIQ_BONUS = '65'; // 'Invalid liquidity bonus parameter for the reserve' string public constant INVALID_DECIMALS = '66'; // 'Invalid decimals parameter of the underlying asset of the reserve' string public constant INVALID_RESERVE_FACTOR = '67'; // 'Invalid reserve factor parameter for the reserve' string public constant INVALID_BORROW_CAP = '68'; // 'Invalid borrow cap for the reserve' string public constant INVALID_SUPPLY_CAP = '69'; // 'Invalid supply cap for the reserve' string public constant INVALID_LIQUIDATION_PROTOCOL_FEE = '70'; // 'Invalid liquidation protocol fee for the reserve' string public constant INVALID_EMODE_CATEGORY = '71'; // 'Invalid eMode category for the reserve' string public constant INVALID_UNBACKED_MINT_CAP = '72'; // 'Invalid unbacked mint cap for the reserve' string public constant INVALID_DEBT_CEILING = '73'; // 'Invalid debt ceiling for the reserve string public constant INVALID_RESERVE_INDEX = '74'; // 'Invalid reserve index' string public constant ACL_ADMIN_CANNOT_BE_ZERO = '75'; // 'ACL admin cannot be set to the zero address' string public constant INCONSISTENT_PARAMS_LENGTH = '76'; // 'Array parameters that should be equal length are not' string public constant ZERO_ADDRESS_NOT_VALID = '77'; // 'Zero address not valid' string public constant INVALID_EXPIRATION = '78'; // 'Invalid expiration' string public constant INVALID_SIGNATURE = '79'; // 'Invalid signature' string public constant OPERATION_NOT_SUPPORTED = '80'; // 'Operation not supported' string public constant DEBT_CEILING_NOT_ZERO = '81'; // 'Debt ceiling is not zero' string public constant ASSET_NOT_LISTED = '82'; // 'Asset is not listed' string public constant INVALID_OPTIMAL_USAGE_RATIO = '83'; // 'Invalid optimal usage ratio' string public constant UNDERLYING_CANNOT_BE_RESCUED = '85'; // 'The underlying asset cannot be rescued' string public constant ADDRESSES_PROVIDER_ALREADY_ADDED = '86'; // 'Reserve has already been added to reserve list' string public constant POOL_ADDRESSES_DO_NOT_MATCH = '87'; // 'The token implementation pool address and the pool address provided by the initializing pool do not match' string public constant SILOED_BORROWING_VIOLATION = '89'; // 'User is trying to borrow multiple assets including a siloed one' string public constant RESERVE_DEBT_NOT_ZERO = '90'; // the total debt of the reserve needs to be 0 string public constant FLASHLOAN_DISABLED = '91'; // FlashLoaning for this asset is disabled string public constant INVALID_MAX_RATE = '92'; // The expect maximum borrow rate is invalid string public constant WITHDRAW_TO_ATOKEN = '93'; // Withdrawing to the aToken is not allowed string public constant SUPPLY_TO_ATOKEN = '94'; // Supplying to the aToken is not allowed string public constant SLOPE_2_MUST_BE_GTE_SLOPE_1 = '95'; // Variable interest rate slope 2 can not be lower than slope 1 string public constant CALLER_NOT_RISK_OR_POOL_OR_EMERGENCY_ADMIN = '96'; // 'The caller of the function is not a risk, pool or emergency admin' string public constant LIQUIDATION_GRACE_SENTINEL_CHECK_FAILED = '97'; // 'Liquidation grace sentinel validation failed' string public constant INVALID_GRACE_PERIOD = '98'; // Grace period above a valid range string public constant INVALID_FREEZE_STATE = '99'; // Reserve is already in the passed freeze state string public constant NOT_BORROWABLE_IN_EMODE = '100'; // Asset not borrowable in eMode string public constant CALLER_NOT_UMBRELLA = '101'; // The caller of the function is not the umbrella contract string public constant RESERVE_NOT_IN_DEFICIT = '102'; // The reserve is not in deficit string public constant MUST_NOT_LEAVE_DUST = '103'; // Below a certain threshold liquidators need to take the full position string public constant USER_CANNOT_HAVE_DEBT = '104'; // Thrown when a user tries to interact with a method that requires a position without debt }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down. */ library PercentageMath { // Maximum percentage factor (100.00%) uint256 internal constant PERCENTAGE_FACTOR = 1e4; // Half percentage factor (50.00%) uint256 internal constant HALF_PERCENTAGE_FACTOR = 0.5e4; /** * @notice Executes a percentage multiplication * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328 * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return result value percentmul percentage */ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256 result) { // to avoid overflow, value <= (type(uint256).max - HALF_PERCENTAGE_FACTOR) / percentage assembly { if iszero( or( iszero(percentage), iszero(gt(value, div(sub(not(0), HALF_PERCENTAGE_FACTOR), percentage))) ) ) { revert(0, 0) } result := div(add(mul(value, percentage), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR) } } /** * @notice Executes a percentage division * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328 * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return result value percentdiv percentage */ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256 result) { // to avoid overflow, value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR assembly { if or( iszero(percentage), iszero(iszero(gt(value, div(sub(not(0), div(percentage, 2)), PERCENTAGE_FACTOR)))) ) { revert(0, 0) } result := div(add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)), percentage) } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; /** * @title WadRayMath library * @author Aave * @notice Provides functions to perform calculations with Wad and Ray units * @dev Provides mul and div function for wads (decimal numbers with 18 digits of precision) and rays (decimal numbers * with 27 digits of precision) * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down. */ library WadRayMath { // HALF_WAD and HALF_RAY expressed with extended notation as constant with operations are not supported in Yul assembly uint256 internal constant WAD = 1e18; uint256 internal constant HALF_WAD = 0.5e18; uint256 internal constant RAY = 1e27; uint256 internal constant HALF_RAY = 0.5e27; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @dev Multiplies two wad, rounding half up to the nearest wad * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328 * @param a Wad * @param b Wad * @return c = a*b, in wad */ function wadMul(uint256 a, uint256 b) internal pure returns (uint256 c) { // to avoid overflow, a <= (type(uint256).max - HALF_WAD) / b assembly { if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_WAD), b))))) { revert(0, 0) } c := div(add(mul(a, b), HALF_WAD), WAD) } } /** * @dev Divides two wad, rounding half up to the nearest wad * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328 * @param a Wad * @param b Wad * @return c = a/b, in wad */ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256 c) { // to avoid overflow, a <= (type(uint256).max - halfB) / WAD assembly { if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), WAD))))) { revert(0, 0) } c := div(add(mul(a, WAD), div(b, 2)), b) } } /** * @notice Multiplies two ray, rounding half up to the nearest ray * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328 * @param a Ray * @param b Ray * @return c = a raymul b */ function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) { // to avoid overflow, a <= (type(uint256).max - HALF_RAY) / b assembly { if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_RAY), b))))) { revert(0, 0) } c := div(add(mul(a, b), HALF_RAY), RAY) } } /** * @notice Divides two ray, rounding half up to the nearest ray * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328 * @param a Ray * @param b Ray * @return c = a raydiv b */ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256 c) { // to avoid overflow, a <= (type(uint256).max - halfB) / RAY assembly { if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), RAY))))) { revert(0, 0) } c := div(add(mul(a, RAY), div(b, 2)), b) } } /** * @dev Casts ray down to wad * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328 * @param a Ray * @return b = a converted to wad, rounded half up to the nearest wad */ function rayToWad(uint256 a) internal pure returns (uint256 b) { assembly { b := div(a, WAD_RAY_RATIO) let remainder := mod(a, WAD_RAY_RATIO) if iszero(lt(remainder, div(WAD_RAY_RATIO, 2))) { b := add(b, 1) } } } /** * @dev Converts wad up to ray * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328 * @param a Wad * @return b = a converted in ray */ function wadToRay(uint256 a) internal pure returns (uint256 b) { // to avoid overflow, b/WAD_RAY_RATIO == a assembly { b := mul(a, WAD_RAY_RATIO) if iszero(eq(div(b, WAD_RAY_RATIO), a)) { revert(0, 0) } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ConfiguratorInputTypes { struct InitReserveInput { address aTokenImpl; address variableDebtTokenImpl; bool useVirtualBalance; address interestRateStrategyAddress; address underlyingAsset; address treasury; address incentivesController; string aTokenName; string aTokenSymbol; string variableDebtTokenName; string variableDebtTokenSymbol; bytes params; bytes interestRateData; } struct UpdateATokenInput { address asset; address treasury; address incentivesController; string name; string symbol; address implementation; bytes params; } struct UpdateDebtTokenInput { address asset; address incentivesController; string name; string symbol; address implementation; bytes params; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library DataTypes { /** * This exists specifically to maintain the `getReserveData()` interface, since the new, internal * `ReserveData` struct includes the reserve's `virtualUnderlyingBalance`. */ struct ReserveDataLegacy { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; // DEPRECATED on v3.2.0 uint128 currentStableBorrowRate; //timestamp of last update uint40 lastUpdateTimestamp; //the id of the reserve. Represents the position in the list of the active reserves uint16 id; //aToken address address aTokenAddress; // DEPRECATED on v3.2.0 address stableDebtTokenAddress; //variableDebtToken address address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the current treasury balance, scaled uint128 accruedToTreasury; //the outstanding unbacked aTokens minted through the bridging feature uint128 unbacked; //the outstanding debt borrowed against this asset in isolation mode uint128 isolationModeTotalDebt; } struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; /// @notice reused `__deprecatedStableBorrowRate` storage from pre 3.2 // the current accumulate deficit in underlying tokens uint128 deficit; //timestamp of last update uint40 lastUpdateTimestamp; //the id of the reserve. Represents the position in the list of the active reserves uint16 id; //timestamp until when liquidations are not allowed on the reserve, if set to past liquidations will be allowed uint40 liquidationGracePeriodUntil; //aToken address address aTokenAddress; // DEPRECATED on v3.2.0 address __deprecatedStableDebtTokenAddress; //variableDebtToken address address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the current treasury balance, scaled uint128 accruedToTreasury; //the outstanding unbacked aTokens minted through the bridging feature uint128 unbacked; //the outstanding debt borrowed against this asset in isolation mode uint128 isolationModeTotalDebt; //the amount of underlying accounted for by the protocol uint128 virtualUnderlyingBalance; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: DEPRECATED: stable rate borrowing enabled //bit 60: asset is paused //bit 61: borrowing in isolation mode is enabled //bit 62: siloed borrowing enabled //bit 63: flashloaning enabled //bit 64-79: reserve factor //bit 80-115: borrow cap in whole tokens, borrowCap == 0 => no cap //bit 116-151: supply cap in whole tokens, supplyCap == 0 => no cap //bit 152-167: liquidation protocol fee //bit 168-175: DEPRECATED: eMode category //bit 176-211: unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled //bit 212-251: debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals //bit 252: virtual accounting is enabled for the reserve //bit 253-255 unused uint256 data; } struct UserConfigurationMap { /** * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset. * The first bit indicates if an asset is used as collateral by the user, the second whether an * asset is borrowed by the user. */ uint256 data; } // DEPRECATED: kept for backwards compatibility, might be removed in a future version struct EModeCategoryLegacy { // each eMode category has a custom ltv and liquidation threshold uint16 ltv; uint16 liquidationThreshold; uint16 liquidationBonus; // DEPRECATED address priceSource; string label; } struct CollateralConfig { uint16 ltv; uint16 liquidationThreshold; uint16 liquidationBonus; } struct EModeCategoryBaseConfiguration { uint16 ltv; uint16 liquidationThreshold; uint16 liquidationBonus; string label; } struct EModeCategory { // each eMode category has a custom ltv and liquidation threshold uint16 ltv; uint16 liquidationThreshold; uint16 liquidationBonus; uint128 collateralBitmap; string label; uint128 borrowableBitmap; } enum InterestRateMode { NONE, __DEPRECATED, VARIABLE } struct ReserveCache { uint256 currScaledVariableDebt; uint256 nextScaledVariableDebt; uint256 currLiquidityIndex; uint256 nextLiquidityIndex; uint256 currVariableBorrowIndex; uint256 nextVariableBorrowIndex; uint256 currLiquidityRate; uint256 currVariableBorrowRate; uint256 reserveFactor; ReserveConfigurationMap reserveConfiguration; address aTokenAddress; address variableDebtTokenAddress; uint40 reserveLastUpdateTimestamp; } struct ExecuteLiquidationCallParams { uint256 reservesCount; uint256 debtToCover; address collateralAsset; address debtAsset; address user; bool receiveAToken; address priceOracle; uint8 userEModeCategory; address priceOracleSentinel; } struct ExecuteSupplyParams { address asset; uint256 amount; address onBehalfOf; uint16 referralCode; } struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; InterestRateMode interestRateMode; uint16 referralCode; bool releaseUnderlying; uint256 reservesCount; address oracle; uint8 userEModeCategory; address priceOracleSentinel; } struct ExecuteRepayParams { address asset; uint256 amount; InterestRateMode interestRateMode; address onBehalfOf; bool useATokens; } struct ExecuteWithdrawParams { address asset; uint256 amount; address to; uint256 reservesCount; address oracle; uint8 userEModeCategory; } struct ExecuteEliminateDeficitParams { address asset; uint256 amount; } struct ExecuteSetUserEModeParams { uint256 reservesCount; address oracle; uint8 categoryId; } struct FinalizeTransferParams { address asset; address from; address to; uint256 amount; uint256 balanceFromBefore; uint256 balanceToBefore; uint256 reservesCount; address oracle; uint8 fromEModeCategory; } struct FlashloanParams { address receiverAddress; address[] assets; uint256[] amounts; uint256[] interestRateModes; address onBehalfOf; bytes params; uint16 referralCode; uint256 flashLoanPremiumToProtocol; uint256 flashLoanPremiumTotal; uint256 reservesCount; address addressesProvider; address pool; uint8 userEModeCategory; bool isAuthorizedFlashBorrower; } struct FlashloanSimpleParams { address receiverAddress; address asset; uint256 amount; bytes params; uint16 referralCode; uint256 flashLoanPremiumToProtocol; uint256 flashLoanPremiumTotal; } struct FlashLoanRepaymentParams { uint256 amount; uint256 totalPremium; uint256 flashLoanPremiumToProtocol; address asset; address receiverAddress; uint16 referralCode; } struct CalculateUserAccountDataParams { UserConfigurationMap userConfig; uint256 reservesCount; address user; address oracle; uint8 userEModeCategory; } struct ValidateBorrowParams { ReserveCache reserveCache; UserConfigurationMap userConfig; address asset; address userAddress; uint256 amount; InterestRateMode interestRateMode; uint256 reservesCount; address oracle; uint8 userEModeCategory; address priceOracleSentinel; bool isolationModeActive; address isolationModeCollateralAddress; uint256 isolationModeDebtCeiling; } struct ValidateLiquidationCallParams { ReserveCache debtReserveCache; uint256 totalDebt; uint256 healthFactor; address priceOracleSentinel; } struct CalculateInterestRatesParams { uint256 unbacked; uint256 liquidityAdded; uint256 liquidityTaken; uint256 totalDebt; uint256 reserveFactor; address reserve; bool usingVirtualBalance; uint256 virtualUnderlyingBalance; } struct InitReserveParams { address asset; address aTokenAddress; address variableDebtAddress; address interestRateStrategyAddress; uint16 reservesCount; uint16 maxNumberReserves; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {Context} from '../../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {WadRayMath} from '../../libraries/math/WadRayMath.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; import {IAaveIncentivesController} from '../../../interfaces/IAaveIncentivesController.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IPool} from '../../../interfaces/IPool.sol'; import {IACLManager} from '../../../interfaces/IACLManager.sol'; /** * @title IncentivizedERC20 * @author Aave, inspired by the Openzeppelin ERC20 implementation * @notice Basic ERC20 implementation */ abstract contract IncentivizedERC20 is Context, IERC20Detailed { using WadRayMath for uint256; using SafeCast for uint256; /** * @dev Only pool admin can call functions marked by this modifier. */ modifier onlyPoolAdmin() { IACLManager aclManager = IACLManager(_addressesProvider.getACLManager()); require(aclManager.isPoolAdmin(msg.sender), Errors.CALLER_NOT_POOL_ADMIN); _; } /** * @dev Only pool can call functions marked by this modifier. */ modifier onlyPool() { require(_msgSender() == address(POOL), Errors.CALLER_MUST_BE_POOL); _; } /** * @dev UserState - additionalData is a flexible field. * ATokens and VariableDebtTokens use this field store the index of the * user's last supply/withdrawal/borrow/repayment. */ struct UserState { uint128 balance; uint128 additionalData; } // Map of users address and their state data (userAddress => userStateData) mapping(address => UserState) internal _userState; // Map of allowances (delegator => delegatee => allowanceAmount) mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; IAaveIncentivesController internal _incentivesController; IPoolAddressesProvider internal immutable _addressesProvider; IPool public immutable POOL; /** * @dev Constructor. * @param pool The reference to the main Pool contract * @param name_ The name of the token * @param symbol_ The symbol of the token * @param decimals_ The number of decimals of the token */ constructor(IPool pool, string memory name_, string memory symbol_, uint8 decimals_) { _addressesProvider = pool.ADDRESSES_PROVIDER(); _name = name_; _symbol = symbol_; _decimals = decimals_; POOL = pool; } /// @inheritdoc IERC20Detailed function name() public view override returns (string memory) { return _name; } /// @inheritdoc IERC20Detailed function symbol() external view override returns (string memory) { return _symbol; } /// @inheritdoc IERC20Detailed function decimals() external view override returns (uint8) { return _decimals; } /// @inheritdoc IERC20 function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /// @inheritdoc IERC20 function balanceOf(address account) public view virtual override returns (uint256) { return _userState[account].balance; } /** * @notice Returns the address of the Incentives Controller contract * @return The address of the Incentives Controller */ function getIncentivesController() external view virtual returns (IAaveIncentivesController) { return _incentivesController; } /** * @notice Sets a new Incentives Controller * @param controller the new Incentives controller */ function setIncentivesController(IAaveIncentivesController controller) external onlyPoolAdmin { _incentivesController = controller; } /// @inheritdoc IERC20 function transfer(address recipient, uint256 amount) external virtual override returns (bool) { uint128 castAmount = amount.toUint128(); _transfer(_msgSender(), recipient, castAmount); return true; } /// @inheritdoc IERC20 function allowance( address owner, address spender ) external view virtual override returns (uint256) { return _allowances[owner][spender]; } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address sender, address recipient, uint256 amount ) external virtual override returns (bool) { uint128 castAmount = amount.toUint128(); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - castAmount); _transfer(sender, recipient, castAmount); return true; } /** * @notice Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` */ function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @notice Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @return `true` */ function decreaseAllowance( address spender, uint256 subtractedValue ) external virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } /** * @notice Transfers tokens between two users and apply incentives if defined. * @param sender The source address * @param recipient The destination address * @param amount The amount getting transferred */ function _transfer(address sender, address recipient, uint128 amount) internal virtual { uint128 oldSenderBalance = _userState[sender].balance; _userState[sender].balance = oldSenderBalance - amount; uint128 oldRecipientBalance = _userState[recipient].balance; _userState[recipient].balance = oldRecipientBalance + amount; IAaveIncentivesController incentivesControllerLocal = _incentivesController; if (address(incentivesControllerLocal) != address(0)) { uint256 currentTotalSupply = _totalSupply; incentivesControllerLocal.handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { incentivesControllerLocal.handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } /** * @notice Approve `spender` to use `amount` of `owner`s balance * @param owner The address owning the tokens * @param spender The address approved for spending * @param amount The amount of tokens to approve spending of */ function _approve(address owner, address spender, uint256 amount) internal virtual { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Update the name of the token * @param newName The new name for the token */ function _setName(string memory newName) internal { _name = newName; } /** * @notice Update the symbol for the token * @param newSymbol The new symbol for the token */ function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } /** * @notice Update the number of decimals for the token * @param newDecimals The new number of decimals for the token */ function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {AggregatorInterface} from '../dependencies/chainlink/AggregatorInterface.sol'; import {IEmissionManager} from './interfaces/IEmissionManager.sol'; import {ITransferStrategyBase} from './interfaces/ITransferStrategyBase.sol'; import {IRewardsController} from './interfaces/IRewardsController.sol'; import {RewardsDataTypes} from './libraries/RewardsDataTypes.sol'; /** * @title EmissionManager * @author Aave * @notice It manages the list of admins of reward emissions and provides functions to control reward emissions. */ contract EmissionManager is Ownable, IEmissionManager { // reward => emissionAdmin mapping(address => address) internal _emissionAdmins; IRewardsController internal _rewardsController; /** * @dev Only emission admin of the given reward can call functions marked by this modifier. **/ modifier onlyEmissionAdmin(address reward) { require(msg.sender == _emissionAdmins[reward], 'ONLY_EMISSION_ADMIN'); _; } /** * Constructor. * @param owner The address of the owner */ constructor(address owner) { transferOwnership(owner); } /// @inheritdoc IEmissionManager function configureAssets(RewardsDataTypes.RewardsConfigInput[] memory config) external override { for (uint256 i = 0; i < config.length; i++) { require(_emissionAdmins[config[i].reward] == msg.sender, 'ONLY_EMISSION_ADMIN'); } _rewardsController.configureAssets(config); } /// @inheritdoc IEmissionManager function setTransferStrategy( address reward, ITransferStrategyBase transferStrategy ) external override onlyEmissionAdmin(reward) { _rewardsController.setTransferStrategy(reward, transferStrategy); } /// @inheritdoc IEmissionManager function setRewardOracle( address reward, AggregatorInterface rewardOracle ) external override onlyEmissionAdmin(reward) { _rewardsController.setRewardOracle(reward, rewardOracle); } /// @inheritdoc IEmissionManager function setDistributionEnd( address asset, address reward, uint32 newDistributionEnd ) external override onlyEmissionAdmin(reward) { _rewardsController.setDistributionEnd(asset, reward, newDistributionEnd); } /// @inheritdoc IEmissionManager function setEmissionPerSecond( address asset, address[] calldata rewards, uint88[] calldata newEmissionsPerSecond ) external override { for (uint256 i = 0; i < rewards.length; i++) { require(_emissionAdmins[rewards[i]] == msg.sender, 'ONLY_EMISSION_ADMIN'); } _rewardsController.setEmissionPerSecond(asset, rewards, newEmissionsPerSecond); } /// @inheritdoc IEmissionManager function setClaimer(address user, address claimer) external override onlyOwner { _rewardsController.setClaimer(user, claimer); } /// @inheritdoc IEmissionManager function setEmissionAdmin(address reward, address admin) external override onlyOwner { address oldAdmin = _emissionAdmins[reward]; _emissionAdmins[reward] = admin; emit EmissionAdminUpdated(reward, oldAdmin, admin); } /// @inheritdoc IEmissionManager function setRewardsController(address controller) external override onlyOwner { _rewardsController = IRewardsController(controller); } /// @inheritdoc IEmissionManager function getRewardsController() external view override returns (IRewardsController) { return _rewardsController; } /// @inheritdoc IEmissionManager function getEmissionAdmin(address reward) external view override returns (address) { return _emissionAdmins[reward]; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {VersionedInitializable} from '../misc/aave-upgradeability/VersionedInitializable.sol'; import {SafeCast} from '../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IScaledBalanceToken} from '../interfaces/IScaledBalanceToken.sol'; import {RewardsDistributor} from './RewardsDistributor.sol'; import {IRewardsController} from './interfaces/IRewardsController.sol'; import {ITransferStrategyBase} from './interfaces/ITransferStrategyBase.sol'; import {RewardsDataTypes} from './libraries/RewardsDataTypes.sol'; import {AggregatorInterface} from '../dependencies/chainlink/AggregatorInterface.sol'; /** * @title RewardsController * @notice Abstract contract template to build Distributors contracts for ERC20 rewards to protocol participants * @author Aave **/ contract RewardsController is RewardsDistributor, VersionedInitializable, IRewardsController { using SafeCast for uint256; uint256 public constant REVISION = 1; // This mapping allows whitelisted addresses to claim on behalf of others // useful for contracts that hold tokens to be rewarded but don't have any native logic to claim Liquidity Mining rewards mapping(address => address) internal _authorizedClaimers; // reward => transfer strategy implementation contract // The TransferStrategy contract abstracts the logic regarding // the source of the reward and how to transfer it to the user. mapping(address => ITransferStrategyBase) internal _transferStrategy; // This mapping contains the price oracle per reward. // A price oracle is enforced for integrators to be able to show incentives at // the current Aave UI without the need to setup an external price registry // At the moment of reward configuration, the Incentives Controller performs // a check to see if the provided reward oracle contains `latestAnswer`. mapping(address => AggregatorInterface) internal _rewardOracle; modifier onlyAuthorizedClaimers(address claimer, address user) { require(_authorizedClaimers[user] == claimer, 'CLAIMER_UNAUTHORIZED'); _; } constructor(address emissionManager) RewardsDistributor(emissionManager) {} /** * @dev Initialize for RewardsController * @dev It expects an address as argument since its initialized via PoolAddressesProvider._updateImpl() **/ function initialize(address) external initializer {} /// @inheritdoc IRewardsController function getClaimer(address user) external view override returns (address) { return _authorizedClaimers[user]; } /** * @dev Returns the revision of the implementation contract * @return uint256, current revision version */ function getRevision() internal pure override returns (uint256) { return REVISION; } /// @inheritdoc IRewardsController function getRewardOracle(address reward) external view override returns (address) { return address(_rewardOracle[reward]); } /// @inheritdoc IRewardsController function getTransferStrategy(address reward) external view override returns (address) { return address(_transferStrategy[reward]); } /// @inheritdoc IRewardsController function configureAssets( RewardsDataTypes.RewardsConfigInput[] memory config ) external override onlyEmissionManager { for (uint256 i = 0; i < config.length; i++) { // Get the current Scaled Total Supply of AToken or Debt token config[i].totalSupply = IScaledBalanceToken(config[i].asset).scaledTotalSupply(); // Install TransferStrategy logic at IncentivesController _installTransferStrategy(config[i].reward, config[i].transferStrategy); // Set reward oracle, enforces input oracle to have latestPrice function _setRewardOracle(config[i].reward, config[i].rewardOracle); } _configureAssets(config); } /// @inheritdoc IRewardsController function setTransferStrategy( address reward, ITransferStrategyBase transferStrategy ) external onlyEmissionManager { _installTransferStrategy(reward, transferStrategy); } /// @inheritdoc IRewardsController function setRewardOracle( address reward, AggregatorInterface rewardOracle ) external onlyEmissionManager { _setRewardOracle(reward, rewardOracle); } /// @inheritdoc IRewardsController function handleAction(address user, uint256 totalSupply, uint256 userBalance) external override { _updateData(msg.sender, user, userBalance, totalSupply); } /// @inheritdoc IRewardsController function claimRewards( address[] calldata assets, uint256 amount, address to, address reward ) external override returns (uint256) { require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimRewards(assets, amount, msg.sender, msg.sender, to, reward); } /// @inheritdoc IRewardsController function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to, address reward ) external override onlyAuthorizedClaimers(msg.sender, user) returns (uint256) { require(user != address(0), 'INVALID_USER_ADDRESS'); require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimRewards(assets, amount, msg.sender, user, to, reward); } /// @inheritdoc IRewardsController function claimRewardsToSelf( address[] calldata assets, uint256 amount, address reward ) external override returns (uint256) { return _claimRewards(assets, amount, msg.sender, msg.sender, msg.sender, reward); } /// @inheritdoc IRewardsController function claimAllRewards( address[] calldata assets, address to ) external override returns (address[] memory rewardsList, uint256[] memory claimedAmounts) { require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimAllRewards(assets, msg.sender, msg.sender, to); } /// @inheritdoc IRewardsController function claimAllRewardsOnBehalf( address[] calldata assets, address user, address to ) external override onlyAuthorizedClaimers(msg.sender, user) returns (address[] memory rewardsList, uint256[] memory claimedAmounts) { require(user != address(0), 'INVALID_USER_ADDRESS'); require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimAllRewards(assets, msg.sender, user, to); } /// @inheritdoc IRewardsController function claimAllRewardsToSelf( address[] calldata assets ) external override returns (address[] memory rewardsList, uint256[] memory claimedAmounts) { return _claimAllRewards(assets, msg.sender, msg.sender, msg.sender); } /// @inheritdoc IRewardsController function setClaimer(address user, address caller) external override onlyEmissionManager { _authorizedClaimers[user] = caller; emit ClaimerSet(user, caller); } /** * @dev Get user balances and total supply of all the assets specified by the assets parameter * @param assets List of assets to retrieve user balance and total supply * @param user Address of the user * @return userAssetBalances contains a list of structs with user balance and total supply of the given assets */ function _getUserAssetBalances( address[] calldata assets, address user ) internal view override returns (RewardsDataTypes.UserAssetBalance[] memory userAssetBalances) { userAssetBalances = new RewardsDataTypes.UserAssetBalance[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userAssetBalances[i].asset = assets[i]; (userAssetBalances[i].userBalance, userAssetBalances[i].totalSupply) = IScaledBalanceToken( assets[i] ).getScaledUserBalanceAndSupply(user); } return userAssetBalances; } /** * @dev Claims one type of reward for a user on behalf, on all the assets of the pool, accumulating the pending rewards. * @param assets List of assets to check eligible distributions before claiming rewards * @param amount Amount of rewards to claim * @param claimer Address of the claimer who claims rewards on behalf of user * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @param reward Address of the reward token * @return Rewards claimed **/ function _claimRewards( address[] calldata assets, uint256 amount, address claimer, address user, address to, address reward ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 totalRewards; _updateDataMultiple(user, _getUserAssetBalances(assets, user)); for (uint256 i = 0; i < assets.length; i++) { address asset = assets[i]; totalRewards += _assets[asset].rewards[reward].usersData[user].accrued; if (totalRewards <= amount) { _assets[asset].rewards[reward].usersData[user].accrued = 0; } else { uint256 difference = totalRewards - amount; totalRewards -= difference; _assets[asset].rewards[reward].usersData[user].accrued = difference.toUint128(); break; } } if (totalRewards == 0) { return 0; } _transferRewards(to, reward, totalRewards); emit RewardsClaimed(user, reward, to, claimer, totalRewards); return totalRewards; } /** * @dev Claims one type of reward for a user on behalf, on all the assets of the pool, accumulating the pending rewards. * @param assets List of assets to check eligible distributions before claiming rewards * @param claimer Address of the claimer on behalf of user * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return * rewardsList List of reward addresses * claimedAmount List of claimed amounts, follows "rewardsList" items order **/ function _claimAllRewards( address[] calldata assets, address claimer, address user, address to ) internal returns (address[] memory rewardsList, uint256[] memory claimedAmounts) { uint256 rewardsListLength = _rewardsList.length; rewardsList = new address[](rewardsListLength); claimedAmounts = new uint256[](rewardsListLength); _updateDataMultiple(user, _getUserAssetBalances(assets, user)); for (uint256 i = 0; i < assets.length; i++) { address asset = assets[i]; for (uint256 j = 0; j < rewardsListLength; j++) { if (rewardsList[j] == address(0)) { rewardsList[j] = _rewardsList[j]; } uint256 rewardAmount = _assets[asset].rewards[rewardsList[j]].usersData[user].accrued; if (rewardAmount != 0) { claimedAmounts[j] += rewardAmount; _assets[asset].rewards[rewardsList[j]].usersData[user].accrued = 0; } } } for (uint256 i = 0; i < rewardsListLength; i++) { _transferRewards(to, rewardsList[i], claimedAmounts[i]); emit RewardsClaimed(user, rewardsList[i], to, claimer, claimedAmounts[i]); } return (rewardsList, claimedAmounts); } /** * @dev Function to transfer rewards to the desired account using delegatecall and * @param to Account address to send the rewards * @param reward Address of the reward token * @param amount Amount of rewards to transfer */ function _transferRewards(address to, address reward, uint256 amount) internal { ITransferStrategyBase transferStrategy = _transferStrategy[reward]; bool success = transferStrategy.performTransfer(to, reward, amount); require(success == true, 'TRANSFER_ERROR'); } /** * @dev Returns true if `account` is a contract. * @param account The address of the account * @return bool, true if contract, false otherwise */ function _isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Internal function to call the optional install hook at the TransferStrategy * @param reward The address of the reward token * @param transferStrategy The address of the reward TransferStrategy */ function _installTransferStrategy( address reward, ITransferStrategyBase transferStrategy ) internal { require(address(transferStrategy) != address(0), 'STRATEGY_CAN_NOT_BE_ZERO'); require(_isContract(address(transferStrategy)) == true, 'STRATEGY_MUST_BE_CONTRACT'); _transferStrategy[reward] = transferStrategy; emit TransferStrategyInstalled(reward, address(transferStrategy)); } /** * @dev Update the Price Oracle of a reward token. The Price Oracle must follow Chainlink AggregatorInterface interface. * @notice The Price Oracle of a reward is used for displaying correct data about the incentives at the UI frontend. * @param reward The address of the reward token * @param rewardOracle The address of the price oracle */ function _setRewardOracle(address reward, AggregatorInterface rewardOracle) internal { require(rewardOracle.latestAnswer() > 0, 'ORACLE_MUST_RETURN_PRICE'); _rewardOracle[reward] = rewardOracle; emit RewardOracleUpdated(reward, address(rewardOracle)); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.10; import {IScaledBalanceToken} from '../interfaces/IScaledBalanceToken.sol'; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeCast} from '../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IRewardsDistributor} from './interfaces/IRewardsDistributor.sol'; import {RewardsDataTypes} from './libraries/RewardsDataTypes.sol'; /** * @title RewardsDistributor * @notice Accounting contract to manage multiple staking distributions with multiple rewards * @author Aave **/ abstract contract RewardsDistributor is IRewardsDistributor { using SafeCast for uint256; // Manager of incentives address public immutable EMISSION_MANAGER; // Deprecated: This storage slot is kept for backwards compatibility purposes. address internal _emissionManager; // Map of rewarded asset addresses and their data (assetAddress => assetData) mapping(address => RewardsDataTypes.AssetData) internal _assets; // Map of reward assets (rewardAddress => enabled) mapping(address => bool) internal _isRewardEnabled; // Rewards list address[] internal _rewardsList; // Assets list address[] internal _assetsList; modifier onlyEmissionManager() { require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER'); _; } constructor(address emissionManager) { EMISSION_MANAGER = emissionManager; } /// @inheritdoc IRewardsDistributor function getRewardsData( address asset, address reward ) external view override returns (uint256, uint256, uint256, uint256) { return ( _assets[asset].rewards[reward].index, _assets[asset].rewards[reward].emissionPerSecond, _assets[asset].rewards[reward].lastUpdateTimestamp, _assets[asset].rewards[reward].distributionEnd ); } /// @inheritdoc IRewardsDistributor function getAssetIndex( address asset, address reward ) external view override returns (uint256, uint256) { RewardsDataTypes.RewardData storage rewardData = _assets[asset].rewards[reward]; return _getAssetIndex( rewardData, IScaledBalanceToken(asset).scaledTotalSupply(), 10 ** _assets[asset].decimals ); } /// @inheritdoc IRewardsDistributor function getDistributionEnd( address asset, address reward ) external view override returns (uint256) { return _assets[asset].rewards[reward].distributionEnd; } /// @inheritdoc IRewardsDistributor function getRewardsByAsset(address asset) external view override returns (address[] memory) { uint128 rewardsCount = _assets[asset].availableRewardsCount; address[] memory availableRewards = new address[](rewardsCount); for (uint128 i = 0; i < rewardsCount; i++) { availableRewards[i] = _assets[asset].availableRewards[i]; } return availableRewards; } /// @inheritdoc IRewardsDistributor function getRewardsList() external view override returns (address[] memory) { return _rewardsList; } /// @inheritdoc IRewardsDistributor function getUserAssetIndex( address user, address asset, address reward ) external view override returns (uint256) { return _assets[asset].rewards[reward].usersData[user].index; } /// @inheritdoc IRewardsDistributor function getUserAccruedRewards( address user, address reward ) external view override returns (uint256) { uint256 totalAccrued; for (uint256 i = 0; i < _assetsList.length; i++) { totalAccrued += _assets[_assetsList[i]].rewards[reward].usersData[user].accrued; } return totalAccrued; } /// @inheritdoc IRewardsDistributor function getUserRewards( address[] calldata assets, address user, address reward ) external view override returns (uint256) { return _getUserReward(user, reward, _getUserAssetBalances(assets, user)); } /// @inheritdoc IRewardsDistributor function getAllUserRewards( address[] calldata assets, address user ) external view override returns (address[] memory rewardsList, uint256[] memory unclaimedAmounts) { RewardsDataTypes.UserAssetBalance[] memory userAssetBalances = _getUserAssetBalances( assets, user ); rewardsList = new address[](_rewardsList.length); unclaimedAmounts = new uint256[](rewardsList.length); // Add unrealized rewards from user to unclaimedRewards for (uint256 i = 0; i < userAssetBalances.length; i++) { for (uint256 r = 0; r < rewardsList.length; r++) { rewardsList[r] = _rewardsList[r]; unclaimedAmounts[r] += _assets[userAssetBalances[i].asset] .rewards[rewardsList[r]] .usersData[user] .accrued; if (userAssetBalances[i].userBalance == 0) { continue; } unclaimedAmounts[r] += _getPendingRewards(user, rewardsList[r], userAssetBalances[i]); } } return (rewardsList, unclaimedAmounts); } /// @inheritdoc IRewardsDistributor function setDistributionEnd( address asset, address reward, uint32 newDistributionEnd ) external override onlyEmissionManager { uint256 oldDistributionEnd = _assets[asset].rewards[reward].distributionEnd; _assets[asset].rewards[reward].distributionEnd = newDistributionEnd; emit AssetConfigUpdated( asset, reward, _assets[asset].rewards[reward].emissionPerSecond, _assets[asset].rewards[reward].emissionPerSecond, oldDistributionEnd, newDistributionEnd, _assets[asset].rewards[reward].index ); } /// @inheritdoc IRewardsDistributor function setEmissionPerSecond( address asset, address[] calldata rewards, uint88[] calldata newEmissionsPerSecond ) external override onlyEmissionManager { require(rewards.length == newEmissionsPerSecond.length, 'INVALID_INPUT'); for (uint256 i = 0; i < rewards.length; i++) { RewardsDataTypes.AssetData storage assetConfig = _assets[asset]; RewardsDataTypes.RewardData storage rewardConfig = _assets[asset].rewards[rewards[i]]; uint256 decimals = assetConfig.decimals; require( decimals != 0 && rewardConfig.lastUpdateTimestamp != 0, 'DISTRIBUTION_DOES_NOT_EXIST' ); (uint256 newIndex, ) = _updateRewardData( rewardConfig, IScaledBalanceToken(asset).scaledTotalSupply(), 10 ** decimals ); uint256 oldEmissionPerSecond = rewardConfig.emissionPerSecond; rewardConfig.emissionPerSecond = newEmissionsPerSecond[i]; emit AssetConfigUpdated( asset, rewards[i], oldEmissionPerSecond, newEmissionsPerSecond[i], rewardConfig.distributionEnd, rewardConfig.distributionEnd, newIndex ); } } /** * @dev Configure the _assets for a specific emission * @param rewardsInput The array of each asset configuration **/ function _configureAssets(RewardsDataTypes.RewardsConfigInput[] memory rewardsInput) internal { for (uint256 i = 0; i < rewardsInput.length; i++) { if (_assets[rewardsInput[i].asset].decimals == 0) { //never initialized before, adding to the list of assets _assetsList.push(rewardsInput[i].asset); } uint256 decimals = _assets[rewardsInput[i].asset].decimals = IERC20Detailed( rewardsInput[i].asset ).decimals(); RewardsDataTypes.RewardData storage rewardConfig = _assets[rewardsInput[i].asset].rewards[ rewardsInput[i].reward ]; // Add reward address to asset available rewards if latestUpdateTimestamp is zero if (rewardConfig.lastUpdateTimestamp == 0) { _assets[rewardsInput[i].asset].availableRewards[ _assets[rewardsInput[i].asset].availableRewardsCount ] = rewardsInput[i].reward; _assets[rewardsInput[i].asset].availableRewardsCount++; } // Add reward address to global rewards list if still not enabled if (_isRewardEnabled[rewardsInput[i].reward] == false) { _isRewardEnabled[rewardsInput[i].reward] = true; _rewardsList.push(rewardsInput[i].reward); } // Due emissions is still zero, updates only latestUpdateTimestamp (uint256 newIndex, ) = _updateRewardData( rewardConfig, rewardsInput[i].totalSupply, 10 ** decimals ); // Configure emission and distribution end of the reward per asset uint88 oldEmissionsPerSecond = rewardConfig.emissionPerSecond; uint32 oldDistributionEnd = rewardConfig.distributionEnd; rewardConfig.emissionPerSecond = rewardsInput[i].emissionPerSecond; rewardConfig.distributionEnd = rewardsInput[i].distributionEnd; emit AssetConfigUpdated( rewardsInput[i].asset, rewardsInput[i].reward, oldEmissionsPerSecond, rewardsInput[i].emissionPerSecond, oldDistributionEnd, rewardsInput[i].distributionEnd, newIndex ); } } /** * @dev Updates the state of the distribution for the specified reward * @param rewardData Storage pointer to the distribution reward config * @param totalSupply Current total of underlying assets for this distribution * @param assetUnit One unit of asset (10**decimals) * @return The new distribution index * @return True if the index was updated, false otherwise **/ function _updateRewardData( RewardsDataTypes.RewardData storage rewardData, uint256 totalSupply, uint256 assetUnit ) internal returns (uint256, bool) { (uint256 oldIndex, uint256 newIndex) = _getAssetIndex(rewardData, totalSupply, assetUnit); bool indexUpdated; if (newIndex != oldIndex) { require(newIndex <= type(uint104).max, 'INDEX_OVERFLOW'); indexUpdated = true; //optimization: storing one after another saves one SSTORE rewardData.index = uint104(newIndex); rewardData.lastUpdateTimestamp = block.timestamp.toUint32(); } else { rewardData.lastUpdateTimestamp = block.timestamp.toUint32(); } return (newIndex, indexUpdated); } /** * @dev Updates the state of the distribution for the specific user * @param rewardData Storage pointer to the distribution reward config * @param user The address of the user * @param userBalance The user balance of the asset * @param newAssetIndex The new index of the asset distribution * @param assetUnit One unit of asset (10**decimals) * @return The rewards accrued since the last update **/ function _updateUserData( RewardsDataTypes.RewardData storage rewardData, address user, uint256 userBalance, uint256 newAssetIndex, uint256 assetUnit ) internal returns (uint256, bool) { uint256 userIndex = rewardData.usersData[user].index; uint256 rewardsAccrued; bool dataUpdated; if ((dataUpdated = userIndex != newAssetIndex)) { // already checked for overflow in _updateRewardData rewardData.usersData[user].index = uint104(newAssetIndex); if (userBalance != 0) { rewardsAccrued = _getRewards(userBalance, newAssetIndex, userIndex, assetUnit); rewardData.usersData[user].accrued += rewardsAccrued.toUint128(); } } return (rewardsAccrued, dataUpdated); } /** * @dev Iterates and accrues all the rewards for asset of the specific user * @param asset The address of the reference asset of the distribution * @param user The user address * @param userBalance The current user asset balance * @param totalSupply Total supply of the asset **/ function _updateData( address asset, address user, uint256 userBalance, uint256 totalSupply ) internal { uint256 assetUnit; uint256 numAvailableRewards = _assets[asset].availableRewardsCount; unchecked { assetUnit = 10 ** _assets[asset].decimals; } if (numAvailableRewards == 0) { return; } unchecked { for (uint128 r = 0; r < numAvailableRewards; r++) { address reward = _assets[asset].availableRewards[r]; RewardsDataTypes.RewardData storage rewardData = _assets[asset].rewards[reward]; (uint256 newAssetIndex, bool rewardDataUpdated) = _updateRewardData( rewardData, totalSupply, assetUnit ); (uint256 rewardsAccrued, bool userDataUpdated) = _updateUserData( rewardData, user, userBalance, newAssetIndex, assetUnit ); if (rewardDataUpdated || userDataUpdated) { emit Accrued(asset, reward, user, newAssetIndex, newAssetIndex, rewardsAccrued); } } } } /** * @dev Accrues all the rewards of the assets specified in the userAssetBalances list * @param user The address of the user * @param userAssetBalances List of structs with the user balance and total supply of a set of assets **/ function _updateDataMultiple( address user, RewardsDataTypes.UserAssetBalance[] memory userAssetBalances ) internal { for (uint256 i = 0; i < userAssetBalances.length; i++) { _updateData( userAssetBalances[i].asset, user, userAssetBalances[i].userBalance, userAssetBalances[i].totalSupply ); } } /** * @dev Return the accrued unclaimed amount of a reward from a user over a list of distribution * @param user The address of the user * @param reward The address of the reward token * @param userAssetBalances List of structs with the user balance and total supply of a set of assets * @return unclaimedRewards The accrued rewards for the user until the moment **/ function _getUserReward( address user, address reward, RewardsDataTypes.UserAssetBalance[] memory userAssetBalances ) internal view returns (uint256 unclaimedRewards) { // Add unrealized rewards for (uint256 i = 0; i < userAssetBalances.length; i++) { if (userAssetBalances[i].userBalance == 0) { unclaimedRewards += _assets[userAssetBalances[i].asset] .rewards[reward] .usersData[user] .accrued; } else { unclaimedRewards += _getPendingRewards(user, reward, userAssetBalances[i]) + _assets[userAssetBalances[i].asset].rewards[reward].usersData[user].accrued; } } return unclaimedRewards; } /** * @dev Calculates the pending (not yet accrued) rewards since the last user action * @param user The address of the user * @param reward The address of the reward token * @param userAssetBalance struct with the user balance and total supply of the incentivized asset * @return The pending rewards for the user since the last user action **/ function _getPendingRewards( address user, address reward, RewardsDataTypes.UserAssetBalance memory userAssetBalance ) internal view returns (uint256) { RewardsDataTypes.RewardData storage rewardData = _assets[userAssetBalance.asset].rewards[ reward ]; uint256 assetUnit = 10 ** _assets[userAssetBalance.asset].decimals; (, uint256 nextIndex) = _getAssetIndex(rewardData, userAssetBalance.totalSupply, assetUnit); return _getRewards( userAssetBalance.userBalance, nextIndex, rewardData.usersData[user].index, assetUnit ); } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param userBalance Balance of the user asset on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @param assetUnit One unit of asset (10**decimals) * @return The rewards **/ function _getRewards( uint256 userBalance, uint256 reserveIndex, uint256 userIndex, uint256 assetUnit ) internal pure returns (uint256) { uint256 result = userBalance * (reserveIndex - userIndex); assembly { result := div(result, assetUnit) } return result; } /** * @dev Calculates the next value of an specific distribution index, with validations * @param rewardData Storage pointer to the distribution reward config * @param totalSupply of the asset being rewarded * @param assetUnit One unit of asset (10**decimals) * @return The new index. **/ function _getAssetIndex( RewardsDataTypes.RewardData storage rewardData, uint256 totalSupply, uint256 assetUnit ) internal view returns (uint256, uint256) { uint256 oldIndex = rewardData.index; uint256 distributionEnd = rewardData.distributionEnd; uint256 emissionPerSecond = rewardData.emissionPerSecond; uint256 lastUpdateTimestamp = rewardData.lastUpdateTimestamp; if ( emissionPerSecond == 0 || totalSupply == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= distributionEnd ) { return (oldIndex, oldIndex); } uint256 currentTimestamp = block.timestamp > distributionEnd ? distributionEnd : block.timestamp; uint256 timeDelta = currentTimestamp - lastUpdateTimestamp; uint256 firstTerm = emissionPerSecond * timeDelta * assetUnit; assembly { firstTerm := div(firstTerm, totalSupply) } return (oldIndex, (firstTerm + oldIndex)); } /** * @dev Get user balances and total supply of all the assets specified by the assets parameter * @param assets List of assets to retrieve user balance and total supply * @param user Address of the user * @return userAssetBalances contains a list of structs with user balance and total supply of the given assets */ function _getUserAssetBalances( address[] calldata assets, address user ) internal view virtual returns (RewardsDataTypes.UserAssetBalance[] memory userAssetBalances); /// @inheritdoc IRewardsDistributor function getAssetDecimals(address asset) external view returns (uint8) { return _assets[asset].decimals; } /// @inheritdoc IRewardsDistributor function getEmissionManager() external view returns (address) { return EMISSION_MANAGER; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {AggregatorInterface} from '../../dependencies/chainlink/AggregatorInterface.sol'; import {RewardsDataTypes} from '../libraries/RewardsDataTypes.sol'; import {ITransferStrategyBase} from './ITransferStrategyBase.sol'; import {IRewardsController} from './IRewardsController.sol'; /** * @title IEmissionManager * @author Aave * @notice Defines the basic interface for the Emission Manager */ interface IEmissionManager { /** * @dev Emitted when the admin of a reward emission is updated. * @param reward The address of the rewarding token * @param oldAdmin The address of the old emission admin * @param newAdmin The address of the new emission admin */ event EmissionAdminUpdated( address indexed reward, address indexed oldAdmin, address indexed newAdmin ); /** * @dev Configure assets to incentivize with an emission of rewards per second until the end of distribution. * @dev Only callable by the emission admin of the given rewards * @param config The assets configuration input, the list of structs contains the following fields: * uint104 emissionPerSecond: The emission per second following rewards unit decimals. * uint256 totalSupply: The total supply of the asset to incentivize * uint40 distributionEnd: The end of the distribution of the incentives for an asset * address asset: The asset address to incentivize * address reward: The reward token address * ITransferStrategy transferStrategy: The TransferStrategy address with the install hook and claim logic. * AggregatorInterface rewardOracle: The Price Oracle of a reward to visualize the incentives at the UI Frontend. * Must follow Chainlink Aggregator AggregatorInterface interface to be compatible. */ function configureAssets(RewardsDataTypes.RewardsConfigInput[] memory config) external; /** * @dev Sets a TransferStrategy logic contract that determines the logic of the rewards transfer * @dev Only callable by the emission admin of the given reward * @param reward The address of the reward token * @param transferStrategy The address of the TransferStrategy logic contract */ function setTransferStrategy(address reward, ITransferStrategyBase transferStrategy) external; /** * @dev Sets an Aave Oracle contract to enforce rewards with a source of value. * @dev Only callable by the emission admin of the given reward * @notice At the moment of reward configuration, the Incentives Controller performs * a check to see if the reward asset oracle is compatible with AggregatorInterface proxy. * This check is enforced for integrators to be able to show incentives at * the current Aave UI without the need to setup an external price registry * @param reward The address of the reward to set the price aggregator * @param rewardOracle The address of price aggregator that follows AggregatorInterface interface */ function setRewardOracle(address reward, AggregatorInterface rewardOracle) external; /** * @dev Sets the end date for the distribution * @dev Only callable by the emission admin of the given reward * @param asset The asset to incentivize * @param reward The reward token that incentives the asset * @param newDistributionEnd The end date of the incentivization, in unix time format **/ function setDistributionEnd(address asset, address reward, uint32 newDistributionEnd) external; /** * @dev Sets the emission per second of a set of reward distributions * @param asset The asset is being incentivized * @param rewards List of reward addresses are being distributed * @param newEmissionsPerSecond List of new reward emissions per second */ function setEmissionPerSecond( address asset, address[] calldata rewards, uint88[] calldata newEmissionsPerSecond ) external; /** * @dev Whitelists an address to claim the rewards on behalf of another address * @dev Only callable by the owner of the EmissionManager * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Updates the admin of the reward emission * @dev Only callable by the owner of the EmissionManager * @param reward The address of the reward token * @param admin The address of the new admin of the emission */ function setEmissionAdmin(address reward, address admin) external; /** * @dev Updates the address of the rewards controller * @dev Only callable by the owner of the EmissionManager * @param controller the address of the RewardsController contract */ function setRewardsController(address controller) external; /** * @dev Returns the rewards controller address * @return The address of the RewardsController contract */ function getRewardsController() external view returns (IRewardsController); /** * @dev Returns the admin of the given reward emission * @param reward The address of the reward token * @return The address of the emission admin */ function getEmissionAdmin(address reward) external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {IRewardsDistributor} from './IRewardsDistributor.sol'; import {ITransferStrategyBase} from './ITransferStrategyBase.sol'; import {AggregatorInterface} from '../../dependencies/chainlink/AggregatorInterface.sol'; import {RewardsDataTypes} from '../libraries/RewardsDataTypes.sol'; /** * @title IRewardsController * @author Aave * @notice Defines the basic interface for a Rewards Controller. */ interface IRewardsController is IRewardsDistributor { /** * @dev Emitted when a new address is whitelisted as claimer of rewards on behalf of a user * @param user The address of the user * @param claimer The address of the claimer */ event ClaimerSet(address indexed user, address indexed claimer); /** * @dev Emitted when rewards are claimed * @param user The address of the user rewards has been claimed on behalf of * @param reward The address of the token reward is claimed * @param to The address of the receiver of the rewards * @param claimer The address of the claimer * @param amount The amount of rewards claimed */ event RewardsClaimed( address indexed user, address indexed reward, address indexed to, address claimer, uint256 amount ); /** * @dev Emitted when a transfer strategy is installed for the reward distribution * @param reward The address of the token reward * @param transferStrategy The address of TransferStrategy contract */ event TransferStrategyInstalled(address indexed reward, address indexed transferStrategy); /** * @dev Emitted when the reward oracle is updated * @param reward The address of the token reward * @param rewardOracle The address of oracle */ event RewardOracleUpdated(address indexed reward, address indexed rewardOracle); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Sets a TransferStrategy logic contract that determines the logic of the rewards transfer * @param reward The address of the reward token * @param transferStrategy The address of the TransferStrategy logic contract */ function setTransferStrategy(address reward, ITransferStrategyBase transferStrategy) external; /** * @dev Sets an Aave Oracle contract to enforce rewards with a source of value. * @notice At the moment of reward configuration, the Incentives Controller performs * a check to see if the reward asset oracle is compatible with IEACAggregator proxy. * This check is enforced for integrators to be able to show incentives at * the current Aave UI without the need to setup an external price registry * @param reward The address of the reward to set the price aggregator * @param rewardOracle The address of price aggregator that follows AggregatorInterface interface */ function setRewardOracle(address reward, AggregatorInterface rewardOracle) external; /** * @dev Get the price aggregator oracle address * @param reward The address of the reward * @return The price oracle of the reward */ function getRewardOracle(address reward) external view returns (address); /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Returns the Transfer Strategy implementation contract address being used for a reward address * @param reward The address of the reward * @return The address of the TransferStrategy contract */ function getTransferStrategy(address reward) external view returns (address); /** * @dev Configure assets to incentivize with an emission of rewards per second until the end of distribution. * @param config The assets configuration input, the list of structs contains the following fields: * uint104 emissionPerSecond: The emission per second following rewards unit decimals. * uint256 totalSupply: The total supply of the asset to incentivize * uint40 distributionEnd: The end of the distribution of the incentives for an asset * address asset: The asset address to incentivize * address reward: The reward token address * ITransferStrategy transferStrategy: The TransferStrategy address with the install hook and claim logic. * AggregatorInterface rewardOracle: The Price Oracle of a reward to visualize the incentives at the UI Frontend. * Must follow Chainlink Aggregator AggregatorInterface interface to be compatible. */ function configureAssets(RewardsDataTypes.RewardsConfigInput[] memory config) external; /** * @dev Called by the corresponding asset on transfer hook in order to update the rewards distribution. * @dev The units of `totalSupply` and `userBalance` should be the same. * @param user The address of the user whose asset balance has changed * @param totalSupply The total supply of the asset prior to user balance change * @param userBalance The previous user balance prior to balance change **/ function handleAction(address user, uint256 totalSupply, uint256 userBalance) external; /** * @dev Claims reward for a user to the desired address, on all the assets of the pool, accumulating the pending rewards * @param assets List of assets to check eligible distributions before claiming rewards * @param amount The amount of rewards to claim * @param to The address that will be receiving the rewards * @param reward The address of the reward token * @return The amount of rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to, address reward ) external returns (uint256); /** * @dev Claims reward for a user on behalf, on all the assets of the pool, accumulating the pending rewards. The * caller must be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param assets The list of assets to check eligible distributions before claiming rewards * @param amount The amount of rewards to claim * @param user The address to check and claim rewards * @param to The address that will be receiving the rewards * @param reward The address of the reward token * @return The amount of rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to, address reward ) external returns (uint256); /** * @dev Claims reward for msg.sender, on all the assets of the pool, accumulating the pending rewards * @param assets The list of assets to check eligible distributions before claiming rewards * @param amount The amount of rewards to claim * @param reward The address of the reward token * @return The amount of rewards claimed **/ function claimRewardsToSelf( address[] calldata assets, uint256 amount, address reward ) external returns (uint256); /** * @dev Claims all rewards for a user to the desired address, on all the assets of the pool, accumulating the pending rewards * @param assets The list of assets to check eligible distributions before claiming rewards * @param to The address that will be receiving the rewards * @return rewardsList List of addresses of the reward tokens * @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardList" **/ function claimAllRewards( address[] calldata assets, address to ) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts); /** * @dev Claims all rewards for a user on behalf, on all the assets of the pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param assets The list of assets to check eligible distributions before claiming rewards * @param user The address to check and claim rewards * @param to The address that will be receiving the rewards * @return rewardsList List of addresses of the reward tokens * @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardsList" **/ function claimAllRewardsOnBehalf( address[] calldata assets, address user, address to ) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts); /** * @dev Claims all reward for msg.sender, on all the assets of the pool, accumulating the pending rewards * @param assets The list of assets to check eligible distributions before claiming rewards * @return rewardsList List of addresses of the reward tokens * @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardsList" **/ function claimAllRewardsToSelf( address[] calldata assets ) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; /** * @title IRewardsDistributor * @author Aave * @notice Defines the basic interface for a Rewards Distributor. */ interface IRewardsDistributor { /** * @dev Emitted when the configuration of the rewards of an asset is updated. * @param asset The address of the incentivized asset * @param reward The address of the reward token * @param oldEmission The old emissions per second value of the reward distribution * @param newEmission The new emissions per second value of the reward distribution * @param oldDistributionEnd The old end timestamp of the reward distribution * @param newDistributionEnd The new end timestamp of the reward distribution * @param assetIndex The index of the asset distribution */ event AssetConfigUpdated( address indexed asset, address indexed reward, uint256 oldEmission, uint256 newEmission, uint256 oldDistributionEnd, uint256 newDistributionEnd, uint256 assetIndex ); /** * @dev Emitted when rewards of an asset are accrued on behalf of a user. * @param asset The address of the incentivized asset * @param reward The address of the reward token * @param user The address of the user that rewards are accrued on behalf of * @param assetIndex The index of the asset distribution * @param userIndex The index of the asset distribution on behalf of the user * @param rewardsAccrued The amount of rewards accrued */ event Accrued( address indexed asset, address indexed reward, address indexed user, uint256 assetIndex, uint256 userIndex, uint256 rewardsAccrued ); /** * @dev Sets the end date for the distribution * @param asset The asset to incentivize * @param reward The reward token that incentives the asset * @param newDistributionEnd The end date of the incentivization, in unix time format **/ function setDistributionEnd(address asset, address reward, uint32 newDistributionEnd) external; /** * @dev Sets the emission per second of a set of reward distributions * @param asset The asset is being incentivized * @param rewards List of reward addresses are being distributed * @param newEmissionsPerSecond List of new reward emissions per second */ function setEmissionPerSecond( address asset, address[] calldata rewards, uint88[] calldata newEmissionsPerSecond ) external; /** * @dev Gets the end date for the distribution * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The timestamp with the end of the distribution, in unix time format **/ function getDistributionEnd(address asset, address reward) external view returns (uint256); /** * @dev Returns the index of a user on a reward distribution * @param user Address of the user * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The current user asset index, not including new distributions **/ function getUserAssetIndex( address user, address asset, address reward ) external view returns (uint256); /** * @dev Returns the configuration of the distribution reward for a certain asset * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The index of the asset distribution * @return The emission per second of the reward distribution * @return The timestamp of the last update of the index * @return The timestamp of the distribution end **/ function getRewardsData( address asset, address reward ) external view returns (uint256, uint256, uint256, uint256); /** * @dev Calculates the next value of an specific distribution index, with validations. * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The old index of the asset distribution * @return The new index of the asset distribution **/ function getAssetIndex(address asset, address reward) external view returns (uint256, uint256); /** * @dev Returns the list of available reward token addresses of an incentivized asset * @param asset The incentivized asset * @return List of rewards addresses of the input asset **/ function getRewardsByAsset(address asset) external view returns (address[] memory); /** * @dev Returns the list of available reward addresses * @return List of rewards supported in this contract **/ function getRewardsList() external view returns (address[] memory); /** * @dev Returns the accrued rewards balance of a user, not including virtually accrued rewards since last distribution. * @param user The address of the user * @param reward The address of the reward token * @return Unclaimed rewards, not including new distributions **/ function getUserAccruedRewards(address user, address reward) external view returns (uint256); /** * @dev Returns a single rewards balance of a user, including virtually accrued and unrealized claimable rewards. * @param assets List of incentivized assets to check eligible distributions * @param user The address of the user * @param reward The address of the reward token * @return The rewards amount **/ function getUserRewards( address[] calldata assets, address user, address reward ) external view returns (uint256); /** * @dev Returns a list all rewards of a user, including already accrued and unrealized claimable rewards * @param assets List of incentivized assets to check eligible distributions * @param user The address of the user * @return The list of reward addresses * @return The list of unclaimed amount of rewards **/ function getAllUserRewards( address[] calldata assets, address user ) external view returns (address[] memory, uint256[] memory); /** * @dev Returns the decimals of an asset to calculate the distribution delta * @param asset The address to retrieve decimals * @return The decimals of an underlying asset */ function getAssetDecimals(address asset) external view returns (uint8); /** * @dev Returns the address of the emission manager * @return The address of the EmissionManager */ function EMISSION_MANAGER() external view returns (address); /** * @dev Returns the address of the emission manager. * Deprecated: This getter is maintained for compatibility purposes. Use the `EMISSION_MANAGER()` function instead. * @return The address of the EmissionManager */ function getEmissionManager() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface ITransferStrategyBase { event EmergencyWithdrawal( address indexed caller, address indexed token, address indexed to, uint256 amount ); /** * @dev Perform custom transfer logic via delegate call from source contract to a TransferStrategy implementation * @param to Account to transfer rewards * @param reward Address of the reward token * @param amount Amount to transfer to the "to" address parameter * @return Returns true bool if transfer logic succeeds */ function performTransfer(address to, address reward, uint256 amount) external returns (bool); /** * @return Returns the address of the Incentives Controller */ function getIncentivesController() external view returns (address); /** * @return Returns the address of the Rewards admin */ function getRewardsAdmin() external view returns (address); /** * @dev Perform an emergency token withdrawal only callable by the Rewards admin * @param token Address of the token to withdraw funds from this contract * @param to Address of the recipient of the withdrawal * @param amount Amount of the withdrawal */ function emergencyWithdrawal(address token, address to, uint256 amount) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {ITransferStrategyBase} from '../interfaces/ITransferStrategyBase.sol'; import {AggregatorInterface} from '../../dependencies/chainlink/AggregatorInterface.sol'; library RewardsDataTypes { struct RewardsConfigInput { uint88 emissionPerSecond; uint256 totalSupply; uint32 distributionEnd; address asset; address reward; ITransferStrategyBase transferStrategy; AggregatorInterface rewardOracle; } struct UserAssetBalance { address asset; uint256 userBalance; uint256 totalSupply; } struct UserData { // Liquidity index of the reward distribution for the user uint104 index; // Amount of accrued rewards for the user since last user index update uint128 accrued; } struct RewardData { // Liquidity index of the reward distribution uint104 index; // Amount of reward tokens distributed per second uint88 emissionPerSecond; // Timestamp of the last reward index update uint32 lastUpdateTimestamp; // The end of the distribution of rewards (in seconds) uint32 distributionEnd; // Map of user addresses and their rewards data (userAddress => userData) mapping(address => UserData) usersData; } struct AssetData { // Map of reward token addresses and their data (rewardTokenAddress => rewardData) mapping(address => RewardData) rewards; // List of reward token addresses for the asset mapping(uint128 => address) availableRewards; // Count of reward tokens for the asset uint128 availableRewardsCount; // Number of decimals of the asset uint8 decimals; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {AccessControlUpgradeable} from 'openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol'; import {ReentrancyGuardUpgradeable} from 'openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol'; import {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from 'openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol'; import {Address} from 'openzeppelin-contracts/contracts/utils/Address.sol'; import {ICollector} from './ICollector.sol'; /** * @title Collector * @notice Stores ERC20 tokens of an ecosystem reserve and allows to dispose of them via approval * or transfer dynamics or streaming capabilities. * Modification of Sablier https://github.com/sablierhq/sablier/blob/develop/packages/protocol/contracts/Sablier.sol * Original can be found also deployed on https://etherscan.io/address/0xCD18eAa163733Da39c232722cBC4E8940b1D8888 * Modifications: * - Sablier "pulls" the funds from the creator of the stream at creation. In the Aave case, we already have the funds. * - Anybody can create streams on Sablier. Here, only the funds admin (Aave governance via controller) can * - Adapted codebase to Solidity 0.8.11, mainly removing SafeMath and CarefulMath to use native safe math * - Same as with creation, on Sablier the `sender` and `recipient` can cancel a stream. Here, only fund admin and recipient * @author BGD Labs **/ contract Collector is AccessControlUpgradeable, ReentrancyGuardUpgradeable, ICollector { using SafeERC20 for IERC20; using Address for address payable; /*** Storage Properties ***/ /// @inheritdoc ICollector address public constant ETH_MOCK_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @inheritdoc ICollector bytes32 public constant FUNDS_ADMIN_ROLE = 'FUNDS_ADMIN'; // Reserved storage space to account for deprecated inherited storage // 0 was lastInitializedRevision // 1-50 were the ____gap // 51 was the reentrancy guard _status // 52 was the _fundsAdmin // On some networks the layout was shifted by 1 due to `initializing` being on slot 1 // The upgrade proposal would in this case manually shift the storage layout to properly align the networks uint256[53] private ______gap; /** * @notice Counter for new stream ids. */ uint256 private _nextStreamId; /** * @notice The stream objects identifiable by their unsigned integer ids. */ mapping(uint256 => Stream) private _streams; /*** Modifiers ***/ /** * @dev Throws if the caller does not have the FUNDS_ADMIN role */ modifier onlyFundsAdmin() { if (_onlyFundsAdmin() == false) { revert OnlyFundsAdmin(); } _; } /** * @dev Throws if the caller is not the funds admin of the recipient of the stream. * @param streamId The id of the stream to query. */ modifier onlyAdminOrRecipient(uint256 streamId) { if (_onlyFundsAdmin() == false && msg.sender != _streams[streamId].recipient) { revert OnlyFundsAdminOrRecipient(); } _; } /** * @dev Throws if the provided id does not point to a valid stream. */ modifier streamExists(uint256 streamId) { if (!_streams[streamId].isEntity) revert StreamDoesNotExist(); _; } constructor() { _disableInitializers(); } /*** Contract Logic Starts Here */ /** @notice Initializes the contracts * @param nextStreamId StreamId to set, applied if greater than 0 * @param admin The default admin managing the FundsAdmins **/ function initialize(uint256 nextStreamId, address admin) external virtual initializer { __AccessControl_init(); __ReentrancyGuard_init(); _grantRole(DEFAULT_ADMIN_ROLE, admin); if (nextStreamId != 0) { _nextStreamId = nextStreamId; } } /*** View Functions ***/ /// @inheritdoc ICollector function isFundsAdmin(address admin) external view returns (bool) { return hasRole(FUNDS_ADMIN_ROLE, admin); } /// @inheritdoc ICollector function getNextStreamId() external view returns (uint256) { return _nextStreamId; } /// @inheritdoc ICollector function getStream( uint256 streamId ) external view streamExists(streamId) returns ( address sender, address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 ratePerSecond ) { sender = _streams[streamId].sender; recipient = _streams[streamId].recipient; deposit = _streams[streamId].deposit; tokenAddress = _streams[streamId].tokenAddress; startTime = _streams[streamId].startTime; stopTime = _streams[streamId].stopTime; remainingBalance = _streams[streamId].remainingBalance; ratePerSecond = _streams[streamId].ratePerSecond; } /** * @notice Returns either the delta in seconds between `block.timestamp` and `startTime` or * between `stopTime` and `startTime, whichever is smaller. If `block.timestamp` is before * `startTime`, it returns 0. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream for which to query the delta. * @notice Returns the time delta in seconds. */ function deltaOf(uint256 streamId) public view streamExists(streamId) returns (uint256 delta) { Stream memory stream = _streams[streamId]; if (block.timestamp <= stream.startTime) return 0; if (block.timestamp < stream.stopTime) return block.timestamp - stream.startTime; return stream.stopTime - stream.startTime; } struct BalanceOfLocalVars { uint256 recipientBalance; uint256 withdrawalAmount; uint256 senderBalance; } /// @inheritdoc ICollector function balanceOf( uint256 streamId, address who ) public view streamExists(streamId) returns (uint256 balance) { Stream memory stream = _streams[streamId]; BalanceOfLocalVars memory vars; uint256 delta = deltaOf(streamId); vars.recipientBalance = delta * stream.ratePerSecond; /* * If the stream `balance` does not equal `deposit`, it means there have been withdrawals. * We have to subtract the total amount withdrawn from the amount of money that has been * streamed until now. */ if (stream.deposit > stream.remainingBalance) { vars.withdrawalAmount = stream.deposit - stream.remainingBalance; vars.recipientBalance = vars.recipientBalance - vars.withdrawalAmount; } if (who == stream.recipient) return vars.recipientBalance; if (who == stream.sender) { vars.senderBalance = stream.remainingBalance - vars.recipientBalance; return vars.senderBalance; } return 0; } /*** Public Effects & Interactions Functions ***/ /// @inheritdoc ICollector function approve(IERC20 token, address recipient, uint256 amount) external onlyFundsAdmin { token.forceApprove(recipient, amount); } /// @inheritdoc ICollector function transfer(IERC20 token, address recipient, uint256 amount) external onlyFundsAdmin { if (recipient == address(0)) revert InvalidZeroAddress(); if (address(token) == ETH_MOCK_ADDRESS) { payable(recipient).sendValue(amount); } else { token.safeTransfer(recipient, amount); } } function _onlyFundsAdmin() internal view returns (bool) { return hasRole(FUNDS_ADMIN_ROLE, msg.sender); } struct CreateStreamLocalVars { uint256 duration; uint256 ratePerSecond; } /// @inheritdoc ICollector /** * @dev Throws if the recipient is the zero address, the contract itself or the caller. * Throws if the deposit is 0. * Throws if the start time is before `block.timestamp`. * Throws if the stop time is before the start time. * Throws if the duration calculation has a math error. * Throws if the deposit is smaller than the duration. * Throws if the deposit is not a multiple of the duration. * Throws if the rate calculation has a math error. * Throws if the next stream id calculation has a math error. * Throws if the contract is not allowed to transfer enough tokens. * Throws if there is a token transfer failure. */ function createStream( address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ) external onlyFundsAdmin returns (uint256) { if (recipient == address(0)) revert InvalidZeroAddress(); if (recipient == address(this)) revert InvalidRecipient(); if (recipient == msg.sender) revert InvalidRecipient(); if (deposit == 0) revert InvalidZeroAmount(); if (startTime < block.timestamp) revert InvalidStartTime(); if (stopTime <= startTime) revert InvalidStopTime(); CreateStreamLocalVars memory vars; vars.duration = stopTime - startTime; /* Without this, the rate per second would be zero. */ if (deposit < vars.duration) revert DepositSmallerTimeDelta(); /* This condition avoids dealing with remainders */ if (deposit % vars.duration > 0) revert DepositNotMultipleTimeDelta(); vars.ratePerSecond = deposit / vars.duration; /* Create and store the stream object. */ uint256 streamId = _nextStreamId; _streams[streamId] = Stream({ remainingBalance: deposit, deposit: deposit, isEntity: true, ratePerSecond: vars.ratePerSecond, recipient: recipient, sender: address(this), startTime: startTime, stopTime: stopTime, tokenAddress: tokenAddress }); /* Increment the next stream id. */ _nextStreamId++; emit CreateStream( streamId, address(this), recipient, deposit, tokenAddress, startTime, stopTime ); return streamId; } /// @inheritdoc ICollector /** * @dev Throws if the id does not point to a valid stream. * Throws if the caller is not the funds admin or the recipient of the stream. * Throws if the amount exceeds the available balance. * Throws if there is a token transfer failure. */ function withdrawFromStream( uint256 streamId, uint256 amount ) external nonReentrant streamExists(streamId) onlyAdminOrRecipient(streamId) returns (bool) { if (amount == 0) revert InvalidZeroAmount(); Stream memory stream = _streams[streamId]; uint256 balance = balanceOf(streamId, stream.recipient); if (balance < amount) revert BalanceExceeded(); _streams[streamId].remainingBalance = stream.remainingBalance - amount; if (_streams[streamId].remainingBalance == 0) delete _streams[streamId]; IERC20(stream.tokenAddress).safeTransfer(stream.recipient, amount); emit WithdrawFromStream(streamId, stream.recipient, amount); return true; } /// @inheritdoc ICollector /** * @dev Throws if the id does not point to a valid stream. * Throws if the caller is not the funds admin or the recipient of the stream. * Throws if there is a token transfer failure. */ function cancelStream( uint256 streamId ) external nonReentrant streamExists(streamId) onlyAdminOrRecipient(streamId) returns (bool) { Stream memory stream = _streams[streamId]; uint256 senderBalance = balanceOf(streamId, stream.sender); uint256 recipientBalance = balanceOf(streamId, stream.recipient); delete _streams[streamId]; IERC20 token = IERC20(stream.tokenAddress); if (recipientBalance > 0) token.safeTransfer(stream.recipient, recipientBalance); emit CancelStream(streamId, stream.sender, stream.recipient, senderBalance, recipientBalance); return true; } /// @dev needed in order to receive ETH from the Aave v1 ecosystem reserve receive() external payable {} }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol'; interface ICollector { struct Stream { uint256 deposit; uint256 ratePerSecond; uint256 remainingBalance; uint256 startTime; uint256 stopTime; address recipient; address sender; address tokenAddress; bool isEntity; } /** * @dev Withdraw amount exceeds available balance */ error BalanceExceeded(); /** * @dev Deposit smaller than time delta */ error DepositSmallerTimeDelta(); /** * @dev Deposit not multiple of time delta */ error DepositNotMultipleTimeDelta(); /** * @dev Recipient cannot be the contract itself or msg.sender */ error InvalidRecipient(); /** * @dev Start time cannot be before block.timestamp */ error InvalidStartTime(); /** * @dev Stop time must be greater than startTime */ error InvalidStopTime(); /** * @dev Provided address cannot be the zero-address */ error InvalidZeroAddress(); /** * @dev Amount cannot be zero */ error InvalidZeroAmount(); /** * @dev Only caller with FUNDS_ADMIN role can call */ error OnlyFundsAdmin(); /** * @dev Only caller with FUNDS_ADMIN role or stream recipient can call */ error OnlyFundsAdminOrRecipient(); /** * @dev The provided ID does not belong to an existing stream */ error StreamDoesNotExist(); /** @notice Emitted when the new stream is created * @param streamId The identifier of the stream. * @param sender The address of the collector. * @param recipient The address towards which the money is streamed. * @param deposit The amount of money to be streamed. * @param tokenAddress The ERC20 token to use as streaming currency. * @param startTime The unix timestamp for when the stream starts. * @param stopTime The unix timestamp for when the stream stops. **/ event CreateStream( uint256 indexed streamId, address indexed sender, address indexed recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ); /** * @notice Emmitted when withdraw happens from the contract to the recipient's account. * @param streamId The id of the stream to withdraw tokens from. * @param recipient The address towards which the money is streamed. * @param amount The amount of tokens to withdraw. */ event WithdrawFromStream(uint256 indexed streamId, address indexed recipient, uint256 amount); /** * @notice Emmitted when the stream is canceled. * @param streamId The id of the stream to withdraw tokens from. * @param sender The address of the collector. * @param recipient The address towards which the money is streamed. * @param senderBalance The sender's balance at the moment of cancelling. * @param recipientBalance The recipient's balance at the moment of cancelling. */ event CancelStream( uint256 indexed streamId, address indexed sender, address indexed recipient, uint256 senderBalance, uint256 recipientBalance ); /** * @notice FUNDS_ADMIN role granted by ACL Manager **/ function FUNDS_ADMIN_ROLE() external view returns (bytes32); /** @notice Returns the mock ETH reference address * @return address The address **/ function ETH_MOCK_ADDRESS() external pure returns (address); /** * @notice Checks if address is funds admin * @return bool If the address has the funds admin role **/ function isFundsAdmin(address admin) external view returns (bool); /** * @notice Returns the available funds for the given stream id and address. * @param streamId The id of the stream for which to query the balance. * @param who The address for which to query the balance. * @notice Returns the total funds allocated to `who` as uint256. **/ function balanceOf(uint256 streamId, address who) external view returns (uint256 balance); /** * @dev Function for the funds admin to give ERC20 allowance to other parties * @param token The address of the token to give allowance from * @param recipient Allowance's recipient * @param amount Allowance to approve **/ function approve(IERC20 token, address recipient, uint256 amount) external; /** * @notice Function for the funds admin to transfer ERC20 tokens to other parties * @param token The address of the token to transfer * @param recipient Transfer's recipient * @param amount Amount to transfer **/ function transfer(IERC20 token, address recipient, uint256 amount) external; /** * @notice Creates a new stream funded by this contracts itself and paid towards `recipient`. * @param recipient The address towards which the money is streamed. * @param deposit The amount of money to be streamed. * @param tokenAddress The ERC20 token to use as streaming currency. * @param startTime The unix timestamp for when the stream starts. * @param stopTime The unix timestamp for when the stream stops. * @return streamId the uint256 id of the newly created stream. */ function createStream( address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ) external returns (uint256 streamId); /** * @notice Returns the stream with all its properties. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream to query. * @notice Returns the stream object. */ function getStream( uint256 streamId ) external view returns ( address sender, address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 ratePerSecond ); /** * @notice Withdraws from the contract to the recipient's account. * @param streamId The id of the stream to withdraw tokens from. * @param amount The amount of tokens to withdraw. * @return bool Returns true if successful. */ function withdrawFromStream(uint256 streamId, uint256 amount) external returns (bool); /** * @notice Cancels the stream and transfers the tokens back on a pro rata basis. * @param streamId The id of the stream to cancel. * @return bool Returns true if successful. */ function cancelStream(uint256 streamId) external returns (bool); /** * @notice Returns the next available stream id * @return nextStreamId Returns the stream id. */ function getNextStreamId() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IRevenueSplitterErrors { error InvalidPercentSplit(); } /// @title IRevenueSplitter /// @notice Interface for RevenueSplitter contract /// @dev The `RevenueSplitter` is a state-less non-upgradeable contract that supports 2 recipients (A and B), and defines the percentage split of the recipient A, with a value between 1 and 99_99. /// The `RevenueSplitter` contract must be attached to the `AaveV3ConfigEngine` as `treasury`, making new listings to use `RevenueSplitter` as treasury (instead of `Collector` ) at the `AToken` initialization, making all revenue managed by ATokens redirected to the RevenueSplitter contract. /// Once parties want to share their revenue, anyone can call `function splitRevenue(IERC20[] memory tokens)` to check the accrued ERC20 balance inside this contract, and split the amounts between the two recipients. /// It also supports split of native currency via `function splitNativeRevenue() external`, in case the instance receives native currency. /// /// Warning: For recipients, you can use any address, but preferable to use `Collector`, a Safe smart contract multisig or a smart contract that can handle both ERC20 and native transfers, to prevent balances to be locked. interface IRevenueSplitter is IRevenueSplitterErrors { /// @notice Split token balances in RevenueSplitter and transfer between two recipients /// @param tokens List of tokens to check balance and split amounts /// @dev Specs: /// - Does not revert if token balance is zero (no-op). /// - Rounds in favor of RECIPIENT_B (1 wei round). /// - Anyone can call this function anytime. /// - This method will always send ERC20 tokens to recipients, even if the recipients does NOT support the ERC20 interface. At deployment time is recommended to ensure both recipients can handle ERC20 and native transfers via e2e tests. function splitRevenue(IERC20[] memory tokens) external; /// @notice Split native currency in RevenueSplitter and transfer between two recipients /// @dev Specs: /// - Does not revert if native balance is zero (no-op) /// - Rounds in favor of RECIPIENT_B (1 wei round). /// - Anyone can call this function anytime. /// - This method will always send native currency to recipients, and does NOT revert if one or both recipients doesn't support handling native currency. At deployment time is recommended to ensure both recipients can handle ERC20 and native transfers via e2e tests. /// - If one recipient can not receive native currency, repeatedly calling the function will rescue/drain the funds of the second recipient (50% per call), allowing manual recovery of funds. function splitNativeRevenue() external; function RECIPIENT_A() external view returns (address payable); function RECIPIENT_B() external view returns (address payable); /// @dev Percentage of the split that goes to RECIPIENT_A, the diff goes to RECIPIENT_B, from 1 to 99_99 function SPLIT_PERCENTAGE_RECIPIENT_A() external view returns (uint16); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.19; import {IRevenueSplitter} from './IRevenueSplitter.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {GPv2SafeERC20} from '../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol'; import {ReentrancyGuard} from '../dependencies/openzeppelin/ReentrancyGuard.sol'; /** * @title RevenueSplitter * @author Catapulta * @dev This periphery contract is responsible for splitting funds between two recipients. * Replace COLLECTOR in ATokens or Debt Tokens with RevenueSplitter, and them set COLLECTORs as recipients. */ contract RevenueSplitter is IRevenueSplitter, ReentrancyGuard { using GPv2SafeERC20 for IERC20; using PercentageMath for uint256; address payable public immutable RECIPIENT_A; address payable public immutable RECIPIENT_B; uint16 public immutable SPLIT_PERCENTAGE_RECIPIENT_A; constructor(address recipientA, address recipientB, uint16 splitPercentageRecipientA) { if ( splitPercentageRecipientA == 0 || splitPercentageRecipientA >= PercentageMath.PERCENTAGE_FACTOR ) { revert InvalidPercentSplit(); } RECIPIENT_A = payable(recipientA); RECIPIENT_B = payable(recipientB); SPLIT_PERCENTAGE_RECIPIENT_A = splitPercentageRecipientA; } /// @inheritdoc IRevenueSplitter function splitRevenue(IERC20[] memory tokens) external nonReentrant { for (uint8 x; x < tokens.length; ++x) { uint256 balance = tokens[x].balanceOf(address(this)); if (balance == 0) { continue; } uint256 amount_A = balance.percentMul(SPLIT_PERCENTAGE_RECIPIENT_A); uint256 amount_B = balance - amount_A; tokens[x].safeTransfer(RECIPIENT_A, amount_A); tokens[x].safeTransfer(RECIPIENT_B, amount_B); } } /// @inheritdoc IRevenueSplitter function splitNativeRevenue() external nonReentrant { uint256 balance = address(this).balance; if (balance == 0) { return; } uint256 amount_A = balance.percentMul(SPLIT_PERCENTAGE_RECIPIENT_A); uint256 amount_B = balance - amount_A; // Do not revert if fails to send to RECIPIENT_A or RECIPIENT_B, to prevent one recipient from blocking the other // if recipient does not accept native currency via fallback function or receive. // This can also be used as a manual recovery mechanism in case of an account does not support receiving native currency. RECIPIENT_A.call{value: amount_A}(''); RECIPIENT_B.call{value: amount_B}(''); } receive() external payable {} }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../../interfaces/IMarketReportTypes.sol'; import {DefaultReserveInterestRateStrategyV2} from '../../../contracts/misc/DefaultReserveInterestRateStrategyV2.sol'; contract AaveV3DefaultRateStrategyProcedure { function _deployDefaultRateStrategyV2(address poolAddressesProvider) internal returns (address) { return address(new DefaultReserveInterestRateStrategyV2(poolAddressesProvider)); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import {EmissionManager} from '../../../contracts/rewards/EmissionManager.sol'; import {RewardsController} from '../../../contracts/rewards/RewardsController.sol'; contract AaveV3IncentiveProcedure { function _deployIncentives(address tempOwner) internal returns (address, address) { address emissionManager = address(new EmissionManager(tempOwner)); address rewardsControllerImplementation = address(new RewardsController(emissionManager)); RewardsController(rewardsControllerImplementation).initialize(address(0)); return (emissionManager, rewardsControllerImplementation); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import '../../interfaces/IMarketReportTypes.sol'; import {AaveOracle} from '../../../contracts/misc/AaveOracle.sol'; contract AaveV3OracleProcedure { function _deployAaveOracle( uint16 oracleDecimals, address poolAddressesProvider ) internal returns (address) { address[] memory emptyArray; address aaveOracle = address( new AaveOracle( IPoolAddressesProvider(poolAddressesProvider), emptyArray, emptyArray, address(0), address(0), 10 ** oracleDecimals ) ); return aaveOracle; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import {TransparentUpgradeableProxy} from 'openzeppelin-contracts/contracts/proxy/transparent/TransparentUpgradeableProxy.sol'; import {Collector} from '../../../contracts/treasury/Collector.sol'; import '../../interfaces/IMarketReportTypes.sol'; contract AaveV3TreasuryProcedure { struct TreasuryReport { address treasuryImplementation; address treasury; } function _deployAaveV3Treasury( address poolAdmin, bytes32 collectorSalt ) internal returns (TreasuryReport memory) { TreasuryReport memory treasuryReport; bytes32 salt = collectorSalt; if (salt != '') { Collector treasuryImplementation = new Collector{salt: salt}(); treasuryReport.treasuryImplementation = address(treasuryImplementation); treasuryReport.treasury = address( new TransparentUpgradeableProxy{salt: salt}( treasuryReport.treasuryImplementation, poolAdmin, abi.encodeWithSelector(treasuryImplementation.initialize.selector, 100_000, poolAdmin) ) ); } else { Collector treasuryImplementation = new Collector(); treasuryReport.treasuryImplementation = address(treasuryImplementation); treasuryReport.treasury = address( new TransparentUpgradeableProxy( treasuryReport.treasuryImplementation, poolAdmin, abi.encodeWithSelector(treasuryImplementation.initialize.selector, 100_000, poolAdmin) ) ); } return treasuryReport; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../../contracts/interfaces/IPoolAddressesProvider.sol'; import '../../contracts/interfaces/IPoolAddressesProviderRegistry.sol'; import '../../contracts/interfaces/IPool.sol'; import '../../contracts/interfaces/IPoolConfigurator.sol'; import '../../contracts/interfaces/IAaveOracle.sol'; import '../../contracts/interfaces/IAToken.sol'; import '../../contracts/interfaces/IVariableDebtToken.sol'; import '../../contracts/interfaces/IACLManager.sol'; import '../../contracts/interfaces/IDefaultInterestRateStrategyV2.sol'; import '../../contracts/helpers/AaveProtocolDataProvider.sol'; import '../../contracts/helpers/UiPoolDataProviderV3.sol'; import '../../contracts/helpers/UiIncentiveDataProviderV3.sol'; import '../../contracts/rewards/interfaces/IEmissionManager.sol'; import '../../contracts/rewards/interfaces/IRewardsController.sol'; import '../../contracts/helpers/WalletBalanceProvider.sol'; import '../../contracts/extensions/paraswap-adapters/ParaSwapLiquiditySwapAdapter.sol'; import '../../contracts/extensions/paraswap-adapters/ParaSwapRepayAdapter.sol'; import '../../contracts/extensions/paraswap-adapters/ParaSwapWithdrawSwapAdapter.sol'; import '../../contracts/helpers/interfaces/IWrappedTokenGatewayV3.sol'; import '../../contracts/helpers/L2Encoder.sol'; import {ICollector} from '../../contracts/treasury/ICollector.sol'; struct ContractsReport { IPoolAddressesProviderRegistry poolAddressesProviderRegistry; IPoolAddressesProvider poolAddressesProvider; IPool poolProxy; IPool poolImplementation; IPoolConfigurator poolConfiguratorProxy; IPoolConfigurator poolConfiguratorImplementation; AaveProtocolDataProvider protocolDataProvider; IAaveOracle aaveOracle; IACLManager aclManager; ICollector treasury; IDefaultInterestRateStrategyV2 defaultInterestRateStrategy; ICollector treasuryImplementation; IWrappedTokenGatewayV3 wrappedTokenGateway; WalletBalanceProvider walletBalanceProvider; UiIncentiveDataProviderV3 uiIncentiveDataProvider; UiPoolDataProviderV3 uiPoolDataProvider; ParaSwapLiquiditySwapAdapter paraSwapLiquiditySwapAdapter; ParaSwapRepayAdapter paraSwapRepayAdapter; ParaSwapWithdrawSwapAdapter paraSwapWithdrawSwapAdapter; L2Encoder l2Encoder; IAToken aToken; IVariableDebtToken variableDebtToken; IEmissionManager emissionManager; IRewardsController rewardsControllerImplementation; IRewardsController rewardsControllerProxy; } struct MarketReport { address poolAddressesProviderRegistry; address poolAddressesProvider; address poolProxy; address poolImplementation; address poolConfiguratorProxy; address poolConfiguratorImplementation; address protocolDataProvider; address aaveOracle; address defaultInterestRateStrategy; address priceOracleSentinel; address aclManager; address treasury; address treasuryImplementation; address wrappedTokenGateway; address walletBalanceProvider; address uiIncentiveDataProvider; address uiPoolDataProvider; address paraSwapLiquiditySwapAdapter; address paraSwapRepayAdapter; address paraSwapWithdrawSwapAdapter; address l2Encoder; address aToken; address variableDebtToken; address emissionManager; address rewardsControllerImplementation; address rewardsControllerProxy; address configEngine; address transparentProxyFactory; address staticATokenFactoryImplementation; address staticATokenFactoryProxy; address staticATokenImplementation; address revenueSplitter; } struct LibrariesReport { address borrowLogic; address bridgeLogic; address configuratorLogic; address eModeLogic; address flashLoanLogic; address liquidationLogic; address poolLogic; address supplyLogic; } struct Roles { address marketOwner; address poolAdmin; address emergencyAdmin; } struct MarketConfig { address networkBaseTokenPriceInUsdProxyAggregator; address marketReferenceCurrencyPriceInUsdProxyAggregator; string marketId; uint8 oracleDecimals; address paraswapAugustusRegistry; address l2SequencerUptimeFeed; uint256 l2PriceOracleSentinelGracePeriod; uint256 providerId; bytes32 salt; address wrappedNativeToken; uint128 flashLoanPremiumTotal; uint128 flashLoanPremiumToProtocol; address incentivesProxy; address treasury; // let empty for deployment of collector, otherwise reuse treasury address address treasuryPartner; // let empty for single treasury, or add treasury partner for revenue split between two organizations. uint16 treasurySplitPercent; // ignored if treasuryPartner is empty, otherwise the split percent for the first treasury (recipientA, values between 00_01 and 100_00) } struct DeployFlags { bool l2; } struct PoolReport { address poolImplementation; address poolConfiguratorImplementation; } struct MiscReport { address priceOracleSentinel; address defaultInterestRateStrategy; } struct ConfigEngineReport { address configEngine; address listingEngine; address eModeEngine; address borrowEngine; address collateralEngine; address priceFeedEngine; address rateEngine; address capsEngine; } struct StaticATokenReport { address transparentProxyFactory; address staticATokenImplementation; address staticATokenFactoryImplementation; address staticATokenFactoryProxy; } struct InitialReport { address poolAddressesProvider; address poolAddressesProviderRegistry; } struct SetupReport { address poolProxy; address poolConfiguratorProxy; address rewardsControllerProxy; address aclManager; } struct PeripheryReport { address aaveOracle; address treasury; address treasuryImplementation; address emissionManager; address rewardsControllerImplementation; address revenueSplitter; } struct ParaswapReport { address paraSwapLiquiditySwapAdapter; address paraSwapRepayAdapter; address paraSwapWithdrawSwapAdapter; }
{ "remappings": [ "solidity-utils/=lib/solidity-utils/src/", "forge-std/=lib/forge-std/src/", "ds-test/=lib/forge-std/lib/ds-test/src/", "openzeppelin-contracts-upgradeable/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/", "openzeppelin-contracts/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/", "@openzeppelin/contracts-upgradeable/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/contracts/", "@openzeppelin/contracts/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/", "erc4626-tests/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/", "halmos-cheatcodes/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "none", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "shanghai", "viaIR": false, "libraries": { "src/contracts/protocol/libraries/logic/BorrowLogic.sol": { "BorrowLogic": "0x62325c94E1c49dcDb5937726aB5D8A4c37bCAd36" }, "src/contracts/protocol/libraries/logic/BridgeLogic.sol": { "BridgeLogic": "0x621Ef86D8A5C693a06295BC288B95C12D4CE4994" }, "src/contracts/protocol/libraries/logic/ConfiguratorLogic.sol": { "ConfiguratorLogic": "0x09e88e877B39D883BAFd46b65E7B06CC56963041" }, "src/contracts/protocol/libraries/logic/EModeLogic.sol": { "EModeLogic": "0xC31d2362fAeD85dF79d0bec99693D0EB0Abd3f74" }, "src/contracts/protocol/libraries/logic/FlashLoanLogic.sol": { "FlashLoanLogic": "0x34039100cc9584Ae5D741d322e16d0d18CEE8770" }, "src/contracts/protocol/libraries/logic/LiquidationLogic.sol": { "LiquidationLogic": "0x4731bF01583F991278692E8727d0700a00A1fBBf" }, "src/contracts/protocol/libraries/logic/PoolLogic.sol": { "PoolLogic": "0xf8C97539934ee66a67C26010e8e027D77E821B0C" }, "src/contracts/protocol/libraries/logic/SupplyLogic.sol": { "SupplyLogic": "0x185477906B46D9b8DE0DEB73A1bBfb87b5b51BC3" } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"address","name":"poolAdmin","type":"address"},{"components":[{"internalType":"address","name":"networkBaseTokenPriceInUsdProxyAggregator","type":"address"},{"internalType":"address","name":"marketReferenceCurrencyPriceInUsdProxyAggregator","type":"address"},{"internalType":"string","name":"marketId","type":"string"},{"internalType":"uint8","name":"oracleDecimals","type":"uint8"},{"internalType":"address","name":"paraswapAugustusRegistry","type":"address"},{"internalType":"address","name":"l2SequencerUptimeFeed","type":"address"},{"internalType":"uint256","name":"l2PriceOracleSentinelGracePeriod","type":"uint256"},{"internalType":"uint256","name":"providerId","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"address","name":"wrappedNativeToken","type":"address"},{"internalType":"uint128","name":"flashLoanPremiumTotal","type":"uint128"},{"internalType":"uint128","name":"flashLoanPremiumToProtocol","type":"uint128"},{"internalType":"address","name":"incentivesProxy","type":"address"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"address","name":"treasuryPartner","type":"address"},{"internalType":"uint16","name":"treasurySplitPercent","type":"uint16"}],"internalType":"struct MarketConfig","name":"config","type":"tuple"},{"internalType":"address","name":"poolAddressesProvider","type":"address"},{"internalType":"address","name":"setupBatch","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"getPeripheryReport","outputs":[{"components":[{"internalType":"address","name":"aaveOracle","type":"address"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"address","name":"treasuryImplementation","type":"address"},{"internalType":"address","name":"emissionManager","type":"address"},{"internalType":"address","name":"rewardsControllerImplementation","type":"address"},{"internalType":"address","name":"revenueSplitter","type":"address"}],"internalType":"struct PeripheryReport","name":"","type":"tuple"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
608060405234801562000010575f80fd5b50604051620092d3380380620092d3833981016040819052620000339162000741565b6060830151620000479060ff168362000296565b5f80546001600160a01b0319166001600160a01b039283161790556101a084015116620000bf575f6200008685856101000151620002f160201b60201c565b6020810151600180546001600160a01b03199081166001600160a01b0393841617909155915160028054909316911617905550620000e5565b6101a0830151600180546001600160a01b0319166001600160a01b039092169190911790555b6101c08301516001600160a01b0316158015906200010b57505f836101e0015161ffff16115b8015620001225750612710836101e0015161ffff16105b15620001af576001546101c08401516101e08501516040516001600160a01b03909316926200015190620005a5565b6001600160a01b03938416815292909116602083015261ffff166040820152606001604051809103905ff0801580156200018d573d5f803e3d5ffd5b50600580546001600160a01b0319166001600160a01b03929092169190911790555b6101808301516001600160a01b03166200020357620001ce81620004c7565b600480546001600160a01b039283166001600160a01b031991821617909155600380549390921692169190911790556200028c565b8261018001516001600160a01b03166392074b086040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000245573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200026b919062000905565b600380546001600160a01b0319166001600160a01b03929092169190911790555b5050505062000b2e565b5f6060818382808380620002ac8a600a62000a35565b604051620002ba90620005b3565b620002cb9695949392919062000a8b565b604051809103905ff080158015620002e5573d5f803e3d5ffd5b50925050505b92915050565b604080518082019091525f8082526020820152604080518082019091525f8082526020820152828015620003f7575f816040516200032f90620005c1565b8190604051809103905ff59050801580156200034d573d5f803e3d5ffd5b506001600160a01b0381811680865260408051620186a06024820152928a1660448085019190915281518085039091018152606490930181526020830180516001600160e01b031663da35a26f60e01b17905251929350849290918991620003b590620005cf565b620003c39392919062000ae0565b8190604051809103905ff5905080158015620003e1573d5f803e3d5ffd5b506001600160a01b0316602084015250620004bf565b5f6040516200040690620005c1565b604051809103905ff08015801562000420573d5f803e3d5ffd5b506001600160a01b0381811680865260408051620186a06024820152928a1660448085019190915281518085039091018152606490930181526020830180516001600160e01b031663da35a26f60e01b17905251929350918891906200048690620005cf565b620004949392919062000ae0565b604051809103905ff080158015620004ae573d5f803e3d5ffd5b506001600160a01b03166020840152505b509392505050565b5f805f83604051620004d990620005dd565b6001600160a01b039091168152602001604051809103905ff08015801562000503573d5f803e3d5ffd5b5090505f816040516200051690620005eb565b6001600160a01b039091168152602001604051809103905ff08015801562000540573d5f803e3d5ffd5b5060405163189acdbd60e31b81525f60048201529091506001600160a01b0382169063c4d66de8906024015f604051808303815f87803b15801562000583575f80fd5b505af115801562000596573d5f803e3d5ffd5b50939792965091945050505050565b6108d38062000c6083390190565b610eb7806200153383390190565b611a2380620023ea83390190565b610dfe8062003e0d83390190565b610f138062004c0b83390190565b6137b58062005b1e83390190565b80516001600160a01b038116811462000610575f80fd5b919050565b634e487b7160e01b5f52604160045260245ffd5b60405161020081016001600160401b03811182821017156200064f576200064f62000615565b60405290565b5f5b838110156200067157818101518382015260200162000657565b50505f910152565b5f82601f83011262000689575f80fd5b81516001600160401b0380821115620006a657620006a662000615565b604051601f8301601f19908116603f01168101908282118183101715620006d157620006d162000615565b81604052838152866020858801011115620006ea575f80fd5b620006fd84602083016020890162000655565b9695505050505050565b805160ff8116811462000610575f80fd5b80516001600160801b038116811462000610575f80fd5b805161ffff8116811462000610575f80fd5b5f805f806080858703121562000755575f80fd5b6200076085620005f9565b60208601519094506001600160401b03808211156200077d575f80fd5b90860190610200828903121562000792575f80fd5b6200079c62000629565b620007a783620005f9565b8152620007b760208401620005f9565b6020820152604083015182811115620007ce575f80fd5b620007dc8a82860162000679565b604083015250620007f06060840162000707565b60608201526200080360808401620005f9565b60808201526200081660a08401620005f9565b60a082015260c083015160c082015260e083015160e08201526101009150818301518282015261012091506200084e828401620005f9565b8282015261014091506200086482840162000718565b8282015261016091506200087a82840162000718565b82820152610180915062000890828401620005f9565b828201526101a09150620008a6828401620005f9565b828201526101c09150620008bc828401620005f9565b828201526101e09150620008d28284016200072f565b82820152809550505050620008ea60408601620005f9565b9150620008fa60608601620005f9565b905092959194509250565b5f6020828403121562000916575f80fd5b6200092182620005f9565b9392505050565b634e487b7160e01b5f52601160045260245ffd5b600181815b808511156200097c57815f190482111562000960576200096062000928565b808516156200096e57918102915b93841c939080029062000941565b509250929050565b5f826200099457506001620002eb565b81620009a257505f620002eb565b8160018114620009bb5760028114620009c657620009e6565b6001915050620002eb565b60ff841115620009da57620009da62000928565b50506001821b620002eb565b5060208310610133831016604e8410600b841016171562000a0b575081810a620002eb565b62000a1783836200093c565b805f190482111562000a2d5762000a2d62000928565b029392505050565b5f6200092161ffff84168362000984565b5f815180845260208085019450602084015f5b8381101562000a805781516001600160a01b03168752958201959082019060010162000a59565b509495945050505050565b5f60018060a01b03808916835260c0602084015262000aae60c084018962000a46565b838103604085015262000ac2818962000a46565b96821660608501525093909316608082015260a00152509392505050565b5f60018060a01b03808616835280851660208401525060606040830152825180606084015262000b1881608085016020870162000655565b601f01601f191691909101608001949350505050565b6101248062000b3c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063620b88461461002d575b5f80fd5b6100b36040805160c0810182525f80825260208201819052918101829052606081018290526080810182905260a0810191909152506040805160c0810182525f546001600160a01b03908116825260015481166020830152600254811692820192909252600354821660608201526004548216608082015260055490911660a082015290565b60405161010e919081516001600160a01b03908116825260208084015182169083015260408084015182169083015260608084015182169083015260808084015182169083015260a092830151169181019190915260c00190565b60405180910390f3fea164736f6c6343000816000a60e060405234801561000f575f80fd5b506040516108d33803806108d383398101604081905261002e916100a1565b60015f5561ffff8116158061004957506127108161ffff1610155b15610067576040516307a6a76b60e31b815260040160405180910390fd5b6001600160a01b03928316608052911660a05261ffff1660c0526100eb565b80516001600160a01b038116811461009c575f80fd5b919050565b5f805f606084860312156100b3575f80fd5b6100bc84610086565b92506100ca60208501610086565b9150604084015161ffff811681146100e0575f80fd5b809150509250925092565b60805160a05160c05161079661013d5f395f818160680152818161025f01526103b301525f8181610133015281816102f2015261046301525f818160d40152818161029801526103e901526107965ff3fe60806040526004361061004c575f3560e01c806330298df414610057578063607ecbea146100a2578063a93aa57e146100c3578063ee8d69a81461010e578063f10d2fd114610122575f80fd5b3661005357005b5f80fd5b348015610062575f80fd5b5061008a7f000000000000000000000000000000000000000000000000000000000000000081565b60405161ffff90911681526020015b60405180910390f35b3480156100ad575f80fd5b506100c16100bc366004610653565b610155565b005b3480156100ce575f80fd5b506100f67f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610099565b348015610119575f80fd5b506100c1610343565b34801561012d575f80fd5b506100f67f000000000000000000000000000000000000000000000000000000000000000081565b60025f54036101ab5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064015b60405180910390fd5b60025f9081555b81518160ff16101561033b575f828260ff16815181106101d4576101d4610713565b60209081029190910101516040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa158015610222573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102469190610727565b9050805f03610255575061032b565b5f6102848261ffff7f0000000000000000000000000000000000000000000000000000000000000000166104cf565b90505f6102918284610752565b90506102ed7f000000000000000000000000000000000000000000000000000000000000000083878760ff16815181106102cd576102cd610713565b60200260200101516001600160a01b03166104f39092919063ffffffff16565b6103277f000000000000000000000000000000000000000000000000000000000000000082878760ff16815181106102cd576102cd610713565b5050505b6103348161076b565b90506101b2565b505060015f55565b60025f54036103945760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016101a2565b60025f90815547908190036103a957506104c9565b5f6103d88261ffff7f0000000000000000000000000000000000000000000000000000000000000000166104cf565b90505f6103e58284610752565b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316826040515f6040518083038185875af1925050503d805f811461044f576040519150601f19603f3d011682016040523d82523d5f602084013e610454565b606091505b50506040516001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016915082905f81818185875af1925050503d805f81146104bd576040519150601f19603f3d011682016040523d82523d5f602084013e6104c2565b606091505b5050505050505b60015f55565b5f811561138819839004841115176104e5575f80fd5b506127109102611388010490565b60405163a9059cbb60e01b8082526001600160a01b038416600483015260248201839052905f8060448382895af161052d573d5f803e3d5ffd5b5061053784610581565b61057b5760405162461bcd60e51b815260206004820152601560248201527423a83b191d103330b4b632b2103a3930b739b332b960591b60448201526064016101a2565b50505050565b5f6105a3565b62461bcd60e51b5f52602060045280602452508060445260645ffd5b3d80156105e25760208114610613576105dd7f475076323a206d616c666f726d6564207472616e7366657220726573756c7400601f610587565b61061e565b823b61060a5761060a7311d41d8c8e881b9bdd08184818dbdb9d1c9858dd60621b6014610587565b6001915061061e565b3d5f803e5f51151591505b50919050565b634e487b7160e01b5f52604160045260245ffd5b80356001600160a01b038116811461064e575f80fd5b919050565b5f6020808385031215610664575f80fd5b823567ffffffffffffffff8082111561067b575f80fd5b818501915085601f83011261068e575f80fd5b8135818111156106a0576106a0610624565b8060051b604051601f19603f830116810181811085821117156106c5576106c5610624565b6040529182528482019250838101850191888311156106e2575f80fd5b938501935b82851015610707576106f885610638565b845293850193928501926106e7565b98975050505050505050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610737575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b818103818111156107655761076561073e565b92915050565b5f60ff821660ff81036107805761078061073e565b6001019291505056fea164736f6c6343000816000a60e060405234801562000010575f80fd5b5060405162000eb738038062000eb7833981016040819052620000339162000339565b6001600160a01b0386166080526200004b83620000aa565b620000578585620000f3565b6001600160a01b03821660a081905260c08290526040518281527fe27c4c1372396a3d15a9922f74f9dfc7c72b1ad6d63868470787249c356454c19060200160405180910390a250505050505062000449565b600180546001600160a01b0319166001600160a01b0383169081179091556040517fce7a780d33665b1ea097af5f155e3821b809ecbaa839d3b33aa83ba28168cefb905f90a250565b8051825114604051806040016040528060028152602001611b9b60f11b815250906200013d5760405162461bcd60e51b8152600401620001349190620003e7565b60405180910390fd5b505f5b825181101562000249578181815181106200015f576200015f62000435565b60200260200101515f808584815181106200017e576200017e62000435565b60200260200101516001600160a01b03166001600160a01b031681526020019081526020015f205f6101000a8154816001600160a01b0302191690836001600160a01b03160217905550818181518110620001dd57620001dd62000435565b60200260200101516001600160a01b031683828151811062000203576200020362000435565b60200260200101516001600160a01b03167f22c5b7b2d8561d39f7f210b6b326a1aa69f15311163082308ac4877db6339dc160405160405180910390a360010162000140565b505050565b6001600160a01b038116811462000263575f80fd5b50565b634e487b7160e01b5f52604160045260245ffd5b805162000287816200024e565b919050565b5f82601f8301126200029c575f80fd5b815160206001600160401b0380831115620002bb57620002bb62000266565b8260051b604051601f19603f83011681018181108482111715620002e357620002e362000266565b604052938452602081870181019490810192508785111562000303575f80fd5b6020870191505b848210156200032e576200031e826200027a565b835291830191908301906200030a565b979650505050505050565b5f805f805f8060c087890312156200034f575f80fd5b86516200035c816200024e565b60208801519096506001600160401b038082111562000379575f80fd5b620003878a838b016200028c565b965060408901519150808211156200039d575f80fd5b50620003ac89828a016200028c565b9450506060870151620003bf816200024e565b6080880151909350620003d2816200024e565b8092505060a087015190509295509295509295565b5f602080835283518060208501525f5b818110156200041557858101830151858201604001528201620003f7565b505f604082860101526040601f19601f8301168501019250505092915050565b634e487b7160e01b5f52603260045260245ffd5b60805160a05160c051610a2f620004885f395f8181610103015261034d01525f81816101a9015261032201525f8181609901526104dc0152610a2f5ff3fe608060405234801561000f575f80fd5b5060043610610090575f3560e01c806392bf2be01161006357806392bf2be0146101335780639d23d9f21461015e578063abfd53101461017e578063b3596f0714610191578063e19f4700146101a4575f80fd5b80630542975c14610094578063170aee73146100d85780636210308c146100ed5780638c89b64f146100fe575b5f80fd5b6100bb7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b6100eb6100e6366004610811565b6101cb565b005b6001546001600160a01b03166100bb565b6101257f000000000000000000000000000000000000000000000000000000000000000081565b6040519081526020016100cf565b6100bb610141366004610811565b6001600160a01b039081165f908152602081905260409020541690565b61017161016c366004610874565b6101df565b6040516100cf91906108b3565b6100eb61018c3660046108f6565b610288565b61012561019f366004610811565b610301565b6100bb7f000000000000000000000000000000000000000000000000000000000000000081565b6101d36104d9565b6101dc81610673565b50565b60605f8267ffffffffffffffff8111156101fb576101fb61095d565b604051908082528060200260200182016040528015610224578160200160208202803683370190505b5090505f5b838110156102805761025b85858381811061024657610246610971565b905060200201602081019061019f9190610811565b82828151811061026d5761026d610971565b6020908102919091010152600101610229565b509392505050565b6102906104d9565b6102fb8484808060200260200160405190810160405280939291908181526020018383602002808284375f92019190915250506040805160208088028281018201909352878252909350879250869182918501908490808284375f920191909152506106bc92505050565b50505050565b6001600160a01b038082165f818152602081905260408120549092908116917f0000000000000000000000000000000000000000000000000000000000000000909116900361037257507f000000000000000000000000000000000000000000000000000000000000000092915050565b6001600160a01b0381166103f35760015460405163b3596f0760e01b81526001600160a01b0385811660048301529091169063b3596f0790602401602060405180830381865afa1580156103c8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103ec9190610985565b9392505050565b5f816001600160a01b03166350d25bcd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610430573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104549190610985565b90505f811315610465579392505050565b60015460405163b3596f0760e01b81526001600160a01b0386811660048301529091169063b3596f0790602401602060405180830381865afa1580156104ad573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104d19190610985565b949350505050565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663707cd7166040518163ffffffff1660e01b8152600401602060405180830381865afa158015610536573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061055a919061099c565b604051629f719760e51b81523360048201529091506001600160a01b038216906313ee32e090602401602060405180830381865afa15801561059e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105c291906109b7565b8061062e5750604051637be53ca160e01b81523360048201526001600160a01b03821690637be53ca190602401602060405180830381865afa15801561060a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061062e91906109b7565b604051806040016040528060018152602001603560f81b8152509061066f5760405162461bcd60e51b815260040161066691906109d6565b60405180910390fd5b5050565b600180546001600160a01b0319166001600160a01b0383169081179091556040517fce7a780d33665b1ea097af5f155e3821b809ecbaa839d3b33aa83ba28168cefb905f90a250565b8051825114604051806040016040528060028152602001611b9b60f11b815250906106fa5760405162461bcd60e51b815260040161066691906109d6565b505f5b82518110156107f85781818151811061071857610718610971565b60200260200101515f8085848151811061073457610734610971565b60200260200101516001600160a01b03166001600160a01b031681526020019081526020015f205f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555081818151811061079057610790610971565b60200260200101516001600160a01b03168382815181106107b3576107b3610971565b60200260200101516001600160a01b03167f22c5b7b2d8561d39f7f210b6b326a1aa69f15311163082308ac4877db6339dc160405160405180910390a36001016106fd565b505050565b6001600160a01b03811681146101dc575f80fd5b5f60208284031215610821575f80fd5b81356103ec816107fd565b5f8083601f84011261083c575f80fd5b50813567ffffffffffffffff811115610853575f80fd5b6020830191508360208260051b850101111561086d575f80fd5b9250929050565b5f8060208385031215610885575f80fd5b823567ffffffffffffffff81111561089b575f80fd5b6108a78582860161082c565b90969095509350505050565b602080825282518282018190525f9190848201906040850190845b818110156108ea578351835292840192918401916001016108ce565b50909695505050505050565b5f805f8060408587031215610909575f80fd5b843567ffffffffffffffff80821115610920575f80fd5b61092c8883890161082c565b90965094506020870135915080821115610944575f80fd5b506109518782880161082c565b95989497509550505050565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610995575f80fd5b5051919050565b5f602082840312156109ac575f80fd5b81516103ec816107fd565b5f602082840312156109c7575f80fd5b815180151581146103ec575f80fd5b5f602080835283518060208501525f5b81811015610a02578581018301518582016040015282016109e6565b505f604082860101526040601f19601f830116850101925050509291505056fea164736f6c6343000816000a608060405234801561000f575f80fd5b5061001861001d565b6100cf565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff161561006d5760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b03908116146100cc5780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b611947806100dc5f395ff3fe60806040526004361061011e575f3560e01c806391d148541161009d578063cc1b4bf611610062578063cc1b4bf614610371578063d547741f14610390578063da35a26f146103af578063e1f21c67146103ce578063f501148c146103ed575f80fd5b806391d14854146102e057806397713592146102ff578063a217fddf14610320578063a82ccd4d14610333578063beabacc814610352575f80fd5b80633656eec2116100e35780633656eec2146101da57806351ee886b146101f95780636db9241b146102385780637a9b2c6c14610257578063894e9a0d14610276575f80fd5b806301ffc9a7146101295780630932f92b1461015d578063248a9ca31461017b5780632f2ff15d1461019a57806336568abe146101bb575f80fd5b3661012557005b5f80fd5b348015610134575f80fd5b5061014861014336600461171c565b61040c565b60405190151581526020015b60405180910390f35b348015610168575f80fd5b506035545b604051908152602001610154565b348015610186575f80fd5b5061016d61019536600461174a565b610442565b3480156101a5575f80fd5b506101b96101b4366004611775565b610462565b005b3480156101c6575f80fd5b506101b96101d5366004611775565b610484565b3480156101e5575f80fd5b5061016d6101f4366004611775565b6104bc565b348015610204575f80fd5b5061022073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b6040516001600160a01b039091168152602001610154565b348015610243575f80fd5b5061014861025236600461174a565b61065f565b348015610262575f80fd5b506101486102713660046117a3565b6108a4565b348015610281575f80fd5b5061029561029036600461174a565b610b24565b604080516001600160a01b03998a1681529789166020890152870195909552959092166060850152608084015260a083015260c082019290925260e081019190915261010001610154565b3480156102eb575f80fd5b506101486102fa366004611775565b610bc7565b34801561030a575f80fd5b5061016d6a232aa72229afa0a226a4a760a91b81565b34801561032b575f80fd5b5061016d5f81565b34801561033e575f80fd5b5061016d61034d36600461174a565b610bfd565b34801561035d575f80fd5b506101b961036c3660046117c3565b610d16565b34801561037c575f80fd5b5061016d61038b366004611801565b610db2565b34801561039b575f80fd5b506101b96103aa366004611775565b611104565b3480156103ba575f80fd5b506101b96103c9366004611775565b611120565b3480156103d9575f80fd5b506101b96103e83660046117c3565b61124d565b3480156103f8575f80fd5b5061014861040736600461184f565b61128a565b5f6001600160e01b03198216637965db0b60e01b148061043c57506301ffc9a760e01b6001600160e01b03198316145b92915050565b5f9081525f805160206118fb833981519152602052604090206001015490565b61046b82610442565b610474816112a3565b61047e83836112b0565b50505050565b6001600160a01b03811633146104ad5760405163334bd91960e11b815260040160405180910390fd5b6104b78282611351565b505050565b5f828152603660205260408120600701548390600160a01b900460ff166104f65760405163314c062560e21b815260040160405180910390fd5b5f8481526036602090815260408083208151610120810183528154815260018201548185015260028201548184015260038201546060808301919091526004830154608083015260058301546001600160a01b0390811660a08401526006840154811660c084015260079093015492831660e0830152600160a01b90920460ff1615156101008201528251918201835284825292810184905290810192909252905f6105a187610bfd565b90508260200151816105b3919061187e565b82526040830151835111156105e957604083015183516105d39190611895565b6020830181905282516105e69190611895565b82525b8260a001516001600160a01b0316866001600160a01b03160361061157505192506106589050565b8260c001516001600160a01b0316866001600160a01b031603610651578151604084015161063f9190611895565b60409092018290525092506106589050565b5f94505050505b5092915050565b5f6106686113ca565b5f828152603660205260409020600701548290600160a01b900460ff166106a25760405163314c062560e21b815260040160405180910390fd5b826106ab611401565b1580156106d157505f818152603660205260409020600501546001600160a01b03163314155b156106ef576040516358c6353d60e11b815260040160405180910390fd5b5f84815260366020908152604080832081516101208101835281548152600182015493810193909352600281015491830191909152600381015460608301526004810154608083015260058101546001600160a01b0390811660a08401526006820154811660c0840181905260079092015490811660e0840152600160a01b900460ff1615156101008301529091906107899087906104bc565b90505f61079a878460a001516104bc565b5f88815260366020526040812081815560018101829055600281018290556003810182905560048101919091556005810180546001600160a01b0319908116909155600682018054909116905560070180546001600160a81b031916905560e084015190915081156108205760a0840151610820906001600160a01b038316908461141f565b8360a001516001600160a01b03168460c001516001600160a01b0316897fca3e6079b726e7728802a0537949e2d1c7762304fa641fb06eb56daf2ba8c6b98686604051610877929190918252602082015260400190565b60405180910390a46001965050505050505061089f60015f8051602061191b83398151915255565b919050565b5f6108ad6113ca565b5f838152603660205260409020600701548390600160a01b900460ff166108e75760405163314c062560e21b815260040160405180910390fd5b836108f0611401565b15801561091657505f818152603660205260409020600501546001600160a01b03163314155b15610934576040516358c6353d60e11b815260040160405180910390fd5b835f0361095457604051630dd484e760e41b815260040160405180910390fd5b5f85815260366020908152604080832081516101208101835281548152600182015493810193909352600281015491830191909152600381015460608301526004810154608083015260058101546001600160a01b0390811660a084018190526006830154821660c085015260079092015490811660e0840152600160a01b900460ff1615156101008301529091906109ee9088906104bc565b905085811015610a1157604051634d9d73a360e01b815260040160405180910390fd5b858260400151610a219190611895565b5f88815260366020526040812060020182905503610a98575f87815260366020526040812081815560018101829055600281018290556003810182905560048101919091556005810180546001600160a01b0319908116909155600682018054909116905560070180546001600160a81b03191690555b610abe8260a00151878460e001516001600160a01b031661141f9092919063ffffffff16565b8160a001516001600160a01b0316877f36c3ab437e6a424ed25dc4bfdeb62706aa06558660fab2dab229d2555adaf89c88604051610afe91815260200190565b60405180910390a3600194505050505061043c60015f8051602061191b83398151915255565b5f805f805f805f808860365f8281526020019081526020015f2060070160149054906101000a900460ff16610b6c5760405163314c062560e21b815260040160405180910390fd5b5050505f968752505060366020525050604090922060068101546005820154825460078401546003850154600486015460028701546001909701546001600160a01b039687169a958716995093975091909416949092909190565b5f9182525f805160206118fb833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b5f818152603660205260408120600701548290600160a01b900460ff16610c375760405163314c062560e21b815260040160405180910390fd5b5f83815260366020908152604091829020825161012081018452815481526001820154928101929092526002810154928201929092526003820154606082018190526004830154608083015260058301546001600160a01b0390811660a08401526006840154811660c084015260079093015492831660e0830152600160a01b90920460ff161515610100820152904211610cd5575f925050610d10565b8060800151421015610cf8576060810151610cf09042611895565b925050610d10565b80606001518160800151610d0c9190611895565b9250505b50919050565b610d1e611401565b15155f03610d3f5760405163277cf38160e01b815260040160405180910390fd5b6001600160a01b038216610d665760405163f6b2911f60e01b815260040160405180910390fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeed196001600160a01b03841601610d9e576104b76001600160a01b03831682611491565b6104b76001600160a01b038416838361141f565b5f610dbb611401565b15155f03610ddc5760405163277cf38160e01b815260040160405180910390fd5b6001600160a01b038616610e035760405163f6b2911f60e01b815260040160405180910390fd5b306001600160a01b03871603610e2c57604051634e46966960e11b815260040160405180910390fd5b336001600160a01b03871603610e5557604051634e46966960e11b815260040160405180910390fd5b845f03610e7557604051630dd484e760e41b815260040160405180910390fd5b42831015610e9657604051632ca4094f60e21b815260040160405180910390fd5b828211610eb657604051635f5ab34960e01b815260040160405180910390fd5b604080518082019091525f8082526020820152610ed38484611895565b808252861015610ef65760405163c4e1993b60e01b815260040160405180910390fd5b80515f90610f0490886118bc565b1115610f2357604051636b3cc5b760e11b815260040160405180910390fd5b8051610f2f90876118cf565b8160200181815250505f603554905060405180610120016040528088815260200183602001518152602001888152602001868152602001858152602001896001600160a01b03168152602001306001600160a01b03168152602001876001600160a01b031681526020016001151581525060365f8381526020019081526020015f205f820151815f01556020820151816001015560408201518160020155606082015181600301556080820151816004015560a0820151816005015f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555060c0820151816006015f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555060e0820151816007015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055506101008201518160070160146101000a81548160ff02191690831515021790555090505060355f81548092919061109b906118e2565b9091555050604080518881526001600160a01b0388811660208301529181018790526060810186905290891690309083907f7b01d409597969366dc268d7f957a990d1ca3d3449baf8fb45db67351aecfe789060800160405180910390a4979650505050505050565b61110d82610442565b611116816112a3565b61047e8383611351565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f811580156111655750825b90505f8267ffffffffffffffff1660011480156111815750303b155b90508115801561118f575080155b156111ad5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff1916600117855583156111d757845460ff60401b1916600160401b1785555b6111df611530565b6111e761153a565b6111f15f876112b0565b5086156111fe5760358790555b831561124457845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b611255611401565b15155f036112765760405163277cf38160e01b815260040160405180910390fd5b6104b76001600160a01b038416838361154a565b5f61043c6a232aa72229afa0a226a4a760a91b83610bc7565b6112ad81336115d9565b50565b5f5f805160206118fb8339815191526112c98484610bc7565b611348575f848152602082815260408083206001600160a01b03871684529091529020805460ff191660011790556112fe3390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4600191505061043c565b5f91505061043c565b5f5f805160206118fb83398151915261136a8484610bc7565b15611348575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4600191505061043c565b5f8051602061191b8339815191528054600119016113fb57604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b5f61141a6a232aa72229afa0a226a4a760a91b33610bc7565b905090565b6040516001600160a01b038381166024830152604482018390526104b791859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611616565b60015f8051602061191b83398151915255565b804710156114c05760405163cf47918160e01b8152476004820152602481018290526044015b60405180910390fd5b5f826001600160a01b0316826040515f6040518083038185875af1925050503d805f8114611509576040519150601f19603f3d011682016040523d82523d5f602084013e61150e565b606091505b50509050806104b75760405163d6bda27560e01b815260040160405180910390fd5b611538611682565b565b611542611682565b6115386116cb565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261159b84826116d3565b61047e576040516001600160a01b0384811660248301525f60448301526115cf91869182169063095ea7b39060640161144c565b61047e8482611616565b6115e38282610bc7565b6116125760405163e2517d3f60e01b81526001600160a01b0382166004820152602481018390526044016114b7565b5050565b5f8060205f8451602086015f885af180611635576040513d5f823e3d81fd5b50505f513d9150811561164c578060011415611659565b6001600160a01b0384163b155b1561047e57604051635274afe760e01b81526001600160a01b03851660048201526024016114b7565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff1661153857604051631afcd79f60e31b815260040160405180910390fd5b61147e611682565b5f805f8060205f8651602088015f8a5af192503d91505f519050828015611712575081156117045780600114611712565b5f866001600160a01b03163b115b9695505050505050565b5f6020828403121561172c575f80fd5b81356001600160e01b031981168114611743575f80fd5b9392505050565b5f6020828403121561175a575f80fd5b5035919050565b6001600160a01b03811681146112ad575f80fd5b5f8060408385031215611786575f80fd5b82359150602083013561179881611761565b809150509250929050565b5f80604083850312156117b4575f80fd5b50508035926020909101359150565b5f805f606084860312156117d5575f80fd5b83356117e081611761565b925060208401356117f081611761565b929592945050506040919091013590565b5f805f805f60a08688031215611815575f80fd5b853561182081611761565b945060208601359350604086013561183781611761565b94979396509394606081013594506080013592915050565b5f6020828403121561185f575f80fd5b813561174381611761565b634e487b7160e01b5f52601160045260245ffd5b808202811582820484141761043c5761043c61186a565b8181038181111561043c5761043c61186a565b634e487b7160e01b5f52601260045260245ffd5b5f826118ca576118ca6118a8565b500690565b5f826118dd576118dd6118a8565b500490565b5f600182016118f3576118f361186a565b506001019056fe02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b6268009b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00a164736f6c6343000816000a60a060405260405162000dfe38038062000dfe8339810160408190526200002691620003bc565b828162000034828262000099565b50508160405162000045906200035a565b6001600160a01b039091168152602001604051809103905ff0801580156200006f573d5f803e3d5ffd5b506001600160a01b0316608052620000906200008a60805190565b620000fe565b505050620004b3565b620000a4826200016f565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a2805115620000f057620000eb8282620001ee565b505050565b620000fa62000267565b5050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6200013f5f8051602062000dde833981519152546001600160a01b031690565b604080516001600160a01b03928316815291841660208301520160405180910390a16200016c8162000289565b50565b806001600160a01b03163b5f03620001aa57604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5b80546001600160a01b0319166001600160a01b039290921691909117905550565b60605f80846001600160a01b0316846040516200020c919062000496565b5f60405180830381855af49150503d805f811462000246576040519150601f19603f3d011682016040523d82523d5f602084013e6200024b565b606091505b5090925090506200025e858383620002ca565b95945050505050565b3415620002875760405163b398979f60e01b815260040160405180910390fd5b565b6001600160a01b038116620002b457604051633173bdd160e11b81525f6004820152602401620001a1565b805f8051602062000dde833981519152620001cd565b606082620002e357620002dd8262000330565b62000329565b8151158015620002fb57506001600160a01b0384163b155b156200032657604051639996b31560e01b81526001600160a01b0385166004820152602401620001a1565b50805b9392505050565b805115620003415780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b6104d3806200090b83390190565b80516001600160a01b03811681146200037f575f80fd5b919050565b634e487b7160e01b5f52604160045260245ffd5b5f5b83811015620003b45781810151838201526020016200039a565b50505f910152565b5f805f60608486031215620003cf575f80fd5b620003da8462000368565b9250620003ea6020850162000368565b60408501519092506001600160401b038082111562000407575f80fd5b818601915086601f8301126200041b575f80fd5b81518181111562000430576200043062000384565b604051601f8201601f19908116603f011681019083821181831017156200045b576200045b62000384565b8160405282815289602084870101111562000474575f80fd5b6200048783602083016020880162000398565b80955050505050509250925092565b5f8251620004a981846020870162000398565b9190910192915050565b608051610440620004cb5f395f601001526104405ff3fe608060405261000c61000e565b005b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316330361007a575f356001600160e01b03191663278f794360e11b14610070576040516334ad5dbb60e21b815260040160405180910390fd5b610078610082565b565b6100786100b0565b5f806100913660048184610303565b81019061009e919061033e565b915091506100ac82826100c0565b5050565b6100786100bb61011a565b610151565b6100c98261016f565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a28051156101125761010d82826101ea565b505050565b6100ac61025c565b5f61014c7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b905090565b365f80375f80365f845af43d5f803e80801561016b573d5ff35b3d5ffd5b806001600160a01b03163b5f036101a957604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b60605f80846001600160a01b0316846040516102069190610407565b5f60405180830381855af49150503d805f811461023e576040519150601f19603f3d011682016040523d82523d5f602084013e610243565b606091505b509150915061025385838361027b565b95945050505050565b34156100785760405163b398979f60e01b815260040160405180910390fd5b6060826102905761028b826102da565b6102d3565b81511580156102a757506001600160a01b0384163b155b156102d057604051639996b31560e01b81526001600160a01b03851660048201526024016101a0565b50805b9392505050565b8051156102ea5780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b5f8085851115610311575f80fd5b8386111561031d575f80fd5b5050820193919092039150565b634e487b7160e01b5f52604160045260245ffd5b5f806040838503121561034f575f80fd5b82356001600160a01b0381168114610365575f80fd5b9150602083013567ffffffffffffffff80821115610381575f80fd5b818501915085601f830112610394575f80fd5b8135818111156103a6576103a661032a565b604051601f8201601f19908116603f011681019083821181831017156103ce576103ce61032a565b816040528281528860208487010111156103e6575f80fd5b826020860160208301375f6020848301015280955050505050509250929050565b5f82515f5b81811015610426576020818601810151858301520161040c565b505f92019182525091905056fea164736f6c6343000816000a608060405234801561000f575f80fd5b506040516104d33803806104d383398101604081905261002e916100bb565b806001600160a01b03811661005c57604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b6100658161006c565b50506100e8565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f602082840312156100cb575f80fd5b81516001600160a01b03811681146100e1575f80fd5b9392505050565b6103de806100f55f395ff3fe608060405260043610610049575f3560e01c8063715018a61461004d5780638da5cb5b146100635780639623609d1461008e578063ad3cb1cc146100a1578063f2fde38b146100de575b5f80fd5b348015610058575f80fd5b506100616100fd565b005b34801561006e575f80fd5b505f546040516001600160a01b0390911681526020015b60405180910390f35b61006161009c366004610260565b610110565b3480156100ac575f80fd5b506100d1604051806040016040528060058152602001640352e302e360dc1b81525081565b6040516100859190610372565b3480156100e9575f80fd5b506100616100f836600461038b565b61017b565b6101056101bd565b61010e5f6101e9565b565b6101186101bd565b60405163278f794360e11b81526001600160a01b03841690634f1ef28690349061014890869086906004016103a6565b5f604051808303818588803b15801561015f575f80fd5b505af1158015610171573d5f803e3d5ffd5b5050505050505050565b6101836101bd565b6001600160a01b0381166101b157604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b6101ba816101e9565b50565b5f546001600160a01b0316331461010e5760405163118cdaa760e01b81523360048201526024016101a8565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b03811681146101ba575f80fd5b634e487b7160e01b5f52604160045260245ffd5b5f805f60608486031215610272575f80fd5b833561027d81610238565b9250602084013561028d81610238565b9150604084013567ffffffffffffffff808211156102a9575f80fd5b818601915086601f8301126102bc575f80fd5b8135818111156102ce576102ce61024c565b604051601f8201601f19908116603f011681019083821181831017156102f6576102f661024c565b8160405282815289602084870101111561030e575f80fd5b826020860160208301375f6020848301015280955050505050509250925092565b5f81518084525f5b8181101561035357602081850181015186830182015201610337565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f610384602083018461032f565b9392505050565b5f6020828403121561039b575f80fd5b813561038481610238565b6001600160a01b03831681526040602082018190525f906103c99083018461032f565b94935050505056fea164736f6c6343000816000ab53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103608060405234801561000f575f80fd5b50604051610f13380380610f1383398101604081905261002e91610173565b5f80546001600160a01b031916339081178255604051909182915f80516020610ef3833981519152908290a3506100648161006a565b506101a0565b5f546001600160a01b031633146100c85760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b6001600160a01b03811661012d5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016100bf565b5f80546040516001600160a01b03808516939216915f80516020610ef383398151915291a35f80546001600160a01b0319166001600160a01b0392909216919091179055565b5f60208284031215610183575f80fd5b81516001600160a01b0381168114610199575f80fd5b9392505050565b610d46806101ad5f395ff3fe608060405234801561000f575f80fd5b50600436106100cb575f3560e01c8063bee36bb311610088578063e15ac62311610063578063e15ac623146101a0578063f2fde38b146101b3578063f5cf673b146101c6578063f996868b146101d9575f80fd5b8063bee36bb314610169578063c5a7b5381461017c578063de2627381461018f575f80fd5b8063529b1e87146100cf5780635453ba1014610116578063715018a61461012b5780638da5cb5b14610133578063955c2ad714610143578063a286c6b414610156575b5f80fd5b6100fa6100dd36600461085c565b6001600160a01b039081165f908152600160205260409020541690565b6040516001600160a01b03909116815260200160405180910390f35b61012961012436600461087e565b6101ec565b005b610129610297565b5f546001600160a01b03166100fa565b610129610151366004610950565b610308565b61012961016436600461087e565b6103e3565b61012961017736600461085c565b61046f565b61012961018a366004610a71565b6104ba565b6002546001600160a01b03166100fa565b6101296101ae36600461087e565b610568565b6101296101c136600461085c565b6105dc565b6101296101d436600461087e565b6106c3565b6101296101e7366004610afd565b610752565b6001600160a01b038281165f90815260016020526040902054839116331461022f5760405162461bcd60e51b815260040161022690610b7a565b60405180910390fd5b6002546040516305453ba160e41b81526001600160a01b038581166004830152848116602483015290911690635453ba10906044015b5f604051808303815f87803b15801561027c575f80fd5b505af115801561028e573d5f803e3d5ffd5b50505050505050565b5f546001600160a01b031633146102c05760405162461bcd60e51b815260040161022690610ba7565b5f80546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a35f80546001600160a01b0319169055565b5f5b815181101561038257336001600160a01b031660015f84848151811061033257610332610bdc565b602090810291909101810151608001516001600160a01b039081168352908201929092526040015f2054161461037a5760405162461bcd60e51b815260040161022690610b7a565b60010161030a565b5060025460405163955c2ad760e01b81526001600160a01b039091169063955c2ad7906103b3908490600401610bf0565b5f604051808303815f87803b1580156103ca575f80fd5b505af11580156103dc573d5f803e3d5ffd5b5050505050565b5f546001600160a01b0316331461040c5760405162461bcd60e51b815260040161022690610ba7565b6001600160a01b038083165f8181526001602052604080822080548686166001600160a01b0319821681179092559151919094169392849290917fda40ea421dd7e42cf8be71255facac4fdc12a3f70f4d5fd373cb16cec4cb53849190a4505050565b5f546001600160a01b031633146104985760405162461bcd60e51b815260040161022690610ba7565b600280546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b038281165f9081526001602052604090205483911633146104f45760405162461bcd60e51b815260040161022690610b7a565b6002546040516318b4f6a760e31b81526001600160a01b038681166004830152858116602483015263ffffffff851660448301529091169063c5a7b538906064015f604051808303815f87803b15801561054c575f80fd5b505af115801561055e573d5f803e3d5ffd5b5050505050505050565b6001600160a01b038281165f9081526001602052604090205483911633146105a25760405162461bcd60e51b815260040161022690610b7a565b60025460405163e15ac62360e01b81526001600160a01b03858116600483015284811660248301529091169063e15ac62390604401610265565b5f546001600160a01b031633146106055760405162461bcd60e51b815260040161022690610ba7565b6001600160a01b03811661066a5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610226565b5f80546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a35f80546001600160a01b0319166001600160a01b0392909216919091179055565b5f546001600160a01b031633146106ec5760405162461bcd60e51b815260040161022690610ba7565b60025460405163f5cf673b60e01b81526001600160a01b03848116600483015283811660248301529091169063f5cf673b906044015f604051808303815f87803b158015610738575f80fd5b505af115801561074a573d5f803e3d5ffd5b505050505050565b5f5b838110156107c8573360015f87878581811061077257610772610bdc565b9050602002016020810190610787919061085c565b6001600160a01b03908116825260208201929092526040015f205416146107c05760405162461bcd60e51b815260040161022690610b7a565b600101610754565b5060025460405163f996868b60e01b81526001600160a01b039091169063f996868b906108019088908890889088908890600401610c97565b5f604051808303815f87803b158015610818575f80fd5b505af115801561082a573d5f803e3d5ffd5b505050505050505050565b6001600160a01b0381168114610849575f80fd5b50565b803561085781610835565b919050565b5f6020828403121561086c575f80fd5b813561087781610835565b9392505050565b5f806040838503121561088f575f80fd5b823561089a81610835565b915060208301356108aa81610835565b809150509250929050565b634e487b7160e01b5f52604160045260245ffd5b60405160e0810167ffffffffffffffff811182821017156108ec576108ec6108b5565b60405290565b604051601f8201601f1916810167ffffffffffffffff8111828210171561091b5761091b6108b5565b604052919050565b80356affffffffffffffffffffff81168114610857575f80fd5b803563ffffffff81168114610857575f80fd5b5f6020808385031215610961575f80fd5b823567ffffffffffffffff80821115610978575f80fd5b818501915085601f83011261098b575f80fd5b81358181111561099d5761099d6108b5565b6109ab848260051b016108f2565b818152848101925060e09182028401850191888311156109c9575f80fd5b938501935b82851015610a655780858a0312156109e4575f80fd5b6109ec6108c9565b6109f586610923565b815286860135878201526040610a0c81880161093d565b90820152606086810135610a1f81610835565b908201526080610a3087820161084c565b9082015260a0610a4187820161084c565b9082015260c0610a5287820161084c565b90820152845293840193928501926109ce565b50979650505050505050565b5f805f60608486031215610a83575f80fd5b8335610a8e81610835565b92506020840135610a9e81610835565b9150610aac6040850161093d565b90509250925092565b5f8083601f840112610ac5575f80fd5b50813567ffffffffffffffff811115610adc575f80fd5b6020830191508360208260051b8501011115610af6575f80fd5b9250929050565b5f805f805f60608688031215610b11575f80fd5b8535610b1c81610835565b9450602086013567ffffffffffffffff80821115610b38575f80fd5b610b4489838a01610ab5565b90965094506040880135915080821115610b5c575f80fd5b50610b6988828901610ab5565b969995985093965092949392505050565b60208082526013908201527227a7262cafa2a6a4a9a9a4a7a72fa0a226a4a760691b604082015260600190565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b634e487b7160e01b5f52603260045260245ffd5b602080825282518282018190525f919060409081850190868401855b82811015610c8a57815180516affffffffffffffffffffff16855286810151878601528581015163ffffffff16868601526060808201516001600160a01b039081169187019190915260808083015182169087015260a08083015182169087015260c091820151169085015260e09093019290850190600101610c0c565b5091979650505050505050565b6001600160a01b038681168252606060208084018290529083018690525f91879160808501845b89811015610ce5578435610cd181610835565b841682529382019390820190600101610cbe565b508581036040870152868152810192508691505f5b86811015610d2a576affffffffffffffffffffff610d1784610923565b1684529281019291810191600101610cfa565b5091999850505050505050505056fea164736f6c6343000816000a8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060a06040525f60055534801562000014575f80fd5b50604051620037b5380380620037b5833981016040819052620000379162000049565b6001600160a01b031660805262000078565b5f602082840312156200005a575f80fd5b81516001600160a01b038116811462000071575f80fd5b9392505050565b6080516136f3620000c25f395f818161044f0152818161054c015281816109e501528181610c2e015281816110b3015281816111c20152818161121401526112b201526136f35ff3fe608060405234801561000f575f80fd5b50600436106101d1575f3560e01c806392074b08116100fe578063bf90f63a1161009e578063dde43cba1161006e578063dde43cba1461056e578063e15ac62314610576578063f5cf673b14610589578063f996868b1461059c575f80fd5b8063bf90f63a1461050e578063c4d66de814610521578063c5a7b53814610534578063cbcbb50714610547575f80fd5b80639ff55db9116100d95780639ff55db9146104cd578063b022418c146104e0578063b45ac1a9146104f3578063bb492bf5146104fb575f80fd5b806392074b081461044d578063955c2ad7146104735780639efd6f7214610486575f80fd5b80635453ba101161017457806370674ab91161014457806370674ab91461035b57806374d945ec1461036e5780637eff4ba814610399578063886fe70b14610425575f80fd5b80635453ba10146102ea57806357b89883146102fd5780635f130b24146103105780636657732f1461033b575f80fd5b806331873e2e116101af57806331873e2e1461025157806333028b99146102665780634c0369c314610279578063533f542a1461029a575f80fd5b80631b839c77146101d5578063236300dc146101fb5780632a17bf601461020e575b5f80fd5b6101e86101e3366004612def565b6105af565b6040519081526020015b60405180910390f35b6101e8610209366004612e66565b6105e8565b61023961021c366004612ed4565b6001600160a01b039081165f908152603b60205260409020541690565b6040516001600160a01b0390911681526020016101f2565b61026461025f366004612ef6565b610631565b005b6101e8610274366004612f28565b610642565b61028c610287366004612fa7565b610736565b6040516101f292919061303c565b6101e86102a8366004613091565b6001600160a01b038083165f90815260016020818152604080842086861685528252808420948816845293909101905220546001600160681b03169392505050565b6102646102f8366004612def565b6109da565b6101e861030b3660046130ce565b610a30565b61023961031e366004612ed4565b6001600160a01b039081165f908152603a60205260409020541690565b61034e610349366004612ed4565b610a49565b6040516101f29190613128565b6101e861036936600461313a565b610b42565b61023961037c366004612ed4565b6001600160a01b039081165f908152603960205260409020541690565b6104056103a7366004612def565b6001600160a01b039182165f9081526001602090815260408083209390941682529190915220546001600160681b038116916001600160581b03600160681b8304169163ffffffff600160c01b8204811692600160e01b9092041690565b6040805194855260208501939093529183015260608201526080016101f2565b610438610433366004612def565b610b58565b604080519283526020830191909152016101f2565b7f0000000000000000000000000000000000000000000000000000000000000000610239565b61026461048136600461322c565b610c23565b6104bb610494366004612ed4565b6001600160a01b03165f90815260016020526040902060020154600160801b900460ff1690565b60405160ff90911681526020016101f2565b61028c6104db36600461313a565b610db2565b6101e86104ee366004612def565b610ea9565b61034e610f34565b61028c610509366004612fa7565b610f94565b61028c61051c366004613352565b610fd6565b61026461052f366004612ed4565b610ff1565b610264610542366004613390565b6110a8565b6102397f000000000000000000000000000000000000000000000000000000000000000081565b6101e8600181565b610264610584366004612def565b6111b7565b610264610597366004612def565b611209565b6102646105aa3660046133d4565b6112a7565b6001600160a01b038281165f90815260016020908152604080832093851683529290522054600160e01b900463ffffffff165b92915050565b5f6001600160a01b0383166106185760405162461bcd60e51b815260040161060f90613450565b60405180910390fd5b610627868686333388886115c6565b9695505050505050565b61063d338483856117c3565b505050565b6001600160a01b038084165f908152603960205260408120549091339186911682146106a75760405162461bcd60e51b815260206004820152601460248201527310d3105253515497d5539055551213d49256915160621b604482015260640161060f565b6001600160a01b0386166106f45760405162461bcd60e51b8152602060048201526014602482015273494e56414c49445f555345525f4144445245535360601b604482015260640161060f565b6001600160a01b03851661071a5760405162461bcd60e51b815260040161060f90613450565b610729898989338a8a8a6115c6565b9998505050505050505050565b6060805f61074586868661190e565b6003549091506001600160401b0381111561076257610762613192565b60405190808252806020026020018201604052801561078b578160200160208202803683370190505b50925082516001600160401b038111156107a7576107a7613192565b6040519080825280602002602001820160405280156107d0578160200160208202803683370190505b5091505f5b81518110156109cf575f5b84518110156109c657600381815481106107fc576107fc61347c565b905f5260205f20015f9054906101000a90046001600160a01b03168582815181106108295761082961347c565b60200260200101906001600160a01b031690816001600160a01b03168152505060015f84848151811061085e5761085e61347c565b60200260200101515f01516001600160a01b03166001600160a01b031681526020019081526020015f205f015f86838151811061089d5761089d61347c565b60200260200101516001600160a01b03166001600160a01b031681526020019081526020015f206001015f876001600160a01b03166001600160a01b031681526020019081526020015f205f01600d9054906101000a90046001600160801b03166001600160801b03168482815181106109195761091961347c565b6020026020010181815161092d91906134a4565b90525082518390839081106109445761094461347c565b6020026020010151602001515f03156109be576109948686838151811061096d5761096d61347c565b60200260200101518585815181106109875761098761347c565b6020026020010151611abb565b8482815181106109a6576109a661347c565b602002602001018181516109ba91906134a4565b9052505b6001016107e0565b506001016107d5565b50505b935093915050565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610a225760405162461bcd60e51b815260040161060f906134b7565b610a2c8282611b59565b5050565b5f610a40858585333333886115c6565b95945050505050565b6001600160a01b0381165f908152600160205260408120600201546060916001600160801b0390911690816001600160401b03811115610a8b57610a8b613192565b604051908082528060200260200182016040528015610ab4578160200160208202803683370190505b5090505f5b826001600160801b0316816001600160801b03161015610b3a576001600160a01b038086165f9081526001602081815260408084206001600160801b03871680865293019091529091205484519216918491908110610b1a57610b1a61347c565b6001600160a01b0390921660209283029190910190910152600101610ab9565b509392505050565b5f610a408383610b5388888861190e565b611c5d565b6001600160a01b038083165f8181526001602090815260408083209486168352938152838220845163b1bf962d60e01b81529451929485949193610c169385939263b1bf962d92600480830193928290030181865afa158015610bbd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610be191906134e6565b6001600160a01b0388165f90815260016020526040902060020154610c1190600160801b900460ff16600a6135dd565b611dab565b92509250505b9250929050565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610c6b5760405162461bcd60e51b815260040161060f906134b7565b5f5b8151811015610da557818181518110610c8857610c8861347c565b6020026020010151606001516001600160a01b031663b1bf962d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ccf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cf391906134e6565b828281518110610d0557610d0561347c565b60200260200101516020018181525050610d59828281518110610d2a57610d2a61347c565b602002602001015160800151838381518110610d4857610d4861347c565b602002602001015160a00151611e71565b610d9d828281518110610d6e57610d6e61347c565b602002602001015160800151838381518110610d8c57610d8c61347c565b602002602001015160c00151611b59565b600101610c6d565b50610daf81611f70565b50565b6001600160a01b038083165f90815260396020526040902054606091829133918691168214610e1a5760405162461bcd60e51b815260206004820152601460248201527310d3105253515497d5539055551213d49256915160621b604482015260640161060f565b6001600160a01b038616610e675760405162461bcd60e51b8152602060048201526014602482015273494e56414c49445f555345525f4144445245535360601b604482015260640161060f565b6001600160a01b038516610e8d5760405162461bcd60e51b815260040161060f90613450565b610e9a88883389896125fc565b93509350505094509492505050565b5f805f5b600454811015610b3a5760015f60048381548110610ecd57610ecd61347c565b5f918252602080832091909101546001600160a01b03908116845283820194909452604092830182208885168352815282822093891682526001909301909252902054610f2a90600160681b90046001600160801b0316836134a4565b9150600101610ead565b60606003805480602002602001604051908101604052809291908181526020018280548015610f8a57602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311610f6c575b5050505050905090565b6060806001600160a01b038316610fbd5760405162461bcd60e51b815260040161060f90613450565b610fca85853333876125fc565b91509150935093915050565b606080610fe684843333336125fc565b915091509250929050565b60065460019060ff16806110045750303b155b80611010575060055481115b6110735760405162461bcd60e51b815260206004820152602e60248201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560448201526d195b881a5b9a5d1a585b1a5e995960921b606482015260840161060f565b60065460ff16158015611093576006805460ff1916600117905560058290555b801561063d576006805460ff19169055505050565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146110f05760405162461bcd60e51b815260040161060f906134b7565b6001600160a01b038381165f8181526001602090815260408083209487168084529482529182902080546001600160e01b038116600160e01b63ffffffff898116828102938417958690558751600160681b9096046001600160581b0316808752968601969096529083041694830185905260608301939093526001600160681b039081169216919091176080820152909291907fac1777479f07f3e7c34da8402139d54027a6a260caaae168bdee825ca5580dc59060a00160405180910390a350505050565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146111ff5760405162461bcd60e51b815260040161060f906134b7565b610a2c8282611e71565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146112515760405162461bcd60e51b815260040161060f906134b7565b6001600160a01b038281165f8181526039602052604080822080546001600160a01b0319169486169485179055517f4925eafc82d0c4d67889898eeed64b18488ab19811e61620f387026dec126a289190a35050565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146112ef5760405162461bcd60e51b815260040161060f906134b7565b82811461132e5760405162461bcd60e51b815260206004820152600d60248201526c1253959053125117d253941555609a1b604482015260640161060f565b5f5b838110156115be576001600160a01b0386165f9081526001602052604081209081818888868181106113645761136461347c565b90506020020160208101906113799190612ed4565b6001600160a01b0316815260208101919091526040015f206002830154909150600160801b900460ff1680158015906113bf57508154600160c01b900463ffffffff1615155b61140b5760405162461bcd60e51b815260206004820152601b60248201527f444953545249425554494f4e5f444f45535f4e4f545f45584953540000000000604482015260640161060f565b5f611480838b6001600160a01b031663b1bf962d6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561144c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061147091906134e6565b61147b85600a6135eb565b6129be565b508354909150600160681b90046001600160581b03168787878181106114a8576114a861347c565b90506020020160208101906114bd91906135f6565b84546001600160581b0391909116600160681b026affffffffffffffffffffff60681b199091161784558989878181106114f9576114f961347c565b905060200201602081019061150e9190612ed4565b6001600160a01b03168b6001600160a01b03167fac1777479f07f3e7c34da8402139d54027a6a260caaae168bdee825ca5580dc5838b8b8b8181106115555761155561347c565b905060200201602081019061156a91906135f6565b8854604080519384526001600160581b039092166020840152600160e01b900463ffffffff1690820181905260608201526080810186905260a00160405180910390a3505060019093019250611330915050565b505050505050565b5f855f036115d557505f6117b8565b5f6115ea856115e58b8b8961190e565b612aa8565b5f5b8881101561174a575f8a8a838181106116075761160761347c565b905060200201602081019061161c9190612ed4565b6001600160a01b038181165f9081526001602081815260408084208b861685528252808420948d168452939091019052205490915061166b90600160681b90046001600160801b0316846134a4565b92508883116116bb576001600160a01b038082165f9081526001602081815260408084208a861685528252808420948c168452939091019052208054600160681b600160e81b0319169055611741565b5f6116c68a8561360f565b90506116d2818561360f565b93506116dd81612b1d565b6001600160a01b039283165f9081526001602081815260408084208b881685528252808420968d1684529590910190529290922080546001600160801b0393909316600160681b02600160681b600160e81b0319909316929092179091555061174a565b506001016115ec565b50805f0361175b575f9150506117b8565b611766848483612b89565b604080516001600160a01b038881168252602082018490528087169286821692918916917fc052130bc4ef84580db505783484b067ea8b71b3bca78a7e12db7aea8658f004910160405180910390a490505b979650505050505050565b6001600160a01b0384165f9081526001602052604081206002015460ff600160801b820416600a0a916001600160801b0390911690819003611806575050611908565b5f5b81816001600160801b03161015611904576001600160a01b038088165f9081526001602081815260408084206001600160801b038716855292830182528084205490941680845291905291812090806118628389896129be565b915091505f80611875858d8d878d612c62565b9150915082806118825750805b156118f2578b6001600160a01b0316866001600160a01b03168e6001600160a01b03167f3303facd24627943a92e9dc87cfbb34b15c49b726eec3ad3487c16be9ab8efe88788876040516118e9939291909283526020830191909152604082015260600190565b60405180910390a45b50506001909401935061180892505050565b5050505b50505050565b6060826001600160401b0381111561192857611928613192565b60405190808252806020026020018201604052801561198357816020015b61197060405180606001604052805f6001600160a01b031681526020015f81526020015f81525090565b8152602001906001900390816119465790505b5090505f5b83811015610b3a578484828181106119a2576119a261347c565b90506020020160208101906119b79190612ed4565b8282815181106119c9576119c961347c565b60209081029190910101516001600160a01b0390911690528484828181106119f3576119f361347c565b9050602002016020810190611a089190612ed4565b604051630afbcdc960e01b81526001600160a01b0385811660048301529190911690630afbcdc9906024016040805180830381865afa158015611a4d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a719190613622565b838381518110611a8357611a8361347c565b6020026020010151602001848481518110611aa057611aa061347c565b60209081029190910101516040019190915252600101611988565b80516001600160a01b039081165f90815260016020818152604080842087861685528252808420865190951684529190528120600201549091908290611b0c90600160801b900460ff16600a6135dd565b90505f611b1e83866040015184611dab565b6020808801516001600160a01b038b165f908152600188019092526040909120549193506117b892509083906001600160681b031685612d54565b5f816001600160a01b03166350d25bcd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b96573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bba91906134e6565b13611c075760405162461bcd60e51b815260206004820152601860248201527f4f5241434c455f4d5553545f52455455524e5f50524943450000000000000000604482015260640161060f565b6001600160a01b038281165f818152603b602052604080822080546001600160a01b0319169486169485179055517f1a1cd5483e52e60b9ff7f3b9d1db3bbd9e9d21c6324ad3a8c79dba9b75e62f4d9190a35050565b5f805b8251811015610b3a57828181518110611c7b57611c7b61347c565b6020026020010151602001515f03611d065760015f848381518110611ca257611ca261347c565b602090810291909101810151516001600160a01b0390811683528282019390935260409182015f90812088851682528252828120938916815260019093019052902054611cff90600160681b90046001600160801b0316836134a4565b9150611da3565b60015f848381518110611d1b57611d1b61347c565b602090810291909101810151516001600160a01b0390811683528282019390935260409182015f908120888516825282528281209389168152600190930190529020548351600160681b9091046001600160801b031690611d8c90879087908790869081106109875761098761347c565b611d9691906134a4565b611da090836134a4565b91505b600101611c60565b82545f9081906001600160681b0381169063ffffffff600160e01b82048116916001600160581b03600160681b82041691600160c01b90910416811580611df0575087155b80611dfa57504281145b80611e055750828110155b15611e1957838495509550505050506109d2565b5f834211611e275742611e29565b835b90505f611e36838361360f565b90505f89611e448387613644565b611e4e9190613644565b8b9004905086611e5e81836134a4565b9850985050505050505050935093915050565b6001600160a01b038116611ec75760405162461bcd60e51b815260206004820152601860248201527f53545241544547595f43414e5f4e4f545f42455f5a45524f0000000000000000604482015260640161060f565b6001813b151514611f1a5760405162461bcd60e51b815260206004820152601960248201527f53545241544547595f4d5553545f42455f434f4e545241435400000000000000604482015260640161060f565b6001600160a01b038281165f818152603a602052604080822080546001600160a01b0319169486169485179055517f8ca1d928f1d72493a6b78c4f74aabde976bc37ffe2570f2a1ce5a8abd3dde0aa9190a35050565b5f5b8151811015610a2c5760015f838381518110611f9057611f9061347c565b6020026020010151606001516001600160a01b03166001600160a01b031681526020019081526020015f2060020160109054906101000a900460ff1660ff165f03612028576004828281518110611fe957611fe961347c565b6020908102919091018101516060015182546001810184555f938452919092200180546001600160a01b0319166001600160a01b039092169190911790555b5f82828151811061203b5761203b61347c565b6020026020010151606001516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015612082573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120a6919061365b565b60015f8585815181106120bb576120bb61347c565b6020026020010151606001516001600160a01b03166001600160a01b031681526020019081526020015f2060020160106101000a81548160ff021916908360ff160217905560ff1690505f60015f85858151811061211b5761211b61347c565b6020026020010151606001516001600160a01b03166001600160a01b031681526020019081526020015f205f015f85858151811061215b5761215b61347c565b6020026020010151608001516001600160a01b03166001600160a01b031681526020019081526020015f209050805f0160189054906101000a900463ffffffff1663ffffffff165f0361231d578383815181106121ba576121ba61347c565b60200260200101516080015160015f8686815181106121db576121db61347c565b6020026020010151606001516001600160a01b03166001600160a01b031681526020019081526020015f206001015f60015f88888151811061221f5761221f61347c565b6020026020010151606001516001600160a01b03166001600160a01b031681526020019081526020015f206002015f9054906101000a90046001600160801b03166001600160801b03166001600160801b031681526020019081526020015f205f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555060015f8585815181106122b7576122b761347c565b602090810291909101810151606001516001600160a01b031682528101919091526040015f90812060020180546001600160801b0316916122f78361367b565b91906101000a8154816001600160801b0302191690836001600160801b03160217905550505b60025f8585815181106123325761233261347c565b602090810291909101810151608001516001600160a01b031682528101919091526040015f9081205460ff161515900361241157600160025f86868151811061237d5761237d61347c565b6020026020010151608001516001600160a01b03166001600160a01b031681526020019081526020015f205f6101000a81548160ff02191690831515021790555060038484815181106123d2576123d261347c565b6020908102919091018101516080015182546001810184555f938452919092200180546001600160a01b0319166001600160a01b039092169190911790555b5f612441828686815181106124285761242861347c565b60200260200101516020015185600a61147b91906135eb565b5082548651919250600160681b81046001600160581b031691600160e01b90910463ffffffff169087908790811061247b5761247b61347c565b60209081029190910101515184546001600160581b03909116600160681b026affffffffffffffffffffff60681b1990911617845586518790879081106124c4576124c461347c565b602090810291909101015160400151845463ffffffff909116600160e01b026001600160e01b0390911617845586518790879081106125055761250561347c565b6020026020010151608001516001600160a01b031687878151811061252c5761252c61347c565b6020026020010151606001516001600160a01b03167fac1777479f07f3e7c34da8402139d54027a6a260caaae168bdee825ca5580dc5848a8a815181106125755761257561347c565b60200260200101515f0151858c8c815181106125935761259361347c565b602002602001015160400151896040516125e39594939291906001600160581b03958616815293909416602084015263ffffffff9182166040840152166060820152608081019190915260a00190565b60405180910390a3505060019093019250611f72915050565b6003546060908190806001600160401b0381111561261c5761261c613192565b604051908082528060200260200182016040528015612645578160200160208202803683370190505b509250806001600160401b0381111561266057612660613192565b604051908082528060200260200182016040528015612689578160200160208202803683370190505b50915061269b856115e58a8a8961190e565b5f5b878110156128c5575f8989838181106126b8576126b861347c565b90506020020160208101906126cd9190612ed4565b90505f5b838110156128bb575f6001600160a01b03168682815181106126f5576126f561347c565b60200260200101516001600160a01b03160361276c576003818154811061271e5761271e61347c565b905f5260205f20015f9054906101000a90046001600160a01b031686828151811061274b5761274b61347c565b60200260200101906001600160a01b031690816001600160a01b0316815250505b6001600160a01b0382165f908152600160205260408120875182908990859081106127995761279961347c565b6020908102919091018101516001600160a01b0390811683528282019390935260409182015f908120938d16815260019093019052902054600160681b90046001600160801b0316905080156128b257808683815181106127fc576127fc61347c565b6020026020010181815161281091906134a4565b9052506001600160a01b0383165f908152600160205260408120885182908a90869081106128405761284061347c565b60200260200101516001600160a01b03166001600160a01b031681526020019081526020015f206001015f8b6001600160a01b03166001600160a01b031681526020019081526020015f205f01600d6101000a8154816001600160801b0302191690836001600160801b031602179055505b506001016126d1565b505060010161269d565b505f5b818110156129b25761290d858583815181106128e6576128e661347c565b60200260200101518584815181106129005761290061347c565b6020026020010151612b89565b846001600160a01b03168482815181106129295761292961347c565b60200260200101516001600160a01b0316876001600160a01b03167fc052130bc4ef84580db505783484b067ea8b71b3bca78a7e12db7aea8658f0048a8786815181106129785761297861347c565b60200260200101516040516129a29291906001600160a01b03929092168252602082015260400190565b60405180910390a46001016128c8565b50509550959350505050565b5f805f806129cd878787611dab565b915091505f828214612a71576001600160681b03821115612a215760405162461bcd60e51b815260206004820152600e60248201526d494e4445585f4f564552464c4f5760901b604482015260640161060f565b5086546cffffffffffffffffffffffffff19166001600160681b0382161787556001612a4c42612d77565b885463ffffffff91909116600160c01b0263ffffffff60c01b19909116178855612a9b565b612a7a42612d77565b885463ffffffff91909116600160c01b0263ffffffff60c01b199091161788555b9097909650945050505050565b5f5b815181101561063d57612b15828281518110612ac857612ac861347c565b60200260200101515f015184848481518110612ae657612ae661347c565b602002602001015160200151858581518110612b0457612b0461347c565b6020026020010151604001516117c3565b600101612aaa565b5f6001600160801b03821115612b855760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20316044820152663238206269747360c81b606482015260840161060f565b5090565b6001600160a01b038281165f818152603a6020526040808220549051630b5f5cc160e11b81528785166004820152602481019390935260448301859052909216919082906316beb982906064016020604051808303815f875af1158015612bf2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c1691906136a0565b9050600181151514612c5b5760405162461bcd60e51b815260206004820152600e60248201526d2a2920a729a322a92fa2a92927a960911b604482015260640161060f565b5050505050565b6001600160a01b0384165f90815260018601602052604081205481906001600160681b031681858214801590612d45576001600160a01b0389165f90815260018b016020526040902080546cffffffffffffffffffffffffff19166001600160681b0389161790558715612d4557612cdc88888589612d54565b9150612ce782612b1d565b6001600160a01b038a165f90815260018c01602052604090208054600d90612d20908490600160681b90046001600160801b03166136bf565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505b90999098509650505050505050565b5f80612d60848661360f565b612d6a9087613644565b9290920495945050505050565b5f63ffffffff821115612b855760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b606482015260840161060f565b6001600160a01b0381168114610daf575f80fd5b5f8060408385031215612e00575f80fd5b8235612e0b81612ddb565b91506020830135612e1b81612ddb565b809150509250929050565b5f8083601f840112612e36575f80fd5b5081356001600160401b03811115612e4c575f80fd5b6020830191508360208260051b8501011115610c1c575f80fd5b5f805f805f60808688031215612e7a575f80fd5b85356001600160401b03811115612e8f575f80fd5b612e9b88828901612e26565b909650945050602086013592506040860135612eb681612ddb565b91506060860135612ec681612ddb565b809150509295509295909350565b5f60208284031215612ee4575f80fd5b8135612eef81612ddb565b9392505050565b5f805f60608486031215612f08575f80fd5b8335612f1381612ddb565b95602085013595506040909401359392505050565b5f805f805f8060a08789031215612f3d575f80fd5b86356001600160401b03811115612f52575f80fd5b612f5e89828a01612e26565b909750955050602087013593506040870135612f7981612ddb565b92506060870135612f8981612ddb565b91506080870135612f9981612ddb565b809150509295509295509295565b5f805f60408486031215612fb9575f80fd5b83356001600160401b03811115612fce575f80fd5b612fda86828701612e26565b9094509250506020840135612fee81612ddb565b809150509250925092565b5f815180845260208085019450602084015f5b838110156130315781516001600160a01b03168752958201959082019060010161300c565b509495945050505050565b604081525f61304e6040830185612ff9565b8281036020848101919091528451808352858201928201905f5b8181101561308457845183529383019391830191600101613068565b5090979650505050505050565b5f805f606084860312156130a3575f80fd5b83356130ae81612ddb565b925060208401356130be81612ddb565b91506040840135612fee81612ddb565b5f805f80606085870312156130e1575f80fd5b84356001600160401b038111156130f6575f80fd5b61310287828801612e26565b90955093505060208501359150604085013561311d81612ddb565b939692955090935050565b602081525f612eef6020830184612ff9565b5f805f806060858703121561314d575f80fd5b84356001600160401b03811115613162575f80fd5b61316e87828801612e26565b909550935050602085013561318281612ddb565b9150604085013561311d81612ddb565b634e487b7160e01b5f52604160045260245ffd5b60405160e081016001600160401b03811182821017156131c8576131c8613192565b60405290565b604051601f8201601f191681016001600160401b03811182821017156131f6576131f6613192565b604052919050565b80356001600160581b0381168114613214575f80fd5b919050565b803563ffffffff81168114613214575f80fd5b5f602080838503121561323d575f80fd5b82356001600160401b0380821115613253575f80fd5b818501915085601f830112613266575f80fd5b81358181111561327857613278613192565b613286848260051b016131ce565b818152848101925060e09182028401850191888311156132a4575f80fd5b938501935b828510156133465780858a0312156132bf575f80fd5b6132c76131a6565b6132d0866131fe565b8152868601358782015260406132e7818801613219565b908201526060868101356132fa81612ddb565b9082015260808681013561330d81612ddb565b9082015260a08681013561332081612ddb565b9082015260c08681013561333381612ddb565b90820152845293840193928501926132a9565b50979650505050505050565b5f8060208385031215613363575f80fd5b82356001600160401b03811115613378575f80fd5b61338485828601612e26565b90969095509350505050565b5f805f606084860312156133a2575f80fd5b83356133ad81612ddb565b925060208401356133bd81612ddb565b91506133cb60408501613219565b90509250925092565b5f805f805f606086880312156133e8575f80fd5b85356133f381612ddb565b945060208601356001600160401b038082111561340e575f80fd5b61341a89838a01612e26565b90965094506040880135915080821115613432575f80fd5b5061343f88828901612e26565b969995985093965092949392505050565b602080825260129082015271494e56414c49445f544f5f4144445245535360701b604082015260600190565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b808201808211156105e2576105e2613490565b60208082526015908201527427a7262cafa2a6a4a9a9a4a7a72fa6a0a720a3a2a960591b604082015260600190565b5f602082840312156134f6575f80fd5b5051919050565b600181815b8085111561353757815f190482111561351d5761351d613490565b8085161561352a57918102915b93841c9390800290613502565b509250929050565b5f8261354d575060016105e2565b8161355957505f6105e2565b816001811461356f576002811461357957613595565b60019150506105e2565b60ff84111561358a5761358a613490565b50506001821b6105e2565b5060208310610133831016604e8410600b84101617156135b8575081810a6105e2565b6135c283836134fd565b805f19048211156135d5576135d5613490565b029392505050565b5f612eef60ff84168361353f565b5f612eef838361353f565b5f60208284031215613606575f80fd5b612eef826131fe565b818103818111156105e2576105e2613490565b5f8060408385031215613633575f80fd5b505080516020909101519092909150565b80820281158282048414176105e2576105e2613490565b5f6020828403121561366b575f80fd5b815160ff81168114612eef575f80fd5b5f6001600160801b0380831681810361369657613696613490565b6001019392505050565b5f602082840312156136b0575f80fd5b81518015158114612eef575f80fd5b6001600160801b038181168382160190808211156136df576136df613490565b509291505056fea164736f6c6343000816000a0000000000000000000000007b62461a3570c6ac8a9f8330421576e417b71ee700000000000000000000000000000000000000000000000000000000000000800000000000000000000000004172e6aaec070acb31aace343a58c93e4c70f44d000000000000000000000000f49821d13c14d13639b11939250ae3ed00db4f48000000000000000000000000c76dfb89ff298145b417d221b2c747d84952e01d000000000000000000000000824364077993847f71293b24cca8567c00c2de1100000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad3800000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000144161766520563320536f6e6963204d61726b6574000000000000000000000000
Deployed Bytecode
0x608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063620b88461461002d575b5f80fd5b6100b36040805160c0810182525f80825260208201819052918101829052606081018290526080810182905260a0810191909152506040805160c0810182525f546001600160a01b03908116825260015481166020830152600254811692820192909252600354821660608201526004548216608082015260055490911660a082015290565b60405161010e919081516001600160a01b03908116825260208084015182169083015260408084015182169083015260608084015182169083015260808084015182169083015260a092830151169181019190915260c00190565b60405180910390f3fea164736f6c6343000816000a
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000007b62461a3570c6ac8a9f8330421576e417b71ee700000000000000000000000000000000000000000000000000000000000000800000000000000000000000004172e6aaec070acb31aace343a58c93e4c70f44d000000000000000000000000f49821d13c14d13639b11939250ae3ed00db4f48000000000000000000000000c76dfb89ff298145b417d221b2c747d84952e01d000000000000000000000000824364077993847f71293b24cca8567c00c2de1100000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad3800000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000144161766520563320536f6e6963204d61726b6574000000000000000000000000
-----Decoded View---------------
Arg [0] : poolAdmin (address): 0x7b62461a3570c6AC8a9f8330421576e417B71EE7
Arg [1] : config (tuple): System.Collections.Generic.List`1[Nethereum.ABI.FunctionEncoding.ParameterOutput]
Arg [2] : poolAddressesProvider (address): 0x4172E6aAEC070ACB31aaCE343A58c93E4C70f44D
Arg [3] : setupBatch (address): 0xf49821D13c14D13639b11939250AE3ED00DB4f48
-----Encoded View---------------
22 Constructor Arguments found :
Arg [0] : 0000000000000000000000007b62461a3570c6ac8a9f8330421576e417b71ee7
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000080
Arg [2] : 0000000000000000000000004172e6aaec070acb31aace343a58c93e4c70f44d
Arg [3] : 000000000000000000000000f49821d13c14d13639b11939250ae3ed00db4f48
Arg [4] : 000000000000000000000000c76dfb89ff298145b417d221b2c747d84952e01d
Arg [5] : 000000000000000000000000824364077993847f71293b24cca8567c00c2de11
Arg [6] : 0000000000000000000000000000000000000000000000000000000000000200
Arg [7] : 0000000000000000000000000000000000000000000000000000000000000008
Arg [8] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [10] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [11] : 000000000000000000000000000000000000000000000000000000000000002f
Arg [12] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [13] : 000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38
Arg [14] : 0000000000000000000000000000000000000000000000000000000000000005
Arg [15] : 0000000000000000000000000000000000000000000000000000000000000004
Arg [16] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [17] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [18] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [19] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [20] : 0000000000000000000000000000000000000000000000000000000000000014
Arg [21] : 4161766520563320536f6e6963204d61726b6574000000000000000000000000
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 31 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
[ Download: CSV Export ]
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.