diff --git a/.github/workflows/lint_pr.yml b/.github copy/workflows/lint_pr.yml
similarity index 100%
rename from .github/workflows/lint_pr.yml
rename to .github copy/workflows/lint_pr.yml
diff --git a/.github/workflows/pr.yml b/.github copy/workflows/pr.yml
similarity index 100%
rename from .github/workflows/pr.yml
rename to .github copy/workflows/pr.yml
diff --git a/.github/workflows/release.yml b/.github copy/workflows/release.yml
similarity index 100%
rename from .github/workflows/release.yml
rename to .github copy/workflows/release.yml
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 70be101e..8f601370 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -3,7 +3,7 @@
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[solidity]": {
- "editor.defaultFormatter": "NomicFoundation.hardhat-solidity"
+ "editor.defaultFormatter": "JuanBlanco.solidity"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -19,6 +19,7 @@
"@ensdomains/=node_modules/@ensdomains/",
"@openzeppelin/=node_modules/@openzeppelin/contracts",
"ds-test/=lib/ds-test/src/",
- "hardhat/=node_modules/hardhat/"
+ "hardhat/=node_modules/hardhat/",
+ "@gearbox-protocol=node_modules/@gearbox-protocol/"
]
}
diff --git a/contracts/adapters/UniversalAdapter.sol b/contracts/adapters/UniversalAdapter.sol
index ccc1e120..8652f031 100644
--- a/contracts/adapters/UniversalAdapter.sol
+++ b/contracts/adapters/UniversalAdapter.sol
@@ -8,7 +8,7 @@ import {AdapterType} from "../interfaces/adapters/IAdapter.sol";
import {ICreditManagerV2} from "../interfaces/ICreditManagerV2.sol";
import {ZeroAddressException} from "../interfaces/IErrors.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {UNIVERSAL_CONTRACT} from "../libraries/Constants.sol";
+import {UNIVERSAL_CONTRACT} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
/// @title UniversalAdapter
/// @dev Implements the initial version of universal adapter, which handles allowance revocations
diff --git a/contracts/core/ACL.sol b/contracts/core/ACL.sol
deleted file mode 100644
index 5d7fce9f..00000000
--- a/contracts/core/ACL.sol
+++ /dev/null
@@ -1,86 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
-import {Claimable} from "./access/Claimable.sol";
-import {IACL} from "../interfaces/IACL.sol";
-
-/// @title ACL contract that stores admin addresses
-/// More info: https://dev.gearbox.fi/security/roles
-contract ACL is IACL, Claimable {
- mapping(address => bool) public pausableAdminSet;
- mapping(address => bool) public unpausableAdminSet;
-
- // Contract version
- uint256 public constant version = 1;
-
- /// @dev Adds an address to the set of admins that can pause contracts
- /// @param newAdmin Address of a new pausable admin
- function addPausableAdmin(address newAdmin)
- external
- onlyOwner // T:[ACL-1]
- {
- pausableAdminSet[newAdmin] = true; // T:[ACL-2]
- emit PausableAdminAdded(newAdmin); // T:[ACL-2]
- }
-
- /// @dev Removes an address from the set of admins that can pause contracts
- /// @param admin Address of admin to be removed
- function removePausableAdmin(address admin)
- external
- onlyOwner // T:[ACL-1]
- {
- if (!pausableAdminSet[admin]) {
- revert AddressNotPausableAdminException(admin);
- }
- pausableAdminSet[admin] = false; // T:[ACL-3]
- emit PausableAdminRemoved(admin); // T:[ACL-3]
- }
-
- /// @dev Returns true if the address is a pausable admin and false if not
- /// @param addr Address to check
- function isPausableAdmin(address addr) external view override returns (bool) {
- return pausableAdminSet[addr]; // T:[ACL-2,3]
- }
-
- /// @dev Adds unpausable admin address to the list
- /// @param newAdmin Address of new unpausable admin
- function addUnpausableAdmin(address newAdmin)
- external
- onlyOwner // T:[ACL-1]
- {
- unpausableAdminSet[newAdmin] = true; // T:[ACL-4]
- emit UnpausableAdminAdded(newAdmin); // T:[ACL-4]
- }
-
- /// @dev Adds an address to the set of admins that can unpause contracts
- /// @param admin Address of admin to be removed
- function removeUnpausableAdmin(address admin)
- external
- onlyOwner // T:[ACL-1]
- {
- if (!unpausableAdminSet[admin]) {
- revert AddressNotUnpausableAdminException(admin);
- }
- unpausableAdminSet[admin] = false; // T:[ACL-5]
- emit UnpausableAdminRemoved(admin); // T:[ACL-5]
- }
-
- /// @dev Returns true if the address is unpausable admin and false if not
- /// @param addr Address to check
- function isUnpausableAdmin(address addr) external view override returns (bool) {
- return unpausableAdminSet[addr]; // T:[ACL-4,5]
- }
-
- /// @dev Returns true if an address has configurator rights
- /// @param account Address to check
- function isConfigurator(address account) external view override returns (bool) {
- return account == owner(); // T:[ACL-6]
- }
-
- function owner() public view override (IACL, Ownable) returns (address) {
- return Ownable.owner();
- }
-}
diff --git a/contracts/core/ACLNonReentrantTrait.sol b/contracts/core/ACLNonReentrantTrait.sol
index 2b4dbcf3..579256a3 100644
--- a/contracts/core/ACLNonReentrantTrait.sol
+++ b/contracts/core/ACLNonReentrantTrait.sol
@@ -4,8 +4,8 @@
pragma solidity ^0.8.10;
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
-import {AddressProvider} from "./AddressProvider.sol";
-import {IACL} from "../interfaces/IACL.sol";
+import {AddressProvider} from "@gearbox-protocol/core-v2/contracts/core/AddressProvider.sol";
+import {IACL} from "@gearbox-protocol/core-v2/contracts/interfaces/IACL.sol";
import {
ZeroAddressException,
CallerNotConfiguratorException,
diff --git a/contracts/core/AccountFactory.sol b/contracts/core/AccountFactory.sol
deleted file mode 100644
index 3c6664a9..00000000
--- a/contracts/core/AccountFactory.sol
+++ /dev/null
@@ -1,342 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-pragma abicoder v2;
-
-import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
-import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
-import {IAccountFactory} from "../interfaces/IAccountFactory.sol";
-import {ICreditAccount} from "../interfaces/ICreditAccount.sol";
-
-import {AddressProvider} from "./AddressProvider.sol";
-import {ContractsRegister} from "./ContractsRegister.sol";
-import {CreditAccount} from "../credit/CreditAccount.sol";
-import {ACLNonReentrantTrait} from "./ACLNonReentrantTrait.sol";
-import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
-
-import {Errors} from "../libraries/Errors.sol";
-
-/// @title Abstract reusable credit accounts factory
-/// @notice Creates, holds & lends credit accounts to Credit Managers
-contract AccountFactory is IAccountFactory, ACLNonReentrantTrait {
- using EnumerableSet for EnumerableSet.AddressSet;
-
- //
- // head
- // ⬇
- // ------- ------- ------- -------
- // | CA1 | -> | CA2 | -> | CA3 | -> | CA4 | -> address(0)
- // ------- ------- ------- -------
- // ⬆
- // tail
- //
-
- /// @dev Credit account linked list
- mapping(address => address) private _nextCreditAccount;
-
- /// @dev Head of linked list
- address public override head;
-
- /// @dev Tail of linked list
- address public override tail;
-
- /// @dev Address of master credit account for cloning
- address public immutable masterCreditAccount;
-
- /// @dev Set of all Credit Accounts
- EnumerableSet.AddressSet private creditAccountsSet;
-
- /// @dev Contracts register
- ContractsRegister public immutable _contractsRegister;
-
- /// @dev Contract version
- uint256 public constant version = 1;
-
- /// @dev Modifier restricting access to Credit Managers registered in the system
- modifier creditManagerOnly() {
- require(_contractsRegister.isCreditManager(msg.sender), Errors.REGISTERED_CREDIT_ACCOUNT_MANAGERS_ONLY);
- _;
- }
-
- /**
- * @dev constructor
- * After the constructor is executed, the list should look as follows
- *
- * head
- * ⬇
- * -------
- * | CA1 | -> address(0)
- * -------
- * ⬆
- * tail
- *
- * @param addressProvider Address of address repository
- */
- constructor(address addressProvider) ACLNonReentrantTrait(addressProvider) {
- require(addressProvider != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED);
-
- _contractsRegister = ContractsRegister(AddressProvider(addressProvider).getContractsRegister()); // T:[AF-1]
-
- masterCreditAccount = address(new CreditAccount()); // T:[AF-1]
- CreditAccount(masterCreditAccount).initialize(); // T:[AF-1]
-
- addCreditAccount(); // T:[AF-1]
- head = tail; // T:[AF-1]
- _nextCreditAccount[address(0)] = address(0); // T:[AF-1]
- }
-
- /**
- * @dev Provides a new credit account to a Credit Manager
- *
- * Before:
- * ---------
- *
- * head
- * ⬇
- * ------- ------- ------- -------
- * | CA1 | -> | CA2 | -> | CA3 | -> | CA4 | -> address(0)
- * ------- ------- ------- -------
- * ⬆
- * tail
- *
- * After:
- * ---------
- *
- * head
- * ⬇
- * ------- ------- -------
- * | CA2 | -> | CA3 | -> | CA4 | -> address(0)
- * ------- ------- -------
- * ⬆
- * tail
- *
- *
- * -------
- * | CA1 | -> address(0)
- * -------
- *
- * If the taken Credit Account is the last one, creates a new one
- *
- * head
- * ⬇
- * -------
- * | CA2 | -> address(0) => _addNewCreditAccount()
- * -------
- * ⬆
- * tail
- *
- * @return Address of credit account
- */
- function takeCreditAccount(uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen)
- external
- override
- creditManagerOnly // T:[AF-12]
- returns (address)
- {
- // Create a new credit account if there are none in stock
- _checkStock(); // T:[AF-3]
-
- address result = head;
- head = _nextCreditAccount[head]; // T:[AF-2]
- _nextCreditAccount[result] = address(0); // T:[AF-2]
-
- // Connect the account to a Credit Manager
- ICreditAccount(result).connectTo(msg.sender, _borrowedAmount, _cumulativeIndexAtOpen); // T:[AF-11, 14]
-
- emit InitializeCreditAccount(result, msg.sender); // T:[AF-5]
- return result; // T:[AF-14]
- }
-
- /**
- * @dev Retrieves the Credit Account from the Credit Manager and adds it to the stock
- *
- * Before:
- * ---------
- *
- * head
- * ⬇
- * ------- ------- ------- -------
- * | CA1 | -> | CA2 | -> | CA3 | -> | CA4 | -> address(0)
- * ------- ------- ------- -------
- * ⬆
- * tail
- *
- * After:
- * ---------
- *
- * head
- * ⬇
- * ------- ------- ------- ------- ---------------
- * | CA1 | -> | CA2 | -> | CA3 | -> | CA4 | -> | usedAccount | -> address(0)
- * ------- ------- ------- ------- ---------------
- * ⬆
- * tail
- *
- *
- * @param usedAccount Address of returned credit account
- */
- function returnCreditAccount(address usedAccount)
- external
- override
- creditManagerOnly // T:[AF-12]
- {
- require(creditAccountsSet.contains(usedAccount), Errors.AF_EXTERNAL_ACCOUNTS_ARE_FORBIDDEN);
- require(
- ICreditAccount(usedAccount).since() != block.number, Errors.AF_CANT_CLOSE_CREDIT_ACCOUNT_IN_THE_SAME_BLOCK
- ); // T:[CM-20]
-
- _nextCreditAccount[tail] = usedAccount; // T:[AF-7]
- tail = usedAccount; // T:[AF-7]
- emit ReturnCreditAccount(usedAccount); // T:[AF-8]
- }
-
- /// @dev Gets the next available credit account after the passed one, or address(0) if the passed account is the tail
- /// @param creditAccount Credit Account previous to the one to retrieve
- function getNext(address creditAccount) external view override returns (address) {
- return _nextCreditAccount[creditAccount];
- }
-
- /**
- * @dev Deploys a new Credit Account and sets it as a list's tail
- *
- * Before:
- * ---------
- *
- * head
- * ⬇
- * ------- ------- ------- -------
- * | CA1 | -> | CA2 | -> | CA3 | -> | CA4 | -> address(0)
- * ------- ------- ------- -------
- * ⬆
- * tail
- *
- * After:
- * ---------
- *
- * head
- * ⬇
- * ------- ------- ------- ------- --------------
- * | CA1 | -> | CA2 | -> | CA3 | -> | CA4 | -> | newAccount | -> address(0)
- * ------- ------- ------- ------- --------------
- * ⬆
- * tail
- *
- *
- */
- function addCreditAccount() public {
- address clonedAccount = Clones.clone(masterCreditAccount); // T:[AF-2]
- ICreditAccount(clonedAccount).initialize();
- _nextCreditAccount[tail] = clonedAccount; // T:[AF-2]
- tail = clonedAccount; // T:[AF-2]
- creditAccountsSet.add(clonedAccount); // T:[AF-10, 16]
- emit NewCreditAccount(clonedAccount);
- }
-
- /// @dev Removes an unused Credit Account from the list forever and connects it to the "to" parameter
- /// @param prev Credit Account before the taken one in the linked list
- /// @param creditAccount Credit Account to take
- /// @param to Address to connect the taken Credit Account to
- function takeOut(address prev, address creditAccount, address to)
- external
- configuratorOnly // T:[AF-13]
- {
- _checkStock();
-
- if (head == creditAccount) {
- address prevHead = head;
- head = _nextCreditAccount[head]; // T:[AF-21] it exists because _checkStock() was called;
- _nextCreditAccount[prevHead] = address(0); // T:[AF-21]
- } else {
- require(_nextCreditAccount[prev] == creditAccount, Errors.AF_CREDIT_ACCOUNT_NOT_IN_STOCK); // T:[AF-15]
-
- // updates tail if the last CA is taken
- if (creditAccount == tail) {
- tail = prev; // T:[AF-22]
- }
-
- _nextCreditAccount[prev] = _nextCreditAccount[creditAccount]; // T:[AF-16]
- _nextCreditAccount[creditAccount] = address(0); // T:[AF-16]
- }
- ICreditAccount(creditAccount).connectTo(to, 0, 0); // T:[AF-16, 21]
- creditAccountsSet.remove(creditAccount); // T:[AF-16]
- emit TakeForever(creditAccount, to); // T:[AF-16, 21]
- }
-
- /**
- * @dev Checks available accounts in stock and deploy a new one if only one remains
- *
- * If:
- * ---------
- *
- * head
- * ⬇
- * -------
- * | CA1 | -> address(0)
- * -------
- * ⬆
- * tail
- *
- * Then:
- * ---------
- *
- * head
- * ⬇
- * ------- --------------
- * | CA1 | -> | newAccount | -> address(0)
- * ------- --------------
- * ⬆
- * tail
- *
- */
- function _checkStock() internal {
- // T:[AF-9]
- if (_nextCreditAccount[head] == address(0)) {
- addCreditAccount(); // T:[AF-3]
- }
- }
-
- /// @dev Cancels token allowance from a Credit Acocunt to a target contract
- /// @param account Address of credit account to be cancelled allowance
- /// @param token Address of token for allowance
- /// @param targetContract Address of contract to cancel allowance
- function cancelAllowance(address account, address token, address targetContract)
- external
- configuratorOnly // T:[AF-13]
- {
- ICreditAccount(account).cancelAllowance(token, targetContract); // T:[AF-20]
- }
-
- //
- // GETTERS
- //
-
- /// @dev Returns the number of unused credit accounts in stock
- function countCreditAccountsInStock() external view override returns (uint256) {
- uint256 count = 0;
- address pointer = head;
- while (pointer != address(0)) {
- pointer = _nextCreditAccount[pointer];
- count++;
- }
- return count;
- }
-
- /// @dev Returns the number of deployed credit accounts
- function countCreditAccounts() external view override returns (uint256) {
- return creditAccountsSet.length(); // T:[AF-10]
- }
-
- /// @dev Returns the credit account address under the passed id
- /// @param id The index of the requested CA
- function creditAccounts(uint256 id) external view override returns (address) {
- return creditAccountsSet.at(id);
- }
-
- /// @dev Returns whether the Credit Account is registered with this factory
- /// @param addr Address of the Credit Account to check
- function isCreditAccount(address addr) external view returns (bool) {
- return creditAccountsSet.contains(addr); // T:[AF-16]
- }
-}
diff --git a/contracts/core/AddressProvider.sol b/contracts/core/AddressProvider.sol
deleted file mode 100644
index 16bac4a9..00000000
--- a/contracts/core/AddressProvider.sol
+++ /dev/null
@@ -1,190 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IAddressProvider} from "../interfaces/IAddressProvider.sol";
-import {Claimable} from "./access/Claimable.sol";
-import {Errors} from "../libraries/Errors.sol";
-
-// Repositories & services
-bytes32 constant CONTRACTS_REGISTER = "CONTRACTS_REGISTER";
-bytes32 constant ACL = "ACL";
-bytes32 constant PRICE_ORACLE = "PRICE_ORACLE";
-bytes32 constant ACCOUNT_FACTORY = "ACCOUNT_FACTORY";
-bytes32 constant DATA_COMPRESSOR = "DATA_COMPRESSOR";
-bytes32 constant TREASURY_CONTRACT = "TREASURY_CONTRACT";
-bytes32 constant GEAR_TOKEN = "GEAR_TOKEN";
-bytes32 constant WETH_TOKEN = "WETH_TOKEN";
-bytes32 constant WETH_GATEWAY = "WETH_GATEWAY";
-bytes32 constant LEVERAGED_ACTIONS = "LEVERAGED_ACTIONS";
-
-/// @title AddressRepository
-/// @notice Stores addresses of deployed contracts
-contract AddressProvider is Claimable, IAddressProvider {
- // Mapping from contract keys to respective addresses
- mapping(bytes32 => address) public addresses;
-
- // Contract version
- uint256 public constant version = 2;
-
- constructor() {
- // @dev Emits first event for contract discovery
- emit AddressSet("ADDRESS_PROVIDER", address(this));
- }
-
- /// @return Address of ACL contract
- function getACL() external view returns (address) {
- return _getAddress(ACL); // F:[AP-3]
- }
-
- /// @dev Sets address of ACL contract
- /// @param _address Address of ACL contract
- function setACL(address _address)
- external
- onlyOwner // F:[AP-12]
- {
- _setAddress(ACL, _address); // F:[AP-3]
- }
-
- /// @return Address of ContractsRegister
- function getContractsRegister() external view returns (address) {
- return _getAddress(CONTRACTS_REGISTER); // F:[AP-4]
- }
-
- /// @dev Sets address of ContractsRegister
- /// @param _address Address of ContractsRegister
- function setContractsRegister(address _address)
- external
- onlyOwner // F:[AP-12]
- {
- _setAddress(CONTRACTS_REGISTER, _address); // F:[AP-4]
- }
-
- /// @return Address of PriceOracle
- function getPriceOracle() external view override returns (address) {
- return _getAddress(PRICE_ORACLE); // F:[AP-5]
- }
-
- /// @dev Sets address of PriceOracle
- /// @param _address Address of PriceOracle
- function setPriceOracle(address _address)
- external
- onlyOwner // F:[AP-12]
- {
- _setAddress(PRICE_ORACLE, _address); // F:[AP-5]
- }
-
- /// @return Address of AccountFactory
- function getAccountFactory() external view returns (address) {
- return _getAddress(ACCOUNT_FACTORY); // F:[AP-6]
- }
-
- /// @dev Sets address of AccountFactory
- /// @param _address Address of AccountFactory
- function setAccountFactory(address _address)
- external
- onlyOwner // F:[AP-12]
- {
- _setAddress(ACCOUNT_FACTORY, _address); // F:[AP-6]
- }
-
- /// @return Address of DataCompressor
- function getDataCompressor() external view override returns (address) {
- return _getAddress(DATA_COMPRESSOR); // F:[AP-7]
- }
-
- /// @dev Sets address of AccountFactory
- /// @param _address Address of AccountFactory
- function setDataCompressor(address _address)
- external
- onlyOwner // F:[AP-12]
- {
- _setAddress(DATA_COMPRESSOR, _address); // F:[AP-7]
- }
-
- /// @return Address of Treasury contract
- function getTreasuryContract() external view returns (address) {
- return _getAddress(TREASURY_CONTRACT); // F:[AP-8]
- }
-
- /// @dev Sets address of Treasury Contract
- /// @param _address Address of Treasury Contract
- function setTreasuryContract(address _address)
- external
- onlyOwner // F:[AP-12]
- {
- _setAddress(TREASURY_CONTRACT, _address); // F:[AP-8]
- }
-
- /// @return Address of GEAR token
- function getGearToken() external view override returns (address) {
- return _getAddress(GEAR_TOKEN); // F:[AP-9]
- }
-
- /// @dev Sets address of GEAR token
- /// @param _address Address of GEAR token
- function setGearToken(address _address)
- external
- onlyOwner // F:[AP-12]
- {
- _setAddress(GEAR_TOKEN, _address); // F:[AP-9]
- }
-
- /// @return Address of WETH token
- function getWethToken() external view override returns (address) {
- return _getAddress(WETH_TOKEN); // F:[AP-10]
- }
-
- /// @dev Sets address of WETH token
- /// @param _address Address of WETH token
- function setWethToken(address _address)
- external
- onlyOwner // F:[AP-12]
- {
- _setAddress(WETH_TOKEN, _address); // F:[AP-10]
- }
-
- /// @return Address of WETH token
- function getWETHGateway() external view override returns (address) {
- return _getAddress(WETH_GATEWAY); // F:[AP-11]
- }
-
- /// @dev Sets address of WETH token
- /// @param _address Address of WETH token
- function setWETHGateway(address _address)
- external
- onlyOwner // F:[AP-12]
- {
- _setAddress(WETH_GATEWAY, _address); // F:[AP-11]
- }
-
- /// @return Address of PathFinder
- function getLeveragedActions() external view returns (address) {
- return _getAddress(LEVERAGED_ACTIONS); // T:[AP-7]
- }
-
- /// @dev Sets address of PathFinder
- /// @param _address Address of PathFinder
- function setLeveragedActions(address _address)
- external
- onlyOwner // T:[AP-15]
- {
- _setAddress(LEVERAGED_ACTIONS, _address); // T:[AP-7]
- }
-
- /// @return Address of key, reverts if the key doesn't exist
- function _getAddress(bytes32 key) internal view returns (address) {
- address result = addresses[key];
- require(result != address(0), Errors.AS_ADDRESS_NOT_FOUND); // F:[AP-1]
- return result; // F:[AP-3, 4, 5, 6, 7, 8, 9, 10, 11]
- }
-
- /// @dev Sets address to map by its key
- /// @param key Key in string format
- /// @param value Address
- function _setAddress(bytes32 key, address value) internal {
- addresses[key] = value; // F:[AP-3, 4, 5, 6, 7, 8, 9, 10, 11]
- emit AddressSet(key, value); // F:[AP-2]
- }
-}
diff --git a/contracts/core/ContractsRegister.sol b/contracts/core/ContractsRegister.sol
deleted file mode 100644
index 70882048..00000000
--- a/contracts/core/ContractsRegister.sol
+++ /dev/null
@@ -1,78 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IContractsRegister} from "../interfaces/IContractsRegister.sol";
-import {Errors} from "../libraries/Errors.sol";
-import {ACLNonReentrantTrait} from "./ACLNonReentrantTrait.sol";
-
-/// @title Pool & Credit Manager registry
-/// @notice Stores addresses of Pools and Credit Managers
-contract ContractsRegister is IContractsRegister, ACLNonReentrantTrait {
- /// @dev List of all registered pools
- address[] public override pools;
-
- /// @dev Mapping storing whether an address is a pool
- mapping(address => bool) public override isPool;
-
- /// @dev List of all registered Credit Managers
- address[] public override creditManagers;
-
- /// @dev Mapping storing whether an address is a Credit Manager
- mapping(address => bool) public override isCreditManager;
-
- /// @dev Contract version
- uint256 public constant version = 1;
-
- constructor(address addressProvider) ACLNonReentrantTrait(addressProvider) {}
-
- /// @dev Adds a pool to the list
- /// @param newPoolAddress Address of the new pool
- function addPool(address newPoolAddress)
- external
- configuratorOnly // T:[CR-1]
- {
- require(newPoolAddress != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED);
- require(!isPool[newPoolAddress], Errors.CR_POOL_ALREADY_ADDED); // T:[CR-2]
- pools.push(newPoolAddress); // T:[CR-3]
- isPool[newPoolAddress] = true; // T:[CR-3]
-
- emit NewPoolAdded(newPoolAddress); // T:[CR-4]
- }
-
- /// @dev Returns the array of registered pool addresses
- function getPools() external view override returns (address[] memory) {
- return pools;
- }
-
- /// @return Returns the number of registered pools
- function getPoolsCount() external view override returns (uint256) {
- return pools.length; // T:[CR-3]
- }
-
- /// @dev Adds credit accounts manager address to the registry
- /// @param newCreditManager Address of the new Credit Manager
- function addCreditManager(address newCreditManager)
- external
- configuratorOnly // T:[CR-1]
- {
- require(newCreditManager != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED);
-
- require(!isCreditManager[newCreditManager], Errors.CR_CREDIT_MANAGER_ALREADY_ADDED); // T:[CR-5]
- creditManagers.push(newCreditManager); // T:[CR-6]
- isCreditManager[newCreditManager] = true; // T:[CR-6]
-
- emit NewCreditManagerAdded(newCreditManager); // T:[CR-7]
- }
-
- /// @dev Returns the array of registered credit manager addresses
- function getCreditManagers() external view override returns (address[] memory) {
- return creditManagers;
- }
-
- /// @return Returns the number of registered credit managers
- function getCreditManagersCount() external view override returns (uint256) {
- return creditManagers.length; // T:[CR-6]
- }
-}
diff --git a/contracts/core/DataCompressor.sol b/contracts/core/DataCompressor.sol
deleted file mode 100644
index 2db65b62..00000000
--- a/contracts/core/DataCompressor.sol
+++ /dev/null
@@ -1,433 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-pragma experimental ABIEncoderV2;
-
-import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
-
-import {IDataCompressor} from "../interfaces/IDataCompressor.sol";
-import {ICreditManager} from "../interfaces/V1/ICreditManager.sol";
-import {ICreditManagerV2} from "../interfaces/ICreditManagerV2.sol";
-import {ICreditFacade} from "../interfaces/ICreditFacade.sol";
-import {ICreditFilter} from "../interfaces/V1/ICreditFilter.sol";
-import {ICreditConfigurator} from "../interfaces/ICreditConfigurator.sol";
-import {ICreditAccount} from "../interfaces/ICreditAccount.sol";
-import {IPoolService} from "../interfaces/IPoolService.sol";
-import {IPool4626} from "../interfaces/IPool4626.sol";
-
-import {IVersion} from "../interfaces/IVersion.sol";
-
-import {AddressProvider} from "./AddressProvider.sol";
-import {ContractsRegister} from "./ContractsRegister.sol";
-
-import {
- CreditAccountData,
- CreditManagerData,
- PoolData,
- TokenInfo,
- TokenBalance,
- ContractAdapter
-} from "../libraries/Types.sol";
-
-// EXCEPTIONS
-import {ZeroAddressException} from "../interfaces/IErrors.sol";
-
-/// @title Data compressor
-/// @notice Collects data from various contracts for use in the dApp
-/// Do not use for data from any onchain activities
-contract DataCompressor is IDataCompressor {
- /// @dev Address of the AddressProvider
- AddressProvider public immutable addressProvider;
-
- /// @dev Address of the ContractsRegister
- ContractsRegister public immutable contractsRegister;
-
- /// @dev Address of WETH
- address public immutable WETHToken;
-
- // Contract version
- uint256 public constant version = 2;
-
- /// @dev Prevents function usage for target contracts that are not Gearbox pools
- modifier targetIsRegisteredPool(address pool) {
- if (!contractsRegister.isPool(pool)) revert NotPoolException(); // T:[WG-1]
- _;
- }
-
- /// @dev Prevents function usage for target contracts that are not Gearbox Credit Managers
- modifier targetIsRegisteredCreditManager(address creditManager) {
- if (!contractsRegister.isCreditManager(creditManager)) {
- revert NotCreditManagerException();
- } // T:[WG-3]
- _;
- }
-
- constructor(address _addressProvider) {
- if (_addressProvider == address(0)) revert ZeroAddressException();
-
- addressProvider = AddressProvider(_addressProvider);
- contractsRegister = ContractsRegister(addressProvider.getContractsRegister());
- WETHToken = addressProvider.getWethToken();
- }
-
- /// @dev Returns CreditAccountData for all opened accounts for particular borrower
- /// @param borrower Borrower address
- function getCreditAccountList(address borrower) external view returns (CreditAccountData[] memory result) {
- // Counts how many opened accounts a borrower has
- uint256 count;
- uint256 creditManagersLength = contractsRegister.getCreditManagersCount();
-
- for (uint256 i = 0; i < creditManagersLength;) {
- unchecked {
- address creditManager = contractsRegister.creditManagers(i);
- if (hasOpenedCreditAccount(creditManager, borrower)) {
- ++count;
- }
- ++i;
- }
- }
-
- result = new CreditAccountData[](count);
-
- // Get data & fill the array
- count = 0;
- for (uint256 i = 0; i < creditManagersLength;) {
- address creditManager = contractsRegister.creditManagers(i);
- unchecked {
- if (hasOpenedCreditAccount(creditManager, borrower)) {
- result[count] = getCreditAccountData(creditManager, borrower);
-
- count++;
- }
-
- ++i;
- }
- }
- }
-
- /// @dev Returns whether the borrower has an open credit account with the credit manager
- /// @param _creditManager Credit manager to check
- /// @param borrower Borrower to check
- function hasOpenedCreditAccount(address _creditManager, address borrower)
- public
- view
- targetIsRegisteredCreditManager(_creditManager)
- returns (bool)
- {
- return _hasOpenedCreditAccount(_creditManager, borrower);
- }
-
- /// @dev Returns CreditAccountData for a particular Credit Account account, based on creditManager and borrower
- /// @param _creditManager Credit manager address
- /// @param borrower Borrower address
- function getCreditAccountData(address _creditManager, address borrower)
- public
- view
- returns (CreditAccountData memory result)
- {
- (
- uint8 ver,
- ICreditManager creditManager,
- ICreditFilter creditFilter,
- ICreditManagerV2 creditManagerV2,
- ICreditFacade creditFacade,
- ) = getCreditContracts(_creditManager);
-
- address creditAccount = (ver == 1)
- ? creditManager.getCreditAccountOrRevert(borrower)
- : creditManagerV2.getCreditAccountOrRevert(borrower);
-
- result.version = ver;
-
- result.borrower = borrower;
- result.creditManager = _creditManager;
- result.addr = creditAccount;
-
- if (ver == 1) {
- result.underlying = creditManager.underlyingToken();
- result.totalValue = creditFilter.calcTotalValue(creditAccount);
- result.healthFactor = creditFilter.calcCreditAccountHealthFactor(creditAccount);
-
- try ICreditManager(creditManager).calcRepayAmount(borrower, false) returns (uint256 value) {
- result.repayAmount = value;
- } catch {}
-
- try ICreditManager(creditManager).calcRepayAmount(borrower, true) returns (uint256 value) {
- result.liquidationAmount = value;
- } catch {}
-
- try ICreditManager(creditManager)._calcClosePayments(creditAccount, result.totalValue, false) returns (
- uint256, uint256, uint256 remainingFunds, uint256, uint256
- ) {
- result.canBeClosed = remainingFunds > 0;
- } catch {}
-
- result.borrowedAmount = ICreditAccount(creditAccount).borrowedAmount();
-
- result.borrowedAmountPlusInterest = creditFilter.calcCreditAccountAccruedInterest(creditAccount);
- } else {
- result.underlying = creditManagerV2.underlying();
- (result.totalValue,) = creditFacade.calcTotalValue(creditAccount);
- result.healthFactor = creditFacade.calcCreditAccountHealthFactor(creditAccount);
-
- (result.borrowedAmount, result.borrowedAmountPlusInterest, result.borrowedAmountPlusInterestAndFees) =
- creditManagerV2.calcCreditAccountAccruedInterest(creditAccount);
- }
-
- address pool = address((ver == 1) ? creditManager.poolService() : creditManagerV2.pool());
- result.borrowRate = IPoolService(pool).borrowAPY_RAY();
-
- uint256 collateralTokenCount =
- (ver == 1) ? creditFilter.allowedTokensCount() : creditManagerV2.collateralTokensCount();
-
- result.enabledTokenMask =
- (ver == 1) ? creditFilter.enabledTokens(creditAccount) : creditManagerV2.enabledTokensMap(creditAccount);
-
- result.balances = new TokenBalance[](collateralTokenCount);
- for (uint256 i = 0; i < collateralTokenCount;) {
- unchecked {
- TokenBalance memory balance;
- uint256 tokenMask = 1 << i;
- if (ver == 1) {
- (balance.token, balance.balance,,) = creditFilter.getCreditAccountTokenById(creditAccount, i);
- balance.isAllowed = creditFilter.isTokenAllowed(balance.token);
- } else {
- (balance.token,) = creditManagerV2.collateralTokens(i);
- balance.balance = IERC20(balance.token).balanceOf(creditAccount);
- balance.isAllowed = creditFacade.isTokenAllowed(balance.token);
- }
- balance.isEnabled = tokenMask & result.enabledTokenMask == 0 ? false : true;
-
- result.balances[i] = balance;
-
- ++i;
- }
- }
-
- result.cumulativeIndexAtOpen = ICreditAccount(creditAccount).cumulativeIndexAtOpen();
-
- result.since = ICreditAccount(creditAccount).since();
- }
-
- /// @dev Returns CreditManagerData for all Credit Managers
- function getCreditManagersList() external view returns (CreditManagerData[] memory result) {
- uint256 creditManagersCount = contractsRegister.getCreditManagersCount();
-
- result = new CreditManagerData[](creditManagersCount);
-
- for (uint256 i = 0; i < creditManagersCount;) {
- address creditManager = contractsRegister.creditManagers(i);
- result[i] = getCreditManagerData(creditManager);
- unchecked {
- ++i;
- }
- }
- }
-
- /// @dev Returns CreditManagerData for a particular _creditManager
- /// @param _creditManager CreditManager address
- function getCreditManagerData(address _creditManager) public view returns (CreditManagerData memory result) {
- (
- uint8 ver,
- ICreditManager creditManager,
- ICreditFilter creditFilter,
- ICreditManagerV2 creditManagerV2,
- ICreditFacade creditFacade,
- ICreditConfigurator creditConfigurator
- ) = getCreditContracts(_creditManager);
-
- result.addr = _creditManager;
- result.version = ver;
-
- result.underlying = (ver == 1) ? creditManager.underlyingToken() : creditManagerV2.underlying();
- result.isWETH = result.underlying == WETHToken;
-
- {
- IPoolService pool = IPoolService((ver == 1) ? creditManager.poolService() : creditManagerV2.pool());
- result.pool = address(pool);
- result.canBorrow = pool.creditManagersCanBorrow(_creditManager);
- result.borrowRate = pool.borrowAPY_RAY();
- result.availableLiquidity = pool.availableLiquidity();
- }
-
- if (ver == 1) {
- result.minAmount = creditManager.minAmount();
- result.maxAmount = creditManager.maxAmount();
- } else {
- (result.minAmount, result.maxAmount) = creditFacade.limits();
- }
- {
- uint256 collateralTokenCount =
- (ver == 1) ? creditFilter.allowedTokensCount() : creditManagerV2.collateralTokensCount();
-
- result.collateralTokens = new address[](collateralTokenCount);
- result.liquidationThresholds = new uint256[](collateralTokenCount);
- unchecked {
- for (uint256 i = 0; i < collateralTokenCount; ++i) {
- if (ver == 1) {
- address token = creditFilter.allowedTokens(i);
- result.collateralTokens[i] = token;
- result.liquidationThresholds[i] = creditFilter.liquidationThresholds(token);
- } else {
- (result.collateralTokens[i], result.liquidationThresholds[i]) =
- creditManagerV2.collateralTokens(i);
- }
- }
- }
- }
- if (ver == 1) {
- uint256 allowedContractsCount = creditFilter.allowedContractsCount();
-
- result.adapters = new ContractAdapter[](allowedContractsCount);
- for (uint256 i = 0; i < allowedContractsCount;) {
- address allowedContract = creditFilter.allowedContracts(i);
-
- result.adapters[i] = ContractAdapter({
- allowedContract: allowedContract,
- adapter: creditFilter.contractToAdapter(allowedContract)
- });
- unchecked {
- ++i;
- }
- }
- } else {
- address[] memory allowedContracts = creditConfigurator.allowedContracts();
- uint256 len = allowedContracts.length;
- result.adapters = new ContractAdapter[](len);
- for (uint256 i = 0; i < len;) {
- address allowedContract = allowedContracts[i];
-
- result.adapters[i] = ContractAdapter({
- allowedContract: allowedContract,
- adapter: creditManagerV2.contractToAdapter(allowedContract)
- });
- unchecked {
- ++i;
- }
- }
- }
-
- if (ver == 1) {
- // VERSION 1 SPECIFIC FIELDS
- result.maxLeverageFactor = ICreditManager(creditManager).maxLeverageFactor();
- result.maxEnabledTokensLength = 255;
- result.feeInterest = uint16(creditManager.feeInterest());
- result.feeLiquidation = uint16(creditManager.feeLiquidation());
- result.liquidationDiscount = uint16(creditManager.feeLiquidation());
- } else {
- // VERSION 2 SPECIFIC FIELDS
- result.creditFacade = address(creditFacade);
- result.creditConfigurator = creditManagerV2.creditConfigurator();
- result.degenNFT = creditFacade.degenNFT();
- (, result.isIncreaseDebtForbidden,) = creditFacade.params(); // V2 only: true if increasing debt is forbidden
- result.forbiddenTokenMask = creditManagerV2.forbiddenTokenMask(); // V2 only: mask which forbids some particular tokens
- result.maxEnabledTokensLength = creditManagerV2.maxAllowedEnabledTokenLength(); // V2 only: a limit on enabled tokens imposed for security
- {
- (
- result.feeInterest,
- result.feeLiquidation,
- result.liquidationDiscount,
- result.feeLiquidationExpired,
- result.liquidationDiscountExpired
- ) = creditManagerV2.fees();
- }
- }
- }
-
- /// @dev Returns PoolData for a particular pool
- /// @param _pool Pool address
- function getPoolData(address _pool) public view targetIsRegisteredPool(_pool) returns (PoolData memory result) {
- IPoolService pool = IPoolService(_pool);
- result.version = uint8(pool.version());
-
- result.addr = _pool;
- result.expectedLiquidity = pool.expectedLiquidity();
- result.expectedLiquidityLimit = pool.expectedLiquidityLimit();
- result.availableLiquidity = pool.availableLiquidity();
- result.totalBorrowed = pool.totalBorrowed();
- result.dieselRate_RAY = pool.getDieselRate_RAY();
- result.linearCumulativeIndex = pool.calcLinearCumulative_RAY();
- result.borrowAPY_RAY = pool.borrowAPY_RAY();
- result.underlying = pool.underlyingToken();
- result.dieselToken = (result.version > 1) ? _pool : pool.dieselToken();
- result.dieselRate_RAY = pool.getDieselRate_RAY();
- result.withdrawFee = pool.withdrawFee();
- result.isWETH = result.underlying == WETHToken;
- result.timestampLU = pool._timestampLU();
- result.cumulativeIndex_RAY = pool._cumulativeIndex_RAY();
-
- uint256 dieselSupply = IERC20(result.dieselToken).totalSupply();
-
- uint256 totalLP =
- (result.version > 1) ? IPool4626(_pool).convertToAssets(dieselSupply) : pool.fromDiesel(dieselSupply);
-
- result.depositAPY_RAY = totalLP == 0
- ? result.borrowAPY_RAY
- : (result.borrowAPY_RAY * result.totalBorrowed) * (PERCENTAGE_FACTOR - result.withdrawFee) / totalLP
- / PERCENTAGE_FACTOR;
-
- return result;
- }
-
- /// @dev Returns PoolData for all registered pools
- function getPoolsList() external view returns (PoolData[] memory result) {
- uint256 poolsLength = contractsRegister.getPoolsCount();
-
- result = new PoolData[](poolsLength);
-
- for (uint256 i = 0; i < poolsLength;) {
- address pool = contractsRegister.pools(i);
- result[i] = getPoolData(pool);
- unchecked {
- ++i;
- }
- }
- }
-
- /// @dev Returns the adapter address for a particular creditManager and targetContract
- function getAdapter(address _creditManager, address _allowedContract)
- external
- view
- targetIsRegisteredCreditManager(_creditManager)
- returns (address adapter)
- {
- (uint8 ver,, ICreditFilter creditFilter, ICreditManagerV2 creditManagerV2,,) =
- getCreditContracts(_creditManager);
-
- adapter = (ver == 1)
- ? creditFilter.contractToAdapter(_allowedContract)
- : creditManagerV2.contractToAdapter(_allowedContract);
- }
-
- /// @dev Internal implementation for hasOpenedCreditAccount
- function _hasOpenedCreditAccount(address creditManager, address borrower) internal view returns (bool) {
- return ICreditManagerV2(creditManager).creditAccounts(borrower) != address(0);
- }
-
- /// @dev Retrieves all relevant credit contracts for a particular Credit Manager
- function getCreditContracts(address _creditManager)
- internal
- view
- targetIsRegisteredCreditManager(_creditManager)
- returns (
- uint8 ver,
- ICreditManager creditManager,
- ICreditFilter creditFilter,
- ICreditManagerV2 creditManagerV2,
- ICreditFacade creditFacade,
- ICreditConfigurator creditConfigurator
- )
- {
- ver = uint8(IVersion(_creditManager).version());
- if (ver == 1) {
- creditManager = ICreditManager(_creditManager);
- creditFilter = ICreditFilter(creditManager.creditFilter());
- } else {
- creditManagerV2 = ICreditManagerV2(_creditManager);
- creditFacade = ICreditFacade(creditManagerV2.creditFacade());
- creditConfigurator = ICreditConfigurator(creditManagerV2.creditConfigurator());
- }
- }
-}
diff --git a/contracts/core/WETHGateway.sol b/contracts/core/WETHGateway.sol
index fe8ec8c0..f29a643e 100644
--- a/contracts/core/WETHGateway.sol
+++ b/contracts/core/WETHGateway.sol
@@ -8,15 +8,15 @@ import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
-import {AddressProvider} from "./AddressProvider.sol";
-import {ContractsRegister} from "./ContractsRegister.sol";
+import {AddressProvider} from "@gearbox-protocol/core-v2/contracts/core/AddressProvider.sol";
+import {ContractsRegister} from "@gearbox-protocol/core-v2/contracts/core/ContractsRegister.sol";
-import {IPoolService} from "../interfaces/IPoolService.sol";
+import {IPoolService} from "@gearbox-protocol/core-v2/contracts/interfaces/IPoolService.sol";
import {IPool4626} from "../interfaces/IPool4626.sol";
-import {IWETH} from "../interfaces/external/IWETH.sol";
+import {IWETH} from "@gearbox-protocol/core-v2/contracts/interfaces/external/IWETH.sol";
import {IWETHGateway} from "../interfaces/IWETHGateway.sol";
-import {Errors} from "../libraries/Errors.sol";
+import {Errors} from "@gearbox-protocol/core-v2/contracts/libraries/Errors.sol";
/// @title WETHGateway
/// @notice Used for converting ETH <> WETH
diff --git a/contracts/core/access/Claimable.sol b/contracts/core/access/Claimable.sol
deleted file mode 100644
index 17aeb668..00000000
--- a/contracts/core/access/Claimable.sol
+++ /dev/null
@@ -1,35 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
-
-/// @title Claimable
-/// @dev Implements logic for a two-step ownership transfer on top of Ownable
-contract Claimable is Ownable {
- /// @dev The new owner that has not claimed ownership yet
- address public pendingOwner;
-
- /// @dev A modifier that restricts the function to the pending owner only
- modifier onlyPendingOwner() {
- if (msg.sender != pendingOwner) {
- revert("Claimable: Sender is not pending owner");
- }
- _;
- }
-
- /// @dev Sets pending owner to the new owner, but does not
- /// transfer ownership yet
- /// @param newOwner The address to become the future owner
- function transferOwnership(address newOwner) public override onlyOwner {
- require(newOwner != address(0), "Claimable: new owner is the zero address");
- pendingOwner = newOwner;
- }
-
- /// @dev Used by the pending owner to claim ownership after transferOwnership
- function claimOwnership() external onlyPendingOwner {
- _transferOwnership(pendingOwner);
- pendingOwner = address(0);
- }
-}
diff --git a/contracts/credit/CreditAccount.sol b/contracts/credit/CreditAccount.sol
deleted file mode 100644
index accbe564..00000000
--- a/contracts/credit/CreditAccount.sol
+++ /dev/null
@@ -1,121 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
-
-import {Address} from "@openzeppelin/contracts/utils/Address.sol";
-
-import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
-import {ICreditAccount} from "../interfaces/ICreditAccount.sol";
-
-/// @title Credit Account
-/// @notice Implements generic credit account logic:
-/// - Holds collateral assets
-/// - Stores general parameters: borrowed amount, cumulative index at open and block when it was initialized
-/// - Transfers assets
-/// - Executes financial orders by calling connected protocols on its behalf
-///
-/// More: https://dev.gearbox.fi/developers/credit/credit_account
-contract CreditAccount is ICreditAccount, Initializable {
- using SafeERC20 for IERC20;
- using Address for address;
-
- /// @dev Address of the Credit Account factory
- address public override factory;
-
- /// @dev Address of the currently connected Credit Manager
- address public override creditManager;
-
- /// @dev The principal amount borrowed from the pool
- uint256 public override borrowedAmount;
-
- /// @dev Cumulative interest index since the last Credit Account's debt update
- uint256 public override cumulativeIndexAtOpen;
-
- /// @dev Block at which the contract was last taken from the factory
- uint256 public override since;
-
- // Contract version
- uint256 public constant version = 1;
-
- /// @dev Restricts operations to the connected Credit Manager only
- modifier creditManagerOnly() {
- if (msg.sender != creditManager) {
- revert CallerNotCreditManagerException();
- }
- _;
- }
-
- /// @dev Restricts operation to the Credit Account factory
- modifier factoryOnly() {
- if (msg.sender != factory) revert CallerNotFactoryException();
- _;
- }
-
- /// @dev Called on new Credit Account creation.
- /// @notice Initialize is used instead of constructor, since the contract is cloned.
- function initialize() external override initializer {
- factory = msg.sender;
- }
-
- /// @dev Connects this credit account to a Credit Manager. Restricted to the account factory (owner) only.
- /// @param _creditManager Credit manager address
- /// @param _borrowedAmount The amount borrowed at Credit Account opening
- /// @param _cumulativeIndexAtOpen The interest index at Credit Account opening
- function connectTo(address _creditManager, uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen)
- external
- override
- factoryOnly
- {
- creditManager = _creditManager; // T:[CA-7]
- borrowedAmount = _borrowedAmount; // T:[CA-3,7]
- cumulativeIndexAtOpen = _cumulativeIndexAtOpen; // T:[CA-3,7]
- since = block.number; // T:[CA-7]
- }
-
- /// @dev Updates borrowed amount and cumulative index. Restricted to the currently connected Credit Manager.
- /// @param _borrowedAmount The amount currently lent to the Credit Account
- /// @param _cumulativeIndexAtOpen New cumulative index to calculate interest from
- function updateParameters(uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen)
- external
- override
- creditManagerOnly // T:[CA-2]
- {
- borrowedAmount = _borrowedAmount; // T:[CA-4]
- cumulativeIndexAtOpen = _cumulativeIndexAtOpen;
- }
-
- /// @dev Removes allowance for a token to a 3rd-party contract. Restricted to factory only.
- /// @param token ERC20 token to remove allowance for.
- /// @param targetContract Target contract to revoke allowance to.
- function cancelAllowance(address token, address targetContract) external override factoryOnly {
- IERC20(token).safeApprove(targetContract, 0);
- }
-
- /// @dev Transfers tokens from the credit account to a provided address. Restricted to the current Credit Manager only.
- /// @param token Token to be transferred from the Credit Account.
- /// @param to Address of the recipient.
- /// @param amount Amount to be transferred.
- function safeTransfer(address token, address to, uint256 amount)
- external
- override
- creditManagerOnly // T:[CA-2]
- {
- IERC20(token).safeTransfer(to, amount); // T:[CA-6]
- }
-
- /// @dev Executes a call to a 3rd party contract with provided data. Restricted to the current Credit Manager only.
- /// @param destination Contract address to be called.
- /// @param data Data to call the contract with.
- function execute(address destination, bytes memory data)
- external
- override
- creditManagerOnly
- returns (bytes memory)
- {
- return destination.functionCall(data); // T: [CM-48]
- }
-}
diff --git a/contracts/credit/CreditConfigurator.sol b/contracts/credit/CreditConfigurator.sol
index e6d889ec..55c64f8e 100644
--- a/contracts/credit/CreditConfigurator.sol
+++ b/contracts/credit/CreditConfigurator.sol
@@ -15,10 +15,11 @@ import {
DEFAULT_FEE_LIQUIDATION_EXPIRED,
DEFAULT_LIQUIDATION_PREMIUM_EXPIRED,
DEFAULT_LIMIT_PER_BLOCK_MULTIPLIER,
- UNIVERSAL_CONTRACT
-} from "../libraries/Constants.sol";
-import {WAD} from "../libraries/Constants.sol";
-import {PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
+ UNIVERSAL_CONTRACT,
+ WAD
+} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
+
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
// CONTRACTS
import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
@@ -27,9 +28,9 @@ import {CreditManager} from "./CreditManager.sol";
// INTERFACES
import {ICreditConfigurator, CollateralToken, CreditManagerOpts} from "../interfaces/ICreditConfigurator.sol";
-import {IPriceOracleV2} from "../interfaces/IPriceOracle.sol";
-import {IPoolService} from "../interfaces/IPoolService.sol";
-import {IAddressProvider} from "../interfaces/IAddressProvider.sol";
+import {IPriceOracleV2} from "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol";
+import {IPoolService} from "@gearbox-protocol/core-v2/contracts/interfaces/IPoolService.sol";
+import {IAddressProvider} from "@gearbox-protocol/core-v2/contracts/interfaces/IAddressProvider.sol";
import {IPoolQuotaKeeper} from "../interfaces/IPoolQuotaKeeper.sol";
// EXCEPTIONS
diff --git a/contracts/credit/CreditFacade.sol b/contracts/credit/CreditFacade.sol
index 8d6a94be..2890b601 100644
--- a/contracts/credit/CreditFacade.sol
+++ b/contracts/credit/CreditFacade.sol
@@ -9,23 +9,23 @@ import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
// DATA
-import {MultiCall} from "../libraries/MultiCall.sol";
-import {Balance, BalanceOps} from "../libraries/Balances.sol";
+import {MultiCall} from "@gearbox-protocol/core-v2/contracts/libraries/MultiCall.sol";
+import {Balance, BalanceOps} from "@gearbox-protocol/core-v2/contracts/libraries/Balances.sol";
import {QuotaUpdate} from "../interfaces/IPoolQuotaKeeper.sol";
/// INTERFACES
import {ICreditFacade, ICreditFacadeExtended, FullCheckParams} from "../interfaces/ICreditFacade.sol";
import {ICreditManagerV2, ClosureAction} from "../interfaces/ICreditManagerV2.sol";
-import {IPriceOracleV2} from "../interfaces/IPriceOracle.sol";
-import {IDegenNFT} from "../interfaces/IDegenNFT.sol";
-import {IWETH} from "../interfaces/external/IWETH.sol";
+import {IPriceOracleV2} from "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol";
+import {IDegenNFT} from "@gearbox-protocol/core-v2/contracts/interfaces/IDegenNFT.sol";
+import {IWETH} from "@gearbox-protocol/core-v2/contracts/interfaces/external/IWETH.sol";
import {IBlacklistHelper} from "../interfaces/IBlacklistHelper.sol";
import {IBotList} from "../interfaces/IBotList.sol";
// CONSTANTS
-import {LEVERAGE_DECIMALS} from "../libraries/Constants.sol";
-import {PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
+import {LEVERAGE_DECIMALS} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
// EXCEPTIONS
import {ZeroAddressException} from "../interfaces/IErrors.sol";
diff --git a/contracts/credit/CreditManager.sol b/contracts/credit/CreditManager.sol
index dd873027..a8e4427d 100644
--- a/contracts/credit/CreditManager.sol
+++ b/contracts/credit/CreditManager.sol
@@ -12,20 +12,20 @@ import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
// INTERFACES
-import {IAccountFactory} from "../interfaces/IAccountFactory.sol";
-import {ICreditAccount} from "../interfaces/ICreditAccount.sol";
-import {IPoolService} from "../interfaces/IPoolService.sol";
+import {IAccountFactory} from "@gearbox-protocol/core-v2/contracts/interfaces/IAccountFactory.sol";
+import {ICreditAccount} from "@gearbox-protocol/core-v2/contracts/interfaces/ICreditAccount.sol";
+import {IPoolService} from "@gearbox-protocol/core-v2/contracts/interfaces/IPoolService.sol";
import {IPool4626} from "../interfaces/IPool4626.sol";
import {IWETHGateway} from "../interfaces/IWETHGateway.sol";
import {ICreditManagerV2, ClosureAction, CollateralTokenData} from "../interfaces/ICreditManagerV2.sol";
-import {IAddressProvider} from "../interfaces/IAddressProvider.sol";
-import {IPriceOracleV2} from "../interfaces/IPriceOracle.sol";
+import {IAddressProvider} from "@gearbox-protocol/core-v2/contracts/interfaces/IAddressProvider.sol";
+import {IPriceOracleV2} from "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol";
import {IPoolQuotaKeeper, QuotaUpdate, TokenLT, QuotaStatusChange} from "../interfaces/IPoolQuotaKeeper.sol";
-import {IVersion} from "../interfaces/IVersion.sol";
+import {IVersion} from "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol";
// CONSTANTS
-import {RAY} from "../libraries/Constants.sol";
-import {PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
+import {RAY} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
import {
DEFAULT_FEE_INTEREST,
DEFAULT_FEE_LIQUIDATION,
@@ -33,13 +33,11 @@ import {
LEVERAGE_DECIMALS,
ALLOWANCE_THRESHOLD,
UNIVERSAL_CONTRACT
-} from "../libraries/Constants.sol";
+} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
uint256 constant ADDR_BIT_SIZE = 160;
uint256 constant INDEX_PRECISION = 10 ** 9;
-import "forge-std/console.sol";
-
struct Slot1 {
/// @dev Interest fee charged by the protocol: fee = interest accrued * feeInterest
uint16 feeInterest;
diff --git a/contracts/factories/CreditManagerFactoryBase.sol b/contracts/factories/CreditManagerFactoryBase.sol
index 72a0bf59..bc2bc7a9 100644
--- a/contracts/factories/CreditManagerFactoryBase.sol
+++ b/contracts/factories/CreditManagerFactoryBase.sol
@@ -3,13 +3,13 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {ContractsRegister} from "../core/ContractsRegister.sol";
-import {PoolService} from "../pool/PoolService.sol";
+import {ContractsRegister} from "@gearbox-protocol/core-v2/contracts/core/ContractsRegister.sol";
+import {PoolService} from "@gearbox-protocol/core-v2/contracts/pool/PoolService.sol";
import {CreditManager} from "../credit/CreditManager.sol";
import {CreditFacade} from "../credit/CreditFacade.sol";
import {CreditConfigurator, CreditManagerOpts} from "../credit/CreditConfigurator.sol";
-import {ContractUpgrader} from "../support/ContractUpgrader.sol";
+import {ContractUpgrader} from "@gearbox-protocol/core-v2/contracts/support/ContractUpgrader.sol";
struct Adapter {
address adapter;
diff --git a/contracts/factories/GenesisFactory.sol b/contracts/factories/GenesisFactory.sol
deleted file mode 100644
index c3608626..00000000
--- a/contracts/factories/GenesisFactory.sol
+++ /dev/null
@@ -1,78 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox. Generalized leverage protocol that allows to take leverage and then use it across other DeFi protocols and platforms in a composable way.
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
-
-import {AddressProvider} from "../core/AddressProvider.sol";
-import {ContractsRegister} from "../core/ContractsRegister.sol";
-import {ACL} from "../core/ACL.sol";
-import {DataCompressor} from "../core/DataCompressor.sol";
-import {AccountFactory} from "../core/AccountFactory.sol";
-
-import {WETHGateway} from "../core/WETHGateway.sol";
-import {PriceOracle, PriceFeedConfig} from "../oracles/PriceOracle.sol";
-import {GearToken} from "../tokens/GearToken.sol";
-
-contract GenesisFactory is Ownable {
- AddressProvider public addressProvider;
- ACL public acl;
- PriceOracle public priceOracle;
-
- constructor(address wethToken, address treasury) {
- addressProvider = new AddressProvider(); // T:[GD-1]
- addressProvider.setWethToken(wethToken); // T:[GD-1]
- addressProvider.setTreasuryContract(treasury); // T:[GD-1]
-
- acl = new ACL(); // T:[GD-1]
- addressProvider.setACL(address(acl)); // T:[GD-1]
-
- ContractsRegister contractsRegister = new ContractsRegister(
- address(addressProvider)
- ); // T:[GD-1]
- addressProvider.setContractsRegister(address(contractsRegister)); // T:[GD-1]
-
- DataCompressor dataCompressor = new DataCompressor(
- address(addressProvider)
- ); // T:[GD-1]
- addressProvider.setDataCompressor(address(dataCompressor)); // T:[GD-1]
-
- PriceFeedConfig[] memory config;
- priceOracle = new PriceOracle(address(addressProvider), config); // T:[GD-1]
- addressProvider.setPriceOracle(address(priceOracle)); // T:[GD-1]
-
- AccountFactory accountFactory = new AccountFactory(
- address(addressProvider)
- ); // T:[GD-1]
- addressProvider.setAccountFactory(address(accountFactory)); // T:[GD-1]
-
- WETHGateway wethGateway = new WETHGateway(address(addressProvider)); // T:[GD-1]
- addressProvider.setWETHGateway(address(wethGateway)); // T:[GD-1]
-
- GearToken gearToken = new GearToken(address(this)); // T:[GD-1]
- addressProvider.setGearToken(address(gearToken)); // T:[GD-1]
- gearToken.transferOwnership(msg.sender); // T:[GD-1]
- addressProvider.transferOwnership(msg.sender); // T:[GD-1]
- acl.transferOwnership(msg.sender); // T:[GD-1]
- }
-
- function addPriceFeeds(PriceFeedConfig[] memory priceFeeds)
- external
- onlyOwner // T:[GD-3]
- {
- for (uint256 i = 0; i < priceFeeds.length; ++i) {
- priceOracle.addPriceFeed(priceFeeds[i].token, priceFeeds[i].priceFeed); // T:[GD-4]
- }
-
- acl.transferOwnership(msg.sender); // T:[GD-4]
- }
-
- function claimACLOwnership() external onlyOwner {
- acl.claimOwnership();
- }
-
- function claimAddressProviderOwnership() external onlyOwner {
- addressProvider.claimOwnership();
- }
-}
diff --git a/contracts/factories/PoolFactory.sol b/contracts/factories/PoolFactory.sol
deleted file mode 100644
index f49ee43b..00000000
--- a/contracts/factories/PoolFactory.sol
+++ /dev/null
@@ -1,60 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox. Generalized leverage protocol that allows to take leverage and then use it across other DeFi protocols and platforms in a composable way.
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-pragma abicoder v2;
-
-import {ContractsRegister} from "../core/ContractsRegister.sol";
-
-import {LinearInterestRateModel} from "../pool/LinearInterestRateModel.sol";
-import {PoolService} from "../pool/PoolService.sol";
-
-import {ContractUpgrader} from "../support/ContractUpgrader.sol";
-
-struct PoolOpts {
- address addressProvider; // address of addressProvider contract
- address underlying; // address of underlying token for pool and creditManager
- uint256 U_optimal; // linear interest model parameter
- uint256 U_reserve; // linear interest model parameter
- uint256 R_base; // linear interest model parameter
- uint256 R_slope1; // linear interest model parameter
- uint256 R_slope2; // linear interest model parameter
- uint256 R_slope3; // linear interest model parameter
- uint256 expectedLiquidityLimit; // linear interest model parameter
- uint256 withdrawFee; // withdrawFee
-}
-
-contract PoolFactory is ContractUpgrader {
- PoolService public immutable pool;
- uint256 public withdrawFee;
-
- constructor(PoolOpts memory opts) ContractUpgrader(opts.addressProvider) {
- LinearInterestRateModel linearModel = new LinearInterestRateModel(
- opts.U_optimal,
- opts.U_reserve,
- opts.R_base,
- opts.R_slope1,
- opts.R_slope2,
- opts.R_slope3,
- false
- ); // T:[PD-1]
-
- pool = new PoolService(
- opts.addressProvider,
- opts.underlying,
- address(linearModel),
- opts.expectedLiquidityLimit
- );
-
- withdrawFee = opts.withdrawFee;
- }
-
- function _configure() internal override {
- ContractsRegister cr = ContractsRegister(addressProvider.getContractsRegister());
-
- pool.setWithdrawFee(withdrawFee);
-
- cr.addPool(address(pool)); // T:[PD-2]
- }
-}
diff --git a/contracts/interfaces/IACL.sol b/contracts/interfaces/IACL.sol
deleted file mode 100644
index beb98805..00000000
--- a/contracts/interfaces/IACL.sol
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IVersion} from "./IVersion.sol";
-
-interface IACLExceptions {
- /// @dev Thrown when attempting to delete an address from a set that is not a pausable admin
- error AddressNotPausableAdminException(address addr);
-
- /// @dev Thrown when attempting to delete an address from a set that is not a unpausable admin
- error AddressNotUnpausableAdminException(address addr);
-}
-
-interface IACLEvents {
- /// @dev Emits when a new admin is added that can pause contracts
- event PausableAdminAdded(address indexed newAdmin);
-
- /// @dev Emits when a Pausable admin is removed
- event PausableAdminRemoved(address indexed admin);
-
- /// @dev Emits when a new admin is added that can unpause contracts
- event UnpausableAdminAdded(address indexed newAdmin);
-
- /// @dev Emits when an Unpausable admin is removed
- event UnpausableAdminRemoved(address indexed admin);
-}
-
-/// @title ACL interface
-interface IACL is IACLEvents, IACLExceptions, IVersion {
- /// @dev Returns true if the address is a pausable admin and false if not
- /// @param addr Address to check
- function isPausableAdmin(address addr) external view returns (bool);
-
- /// @dev Returns true if the address is unpausable admin and false if not
- /// @param addr Address to check
- function isUnpausableAdmin(address addr) external view returns (bool);
-
- /// @dev Returns true if an address has configurator rights
- /// @param account Address to check
- function isConfigurator(address account) external view returns (bool);
-
- /// @dev Returns address of configurator
- function owner() external view returns (address);
-}
diff --git a/contracts/interfaces/IAccountFactory.sol b/contracts/interfaces/IAccountFactory.sol
deleted file mode 100644
index 6ee1ba62..00000000
--- a/contracts/interfaces/IAccountFactory.sol
+++ /dev/null
@@ -1,56 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IVersion} from "./IVersion.sol";
-
-interface IAccountFactoryEvents {
- /// @dev Emits when the account mining contract is changed
- /// @notice Not applicable to factories deployed after V2
- event AccountMinerChanged(address indexed miner);
-
- /// @dev Emits when a new Credit Account is created
- event NewCreditAccount(address indexed account);
-
- /// @dev Emits when a Credit Manager takes an account from the factory
- event InitializeCreditAccount(address indexed account, address indexed creditManager);
-
- /// @dev Emits when a Credit Manager returns an account to the factory
- event ReturnCreditAccount(address indexed account);
-
- /// @dev Emits when a Credit Account is taking out of the factory forever
- /// by root
- event TakeForever(address indexed creditAccount, address indexed to);
-}
-
-interface IAccountFactoryGetters {
- /// @dev Gets the next available credit account after the passed one, or address(0) if the passed account is the tail
- /// @param creditAccount Credit Account previous to the one to retrieve
- function getNext(address creditAccount) external view returns (address);
-
- /// @dev Head of CA linked list
- function head() external view returns (address);
-
- /// @dev Tail of CA linked list
- function tail() external view returns (address);
-
- /// @dev Returns the number of unused credit accounts in stock
- function countCreditAccountsInStock() external view returns (uint256);
-
- /// @dev Returns the credit account address under the passed id
- /// @param id The index of the requested CA
- function creditAccounts(uint256 id) external view returns (address);
-
- /// @dev Returns the number of deployed credit accounts
- function countCreditAccounts() external view returns (uint256);
-}
-
-interface IAccountFactory is IAccountFactoryGetters, IAccountFactoryEvents, IVersion {
- /// @dev Provides a new credit account to a Credit Manager
- function takeCreditAccount(uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen) external returns (address);
-
- /// @dev Retrieves the Credit Account from the Credit Manager and adds it to the stock
- /// @param usedAccount Address of returned credit account
- function returnCreditAccount(address usedAccount) external;
-}
diff --git a/contracts/interfaces/IAddressProvider.sol b/contracts/interfaces/IAddressProvider.sol
deleted file mode 100644
index 0f5386ef..00000000
--- a/contracts/interfaces/IAddressProvider.sol
+++ /dev/null
@@ -1,44 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IVersion} from "./IVersion.sol";
-
-interface IAddressProviderEvents {
- /// @dev Emits when an address is set for a contract role
- event AddressSet(bytes32 indexed service, address indexed newAddress);
-}
-
-/// @title Optimised for front-end Address Provider interface
-interface IAddressProvider is IAddressProviderEvents, IVersion {
- /// @return Address of ACL contract
- function getACL() external view returns (address);
-
- /// @return Address of ContractsRegister
- function getContractsRegister() external view returns (address);
-
- /// @return Address of AccountFactory
- function getAccountFactory() external view returns (address);
-
- /// @return Address of DataCompressor
- function getDataCompressor() external view returns (address);
-
- /// @return Address of GEAR token
- function getGearToken() external view returns (address);
-
- /// @return Address of WETH token
- function getWethToken() external view returns (address);
-
- /// @return Address of WETH Gateway
- function getWETHGateway() external view returns (address);
-
- /// @return Address of PriceOracle
- function getPriceOracle() external view returns (address);
-
- /// @return Address of DAO Treasury Multisig
- function getTreasuryContract() external view returns (address);
-
- /// @return Address of PathFinder
- function getLeveragedActions() external view returns (address);
-}
diff --git a/contracts/interfaces/IAirdropDistributor.sol b/contracts/interfaces/IAirdropDistributor.sol
deleted file mode 100644
index 01847c69..00000000
--- a/contracts/interfaces/IAirdropDistributor.sol
+++ /dev/null
@@ -1,42 +0,0 @@
-// SPDX-License-Identifier: MIT
-pragma solidity >=0.5.0;
-
-import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-
-struct DistributionData {
- address account;
- uint8 campaignId;
- uint256 amount;
-}
-
-struct ClaimedData {
- address account;
- uint256 amount;
-}
-
-interface IAirdropDistributorEvents {
- /// @dev Emits when a user claims tokens
- event Claimed(address indexed account, uint256 amount, bool indexed historic);
-
- /// @dev Emits when the owner replaces the merkle root
- event RootUpdated(bytes32 oldRoot, bytes32 indexed newRoot);
-
- /// @dev Emitted from a special function after updating the root to index allocations
- event TokenAllocated(address indexed account, uint8 indexed campaignId, uint256 amount);
-}
-
-interface IAirdropDistributor is IAirdropDistributorEvents {
- /// @dev Returns the token distributed by this contract.
- function token() external view returns (IERC20);
-
- /// @dev Returns the current merkle root containing total claimable balances
- function merkleRoot() external view returns (bytes32);
-
- /// @dev Returns the total amount of token claimed by the user
- function claimed(address user) external view returns (uint256);
-
- // Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
- /// @dev Claims the given amount of the token for the account. Reverts if the inputs are not a leaf in the tree
- /// or the total claimed amount for the account is more than the leaf amount.
- function claim(uint256 index, address account, uint256 totalAmount, bytes32[] calldata merkleProof) external;
-}
diff --git a/contracts/interfaces/IContractsRegister.sol b/contracts/interfaces/IContractsRegister.sol
deleted file mode 100644
index f620ab58..00000000
--- a/contracts/interfaces/IContractsRegister.sol
+++ /dev/null
@@ -1,50 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IVersion} from "./IVersion.sol";
-
-interface IContractsRegisterEvents {
- /// @dev Emits when a new pool is registered in the system
- event NewPoolAdded(address indexed pool);
-
- /// @dev Emits when a new Credit Manager is registered in the system
- event NewCreditManagerAdded(address indexed creditManager);
-}
-
-interface IContractsRegister is IContractsRegisterEvents, IVersion {
- //
- // POOLS
- //
-
- /// @dev Returns the array of registered pools
- function getPools() external view returns (address[] memory);
-
- /// @dev Returns a pool address from the list under the passed index
- /// @param i Index of the pool to retrieve
- function pools(uint256 i) external returns (address);
-
- /// @return Returns the number of registered pools
- function getPoolsCount() external view returns (uint256);
-
- /// @dev Returns true if the passed address is a pool
- function isPool(address) external view returns (bool);
-
- //
- // CREDIT MANAGERS
- //
-
- /// @dev Returns the array of registered Credit Managers
- function getCreditManagers() external view returns (address[] memory);
-
- /// @dev Returns a Credit Manager's address from the list under the passed index
- /// @param i Index of the Credit Manager to retrieve
- function creditManagers(uint256 i) external returns (address);
-
- /// @return Returns the number of registered Credit Managers
- function getCreditManagersCount() external view returns (uint256);
-
- /// @dev Returns true if the passed address is a Credit Manager
- function isCreditManager(address) external view returns (bool);
-}
diff --git a/contracts/interfaces/ICreditAccount.sol b/contracts/interfaces/ICreditAccount.sol
deleted file mode 100644
index d1da8ec3..00000000
--- a/contracts/interfaces/ICreditAccount.sol
+++ /dev/null
@@ -1,71 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IVersion} from "./IVersion.sol";
-
-/// @title Credit Account
-/// @notice Implements generic credit account logic:
-/// - Holds collateral assets
-/// - Stores general parameters: borrowed amount, cumulative index at open and block when it was initialized
-/// - Transfers assets
-/// - Executes financial orders by calling connected protocols on its behalf
-///
-/// More: https://dev.gearbox.fi/developers/credit/credit_account
-
-interface ICrediAccountExceptions {
- /// @dev throws if the caller is not the connected Credit Manager
- error CallerNotCreditManagerException();
-
- /// @dev throws if the caller is not the factory
- error CallerNotFactoryException();
-}
-
-interface ICreditAccount is ICrediAccountExceptions, IVersion {
- /// @dev Called on new Credit Account creation.
- /// @notice Initialize is used instead of constructor, since the contract is cloned.
- function initialize() external;
-
- /// @dev Connects this credit account to a Credit Manager. Restricted to the account factory (owner) only.
- /// @param _creditManager Credit manager address
- /// @param _borrowedAmount The amount borrowed at Credit Account opening
- /// @param _cumulativeIndexAtOpen The interest index at Credit Account opening
- function connectTo(address _creditManager, uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen) external;
-
- /// @dev Updates borrowed amount and cumulative index. Restricted to the currently connected Credit Manager.
- /// @param _borrowedAmount The amount currently lent to the Credit Account
- /// @param _cumulativeIndexAtOpen New cumulative index to calculate interest from
- function updateParameters(uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen) external;
-
- /// @dev Removes allowance for a token to a 3rd-party contract. Restricted to factory only.
- /// @param token ERC20 token to remove allowance for.
- /// @param targetContract Target contract to revoke allowance to.
- function cancelAllowance(address token, address targetContract) external;
-
- /// @dev Transfers tokens from the credit account to a provided address. Restricted to the current Credit Manager only.
- /// @param token Token to be transferred from the Credit Account.
- /// @param to Address of the recipient.
- /// @param amount Amount to be transferred.
- function safeTransfer(address token, address to, uint256 amount) external;
-
- /// @dev Returns the principal amount borrowed from the pool
- function borrowedAmount() external view returns (uint256);
-
- /// @dev Returns the cumulative interest index since the last Credit Account's debt update
- function cumulativeIndexAtOpen() external view returns (uint256);
-
- /// @dev Returns the block at which the contract was last taken from the factory
- function since() external view returns (uint256);
-
- /// @dev Returns the address of the currently connected Credit Manager
- function creditManager() external view returns (address);
-
- /// @dev Address of the Credit Account factory
- function factory() external view returns (address);
-
- /// @dev Executes a call to a 3rd party contract with provided data. Restricted to the current Credit Manager only.
- /// @param destination Contract address to be called.
- /// @param data Data to call the contract with.
- function execute(address destination, bytes memory data) external returns (bytes memory);
-}
diff --git a/contracts/interfaces/ICreditConfigurator.sol b/contracts/interfaces/ICreditConfigurator.sol
index c792e9a3..22953c46 100644
--- a/contracts/interfaces/ICreditConfigurator.sol
+++ b/contracts/interfaces/ICreditConfigurator.sol
@@ -3,10 +3,10 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {IAddressProvider} from "./IAddressProvider.sol";
+import {IAddressProvider} from "@gearbox-protocol/core-v2/contracts/interfaces/IAddressProvider.sol";
import {CreditManager} from "../credit/CreditManager.sol";
import {CreditFacade} from "../credit/CreditFacade.sol";
-import {IVersion} from "./IVersion.sol";
+import {IVersion} from "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol";
/// @dev A struct containing parameters for a recognized collateral token in the system
struct CollateralToken {
diff --git a/contracts/interfaces/ICreditFacade.sol b/contracts/interfaces/ICreditFacade.sol
index 5665f55d..ecc93910 100644
--- a/contracts/interfaces/ICreditFacade.sol
+++ b/contracts/interfaces/ICreditFacade.sol
@@ -3,11 +3,11 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {Balance} from "../libraries/Balances.sol";
-import {MultiCall} from "../libraries/MultiCall.sol";
+import {Balance} from "@gearbox-protocol/core-v2/contracts/libraries/Balances.sol";
+import {MultiCall} from "@gearbox-protocol/core-v2/contracts/libraries/MultiCall.sol";
import {ICreditManagerV2, ICreditManagerV2Exceptions} from "./ICreditManagerV2.sol";
import {QuotaUpdate} from "./IPoolQuotaKeeper.sol";
-import {IVersion} from "./IVersion.sol";
+import {IVersion} from "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol";
struct FullCheckParams {
uint256[] collateralHints;
diff --git a/contracts/interfaces/ICreditManagerV2.sol b/contracts/interfaces/ICreditManagerV2.sol
index ae95c8da..a18a7c61 100644
--- a/contracts/interfaces/ICreditManagerV2.sol
+++ b/contracts/interfaces/ICreditManagerV2.sol
@@ -3,9 +3,9 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {IPriceOracleV2} from "./IPriceOracle.sol";
+import {IPriceOracleV2} from "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol";
import {QuotaUpdate} from "./IPoolQuotaKeeper.sol";
-import {IVersion} from "./IVersion.sol";
+import {IVersion} from "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol";
enum ClosureAction {
CLOSE_ACCOUNT,
diff --git a/contracts/interfaces/IDataCompressor.sol b/contracts/interfaces/IDataCompressor.sol
deleted file mode 100644
index 7c567b29..00000000
--- a/contracts/interfaces/IDataCompressor.sol
+++ /dev/null
@@ -1,53 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {CreditAccountData, CreditManagerData, PoolData, TokenInfo} from "../libraries/Types.sol";
-import {IVersion} from "./IVersion.sol";
-
-interface IDataCompressorExceptions {
- /// @dev Thrown if attempting to get data on a contract that is not a registered
- /// Credit Manager
- error NotCreditManagerException();
-
- /// @dev Thrown if attempting the get data on a contract that is not a registered
- /// pool
- error NotPoolException();
-}
-
-interface IDataCompressor is IDataCompressorExceptions, IVersion {
- /// @dev Returns CreditAccountData for all opened accounts for particular borrower
- /// @param borrower Borrower address
- function getCreditAccountList(address borrower) external view returns (CreditAccountData[] memory);
-
- /// @dev Returns whether the borrower has an open credit account with the credit manager
- /// @param creditManager Credit manager to check
- /// @param borrower Borrower to check
- function hasOpenedCreditAccount(address creditManager, address borrower) external view returns (bool);
-
- /// @dev Returns CreditAccountData for a particular Credit Account account, based on creditManager and borrower
- /// @param _creditManager Credit manager address
- /// @param borrower Borrower address
- function getCreditAccountData(address _creditManager, address borrower)
- external
- view
- returns (CreditAccountData memory);
-
- /// @dev Returns CreditManagerData for all Credit Managers
- function getCreditManagersList() external view returns (CreditManagerData[] memory);
-
- /// @dev Returns CreditManagerData for a particular _creditManager
- /// @param _creditManager CreditManager address
- function getCreditManagerData(address _creditManager) external view returns (CreditManagerData memory);
-
- /// @dev Returns PoolData for a particular pool
- /// @param _pool Pool address
- function getPoolData(address _pool) external view returns (PoolData memory);
-
- /// @dev Returns PoolData for all registered pools
- function getPoolsList() external view returns (PoolData[] memory);
-
- /// @dev Returns the adapter address for a particular creditManager and targetContract
- function getAdapter(address _creditManager, address _allowedContract) external view returns (address adapter);
-}
diff --git a/contracts/interfaces/IDegenDistributor.sol b/contracts/interfaces/IDegenDistributor.sol
deleted file mode 100644
index 50a7c411..00000000
--- a/contracts/interfaces/IDegenDistributor.sol
+++ /dev/null
@@ -1,28 +0,0 @@
-// SPDX-License-Identifier: MIT
-pragma solidity >=0.5.0;
-
-import {IDegenNFT} from "./IDegenNFT.sol";
-
-interface IDegenDistributorEvents {
- /// @dev Emits when a user claims tokens
- event Claimed(address indexed account, uint256 amount);
-
- /// @dev Emits when the owner replaces the merkle root
- event RootUpdated(bytes32 oldRoot, bytes32 indexed newRoot);
-}
-
-interface IDegenDistributor is IDegenDistributorEvents {
- // Returns the address of the token distributed by this contract.
- function degenNFT() external view returns (IDegenNFT);
-
- // Returns the merkle root of the merkle tree containing account balances available to claim.
- function merkleRoot() external view returns (bytes32);
-
- /// @dev Returns the total amount of token claimed by the user
- function claimed(address user) external view returns (uint256);
-
- // Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
- /// @dev Claims the remaining unclaimed amount of the token for the account. Reverts if the inputs are not a leaf in the tree
- /// or the total claimed amount for the account is more than the leaf amount.
- function claim(uint256 index, address account, uint256 totalAmount, bytes32[] calldata merkleProof) external;
-}
diff --git a/contracts/interfaces/IDegenNFT.sol b/contracts/interfaces/IDegenNFT.sol
deleted file mode 100644
index b4983bf7..00000000
--- a/contracts/interfaces/IDegenNFT.sol
+++ /dev/null
@@ -1,53 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IVersion} from "./IVersion.sol";
-import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
-
-interface IDegenNFTExceptions {
- /// @dev Thrown if an access-restricted function was called by non-CreditFacade
- error CreditFacadeOrConfiguratorOnlyException();
-
- /// @dev Thrown if an access-restricted function was called by non-minter
- error MinterOnlyException();
-
- /// @dev Thrown if trying to add a burner address that is not a correct Credit Facade
- error InvalidCreditFacadeException();
-
- /// @dev Thrown if the account's balance is not sufficient for an action (usually a burn)
- error InsufficientBalanceException();
-}
-
-interface IDegenNFTEvents {
- /// @dev Minted when new minter set
- event NewMinterSet(address indexed);
-
- /// @dev Minted each time when new credit facade added
- event NewCreditFacadeAdded(address indexed);
-
- /// @dev Minted each time when new credit facade added
- event NewCreditFacadeRemoved(address indexed);
-}
-
-interface IDegenNFT is IDegenNFTExceptions, IDegenNFTEvents, IVersion, IERC721Metadata {
- /// @dev address of the current minter
- function minter() external view returns (address);
-
- /// @dev Stores the total number of tokens on holder accounts
- function totalSupply() external view returns (uint256);
-
- /// @dev Stores the base URI for NFT metadata
- function baseURI() external view returns (string memory);
-
- /// @dev Mints a specified amount of tokens to the address
- /// @param to Address the tokens are minted to
- /// @param amount The number of tokens to mint
- function mint(address to, uint256 amount) external;
-
- /// @dev Burns a number of tokens from a specified address
- /// @param from The address a token will be burnt from
- /// @param amount The number of tokens to burn
- function burn(address from, uint256 amount) external;
-}
diff --git a/contracts/interfaces/IDieselToken.sol b/contracts/interfaces/IDieselToken.sol
deleted file mode 100644
index ccf2ee79..00000000
--- a/contracts/interfaces/IDieselToken.sol
+++ /dev/null
@@ -1,16 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-
-interface IDieselTokenExceptions {
- /// @dev Thrown if an access-restricted function was called by non-PoolService
- error PoolServiceOnlyException();
-}
-
-interface IDieselToken is IERC20, IDieselTokenExceptions {
- /// @dev Returns the address of the pool this Diesel token belongs to
- function poolService() external view returns (address);
-}
diff --git a/contracts/interfaces/IGearToken.sol b/contracts/interfaces/IGearToken.sol
deleted file mode 100644
index f6513000..00000000
--- a/contracts/interfaces/IGearToken.sol
+++ /dev/null
@@ -1,56 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-pragma abicoder v2;
-
-import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-
-interface IGearToken is IERC20 {
- /**
- * @dev Approves token spending by signature
- * @param owner The address to approve from
- * @param spender The address to be approved
- * @param rawAmount The number of tokens that are approved (type(uint256).max sets allowance to infinite)
- * @param deadline The time at which to expire the signature
- * @param v The recovery byte of the signature
- * @param r Half of the ECDSA signature pair
- * @param s Half of the ECDSA signature pair
- */
- function permit(address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
- external;
-
- /**
- * @notice Delegate votes from `msg.sender` to `delegatee`
- * @param delegatee The address to delegate votes to
- */
- function delegate(address delegatee) external;
-
- /**
- * @notice Delegate votes by signature
- * @param delegatee The address to delegate votes to
- * @param nonce The contract state required to match the signature
- * @param expiry The time at which to expire the signature
- * @param v The recovery byte of the signature
- * @param r Half of the ECDSA signature pair
- * @param s Half of the ECDSA signature pair
- */
- function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;
-
- /**
- * @notice Returns the current total votes for `account`
- * @param account The address to get voting power for
- * @return The number of current votes for `account`
- */
- function getCurrentVotes(address account) external view returns (uint96);
-
- /**
- * @notice Determine the number of votes for an account as of a prior block number
- * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
- * @param account The address of the account to check
- * @param blockNumber The block number to get the vote balance at
- * @return The number of votes the account had as of the given block
- */
- function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96);
-}
diff --git a/contracts/interfaces/IInterestRateModel.sol b/contracts/interfaces/IInterestRateModel.sol
index 87c42ec1..d846eb28 100644
--- a/contracts/interfaces/IInterestRateModel.sol
+++ b/contracts/interfaces/IInterestRateModel.sol
@@ -3,7 +3,7 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {IVersion} from "./IVersion.sol";
+import {IVersion} from "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol";
interface IInterestRateModelExceptions {
error IncorrectParameterException();
diff --git a/contracts/interfaces/ILPPriceFeed.sol b/contracts/interfaces/ILPPriceFeed.sol
deleted file mode 100644
index 53d8b627..00000000
--- a/contracts/interfaces/ILPPriceFeed.sol
+++ /dev/null
@@ -1,38 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
-import {IPriceFeedType} from "./IPriceFeedType.sol";
-
-interface ILPPriceFeedEvents {
- /// @dev Emits on updating the virtual price bounds
- event NewLimiterParams(uint256 lowerBound, uint256 upperBound);
-}
-
-interface ILPPriceFeedExceptions {
- /// @dev Thrown on returning a value that violates the current bounds
- error ValueOutOfRangeException();
-
- /// @dev Thrown on failing sanity checks when setting new bounds
- error IncorrectLimitsException();
-}
-
-/// @title Interface for LP PriceFeeds with limiter
-interface ILPPriceFeed is AggregatorV3Interface, IPriceFeedType, ILPPriceFeedEvents, ILPPriceFeedExceptions {
- /// @dev Sets the lower and upper bounds for virtual price.
- /// @param _lowerBound The new lower bound
- /// @notice The upper bound is computed automatically
- function setLimiter(uint256 _lowerBound) external;
-
- /// @dev Returns the lower bound
- function lowerBound() external view returns (uint256);
-
- /// @dev Returns the upper bound
- function upperBound() external view returns (uint256);
-
- /// @dev Returns the pre-defined window between the lower and upper bounds
- /// @notice In bp format
- function delta() external view returns (uint256);
-}
diff --git a/contracts/interfaces/IMerkleDistributor.sol b/contracts/interfaces/IMerkleDistributor.sol
deleted file mode 100644
index 3e23f998..00000000
--- a/contracts/interfaces/IMerkleDistributor.sol
+++ /dev/null
@@ -1,20 +0,0 @@
-// SPDX-License-Identifier: MIT
-pragma solidity >=0.5.0;
-
-// Allows anyone to claim a token if they exist in a merkle root.
-interface IMerkleDistributor {
- // Returns the address of the token distributed by this contract.
- function token() external view returns (address);
-
- // Returns the merkle root of the merkle tree containing account balances available to claim.
- function merkleRoot() external view returns (bytes32);
-
- // Returns true if the index has been marked claimed.
- function isClaimed(uint256 index) external view returns (bool);
-
- // Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
- function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
-
- // This event is triggered whenever a call to #claim succeeds.
- event Claimed(uint256 index, address account, uint256 amount);
-}
diff --git a/contracts/interfaces/IPhantomERC20.sol b/contracts/interfaces/IPhantomERC20.sol
deleted file mode 100644
index 7d587f3f..00000000
--- a/contracts/interfaces/IPhantomERC20.sol
+++ /dev/null
@@ -1,14 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
-
-/// @title IPhantomERC20
-/// @dev Phantom tokens track balances in pools / contracts
-/// that do not mint an LP or a share token. Non-transferrabl.
-interface IPhantomERC20 is IERC20Metadata {
- /// @dev Returns the address of the token that is staked into the tracked position
- function underlying() external view returns (address);
-}
diff --git a/contracts/interfaces/IPool4626.sol b/contracts/interfaces/IPool4626.sol
index 34be89a4..f1faf692 100644
--- a/contracts/interfaces/IPool4626.sol
+++ b/contracts/interfaces/IPool4626.sol
@@ -4,7 +4,7 @@
pragma solidity ^0.8.10;
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
-import {IVersion} from "./IVersion.sol";
+import {IVersion} from "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol";
struct Pool4626Opts {
address addressProvider;
diff --git a/contracts/interfaces/IPoolQuotaKeeper.sol b/contracts/interfaces/IPoolQuotaKeeper.sol
index 804f3e7f..a780db54 100644
--- a/contracts/interfaces/IPoolQuotaKeeper.sol
+++ b/contracts/interfaces/IPoolQuotaKeeper.sol
@@ -3,7 +3,7 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {IVersion} from "./IVersion.sol";
+import {IVersion} from "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol";
enum QuotaStatusChange {
NOT_CHANGED,
diff --git a/contracts/interfaces/IPoolService.sol b/contracts/interfaces/IPoolService.sol
deleted file mode 100644
index 8a8b2bbc..00000000
--- a/contracts/interfaces/IPoolService.sol
+++ /dev/null
@@ -1,174 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import "../core/AddressProvider.sol";
-import {IVersion} from "./IVersion.sol";
-
-interface IPoolServiceEvents {
- /// @dev Emits on new liquidity being added to the pool
- event AddLiquidity(address indexed sender, address indexed onBehalfOf, uint256 amount, uint256 referralCode);
-
- /// @dev Emits on liquidity being removed to the pool
- event RemoveLiquidity(address indexed sender, address indexed to, uint256 amount);
-
- /// @dev Emits on a Credit Manager borrowing funds for a Credit Account
- event Borrow(address indexed creditManager, address indexed creditAccount, uint256 amount);
-
- /// @dev Emits on repayment of a Credit Account's debt
- event Repay(address indexed creditManager, uint256 borrowedAmount, uint256 profit, uint256 loss);
-
- /// @dev Emits on updating the interest rate model
- event NewInterestRateModel(address indexed newInterestRateModel);
-
- /// @dev Emits on connecting a new Credit Manager
- event NewCreditManagerConnected(address indexed creditManager);
-
- /// @dev Emits when a Credit Manager is forbidden to borrow
- event BorrowForbidden(address indexed creditManager);
-
- /// @dev Emitted when loss is incurred that can't be covered by treasury funds
- event UncoveredLoss(address indexed creditManager, uint256 loss);
-
- /// @dev Emits when the liquidity limit is changed
- event NewExpectedLiquidityLimit(uint256 newLimit);
-
- /// @dev Emits when the withdrawal fee is changed
- event NewWithdrawFee(uint256 fee);
-}
-
-/// @title Pool Service Interface
-/// @notice Implements business logic:
-/// - Adding/removing pool liquidity
-/// - Managing diesel tokens & diesel rates
-/// - Taking/repaying Credit Manager debt
-/// More: https://dev.gearbox.fi/developers/pool/abstractpoolservice
-interface IPoolService is IPoolServiceEvents, IVersion {
- //
- // LIQUIDITY MANAGEMENT
- //
-
- /**
- * @dev Adds liquidity to pool
- * - transfers the underlying to the pool
- * - mints Diesel (LP) tokens to onBehalfOf
- * @param amount Amount of tokens to be deposited
- * @param onBehalfOf The address that will receive the dToken
- * @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 a facilitator.
- */
- function addLiquidity(uint256 amount, address onBehalfOf, uint256 referralCode) external;
-
- /**
- * @dev Removes liquidity from pool
- * - burns LP's Diesel (LP) tokens
- * - returns the equivalent amount of underlying to 'to'
- * @param amount Amount of Diesel tokens to burn
- * @param to Address to transfer the underlying to
- */
-
- function removeLiquidity(uint256 amount, address to) external returns (uint256);
-
- /**
- * @dev Lends pool funds to a Credit Account
- * @param borrowedAmount Credit Account's debt principal
- * @param creditAccount Credit Account's address
- */
- function lendCreditAccount(uint256 borrowedAmount, address creditAccount) external;
-
- /**
- * @dev Repays the Credit Account's debt
- * @param borrowedAmount Amount of principal ro repay
- * @param profit The treasury profit from repayment
- * @param loss Amount of underlying that the CA wan't able to repay
- * @notice Assumes that the underlying (including principal + interest + fees)
- * was already transferred
- */
- function repayCreditAccount(uint256 borrowedAmount, uint256 profit, uint256 loss) external;
-
- //
- // GETTERS
- //
-
- /**
- * @dev Returns the total amount of liquidity in the pool, including borrowed and available funds
- */
- function expectedLiquidity() external view returns (uint256);
-
- /**
- * @dev Returns the limit on total liquidity
- */
- function expectedLiquidityLimit() external view returns (uint256);
-
- /**
- * @dev Returns the available liquidity, which is expectedLiquidity - totalBorrowed
- */
- function availableLiquidity() external view returns (uint256);
-
- /**
- * @dev Calculates the current interest index, RAY format
- */
- function calcLinearCumulative_RAY() external view returns (uint256);
-
- /**
- * @dev Calculates the current borrow rate, RAY format
- */
- function borrowAPY_RAY() external view returns (uint256);
-
- /**
- * @dev Returns the total borrowed amount (includes principal only)
- */
- function totalBorrowed() external view returns (uint256);
-
- /**
- * ç
- *
- */
-
- function getDieselRate_RAY() external view returns (uint256);
-
- /**
- * @dev Returns the address of the underlying
- */
- function underlyingToken() external view returns (address);
-
- /**
- * @dev Returns the address of the diesel token
- */
- function dieselToken() external view returns (address);
-
- /**
- * @dev Returns the address of a Credit Manager by its id
- */
- function creditManagers(uint256 id) external view returns (address);
-
- /**
- * @dev Returns the number of known Credit Managers
- */
- function creditManagersCount() external view returns (uint256);
-
- /**
- * @dev Maps Credit Manager addresses to their status as a borrower.
- * Returns false if borrowing is not allowed.
- */
- function creditManagersCanBorrow(address id) external view returns (bool);
-
- /// @dev Converts a quantity of the underlying to Diesel tokens
- function toDiesel(uint256 amount) external view returns (uint256);
-
- /// @dev Converts a quantity of Diesel tokens to the underlying
- function fromDiesel(uint256 amount) external view returns (uint256);
-
- /// @dev Returns the withdrawal fee
- function withdrawFee() external view returns (uint256);
-
- /// @dev Returns the timestamp of the pool's last update
- function _timestampLU() external view returns (uint256);
-
- /// @dev Returns the interest index at the last pool update
- function _cumulativeIndex_RAY() external view returns (uint256);
-
- /// @dev Returns the address provider
- function addressProvider() external view returns (AddressProvider);
-}
diff --git a/contracts/interfaces/IPriceFeedAddress.sol b/contracts/interfaces/IPriceFeedAddress.sol
deleted file mode 100644
index 0d1a0795..00000000
--- a/contracts/interfaces/IPriceFeedAddress.sol
+++ /dev/null
@@ -1,20 +0,0 @@
-// SPDX-License-Identifier: MIT
-pragma solidity ^0.8.0;
-
-interface IPriceFeedAddress {
- /// @dev Returns the number of decimals in the price feed's returned result
- function decimals() external view returns (uint8);
-
- /// @dev Returns the price feed descriptiom
- function description() external view returns (string memory);
-
- /// @dev Returns the price feed version
- function version() external view returns (uint256);
-
- /// @dev Returns the latest price feed value
- /// @notice Return type is according to Chainlink spec
- function latestRoundData(address creditAccount)
- external
- view
- returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
-}
diff --git a/contracts/interfaces/IPriceFeedType.sol b/contracts/interfaces/IPriceFeedType.sol
deleted file mode 100644
index 5c4fd637..00000000
--- a/contracts/interfaces/IPriceFeedType.sol
+++ /dev/null
@@ -1,28 +0,0 @@
-// SPDX-License-Identifier: MIT
-pragma solidity ^0.8.0;
-
-enum PriceFeedType {
- CHAINLINK_ORACLE,
- YEARN_ORACLE,
- CURVE_2LP_ORACLE,
- CURVE_3LP_ORACLE,
- CURVE_4LP_ORACLE,
- CURVE_CRYPTO_ORACLE,
- ZERO_ORACLE,
- WSTETH_ORACLE,
- BOUNDED_ORACLE,
- COMPOSITE_ORACLE,
- BALANCER_WEIGHTED_LP_ORACLE,
- BALANCER_STABLE_LP_ORACLE,
- AAVE_ORACLE,
- EULER_ORACLE,
- COMPOUND_ORACLE
-}
-
-interface IPriceFeedType {
- /// @dev Returns the price feed type
- function priceFeedType() external view returns (PriceFeedType);
-
- /// @dev Returns whether sanity checks on price feed result should be skipped
- function skipPriceCheck() external view returns (bool);
-}
diff --git a/contracts/interfaces/IPriceOracle.sol b/contracts/interfaces/IPriceOracle.sol
deleted file mode 100644
index 5e7aa856..00000000
--- a/contracts/interfaces/IPriceOracle.sol
+++ /dev/null
@@ -1,77 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IVersion} from "./IVersion.sol";
-
-interface IPriceOracleV2Events {
- /// @dev Emits when a new price feed is added
- event NewPriceFeed(address indexed token, address indexed priceFeed);
-}
-
-interface IPriceOracleV2Exceptions {
- /// @dev Thrown if a price feed returns 0
- error ZeroPriceException();
-
- /// @dev Thrown if the last recorded result was not updated in the last round
- error ChainPriceStaleException();
-
- /// @dev Thrown on attempting to get a result for a token that does not have a price feed
- error PriceOracleNotExistsException();
-}
-
-/// @title Price oracle interface
-interface IPriceOracleV2 is IPriceOracleV2Events, IPriceOracleV2Exceptions, IVersion {
- /// @dev Converts a quantity of an asset to USD (decimals = 8).
- /// @param amount Amount to convert
- /// @param token Address of the token to be converted
- function convertToUSD(uint256 amount, address token) external view returns (uint256);
-
- /// @dev Converts a quantity of USD (decimals = 8) to an equivalent amount of an asset
- /// @param amount Amount to convert
- /// @param token Address of the token converted to
- function convertFromUSD(uint256 amount, address token) external view returns (uint256);
-
- /// @dev Converts one asset into another
- ///
- /// @param amount Amount to convert
- /// @param tokenFrom Address of the token to convert from
- /// @param tokenTo Address of the token to convert to
- function convert(uint256 amount, address tokenFrom, address tokenTo) external view returns (uint256);
-
- /// @dev Returns collateral values for two tokens, required for a fast check
- /// @param amountFrom Amount of the outbound token
- /// @param tokenFrom Address of the outbound token
- /// @param amountTo Amount of the inbound token
- /// @param tokenTo Address of the inbound token
- /// @return collateralFrom Value of the outbound token amount in USD
- /// @return collateralTo Value of the inbound token amount in USD
- function fastCheck(uint256 amountFrom, address tokenFrom, uint256 amountTo, address tokenTo)
- external
- view
- returns (uint256 collateralFrom, uint256 collateralTo);
-
- /// @dev Returns token's price in USD (8 decimals)
- /// @param token The token to compute the price for
- function getPrice(address token) external view returns (uint256);
-
- /// @dev Returns the price feed address for the passed token
- /// @param token Token to get the price feed for
- function priceFeeds(address token) external view returns (address priceFeed);
-
- /// @dev Returns the price feed for the passed token,
- /// with additional parameters
- /// @param token Token to get the price feed for
- function priceFeedsWithFlags(address token)
- external
- view
- returns (address priceFeed, bool skipCheck, uint256 decimals);
-}
-
-interface IPriceOracleV2Ext is IPriceOracleV2 {
- /// @dev Sets a price feed if it doesn't exist, or updates an existing one
- /// @param token Address of the token to set the price feed for
- /// @param priceFeed Address of a USD price feed adhering to Chainlink's interface
- function addPriceFeed(address token, address priceFeed) external;
-}
diff --git a/contracts/interfaces/IVersion.sol b/contracts/interfaces/IVersion.sol
deleted file mode 100644
index def71498..00000000
--- a/contracts/interfaces/IVersion.sol
+++ /dev/null
@@ -1,11 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-/// @title IVersion
-/// @dev Declares a version function which returns the contract's version
-interface IVersion {
- /// @dev Returns contract version
- function version() external view returns (uint256);
-}
diff --git a/contracts/interfaces/V1/ICreditFilter.sol b/contracts/interfaces/V1/ICreditFilter.sol
deleted file mode 100644
index 5f43060a..00000000
--- a/contracts/interfaces/V1/ICreditFilter.sol
+++ /dev/null
@@ -1,165 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-interface ICreditFilter {
- /// @dev Emits when a token is allowed or a liquidtion threshold is changed
- event TokenAllowed(address indexed token, uint256 liquidityThreshold);
-
- /// @dev Emits when a token is forbidden
- event TokenForbidden(address indexed token);
-
- /// @dev Emits when a 3rd-party contract / adapter pair is allowed
- event ContractAllowed(address indexed protocol, address indexed adapter);
-
- /// @dev Emits when a 3rd-party contract
- event ContractForbidden(address indexed protocol);
-
- /// @dev Emits when fast check parameters are updated
- event NewFastCheckParameters(uint256 chiThreshold, uint256 fastCheckDelay);
-
- /// @dev Emits when account transfer allowance status is changed between two addresses
- event TransferAccountAllowed(address indexed from, address indexed to, bool state);
-
- /// @dev Emits when a priviledged address that can transfer accounts to anyone, is allowed
- event TransferPluginAllowed(address indexed plugin, bool state);
-
- /// @dev Emits when a new price oracle address is set
- event PriceOracleUpdated(address indexed newPriceOracle);
-
- //
- // STATE-CHANGING FUNCTIONS
- //
-
- /// @dev Adds a token to the list of allowed tokens
- /// @param token Address of allowed token
- /// @param liquidationThreshold A constant determining the maximal allowed ratio of Loan-To-Value for the allowed token.
- function allowToken(address token, uint256 liquidationThreshold) external;
-
- /// @dev Allows an adapter <> 3rd-party contract to be used with the connected Credit Manager
- /// @param targetContract Address of contract to be allowed
- /// @param adapter Adapter contract address
- function allowContract(address targetContract, address adapter) external;
-
- /// @dev Forbids contract and removes it from the list of allowed contracts
- /// @param targetContract Address of allowed contract
- function forbidContract(address targetContract) external;
-
- /// @dev Checks financial order and reverts if tokens aren't in list or collateral protection alerts
- /// @param creditAccount Address of credit account
- /// @param tokenIn Address of token In in swap operation
- /// @param tokenOut Address of token Out in swap operation
- /// @param amountIn Amount of tokens in
- /// @param amountOut Amount of tokens out
- function checkCollateralChange(
- address creditAccount,
- address tokenIn,
- address tokenOut,
- uint256 amountIn,
- uint256 amountOut
- ) external;
-
- function checkMultiTokenCollateral(
- address creditAccount,
- uint256[] memory amountIn,
- uint256[] memory amountOut,
- address[] memory tokenIn,
- address[] memory tokenOut
- ) external;
-
- /// @dev Connects credit managaer, hecks that all needed price feeds exists and finalize config
- function connectCreditManager(address poolService) external;
-
- /// @dev Sets collateral protection for new credit accounts
- function initEnabledTokens(address creditAccount) external;
-
- function checkAndEnableToken(address creditAccount, address token) external;
-
- //
- // GETTERS
- //
-
- /// @dev Returns quantity of contracts in allowed list
- function allowedContractsCount() external view returns (uint256);
-
- /// @dev Returns of contract address from the allowed list by its id
- function allowedContracts(uint256 id) external view returns (address);
-
- /// @dev Reverts if token isn't in token allowed list
- function revertIfTokenNotAllowed(address token) external view;
-
- /// @dev Returns true if token is in allowed list otherwise false
- function isTokenAllowed(address token) external view returns (bool);
-
- /// @dev Returns quantity of tokens in allowed list
- function allowedTokensCount() external view returns (uint256);
-
- /// @dev Returns of token address from allowed list by its id
- function allowedTokens(uint256 id) external view returns (address);
-
- /// @dev Calculates total value for provided address
- /// More: https://dev.gearbox.fi/developers/credit/economy#total-value
- ///
- /// @param creditAccount Token creditAccount address
- function calcTotalValue(address creditAccount) external view returns (uint256 total);
-
- /// @dev Calculates Threshold Weighted Total Value
- /// More: https://dev.gearbox.fi/developers/credit/economy#threshold-weighted-value
- ///
- ///@param creditAccount Credit account address
- function calcThresholdWeightedValue(address creditAccount) external view returns (uint256 total);
-
- function contractToAdapter(address allowedContract) external view returns (address);
-
- /// @dev Returns address of underlying token
- function underlyingToken() external view returns (address);
-
- /// @dev Returns address & balance of token by the id of allowed token in the list
- /// @param creditAccount Credit account address
- /// @param id Id of token in allowed list
- /// @return token Address of token
- /// @return balance Token balance
- function getCreditAccountTokenById(address creditAccount, uint256 id)
- external
- view
- returns (address token, uint256 balance, uint256 tv, uint256 twv);
-
- /**
- * @dev Calculates health factor for the credit account
- *
- * sum(asset[i] * liquidation threshold[i])
- * Hf = --------------------------------------------
- * borrowed amount + interest accrued
- *
- *
- * More info: https://dev.gearbox.fi/developers/credit/economy#health-factor
- *
- * @param creditAccount Credit account address
- * @return Health factor in percents (see PERCENTAGE FACTOR in Constants.sol)
- */
- function calcCreditAccountHealthFactor(address creditAccount) external view returns (uint256);
-
- /// @dev Calculates credit account interest accrued
- /// More: https://dev.gearbox.fi/developers/credit/economy#interest-rate-accrued
- ///
- /// @param creditAccount Credit account address
- function calcCreditAccountAccruedInterest(address creditAccount) external view returns (uint256);
-
- /// @dev Return enabled tokens - token masks where each bit is "1" is token is enabled
- function enabledTokens(address creditAccount) external view returns (uint256);
-
- function liquidationThresholds(address token) external view returns (uint256);
-
- function priceOracle() external view returns (address);
-
- function updateUnderlyingTokenLiquidationThreshold() external;
-
- function revertIfCantIncreaseBorrowing(address creditAccount, uint256 minHealthFactor) external view;
-
- function revertIfAccountTransferIsNotAllowed(address onwer, address creditAccount) external view;
-
- function approveAccountTransfer(address from, bool state) external;
-
- function allowanceForAccountTransfers(address from, address to) external view returns (bool);
-}
diff --git a/contracts/interfaces/V1/ICreditManager.sol b/contracts/interfaces/V1/ICreditManager.sol
deleted file mode 100644
index 50467907..00000000
--- a/contracts/interfaces/V1/ICreditManager.sol
+++ /dev/null
@@ -1,207 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {ICreditFilter} from "./ICreditFilter.sol";
-
-struct Exchange {
- address[] path;
- uint256 amountOutMin;
-}
-
-/// @title Credit Manager interface
-/// @notice It encapsulates business logic for managing credit accounts
-///
-/// More info: https://dev.gearbox.fi/developers/credit/credit_manager
-interface ICreditManager {
- // Emits each time when the credit account is opened
- event OpenCreditAccount(
- address indexed sender,
- address indexed onBehalfOf,
- address indexed creditAccount,
- uint256 amount,
- uint256 borrowAmount,
- uint256 referralCode
- );
-
- // Emits each time when the credit account is closed
- event CloseCreditAccount(address indexed owner, address indexed to, uint256 remainingFunds);
-
- // Emits each time when the credit account is liquidated
- event LiquidateCreditAccount(address indexed owner, address indexed liquidator, uint256 remainingFunds);
-
- // Emits each time when borrower increases borrowed amount
- event IncreaseBorrowedAmount(address indexed borrower, uint256 amount);
-
- // Emits each time when borrower adds collateral
- event AddCollateral(address indexed onBehalfOf, address indexed token, uint256 value);
-
- // Emits each time when the credit account is repaid
- event RepayCreditAccount(address indexed owner, address indexed to);
-
- // Emit each time when financial order is executed
- event ExecuteOrder(address indexed borrower, address indexed target);
-
- // Emits each time when new fees are set
- event NewParameters(
- uint256 minAmount,
- uint256 maxAmount,
- uint256 maxLeverage,
- uint256 feeInterest,
- uint256 feeLiquidation,
- uint256 liquidationDiscount
- );
-
- event TransferAccount(address indexed oldOwner, address indexed newOwner);
-
- //
- // CREDIT ACCOUNT MANAGEMENT
- //
-
- /**
- * @dev Opens credit account and provides credit funds.
- * - Opens credit account (take it from account factory)
- * - Transfers trader /farmers initial funds to credit account
- * - Transfers borrowed leveraged amount from pool (= amount x leverageFactor) calling lendCreditAccount() on connected Pool contract.
- * - Emits OpenCreditAccount event
- * Function reverts if user has already opened position
- *
- * More info: https://dev.gearbox.fi/developers/credit/credit_manager#open-credit-account
- *
- * @param amount Borrowers own funds
- * @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 leverageFactor Multiplier to borrowers own funds
- * @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 openCreditAccount(uint256 amount, address onBehalfOf, uint256 leverageFactor, uint256 referralCode)
- external;
-
- /**
- * @dev Closes credit account
- * - Swaps all assets to underlying one using default swap protocol
- * - Pays borrowed amount + interest accrued + fees back to the pool by calling repayCreditAccount
- * - Transfers remaining funds to the trader / farmer
- * - Closes the credit account and return it to account factory
- * - Emits CloseCreditAccount event
- *
- * More info: https://dev.gearbox.fi/developers/credit/credit_manager#close-credit-account
- *
- * @param to Address to send remaining funds
- * @param paths Exchange type data which provides paths + amountMinOut
- */
- function closeCreditAccount(address to, Exchange[] calldata paths) external;
-
- /**
- * @dev Liquidates credit account
- * - Transfers discounted total credit account value from liquidators account
- * - Pays borrowed funds + interest + fees back to pool, than transfers remaining funds to credit account owner
- * - Transfer all assets from credit account to liquidator ("to") account
- * - Returns credit account to factory
- * - Emits LiquidateCreditAccount event
- *
- * More info: https://dev.gearbox.fi/developers/credit/credit_manager#liquidate-credit-account
- *
- * @param borrower Borrower address
- * @param to Address to transfer all assets from credit account
- * @param force If true, use transfer function for transferring tokens instead of safeTransfer
- */
- function liquidateCreditAccount(address borrower, address to, bool force) external;
-
- /// @dev Repays credit account
- /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#repay-credit-account
- ///
- /// @param to Address to send credit account assets
- function repayCreditAccount(address to) external;
-
- /// @dev Repays credit account with ETH. Restricted to be called by WETH Gateway only
- ///
- /// @param borrower Address of borrower
- /// @param to Address to send credit account assets
- function repayCreditAccountETH(address borrower, address to) external returns (uint256);
-
- /// @dev Increases borrowed amount by transferring additional funds from
- /// the pool if after that HealthFactor > minHealth
- /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrowed-amount
- ///
- /// @param amount Amount to increase borrowed amount
- function increaseBorrowedAmount(uint256 amount) external;
-
- /// @dev Adds collateral to borrower's credit account
- /// @param onBehalfOf Address of borrower to add funds
- /// @param token Token address
- /// @param amount Amount to add
- function addCollateral(address onBehalfOf, address token, uint256 amount) external;
-
- /// @dev Returns true if the borrower has opened a credit account
- /// @param borrower Borrower account
- function hasOpenedCreditAccount(address borrower) external view returns (bool);
-
- /// @dev Calculates Repay amount = borrow amount + interest accrued + fee
- ///
- /// More info: https://dev.gearbox.fi/developers/credit/economy#repay
- /// https://dev.gearbox.fi/developers/credit/economy#liquidate
- ///
- /// @param borrower Borrower address
- /// @param isLiquidated True if calculated repay amount for liquidator
- function calcRepayAmount(address borrower, bool isLiquidated) external view returns (uint256);
-
- /// @dev Returns minimal amount for open credit account
- function minAmount() external view returns (uint256);
-
- /// @dev Returns maximum amount for open credit account
- function maxAmount() external view returns (uint256);
-
- /// @dev Returns maximum leveraged factor allowed for this pool
- function maxLeverageFactor() external view returns (uint256);
-
- /// @dev Returns underlying token address
- function underlyingToken() external view returns (address);
-
- /// @dev Returns address of connected pool
- function poolService() external view returns (address);
-
- /// @dev Returns address of CreditFilter
- function creditFilter() external view returns (ICreditFilter);
-
- /// @dev Returns address of CreditFilter
- function creditAccounts(address borrower) external view returns (address);
-
- /// @dev Executes filtered order on credit account which is connected with particular borrowers
- /// @param borrower Borrower address
- /// @param target Target smart-contract
- /// @param data Call data for call
- function executeOrder(address borrower, address target, bytes memory data) external returns (bytes memory);
-
- /// @dev Approves token for msg.sender's credit account
- function approve(address targetContract, address token) external;
-
- /// @dev Approve tokens for credit accounts. Restricted for adapters only
- function provideCreditAccountAllowance(address creditAccount, address toContract, address token) external;
-
- function transferAccountOwnership(address newOwner) external;
-
- /// @dev Returns address of borrower's credit account and reverts of borrower has no one.
- /// @param borrower Borrower address
- function getCreditAccountOrRevert(address borrower) external view returns (address);
-
- // function feeSuccess() external view returns (uint256);
-
- function feeInterest() external view returns (uint256);
-
- function feeLiquidation() external view returns (uint256);
-
- function liquidationDiscount() external view returns (uint256);
-
- function minHealthFactor() external view returns (uint256);
-
- function defaultSwapContract() external view returns (address);
-
- function _calcClosePayments(address creditAccount, uint256 totalValue, bool isLiquidated)
- external
- view
- returns (uint256 _borrowedAmount, uint256 amountToPool, uint256 remainingFunds, uint256 profit, uint256 loss);
-}
diff --git a/contracts/interfaces/V1/IPriceOracle.sol b/contracts/interfaces/V1/IPriceOracle.sol
deleted file mode 100644
index 913bc6e5..00000000
--- a/contracts/interfaces/V1/IPriceOracle.sol
+++ /dev/null
@@ -1,42 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-pragma abicoder v1;
-
-/// @title Price oracle interface
-interface IPriceOracle {
- // Emits each time new configurator is set up
- event NewPriceFeed(address indexed token, address indexed priceFeed);
-
- /**
- * @dev Sets price feed if it doesn't exists
- * If pricefeed exists, it changes nothing
- * This logic is done to protect Gearbox from priceOracle attack
- * when potential attacker can get access to price oracle, change them to fraud ones
- * and then liquidate all funds
- * @param token Address of token
- * @param priceFeedToken Address of chainlink price feed token => Eth
- */
- function addPriceFeed(address token, address priceFeedToken) external;
-
- /**
- * @dev Converts one asset into another using rate. Reverts if price feed doesn't exist
- *
- * @param amount Amount to convert
- * @param tokenFrom Token address converts from
- * @param tokenTo Token address - converts to
- * @return Amount converted to tokenTo asset
- */
- function convert(uint256 amount, address tokenFrom, address tokenTo) external view returns (uint256);
-
- /**
- * @dev Gets token rate with 18 decimals. Reverts if priceFeed doesn't exist
- *
- * @param tokenFrom Converts from token address
- * @param tokenTo Converts to token address
- * @return Rate in WAD format
- */
- function getLastPrice(address tokenFrom, address tokenTo) external view returns (uint256);
-}
diff --git a/contracts/interfaces/external/IWETH.sol b/contracts/interfaces/external/IWETH.sol
deleted file mode 100644
index 7cca4aa9..00000000
--- a/contracts/interfaces/external/IWETH.sol
+++ /dev/null
@@ -1,14 +0,0 @@
-// SPDX-License-Identifier: MIT
-
-pragma solidity >=0.7.4;
-
-interface IWETH {
- /// @dev Deposits native ETH into the contract and mints WETH
- function deposit() external payable;
-
- /// @dev Transfers WETH to another account
- function transfer(address to, uint256 value) external returns (bool);
-
- /// @dev Burns WETH from msg.sender and send back native ETH
- function withdraw(uint256) external;
-}
diff --git a/contracts/libraries/AddressList.sol b/contracts/libraries/AddressList.sol
deleted file mode 100644
index 4f8df508..00000000
--- a/contracts/libraries/AddressList.sol
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-pragma solidity ^0.8.10;
-
-library AddressList {
- function includes(address[] memory array, address item) internal pure returns (bool) {
- uint256 len = array.length;
-
- for (uint256 i; i < len;) {
- if (array[i] == item) return true;
- unchecked {
- ++i;
- }
- }
-
- return false;
- }
-
- function trim(address[] memory array) internal pure returns (address[] memory trimmed) {
- uint256 len = array.length;
-
- if (len == 0) return array;
-
- uint256 foundLen;
- while (array[foundLen] != address(0)) {
- unchecked {
- ++foundLen;
- if (foundLen == len) return array;
- }
- }
-
- if (foundLen > 0) return copy(array, foundLen);
- }
-
- function copy(address[] memory array, uint256 len) internal pure returns (address[] memory res) {
- res = new address[](len);
- for (uint256 i; i < len;) {
- res[i] = array[i];
- unchecked {
- ++i;
- }
- }
- }
-
- function concat(address[] memory calls1, address[] memory calls2) internal pure returns (address[] memory res) {
- uint256 len1 = calls1.length;
- uint256 lenTotal = len1 + calls2.length;
-
- if (lenTotal == len1) return calls1;
-
- res = new address[](lenTotal);
-
- for (uint256 i; i < lenTotal;) {
- res[i] = (i < len1) ? calls1[i] : calls2[i - len1];
- unchecked {
- ++i;
- }
- }
- }
-
- function append(address[] memory addrs, address newAddr) internal pure returns (address[] memory res) {
- address[] memory newAddrArray = new address[](1);
- newAddrArray[0] = newAddr;
- return concat(addrs, newAddrArray);
- }
-}
diff --git a/contracts/libraries/Balances.sol b/contracts/libraries/Balances.sol
deleted file mode 100644
index b43009bf..00000000
--- a/contracts/libraries/Balances.sol
+++ /dev/null
@@ -1,72 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-struct Balance {
- address token;
- uint256 balance;
-}
-
-library BalanceOps {
- error UnknownToken(address);
-
- function copyBalance(Balance memory b) internal pure returns (Balance memory) {
- return Balance({token: b.token, balance: b.balance});
- }
-
- function addBalance(Balance[] memory b, address token, uint256 amount) internal pure {
- b[getIndex(b, token)].balance += amount;
- }
-
- function subBalance(Balance[] memory b, address token, uint256 amount) internal pure {
- b[getIndex(b, token)].balance -= amount;
- }
-
- function getBalance(Balance[] memory b, address token) internal pure returns (uint256 amount) {
- return b[getIndex(b, token)].balance;
- }
-
- function setBalance(Balance[] memory b, address token, uint256 amount) internal pure {
- b[getIndex(b, token)].balance = amount;
- }
-
- function getIndex(Balance[] memory b, address token) internal pure returns (uint256 index) {
- for (uint256 i; i < b.length;) {
- if (b[i].token == token) {
- return i;
- }
-
- unchecked {
- ++i;
- }
- }
- revert UnknownToken(token);
- }
-
- function copy(Balance[] memory b, uint256 len) internal pure returns (Balance[] memory res) {
- res = new Balance[](len);
- for (uint256 i; i < len;) {
- res[i] = copyBalance(b[i]);
- unchecked {
- ++i;
- }
- }
- }
-
- function clone(Balance[] memory b) internal pure returns (Balance[] memory) {
- return copy(b, b.length);
- }
-
- function getModifiedAfterSwap(
- Balance[] memory b,
- address tokenFrom,
- uint256 amountFrom,
- address tokenTo,
- uint256 amountTo
- ) internal pure returns (Balance[] memory res) {
- res = copy(b, b.length);
- setBalance(res, tokenFrom, getBalance(b, tokenFrom) - amountFrom);
- setBalance(res, tokenTo, getBalance(b, tokenTo) + amountTo);
- }
-}
diff --git a/contracts/libraries/Constants.sol b/contracts/libraries/Constants.sol
deleted file mode 100644
index 7b8b9328..00000000
--- a/contracts/libraries/Constants.sol
+++ /dev/null
@@ -1,48 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-// Denominations
-
-uint256 constant WAD = 1e18;
-uint256 constant RAY = 1e27;
-uint16 constant PERCENTAGE_FACTOR = 1e4;
-
-// 25% of type(uint256).max
-uint256 constant ALLOWANCE_THRESHOLD = type(uint96).max >> 3;
-
-// FEE = 50%
-uint16 constant DEFAULT_FEE_INTEREST = 50_00; // 50%
-
-// LIQUIDATION_FEE 1.5%
-uint16 constant DEFAULT_FEE_LIQUIDATION = 1_50; // 1.5%
-
-// LIQUIDATION PREMIUM 4%
-uint16 constant DEFAULT_LIQUIDATION_PREMIUM = 4_00; // 4%
-
-// LIQUIDATION_FEE_EXPIRED 2%
-uint16 constant DEFAULT_FEE_LIQUIDATION_EXPIRED = 1_00; // 2%
-
-// LIQUIDATION PREMIUM EXPIRED 2%
-uint16 constant DEFAULT_LIQUIDATION_PREMIUM_EXPIRED = 2_00; // 2%
-
-// DEFAULT PROPORTION OF MAX BORROWED PER BLOCK TO MAX BORROWED PER ACCOUNT
-uint16 constant DEFAULT_LIMIT_PER_BLOCK_MULTIPLIER = 2;
-
-// Seconds in a year
-uint256 constant SECONDS_PER_YEAR = 365 days;
-uint256 constant SECONDS_PER_ONE_AND_HALF_YEAR = (SECONDS_PER_YEAR * 3) / 2;
-
-// OPERATIONS
-
-// Leverage decimals - 100 is equal to 2x leverage (100% * collateral amount + 100% * borrowed amount)
-uint8 constant LEVERAGE_DECIMALS = 100;
-
-// Maximum withdraw fee for pool in PERCENTAGE_FACTOR format
-uint8 constant MAX_WITHDRAW_FEE = 100;
-
-uint256 constant EXACT_INPUT = 1;
-uint256 constant EXACT_OUTPUT = 2;
-
-address constant UNIVERSAL_CONTRACT = 0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC;
diff --git a/contracts/libraries/Errors.sol b/contracts/libraries/Errors.sol
deleted file mode 100644
index 52b0e52e..00000000
--- a/contracts/libraries/Errors.sol
+++ /dev/null
@@ -1,80 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-/// @title Errors library
-library Errors {
- //
- // COMMON
- //
- string public constant ZERO_ADDRESS_IS_NOT_ALLOWED = "Z0";
- string public constant NOT_IMPLEMENTED = "NI";
- string public constant INCORRECT_PATH_LENGTH = "PL";
- string public constant INCORRECT_ARRAY_LENGTH = "CR";
- string public constant REGISTERED_CREDIT_ACCOUNT_MANAGERS_ONLY = "CP";
- string public constant REGISTERED_POOLS_ONLY = "RP";
- string public constant INCORRECT_PARAMETER = "IP";
-
- //
- // MATH
- //
- string public constant MATH_MULTIPLICATION_OVERFLOW = "M1";
- string public constant MATH_ADDITION_OVERFLOW = "M2";
- string public constant MATH_DIVISION_BY_ZERO = "M3";
-
- //
- // POOL
- //
- string public constant POOL_CONNECTED_CREDIT_MANAGERS_ONLY = "PS0";
- string public constant POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER = "PS1";
- string public constant POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT = "PS2";
- string public constant POOL_INCORRECT_WITHDRAW_FEE = "PS3";
- string public constant POOL_CANT_ADD_CREDIT_MANAGER_TWICE = "PS4";
-
- //
- // ACCOUNT FACTORY
- //
- string public constant AF_CANT_CLOSE_CREDIT_ACCOUNT_IN_THE_SAME_BLOCK = "AF1";
- string public constant AF_MINING_IS_FINISHED = "AF2";
- string public constant AF_CREDIT_ACCOUNT_NOT_IN_STOCK = "AF3";
- string public constant AF_EXTERNAL_ACCOUNTS_ARE_FORBIDDEN = "AF4";
-
- //
- // ADDRESS PROVIDER
- //
- string public constant AS_ADDRESS_NOT_FOUND = "AP1";
-
- //
- // CONTRACTS REGISTER
- //
- string public constant CR_POOL_ALREADY_ADDED = "CR1";
- string public constant CR_CREDIT_MANAGER_ALREADY_ADDED = "CR2";
-
- //
- // CREDIT ACCOUNT
- //
- string public constant CA_CONNECTED_CREDIT_MANAGER_ONLY = "CA1";
- string public constant CA_FACTORY_ONLY = "CA2";
-
- //
- // ACL
- //
- string public constant ACL_CALLER_NOT_PAUSABLE_ADMIN = "ACL1";
- string public constant ACL_CALLER_NOT_CONFIGURATOR = "ACL2";
-
- //
- // WETH GATEWAY
- //
- string public constant WG_DESTINATION_IS_NOT_WETH_COMPATIBLE = "WG1";
- string public constant WG_RECEIVE_IS_NOT_ALLOWED = "WG2";
- string public constant WG_NOT_ENOUGH_FUNDS = "WG3";
-
- //
- // TOKEN DISTRIBUTOR
- //
- string public constant TD_WALLET_IS_ALREADY_CONNECTED_TO_VC = "TD1";
- string public constant TD_INCORRECT_WEIGHTS = "TD2";
- string public constant TD_NON_ZERO_BALANCE_AFTER_DISTRIBUTION = "TD3";
- string public constant TD_CONTRIBUTOR_IS_NOT_REGISTERED = "TD4";
-}
diff --git a/contracts/libraries/LICENSE AGPL 3.0 b/contracts/libraries/LICENSE AGPL 3.0
deleted file mode 100644
index 76f48362..00000000
--- a/contracts/libraries/LICENSE AGPL 3.0
+++ /dev/null
@@ -1,144 +0,0 @@
-GNU AFFERO GENERAL PUBLIC LICENSE
-Version 3, 19 November 2007
-Copyright © 2007 Free Software Foundation, Inc.
-Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
-
-Preamble
-
-The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
-The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
-When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
-Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
-A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
-The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
-An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
-The precise terms and conditions for copying, distribution and modification follow.
-
-TERMS AND CONDITIONS
-0. Definitions.
-
-"This License" refers to version 3 of the GNU Affero General Public License.
-"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
-"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
-To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
-A "covered work" means either the unmodified Program or a work based on the Program.
-To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
-To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
-An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
-
-1. Source Code.
-
-The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
-A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
-The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
-The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
-The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
-The Corresponding Source for a work in source code form is that same work.
-
-2. Basic Permissions.
-
-All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
-You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
-Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
-
-3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
-No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
-When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
-
-4. Conveying Verbatim Copies.
-
-You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
-You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
-
-5. Conveying Modified Source Versions.
-
-You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
-a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
-b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
-c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
-d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
-A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
-
-6. Conveying Non-Source Forms.
-
-You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
-a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
-b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
-c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
-d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
-e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
-A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
-A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
-"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
-If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
-The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
-Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
-
-7. Additional Terms.
-
-"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
-When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
-Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
-a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
-b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
-c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
-d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
-e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
-f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
-All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
-If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
-Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
-
-8. Termination.
-
-You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
-However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
-Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
-Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
-
-9. Acceptance Not Required for Having Copies.
-
-You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
-10. Automatic Licensing of Downstream Recipients.
-Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
-An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
-You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
-
-11. Patents.
-
-A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
-A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
-Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
-In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
-If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
-If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
-A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
-Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
-
-12. No Surrender of Others' Freedom.
-
-If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
-13. Remote Network Interaction; Use with the GNU General Public License.
-Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
-Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
-14. Revised Versions of this License.
-The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
-Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
-If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
-Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
-
-15. Disclaimer of Warranty.
-
-THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-16. Limitation of Liability.
-
-IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-17. Interpretation of Sections 15 and 16.
-
-If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
-
-END OF TERMS AND CONDITIONS
-
diff --git a/contracts/libraries/LICENSE GPL 2.0 b/contracts/libraries/LICENSE GPL 2.0
deleted file mode 100644
index ecbc0593..00000000
--- a/contracts/libraries/LICENSE GPL 2.0
+++ /dev/null
@@ -1,339 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along
- with this program; if not, write to the Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- , 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
\ No newline at end of file
diff --git a/contracts/libraries/MultiCall.sol b/contracts/libraries/MultiCall.sol
deleted file mode 100644
index c8343ece..00000000
--- a/contracts/libraries/MultiCall.sol
+++ /dev/null
@@ -1,97 +0,0 @@
-// SPDX-License-Identifier: MIT
-pragma solidity ^0.8.10;
-
-struct MultiCall {
- address target;
- bytes callData;
-}
-
-library MultiCallOps {
- function copyMulticall(MultiCall memory call) internal pure returns (MultiCall memory) {
- return MultiCall({target: call.target, callData: call.callData});
- }
-
- function trim(MultiCall[] memory calls) internal pure returns (MultiCall[] memory trimmed) {
- uint256 len = calls.length;
-
- if (len == 0) return calls;
-
- uint256 foundLen;
- while (calls[foundLen].target != address(0)) {
- unchecked {
- ++foundLen;
- if (foundLen == len) return calls;
- }
- }
-
- if (foundLen > 0) return copy(calls, foundLen);
- }
-
- function copy(MultiCall[] memory calls, uint256 len) internal pure returns (MultiCall[] memory res) {
- res = new MultiCall[](len);
- for (uint256 i; i < len;) {
- res[i] = copyMulticall(calls[i]);
- unchecked {
- ++i;
- }
- }
- }
-
- function clone(MultiCall[] memory calls) internal pure returns (MultiCall[] memory res) {
- return copy(calls, calls.length);
- }
-
- function append(MultiCall[] memory calls, MultiCall memory newCall)
- internal
- pure
- returns (MultiCall[] memory res)
- {
- uint256 len = calls.length;
- res = new MultiCall[](len + 1);
- for (uint256 i; i < len;) {
- res[i] = copyMulticall(calls[i]);
- unchecked {
- ++i;
- }
- }
- res[len] = copyMulticall(newCall);
- }
-
- function prepend(MultiCall[] memory calls, MultiCall memory newCall)
- internal
- pure
- returns (MultiCall[] memory res)
- {
- uint256 len = calls.length;
- res = new MultiCall[](len + 1);
- res[0] = copyMulticall(newCall);
-
- for (uint256 i = 1; i < len + 1;) {
- res[i] = copyMulticall(calls[i]);
- unchecked {
- ++i;
- }
- }
- }
-
- function concat(MultiCall[] memory calls1, MultiCall[] memory calls2)
- internal
- pure
- returns (MultiCall[] memory res)
- {
- uint256 len1 = calls1.length;
- uint256 lenTotal = len1 + calls2.length;
-
- if (lenTotal == calls1.length) return clone(calls1);
- if (lenTotal == calls2.length) return clone(calls2);
-
- res = new MultiCall[](lenTotal);
-
- for (uint256 i; i < lenTotal;) {
- res[i] = (i < len1) ? copyMulticall(calls1[i]) : copyMulticall(calls2[i - len1]);
- unchecked {
- ++i;
- }
- }
- }
-}
diff --git a/contracts/libraries/Types.sol b/contracts/libraries/Types.sol
deleted file mode 100644
index 60711f98..00000000
--- a/contracts/libraries/Types.sol
+++ /dev/null
@@ -1,118 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-/// @title DataType library
-
-struct Exchange {
- address[] path;
- uint256 amountOutMin;
-}
-
-struct TokenBalance {
- address token;
- uint256 balance;
- bool isAllowed;
- bool isEnabled;
-}
-
-struct ContractAdapter {
- address allowedContract;
- address adapter;
-}
-
-struct CreditAccountData {
- address addr;
- address borrower;
- bool inUse;
- address creditManager;
- address underlying;
- uint256 borrowedAmountPlusInterest;
- uint256 borrowedAmountPlusInterestAndFees;
- uint256 totalValue;
- uint256 healthFactor;
- uint256 borrowRate;
- TokenBalance[] balances;
- uint256 repayAmount; // for v1 accounts only
- uint256 liquidationAmount; // for v1 accounts only
- bool canBeClosed; // for v1 accounts only
- uint256 borrowedAmount;
- uint256 cumulativeIndexAtOpen;
- uint256 since;
- uint8 version;
- uint256 enabledTokenMask;
-}
-
-struct CreditManagerData {
- address addr;
- address underlying;
- address pool;
- bool isWETH;
- bool canBorrow;
- uint256 borrowRate;
- uint256 minAmount;
- uint256 maxAmount;
- uint256 maxLeverageFactor; // for V1 only
- uint256 availableLiquidity;
- address[] collateralTokens;
- ContractAdapter[] adapters;
- uint256[] liquidationThresholds;
- uint8 version;
- address creditFacade; // V2 only: address of creditFacade
- address creditConfigurator; // V2 only: address of creditConfigurator
- bool isDegenMode; // V2 only: true if contract is in Degen mode
- address degenNFT; // V2 only: degenNFT, address(0) if not in degen mode
- bool isIncreaseDebtForbidden; // V2 only: true if increasing debt is forbidden
- uint256 forbiddenTokenMask; // V2 only: mask which forbids some particular tokens
- uint8 maxEnabledTokensLength; // V2 only: in V1 as many tokens as the CM can support (256)
- uint16 feeInterest; // Interest fee protocol charges: fee = interest accrues * feeInterest
- uint16 feeLiquidation; // Liquidation fee protocol charges: fee = totalValue * feeLiquidation
- uint16 liquidationDiscount; // Miltiplier to get amount which liquidator should pay: amount = totalValue * liquidationDiscount
- uint16 feeLiquidationExpired; // Liquidation fee protocol charges on expired accounts
- uint16 liquidationDiscountExpired; // Multiplier for the amount the liquidator has to pay when closing an expired account
-}
-
-struct PoolData {
- address addr;
- bool isWETH;
- address underlying;
- address dieselToken;
- uint256 linearCumulativeIndex;
- uint256 availableLiquidity;
- uint256 expectedLiquidity;
- uint256 expectedLiquidityLimit;
- uint256 totalBorrowed;
- uint256 depositAPY_RAY;
- uint256 borrowAPY_RAY;
- uint256 dieselRate_RAY;
- uint256 withdrawFee;
- uint256 cumulativeIndex_RAY;
- uint256 timestampLU;
- uint8 version;
-}
-
-struct TokenInfo {
- address addr;
- string symbol;
- uint8 decimals;
-}
-
-struct AddressProviderData {
- address contractRegister;
- address acl;
- address priceOracle;
- address traderAccountFactory;
- address dataCompressor;
- address farmingFactory;
- address accountMiner;
- address treasuryContract;
- address gearToken;
- address wethToken;
- address wethGateway;
-}
-
-struct MiningApproval {
- address token;
- address swapContract;
-}
diff --git a/contracts/libraries/USDT_Transfer.sol b/contracts/libraries/USDT_Transfer.sol
index df954e00..7fe7d404 100644
--- a/contracts/libraries/USDT_Transfer.sol
+++ b/contracts/libraries/USDT_Transfer.sol
@@ -6,9 +6,7 @@ pragma solidity ^0.8.10;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IUSDT} from "../interfaces/external/IUSDT.sol";
-import {PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
-
-import "forge-std/console.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
contract USDT_Transfer {
using SafeERC20 for IERC20;
diff --git a/contracts/multicall/CreditFacadeCalls.sol b/contracts/multicall/CreditFacadeCalls.sol
deleted file mode 100644
index 412151fd..00000000
--- a/contracts/multicall/CreditFacadeCalls.sol
+++ /dev/null
@@ -1,101 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.17;
-
-import {MultiCall} from "../libraries/MultiCall.sol";
-import {Balance, BalanceOps} from "../libraries/Balances.sol";
-import {QuotaUpdate} from "../interfaces/IPoolQuotaKeeper.sol";
-import {ICreditFacade, ICreditFacadeExtended} from "../interfaces/ICreditFacade.sol";
-
-interface CreditFacadeMulticaller {}
-
-library CreditFacadeCalls {
- function revertIfReceivedLessThan(CreditFacadeMulticaller creditFacade, Balance[] memory expectedBalances)
- internal
- pure
- returns (MultiCall memory)
- {
- return MultiCall({
- target: address(creditFacade),
- callData: abi.encodeCall(ICreditFacadeExtended.revertIfReceivedLessThan, (expectedBalances))
- });
- }
-
- function addCollateral(CreditFacadeMulticaller creditFacade, address borrower, address token, uint256 amount)
- internal
- pure
- returns (MultiCall memory)
- {
- return MultiCall({
- target: address(creditFacade),
- callData: abi.encodeCall(ICreditFacade.addCollateral, (borrower, token, amount))
- });
- }
-
- function increaseDebt(CreditFacadeMulticaller creditFacade, uint256 amount)
- internal
- pure
- returns (MultiCall memory)
- {
- return MultiCall({
- target: address(creditFacade),
- callData: abi.encodeCall(ICreditFacadeExtended.increaseDebt, (amount))
- });
- }
-
- function decreaseDebt(CreditFacadeMulticaller creditFacade, uint256 amount)
- internal
- pure
- returns (MultiCall memory)
- {
- return MultiCall({
- target: address(creditFacade),
- callData: abi.encodeCall(ICreditFacadeExtended.decreaseDebt, (amount))
- });
- }
-
- function enableToken(CreditFacadeMulticaller creditFacade, address token)
- internal
- pure
- returns (MultiCall memory)
- {
- return MultiCall({
- target: address(creditFacade),
- callData: abi.encodeCall(ICreditFacadeExtended.enableToken, (token))
- });
- }
-
- function disableToken(CreditFacadeMulticaller creditFacade, address token)
- internal
- pure
- returns (MultiCall memory)
- {
- return MultiCall({
- target: address(creditFacade),
- callData: abi.encodeCall(ICreditFacadeExtended.disableToken, (token))
- });
- }
-
- function updateQuotas(CreditFacadeMulticaller creditFacade, QuotaUpdate[] memory quotaUpdates)
- internal
- pure
- returns (MultiCall memory)
- {
- return MultiCall({
- target: address(creditFacade),
- callData: abi.encodeCall(ICreditFacadeExtended.updateQuotas, quotaUpdates)
- });
- }
-
- function setFullCheckParams(
- CreditFacadeMulticaller creditFacade,
- uint256[] memory collateralHints,
- uint16 minHealthFactor
- ) internal pure returns (MultiCall memory) {
- return MultiCall({
- target: address(creditFacade),
- callData: abi.encodeCall(ICreditFacadeExtended.setFullCheckParams, (collateralHints, minHealthFactor))
- });
- }
-}
diff --git a/contracts/oracles/BoundedPriceFeed.sol b/contracts/oracles/BoundedPriceFeed.sol
deleted file mode 100644
index 00677585..00000000
--- a/contracts/oracles/BoundedPriceFeed.sol
+++ /dev/null
@@ -1,103 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
-import {AggregatorV2V3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol";
-import {PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
-import {PriceFeedType, IPriceFeedType} from "../interfaces/IPriceFeedType.sol";
-
-// EXCEPTIONS
-import {NotImplementedException} from "../interfaces/IErrors.sol";
-
-interface ChainlinkReadableAggregator {
- function aggregator() external view returns (address);
-
- function phaseAggregators(uint16 idx) external view returns (AggregatorV2V3Interface);
-
- function phaseId() external view returns (uint16);
-}
-
-/// @title Price feed with an upper bound on price
-/// @notice Used to limit prices on assets that should not rise above
-/// a certain level, such as stablecoins and other pegged assets
-contract BoundedPriceFeed is ChainlinkReadableAggregator, AggregatorV3Interface, IPriceFeedType {
- /// @dev Chainlink price feed for the Vault's underlying
- AggregatorV3Interface public immutable priceFeed;
-
- /// @dev The upper bound on Chainlink price for the asset
- int256 public immutable upperBound;
-
- /// @dev Decimals of the returned result.
- uint8 public immutable override decimals;
-
- /// @dev Price feed description
- string public override description;
-
- uint256 public constant override version = 1;
-
- PriceFeedType public constant override priceFeedType = PriceFeedType.BOUNDED_ORACLE;
-
- bool public constant override skipPriceCheck = false;
-
- /// @dev Constructor
- /// @param _priceFeed Chainlink price feed to receive results from
- /// @param _upperBound Initial upper bound for the Chainlink price
- constructor(address _priceFeed, int256 _upperBound) {
- priceFeed = AggregatorV3Interface(_priceFeed);
- description = string(abi.encodePacked(priceFeed.description(), " Bounded"));
- decimals = priceFeed.decimals();
- upperBound = _upperBound;
- }
-
- /// @dev Implemented for compatibility, but reverts since Gearbox's price feeds
- /// do not store historical data.
- function getRoundData(uint80)
- external
- pure
- virtual
- override
- returns (
- uint80, // roundId,
- int256, // answer,
- uint256, // startedAt,
- uint256, // updatedAt,
- uint80 // answeredInRound
- )
- {
- revert NotImplementedException(); // F:[LPF-2]
- }
-
- /// @dev Returns the value if it is below the upper bound, otherwise returns the upper bound
- /// @param value Value to be checked and bounded
- function _upperBoundValue(int256 value) internal view returns (int256) {
- return (value > upperBound) ? upperBound : value;
- }
-
- /// @dev Returns the upper-bounded USD price of the token
- function latestRoundData()
- external
- view
- override
- returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
- {
- (roundId, answer, startedAt, updatedAt, answeredInRound) = priceFeed.latestRoundData(); // F:[OYPF-4]
-
- answer = _upperBoundValue(answer);
- }
-
- /// @dev Returns the current phase's aggregator address
- function aggregator() external view returns (address) {
- return ChainlinkReadableAggregator(address(priceFeed)).aggregator();
- }
-
- /// @dev Returns a phase aggregator by index
- function phaseAggregators(uint16 idx) external view returns (AggregatorV2V3Interface) {
- return ChainlinkReadableAggregator(address(priceFeed)).phaseAggregators(idx);
- }
-
- function phaseId() external view returns (uint16) {
- return ChainlinkReadableAggregator(address(priceFeed)).phaseId();
- }
-}
diff --git a/contracts/oracles/CompositePriceFeed.sol b/contracts/oracles/CompositePriceFeed.sol
deleted file mode 100644
index be27a565..00000000
--- a/contracts/oracles/CompositePriceFeed.sol
+++ /dev/null
@@ -1,86 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
-import {PriceFeedChecker} from "./PriceFeedChecker.sol";
-import {PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
-import {PriceFeedType, IPriceFeedType} from "../interfaces/IPriceFeedType.sol";
-
-// EXCEPTIONS
-import {NotImplementedException} from "../interfaces/IErrors.sol";
-
-/// @title Price feed that composes an base asset-denominated price feed with a USD one
-/// @notice Used for better price tracking for correlated assets (such as stETH or WBTC) or on networks where
-/// only feeds for the native tokens exist
-contract CompositePriceFeed is PriceFeedChecker, AggregatorV3Interface, IPriceFeedType {
- /// @dev Chainlink base asset price feed for the target asset
- AggregatorV3Interface public immutable targetToBasePriceFeed;
-
- /// @dev Chainlink Base asset / USD price feed
- AggregatorV3Interface public immutable baseToUsdPriceFeed;
-
- /// @dev Decimals of the returned result.
- uint8 public immutable override decimals;
-
- /// @dev 10 ^ Decimals of Target / Base price feed, to divide the product of answers
- int256 public immutable answerDenominator;
-
- /// @dev Price feed description
- string public override description;
-
- uint256 public constant override version = 1;
-
- PriceFeedType public constant override priceFeedType = PriceFeedType.COMPOSITE_ORACLE;
-
- bool public constant override skipPriceCheck = true;
-
- /// @dev Constructor
- /// @param _targetToBasePriceFeed Base asset price feed for target asset
- /// @param _baseToUsdPriceFeed USD price feed for base asset
- constructor(address _targetToBasePriceFeed, address _baseToUsdPriceFeed) {
- targetToBasePriceFeed = AggregatorV3Interface(_targetToBasePriceFeed);
- baseToUsdPriceFeed = AggregatorV3Interface(_baseToUsdPriceFeed);
- description = string(abi.encodePacked(targetToBasePriceFeed.description(), " to USD Composite"));
- decimals = baseToUsdPriceFeed.decimals();
- answerDenominator = int256(10 ** targetToBasePriceFeed.decimals());
- }
-
- /// @dev Implemented for compatibility, but reverts since Gearbox's price feeds
- /// do not store historical data.
- function getRoundData(uint80)
- external
- pure
- virtual
- override
- returns (
- uint80, // roundId,
- int256, // answer,
- uint256, // startedAt,
- uint256, // updatedAt,
- uint80 // answeredInRound
- )
- {
- revert NotImplementedException();
- }
-
- /// @dev Returns the composite USD-denominated price of the asset, computed as (Target / base rate * base / USD rate)
- function latestRoundData()
- external
- view
- override
- returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
- {
- (uint80 roundId0, int256 answer0, uint256 startedAt0, uint256 updatedAt0, uint80 answeredInRound0) =
- targetToBasePriceFeed.latestRoundData();
-
- _checkAnswer(roundId0, answer0, updatedAt0, answeredInRound0);
-
- (roundId, answer, startedAt, updatedAt, answeredInRound) = baseToUsdPriceFeed.latestRoundData();
-
- _checkAnswer(roundId, answer, updatedAt, answeredInRound);
-
- answer = (answer0 * answer) / answerDenominator;
- }
-}
diff --git a/contracts/oracles/LPPriceFeed.sol b/contracts/oracles/LPPriceFeed.sol
deleted file mode 100644
index c680ebaa..00000000
--- a/contracts/oracles/LPPriceFeed.sol
+++ /dev/null
@@ -1,107 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {ILPPriceFeed} from "../interfaces/ILPPriceFeed.sol";
-import {PriceFeedChecker} from "./PriceFeedChecker.sol";
-import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
-import {PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
-
-// EXCEPTIONS
-import {NotImplementedException} from "../interfaces/IErrors.sol";
-
-/// @title Abstract PriceFeed for an LP token
-/// @notice For most pools/vaults, the LP token price depends on Chainlink prices of pool assets and the pool's
-/// internal exchange rate.
-abstract contract LPPriceFeed is ILPPriceFeed, PriceFeedChecker, ACLNonReentrantTrait {
- /// @dev The lower bound for the contract's token-to-underlying exchange rate.
- /// @notice Used to protect against LP token / share price manipulation.
- uint256 public lowerBound;
-
- /// @dev Window size in PERCENTAGE format. Upper bound = lowerBound * (1 + delta)
- uint256 public immutable delta;
-
- /// @dev Decimals of the returned result.
- uint8 public constant override decimals = 8;
-
- /// @dev Price feed description
- string public override description;
-
- /// @dev Constructor
- /// @param addressProvider Address of address provier which is use for getting ACL
- /// @param _delta Pre-defined window in PERCENTAGE FORMAT which is allowed for SC value
- /// @param _description Price feed description
- constructor(address addressProvider, uint256 _delta, string memory _description)
- ACLNonReentrantTrait(addressProvider)
- {
- description = _description; // F:[LPF-1]
- delta = _delta; // F:[LPF-1]
- }
-
- /// @dev Implemented for compatibility, but reverts since Gearbox's price feeds
- /// do not store historical data.
- function getRoundData(uint80)
- external
- pure
- virtual
- override
- returns (
- uint80, // roundId,
- int256, // answer,
- uint256, // startedAt,
- uint256, // updatedAt,
- uint80 // answeredInRound
- )
- {
- revert NotImplementedException(); // F:[LPF-2]
- }
-
- /// @dev Checks that value is in range [lowerBound; upperBound],
- /// Reverts if below lowerBound and returns min(value, upperBound)
- /// @param value Value to be checked and bounded
- function _checkAndUpperBoundValue(uint256 value) internal view returns (uint256) {
- uint256 lb = lowerBound;
- if (value < lb) revert ValueOutOfRangeException(); // F:[LPF-3]
-
- uint256 uBound = _upperBound(lb);
-
- return (value > uBound) ? uBound : value;
- }
-
- /// @dev Updates the bounds for the exchange rate value
- /// @param _lowerBound The new lower bound (the upper bound is computed dynamically)
- /// from the lower bound
- function setLimiter(uint256 _lowerBound)
- external
- override
- configuratorOnly // F:[LPF-4]
- {
- _setLimiter(_lowerBound); // F:[LPF-4,5]
- }
-
- /// @dev IMPLEMENTATION: setLimiter
- function _setLimiter(uint256 _lowerBound) internal {
- if (_lowerBound == 0 || !_checkCurrentValueInBounds(_lowerBound, _upperBound(_lowerBound))) {
- revert IncorrectLimitsException();
- } // F:[LPF-4]
-
- lowerBound = _lowerBound; // F:[LPF-5]
- emit NewLimiterParams(lowerBound, _upperBound(_lowerBound)); // F:[LPF-5]
- }
-
- function _upperBound(uint256 lb) internal view returns (uint256) {
- return (lb * (PERCENTAGE_FACTOR + delta)) / PERCENTAGE_FACTOR; // F:[LPF-5]
- }
-
- /// @dev Returns the upper bound, calculated based on the lower bound
- function upperBound() external view returns (uint256) {
- return _upperBound(lowerBound); // F:[LPF-5]
- }
-
- function _checkCurrentValueInBounds(uint256 _lowerBound, uint256 _upperBound)
- internal
- view
- virtual
- returns (bool);
-}
diff --git a/contracts/oracles/PriceFeedChecker.sol b/contracts/oracles/PriceFeedChecker.sol
deleted file mode 100644
index a684028f..00000000
--- a/contracts/oracles/PriceFeedChecker.sol
+++ /dev/null
@@ -1,16 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IPriceOracleV2Exceptions} from "../interfaces/IPriceOracle.sol";
-
-/// @title Sanity checker for Chainlink price feed results
-contract PriceFeedChecker is IPriceOracleV2Exceptions {
- function _checkAnswer(uint80 roundID, int256 price, uint256 updatedAt, uint80 answeredInRound) internal pure {
- if (price <= 0) revert ZeroPriceException(); // F:[PO-5]
- if (answeredInRound < roundID || updatedAt == 0) {
- revert ChainPriceStaleException();
- } // F:[PO-5]
- }
-}
diff --git a/contracts/oracles/PriceOracle.sol b/contracts/oracles/PriceOracle.sol
deleted file mode 100644
index 9a8e22ba..00000000
--- a/contracts/oracles/PriceOracle.sol
+++ /dev/null
@@ -1,214 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
-import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
-import {Address} from "@openzeppelin/contracts/utils/Address.sol";
-
-import {IPriceFeedType} from "../interfaces/IPriceFeedType.sol";
-import {PriceFeedChecker} from "./PriceFeedChecker.sol";
-import {IPriceOracleV2} from "../interfaces/IPriceOracle.sol";
-import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
-
-// CONSTANTS
-
-// EXCEPTIONS
-import {
- ZeroAddressException,
- AddressIsNotContractException,
- IncorrectPriceFeedException,
- IncorrectTokenContractException
-} from "../interfaces/IErrors.sol";
-
-struct PriceFeedConfig {
- address token;
- address priceFeed;
-}
-
-uint256 constant SKIP_PRICE_CHECK_FLAG = 1 << 161;
-uint256 constant DECIMALS_SHIFT = 162;
-
-/// @title Price Oracle based on Chainlink's price feeds
-/// @notice Works as router and provide cross rates using converting via USD
-contract PriceOracle is ACLNonReentrantTrait, IPriceOracleV2, PriceFeedChecker {
- using Address for address;
-
- /// @dev Map of token addresses to corresponding price feeds and their parameters,
- /// encoded into a single uint256
- mapping(address => uint256) internal _priceFeeds;
-
- // Contract version
- uint256 public constant version = 2;
-
- constructor(address addressProvider, PriceFeedConfig[] memory defaults) ACLNonReentrantTrait(addressProvider) {
- uint256 len = defaults.length;
- for (uint256 i = 0; i < len;) {
- _addPriceFeed(defaults[i].token, defaults[i].priceFeed); // F:[PO-1]
-
- unchecked {
- ++i;
- }
- }
- }
-
- /// @dev Sets a price feed if it doesn't exist, or updates an existing one
- /// @param token Address of the token to set the price feed for
- /// @param priceFeed Address of a USD price feed adhering to Chainlink's interface
- function addPriceFeed(address token, address priceFeed) external configuratorOnly {
- _addPriceFeed(token, priceFeed);
- }
-
- /// @dev IMPLEMENTATION: addPriceFeed
- /// @param token Address of the token to set the price feed for
- /// @param priceFeed Address of a USD price feed adhering to Chainlink's interface
- function _addPriceFeed(address token, address priceFeed) internal {
- if (token == address(0) || priceFeed == address(0)) {
- revert ZeroAddressException();
- } // F:[PO-2]
-
- if (!token.isContract()) revert AddressIsNotContractException(token); // F:[PO-2]
-
- if (!priceFeed.isContract()) {
- revert AddressIsNotContractException(priceFeed);
- } // F:[PO-2]
-
- try AggregatorV3Interface(priceFeed).decimals() returns (uint8 _decimals) {
- if (_decimals != 8) revert IncorrectPriceFeedException(); // F:[PO-2]
- } catch {
- revert IncorrectPriceFeedException(); // F:[PO-2]
- }
-
- bool skipCheck;
-
- try IPriceFeedType(priceFeed).skipPriceCheck() returns (bool property) {
- skipCheck = property; // F:[PO-2]
- } catch {}
-
- uint8 decimals;
- try ERC20(token).decimals() returns (uint8 _decimals) {
- if (_decimals > 18) revert IncorrectTokenContractException(); // F:[PO-2]
-
- decimals = _decimals; // F:[PO-3]
- } catch {
- revert IncorrectTokenContractException(); // F:[PO-2]
- }
-
- try AggregatorV3Interface(priceFeed).latestRoundData() returns (
- uint80 roundID, int256 price, uint256, uint256 updatedAt, uint80 answeredInRound
- ) {
- // Checks result if skipCheck is not set
- if (!skipCheck) {
- _checkAnswer(roundID, price, updatedAt, answeredInRound);
- }
- } catch {
- revert IncorrectPriceFeedException(); // F:[PO-2]
- }
-
- _setPriceFeedWithFlags(token, priceFeed, skipCheck, decimals);
-
- emit NewPriceFeed(token, priceFeed); // F:[PO-3]
- }
-
- /// @dev Returns token's price in USD (8 decimals)
- /// @param token The token to compute the price for
- function getPrice(address token) public view override returns (uint256 price) {
- (price,) = _getPrice(token);
- }
-
- /// @dev IMPLEMENTATION: getPrice
- function _getPrice(address token) internal view returns (uint256 price, uint256 decimals) {
- address priceFeed;
- bool skipCheck;
- (priceFeed, skipCheck, decimals) = priceFeedsWithFlags(token); //
- (uint80 roundID, int256 _price,, uint256 updatedAt, uint80 answeredInRound) =
- AggregatorV3Interface(priceFeed).latestRoundData(); // F:[PO-6]
-
- // Checks if SKIP_PRICE_CHECK_FLAG is not set
- if (!skipCheck) {
- _checkAnswer(roundID, _price, updatedAt, answeredInRound);
- } // F:[PO-5]
-
- price = (uint256(_price)); // F:[PO-6]
- }
-
- /// @dev Converts a quantity of an asset to USD (decimals = 8).
- /// @param amount Amount to convert
- /// @param token Address of the token to be converted
- function convertToUSD(uint256 amount, address token) public view override returns (uint256) {
- (uint256 price, uint256 decimals) = _getPrice(token);
- return (amount * price) / (10 ** decimals); // F:[PO-7]
- }
-
- /// @dev Converts a quantity of USD (decimals = 8) to an equivalent amount of an asset
- /// @param amount Amount to convert
- /// @param token Address of the token converted to
- function convertFromUSD(uint256 amount, address token) public view override returns (uint256) {
- (uint256 price, uint256 decimals) = _getPrice(token);
- return (amount * (10 ** decimals)) / price; // F:[PO-7]
- }
-
- /// @dev Converts one asset into another
- ///
- /// @param amount Amount to convert
- /// @param tokenFrom Address of the token to convert from
- /// @param tokenTo Address of the token to convert to
- function convert(uint256 amount, address tokenFrom, address tokenTo) public view override returns (uint256) {
- return convertFromUSD(convertToUSD(amount, tokenFrom), tokenTo); // F:[PO-8]
- }
-
- /// @dev Returns collateral values for two tokens, required for a fast check
- /// @param amountFrom Amount of the outbound token
- /// @param tokenFrom Address of the outbound token
- /// @param amountTo Amount of the inbound token
- /// @param tokenTo Address of the inbound token
- /// @return collateralFrom Value of the outbound token amount in USD
- /// @return collateralTo Value of the inbound token amount in USD
- function fastCheck(uint256 amountFrom, address tokenFrom, uint256 amountTo, address tokenTo)
- external
- view
- override
- returns (uint256 collateralFrom, uint256 collateralTo)
- {
- collateralFrom = convertToUSD(amountFrom, tokenFrom); // F:[PO-9]
- collateralTo = convertToUSD(amountTo, tokenTo); // F:[PO-9]
- }
-
- /// @dev Returns the price feed address for the passed token
- /// @param token Token to get the price feed for
- function priceFeeds(address token) external view override returns (address priceFeed) {
- (priceFeed,,) = priceFeedsWithFlags(token); // F:[PO-3]
- }
-
- /// @dev Returns the price feed for the passed token,
- /// with additional parameters
- /// @param token Token to get the price feed for
- function priceFeedsWithFlags(address token)
- public
- view
- override
- returns (address priceFeed, bool skipCheck, uint256 decimals)
- {
- uint256 pf = _priceFeeds[token]; // F:[PO-3]
- if (pf == 0) revert PriceOracleNotExistsException();
-
- priceFeed = address(uint160(pf)); // F:[PO-3]
-
- skipCheck = pf & SKIP_PRICE_CHECK_FLAG != 0; // F:[PO-3]
- decimals = pf >> DECIMALS_SHIFT;
- }
-
- /// @dev Encodes the price feed address with parameters into a uint256,
- /// and saves it into a map
- /// @param token Address of the token to add the price feed for
- /// @param priceFeed Address of the price feed
- /// @param skipCheck Whether price feed result sanity checks should be skipped
- /// @param decimals Decimals for the price feed's result
- function _setPriceFeedWithFlags(address token, address priceFeed, bool skipCheck, uint8 decimals) internal {
- uint256 value = uint160(priceFeed); // F:[PO-3]
- if (skipCheck) value |= SKIP_PRICE_CHECK_FLAG; // F:[PO-3]
-
- _priceFeeds[token] = value + (uint256(decimals) << DECIMALS_SHIFT); // F:[PO-3]
- }
-}
diff --git a/contracts/oracles/ZeroPriceFeed.sol b/contracts/oracles/ZeroPriceFeed.sol
deleted file mode 100644
index c80b8f67..00000000
--- a/contracts/oracles/ZeroPriceFeed.sol
+++ /dev/null
@@ -1,57 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
-import {IPriceFeedType, PriceFeedType} from "../interfaces/IPriceFeedType.sol";
-
-// EXCEPTIONS
-import {NotImplementedException} from "../interfaces/IErrors.sol";
-
-/// @title Pricefeed which always returns 0
-/// @notice Used for collateral tokens that do not have a valid USD price feed
-contract ZeroPriceFeed is AggregatorV3Interface, IPriceFeedType {
- string public constant override description = "Zero pricefeed"; // F:[ZPF-1]
-
- uint8 public constant override decimals = 8; // F:[ZPF-1]
-
- uint256 public constant override version = 1;
-
- PriceFeedType public constant override priceFeedType = PriceFeedType.ZERO_ORACLE;
-
- bool public constant override skipPriceCheck = true; // F:[ZPF-1]
-
- /// @dev Not implemented, since Gearbox does not use historical data
- function getRoundData(
- uint80 //_roundId)
- )
- external
- pure
- override
- returns (
- uint80, // roundId,
- int256, //answer,
- uint256, // startedAt,
- uint256, // updatedAt,
- uint80 // answeredInRound
- )
- {
- revert NotImplementedException(); // F:[ZPF-2]
- }
-
- /// @dev Returns the latest result according to Chainlink spec
- /// @notice 'answer' is always 0
- function latestRoundData()
- external
- view
- override
- returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
- {
- roundId = 1; // F:[ZPF-3]
- answer = 0; // F:[ZPF-3]
- startedAt = block.timestamp; // F:[ZPF-3]
- updatedAt = block.timestamp; // F:[ZPF-3]
- answeredInRound = 1; // F:[ZPF-3]
- }
-}
diff --git a/contracts/pool/Gauge.sol b/contracts/pool/Gauge.sol
index daf51c6b..b4146608 100644
--- a/contracts/pool/Gauge.sol
+++ b/contracts/pool/Gauge.sol
@@ -10,8 +10,8 @@ import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IER
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
-import {AddressProvider} from "../core/AddressProvider.sol";
-import {ContractsRegister} from "../core/ContractsRegister.sol";
+import {AddressProvider} from "@gearbox-protocol/core-v2/contracts/core/AddressProvider.sol";
+import {ContractsRegister} from "@gearbox-protocol/core-v2/contracts/core/ContractsRegister.sol";
import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
// interfaces
@@ -19,15 +19,14 @@ import {IGauge, GaugeOpts, QuotaRateParams, UserVotes} from "../interfaces/IGaug
import {IPoolQuotaKeeper, QuotaRateUpdate} from "../interfaces/IPoolQuotaKeeper.sol";
import {IGearStaking} from "../interfaces/IGearStaking.sol";
-import {RAY, PERCENTAGE_FACTOR, SECONDS_PER_YEAR, MAX_WITHDRAW_FEE} from "../libraries/Constants.sol";
-import {Errors} from "../libraries/Errors.sol";
+import {RAY, SECONDS_PER_YEAR, MAX_WITHDRAW_FEE} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
+import {Errors} from "@gearbox-protocol/core-v2/contracts/libraries/Errors.sol";
import {Pool4626} from "./Pool4626.sol";
// EXCEPTIONS
import {ZeroAddressException} from "../interfaces/IErrors.sol";
-import "forge-std/console.sol";
-
/// @title Gauge fore new 4626 pools
contract Gauge is IGauge, ACLNonReentrantTrait {
using EnumerableSet for EnumerableSet.AddressSet;
diff --git a/contracts/pool/LinearInterestRateModel.sol b/contracts/pool/LinearInterestRateModel.sol
index 687b85e5..634a5dd2 100644
--- a/contracts/pool/LinearInterestRateModel.sol
+++ b/contracts/pool/LinearInterestRateModel.sol
@@ -3,9 +3,10 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {WAD, RAY, PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
+import {WAD, RAY} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
import {IInterestRateModel} from "../interfaces/IInterestRateModel.sol";
-import {Errors} from "../libraries/Errors.sol";
+import {Errors} from "@gearbox-protocol/core-v2/contracts/libraries/Errors.sol";
/// @title Linear Interest Rate Model
/// @notice Linear interest rate model, similar which Aave uses
@@ -67,7 +68,6 @@ contract LinearInterestRateModel is IInterestRateModel {
U_Optimal_inverted_WAD = WAD - U_optimal_WAD;
// Convert percetns to WAD
- uint256 U_Reserve_wad = WAD * U_reserve / PERCENTAGE_FACTOR;
U_Reserve_WAD = WAD * U_reserve / PERCENTAGE_FACTOR;
// 1 - UReserve in WAD
diff --git a/contracts/pool/Pool4626.sol b/contracts/pool/Pool4626.sol
index d14ef0f6..584baa1c 100644
--- a/contracts/pool/Pool4626.sol
+++ b/contracts/pool/Pool4626.sol
@@ -13,25 +13,24 @@ import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IER
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
-import {IWETH} from "../interfaces/external/IWETH.sol";
+import {IWETH} from "@gearbox-protocol/core-v2/contracts/interfaces/external/IWETH.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
-import {AddressProvider} from "../core/AddressProvider.sol";
-import {ContractsRegister} from "../core/ContractsRegister.sol";
+import {AddressProvider} from "@gearbox-protocol/core-v2/contracts/core/AddressProvider.sol";
+import {ContractsRegister} from "@gearbox-protocol/core-v2/contracts/core/ContractsRegister.sol";
import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
import {IInterestRateModel} from "../interfaces/IInterestRateModel.sol";
import {IPool4626, Pool4626Opts} from "../interfaces/IPool4626.sol";
import {ICreditManagerV2} from "../interfaces/ICreditManagerV2.sol";
-import {RAY, PERCENTAGE_FACTOR, SECONDS_PER_YEAR, MAX_WITHDRAW_FEE} from "../libraries/Constants.sol";
-import {Errors} from "../libraries/Errors.sol";
+import {RAY, SECONDS_PER_YEAR, MAX_WITHDRAW_FEE} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
+import {Errors} from "@gearbox-protocol/core-v2/contracts/libraries/Errors.sol";
// EXCEPTIONS
import {ZeroAddressException} from "../interfaces/IErrors.sol";
-import "forge-std/console.sol";
-
struct CreditManagerDebt {
uint128 totalBorrowed;
uint128 limit;
diff --git a/contracts/pool/PoolQuotaKeeper.sol b/contracts/pool/PoolQuotaKeeper.sol
index 1f931152..b7766119 100644
--- a/contracts/pool/PoolQuotaKeeper.sol
+++ b/contracts/pool/PoolQuotaKeeper.sol
@@ -11,11 +11,11 @@ import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IER
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
-import {IWETH} from "../interfaces/external/IWETH.sol";
-import {IPriceOracleV2} from "../interfaces/IPriceOracle.sol";
+import {IWETH} from "@gearbox-protocol/core-v2/contracts/interfaces/external/IWETH.sol";
+import {IPriceOracleV2} from "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol";
-import {AddressProvider} from "../core/AddressProvider.sol";
-import {ContractsRegister} from "../core/ContractsRegister.sol";
+import {AddressProvider} from "@gearbox-protocol/core-v2/contracts/core/AddressProvider.sol";
+import {ContractsRegister} from "@gearbox-protocol/core-v2/contracts/core/ContractsRegister.sol";
import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
import {Pool4626} from "./Pool4626.sol";
@@ -31,14 +31,13 @@ import {
import {ICreditManagerV2} from "../interfaces/ICreditManagerV2.sol";
import {IGauge} from "../interfaces/IGauge.sol";
-import {RAY, PERCENTAGE_FACTOR, SECONDS_PER_YEAR, MAX_WITHDRAW_FEE} from "../libraries/Constants.sol";
-import {Errors} from "../libraries/Errors.sol";
+import {RAY, SECONDS_PER_YEAR, MAX_WITHDRAW_FEE} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
+import {Errors} from "@gearbox-protocol/core-v2/contracts/libraries/Errors.sol";
// EXCEPTIONS
import {ZeroAddressException} from "../interfaces/IErrors.sol";
-import "forge-std/console.sol";
-
uint192 constant RAY_DIVIDED_BY_PERCENTAGE = uint192(RAY / PERCENTAGE_FACTOR);
uint192 constant SECONDS_PER_YEAR_192 = uint192(SECONDS_PER_YEAR);
diff --git a/contracts/pool/PoolService.sol b/contracts/pool/PoolService.sol
deleted file mode 100644
index 698b29d5..00000000
--- a/contracts/pool/PoolService.sol
+++ /dev/null
@@ -1,502 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
-import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
-
-import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
-import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
-
-import {RAY} from "../libraries/Constants.sol";
-
-import {IInterestRateModel} from "../interfaces/IInterestRateModel.sol";
-import {IPoolService} from "../interfaces/IPoolService.sol";
-import {ICreditManagerV2} from "../interfaces/ICreditManagerV2.sol";
-
-import {AddressProvider} from "../core/AddressProvider.sol";
-import {DieselToken} from "../tokens/DieselToken.sol";
-import {SECONDS_PER_YEAR, MAX_WITHDRAW_FEE, PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
-import {Errors} from "../libraries/Errors.sol";
-
-/// @title Pool Service Interface
-/// @notice Implements business logic:
-/// - Adding/removing pool liquidity
-/// - Managing diesel tokens & diesel rates
-/// - Taking/repaying Credit Manager debt
-///
-/// More: https://dev.gearbox.fi/developers/pools/pool-service
-contract PoolService is IPoolService, ACLNonReentrantTrait {
- using SafeERC20 for IERC20;
-
- /// @dev Expected liquidity at last update (LU)
- uint256 public _expectedLiquidityLU;
-
- /// @dev The limit on expected (total) liquidity
- uint256 public override expectedLiquidityLimit;
-
- /// @dev Total borrowed amount
- /// @notice https://dev.gearbox.fi/developers/pools/economy/total-borrowed
- uint256 public override totalBorrowed;
-
- /// @dev Address provider
- AddressProvider public override addressProvider;
-
- /// @dev Interest rate model
- IInterestRateModel public interestRateModel;
-
- /// @dev The pool's underlying asset
- address public override underlyingToken;
-
- /// @dev Diesel(LP) token address
- address public immutable override dieselToken;
-
- /// @dev Map from Credit Manager addresses to the status of their ability to borrow
- mapping(address => bool) public override creditManagersCanBorrow;
-
- /// @dev Map from Credit Manager addresses to the status of their ability to repay
- mapping(address => bool) public creditManagersCanRepay;
-
- /// @dev The list of all Credit Managers
- address[] public override creditManagers;
-
- /// @dev Address of the protocol treasury
- address public treasuryAddress;
-
- /// @dev The cumulative interest index at last update
- uint256 public override _cumulativeIndex_RAY;
-
- /// @dev The current borrow rate
- /// @notice https://dev.gearbox.fi/developers/pools/economy#borrow-apy
- uint256 public override borrowAPY_RAY;
-
- /// @dev Timestamp of last update
- uint256 public override _timestampLU;
-
- /// @dev Withdrawal fee in PERCENTAGE FORMAT
- uint256 public override withdrawFee;
-
- /// @dev Contract version
- uint256 public constant override version = 1;
-
- //
- // CONSTRUCTOR
- //
-
- /// @dev Constructor
- /// @param _addressProvider Address provider
- /// @param _underlyingToken Address of the underlying token
- /// @param _interestRateModelAddress Address of the initial interest rate model
- constructor(
- address _addressProvider,
- address _underlyingToken,
- address _interestRateModelAddress,
- uint256 _expectedLiquidityLimit
- ) ACLNonReentrantTrait(_addressProvider) {
- require(
- _addressProvider != address(0) && _underlyingToken != address(0) && _interestRateModelAddress != address(0),
- Errors.ZERO_ADDRESS_IS_NOT_ALLOWED
- );
-
- addressProvider = AddressProvider(_addressProvider);
-
- underlyingToken = _underlyingToken;
-
- dieselToken = address(
- new DieselToken(
- string(
- abi.encodePacked(
- "diesel ",
- IERC20Metadata(_underlyingToken).name()
- )
- ),
- string(
- abi.encodePacked(
- "d",
- IERC20Metadata(_underlyingToken).symbol()
- )
- ),
- IERC20Metadata(_underlyingToken).decimals()
- )
- );
-
- treasuryAddress = addressProvider.getTreasuryContract();
-
- _timestampLU = block.timestamp;
- _cumulativeIndex_RAY = RAY; // T:[PS-5]
- _updateInterestRateModel(_interestRateModelAddress);
- expectedLiquidityLimit = _expectedLiquidityLimit;
- }
-
- //
- // LIQUIDITY MANAGEMENT
- //
-
- /**
- * @dev Adds liquidity to the pool
- * - Transfers the underlying asset from sender to the pool
- * - Mints diesel (LP) token фе current diesel rate
- * - Updates expected liquidity
- * - Updates borrow rate
- *
- * More: https://dev.gearbox.fi/developers/pools/pool-service#addliquidity
- *
- * @param amount Amount of tokens to be deposited
- * @param onBehalfOf The address that will receive the dToken
- * @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 a facilitator.
- *
- * #if_succeeds {:msg "After addLiquidity() the pool gets the correct amoung of underlyingToken(s)"}
- * IERC20(underlyingToken).balanceOf(address(this)) == old(IERC20(underlyingToken).balanceOf(address(this))) + amount;
- * #if_succeeds {:msg "After addLiquidity() onBehalfOf gets the right amount of dieselTokens"}
- * IERC20(dieselToken).balanceOf(onBehalfOf) == old(IERC20(dieselToken).balanceOf(onBehalfOf)) + old(toDiesel(amount));
- * #if_succeeds {:msg "After addLiquidity() borrow rate decreases"}
- * amount > 0 ==> borrowAPY_RAY <= old(currentBorrowRate());
- * #limit {:msg "Not more than 1 day since last borrow rate update"} block.timestamp <= _timestampLU + 3600 * 24;
- */
- function addLiquidity(uint256 amount, address onBehalfOf, uint256 referralCode)
- external
- override
- whenNotPaused // T:[PS-4]
- nonReentrant
- {
- require(onBehalfOf != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED);
-
- require(expectedLiquidity() + amount <= expectedLiquidityLimit, Errors.POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT); // T:[PS-31]
-
- uint256 balanceBefore = IERC20(underlyingToken).balanceOf(address(this));
-
- IERC20(underlyingToken).safeTransferFrom(msg.sender, address(this), amount); // T:[PS-2, 7]
-
- amount = IERC20(underlyingToken).balanceOf(address(this)) - balanceBefore; // T:[FT-1]
-
- DieselToken(dieselToken).mint(onBehalfOf, toDiesel(amount)); // T:[PS-2, 7]
-
- _expectedLiquidityLU = _expectedLiquidityLU + amount; // T:[PS-2, 7]
- _updateBorrowRate(0); // T:[PS-2, 7]
-
- emit AddLiquidity(msg.sender, onBehalfOf, amount, referralCode); // T:[PS-2, 7]
- }
-
- /**
- * @dev Removes liquidity from pool
- * - Transfers to the sender the underlying amount equivalent to the passed Diesel amount
- * - Burns Diesel tokens
- * - Subtracts the removed underlying from expectedLiquidity
- * - Updates borrow rate
- *
- * More: https://dev.gearbox.fi/developers/pools/pool-service#removeliquidity
- *
- * @param amount Amount of Diesel tokens to burn
- * @param to Address to transfer the underlying to
- *
- * #if_succeeds {:msg "For removeLiquidity() sender must have sufficient diesel"}
- * old(DieselToken(dieselToken).balanceOf(msg.sender)) >= amount;
- * #if_succeeds {:msg "After removeLiquidity() `to` gets the liquidity in underlyingToken(s)"}
- * (to != address(this) && to != treasuryAddress) ==>
- * IERC20(underlyingToken).balanceOf(to) == old(IERC20(underlyingToken).balanceOf(to) + (let t:= fromDiesel(amount) in t.sub(t.percentMul(withdrawFee))));
- * #if_succeeds {:msg "After removeLiquidity() treasury gets the withdraw fee in underlyingToken(s)"}
- * (to != address(this) && to != treasuryAddress) ==>
- * IERC20(underlyingToken).balanceOf(treasuryAddress) == old(IERC20(underlyingToken).balanceOf(treasuryAddress) + fromDiesel(amount).percentMul(withdrawFee));
- * #if_succeeds {:msg "After removeLiquidity() borrow rate increases"}
- * (to != address(this) && amount > 0) ==> borrowAPY_RAY >= old(currentBorrowRate());
- * #limit {:msg "Not more than 1 day since last borrow rate update"} block.timestamp <= _timestampLU + 3600 * 24;
- */
- function removeLiquidity(uint256 amount, address to)
- external
- override
- whenNotPaused // T:[PS-4]
- nonReentrant
- returns (uint256)
- {
- require(to != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED);
-
- uint256 underlyingTokensAmount = fromDiesel(amount); // T:[PS-3, 8]
-
- uint256 amountTreasury = underlyingTokensAmount * withdrawFee / PERCENTAGE_FACTOR;
- uint256 amountSent = underlyingTokensAmount - amountTreasury;
-
- IERC20(underlyingToken).safeTransfer(to, amountSent); // T:[PS-3, 34]
-
- if (amountTreasury > 0) {
- IERC20(underlyingToken).safeTransfer(treasuryAddress, amountTreasury);
- } // T:[PS-3, 34]
-
- DieselToken(dieselToken).burn(msg.sender, amount); // T:[PS-3, 8]
-
- _expectedLiquidityLU = _expectedLiquidityLU - underlyingTokensAmount; // T:[PS-3, 8]
- _updateBorrowRate(0); // T:[PS-3,8 ]
-
- emit RemoveLiquidity(msg.sender, to, amount); // T:[PS-3, 8]
-
- return amountSent;
- }
-
- /// @dev Returns expected liquidity - the amount of money that should be in the pool
- /// after all users close their Credit accounts and fully repay debts
- ///
- /// More: https://dev.gearbox.fi/developers/pools/economy#expected-liquidity
- function expectedLiquidity() public view override returns (uint256) {
- // timeDifference = blockTime - previous timeStamp
- uint256 timeDifference = block.timestamp - _timestampLU;
-
- // currentBorrowRate * timeDifference
- // interestAccrued = totalBorrow * ------------------------------------
- // SECONDS_PER_YEAR
- //
- uint256 interestAccrued = (totalBorrowed * borrowAPY_RAY * timeDifference) / RAY / SECONDS_PER_YEAR;
- // T:[PS-29]
-
- return _expectedLiquidityLU + interestAccrued; // T:[PS-29]
- }
-
- /// @dev Returns available liquidity in the pool (pool balance)
- /// More: https://dev.gearbox.fi/developers/
- function availableLiquidity() public view override returns (uint256) {
- return IERC20(underlyingToken).balanceOf(address(this));
- }
-
- //
- // CREDIT ACCOUNT LENDING
- //
-
- /// @dev Lends funds to a Credit Account and updates the pool parameters
- /// More: https://dev.gearbox.fi/developers/pools/pool-service#lendcreditAccount
- ///
- /// @param borrowedAmount Credit Account's debt principal
- /// @param creditAccount Credit Account's address
- ///
- /// #if_succeeds {:msg "After lendCreditAccount() borrow rate increases"}
- /// borrowedAmount > 0 ==> borrowAPY_RAY >= old(currentBorrowRate());
- /// #limit {:msg "Not more than 1 day since last borrow rate update"} block.timestamp <= _timestampLU + 3600 * 24;
- function lendCreditAccount(uint256 borrowedAmount, address creditAccount)
- external
- override
- whenNotPaused // T:[PS-4]
- {
- require(creditManagersCanBorrow[msg.sender], Errors.POOL_CONNECTED_CREDIT_MANAGERS_ONLY); // T:[PS-12, 13]
-
- // Transfer funds to credit account
- IERC20(underlyingToken).safeTransfer(creditAccount, borrowedAmount); // T:[PS-14]
-
- // Update borrow Rate
- _updateBorrowRate(0); // T:[PS-17]
-
- // Increase total borrowed amount
- totalBorrowed = totalBorrowed + borrowedAmount; // T:[PS-16]
-
- emit Borrow(msg.sender, creditAccount, borrowedAmount); // T:[PS-15]
- }
-
- /// @dev Registers Credit Account's debt repayment and updates parameters
- /// More: https://dev.gearbox.fi/developers/pools/pool-service#repaycreditAccount
- ///
- /// @param borrowedAmount Amount of principal ro repay
- /// @param profit The treasury profit from repayment
- /// @param loss Amount of underlying that the CA wan't able to repay
- /// @notice Assumes that the underlying (including principal + interest + fees)
- /// was already transferred
- ///
- /// #if_succeeds {:msg "Cant have both profit and loss"} !(profit > 0 && loss > 0);
- /// #if_succeeds {:msg "After repayCreditAccount() if we are profitabe, or treasury can cover the losses, diesel rate doesn't decrease"}
- /// (profit > 0 || toDiesel(loss) >= DieselToken(dieselToken).balanceOf(treasuryAddress)) ==> getDieselRate_RAY() >= old(getDieselRate_RAY());
- /// #limit {:msg "Not more than 1 day since last borrow rate update"} block.timestamp <= _timestampLU + 3600 * 24;
- function repayCreditAccount(uint256 borrowedAmount, uint256 profit, uint256 loss)
- external
- override
- whenNotPaused // T:[PS-4]
- {
- require(creditManagersCanRepay[msg.sender], Errors.POOL_CONNECTED_CREDIT_MANAGERS_ONLY); // T:[PS-12]
-
- // For fee surplus we mint tokens for treasury
- if (profit > 0) {
- // T:[PS-22] provess that diesel rate will be the same within the margin of error
- DieselToken(dieselToken).mint(treasuryAddress, toDiesel(profit)); // T:[PS-21, 22]
- _expectedLiquidityLU = _expectedLiquidityLU + profit; // T:[PS-21, 22]
- }
- // If returned money < borrowed amount + interest accrued
- // it tries to compensate loss by burning diesel (LP) tokens
- // from treasury fund
- else {
- uint256 amountToBurn = toDiesel(loss); // T:[PS-19,20]
-
- uint256 treasuryBalance = DieselToken(dieselToken).balanceOf(treasuryAddress); // T:[PS-19,20]
-
- if (treasuryBalance < amountToBurn) {
- amountToBurn = treasuryBalance;
- emit UncoveredLoss(msg.sender, loss - fromDiesel(treasuryBalance)); // T:[PS-23]
- }
-
- // If treasury has enough funds, it just burns needed amount
- // to keep diesel rate on the same level
- DieselToken(dieselToken).burn(treasuryAddress, amountToBurn); // T:[PS-19, 20]
-
- // _expectedLiquidityLU = _expectedLiquidityLU.sub(loss); //T:[PS-19,20]
- }
-
- // Update available liquidity
- _updateBorrowRate(loss); // T:[PS-19, 20, 21]
-
- // Reduce total borrowed. Should be after _updateBorrowRate() for correct calculations
- totalBorrowed -= borrowedAmount; // T:[PS-19, 20]
-
- emit Repay(msg.sender, borrowedAmount, profit, loss); // T:[PS-18]
- }
-
- //
- // INTEREST RATE MANAGEMENT
- //
-
- /**
- * @dev Calculates the most current value of the cumulative interest index
- *
- * / currentBorrowRate * timeDifference \
- * newIndex = currentIndex * | 1 + ------------------------------------ |
- * \ SECONDS_PER_YEAR /
- *
- * @return current cumulative index in RAY
- */
- function calcLinearCumulative_RAY() public view override returns (uint256) {
- //solium-disable-next-line
- uint256 timeDifference = block.timestamp - _timestampLU; // T:[PS-28]
-
- return calcLinearIndex_RAY(_cumulativeIndex_RAY, borrowAPY_RAY, timeDifference); // T:[PS-28]
- }
-
- /// @dev Calculates a new cumulative index value from the initial value, borrow rate and time elapsed
- /// @param cumulativeIndex_RAY Cumulative index at last update, in RAY
- /// @param currentBorrowRate_RAY Current borrow rate, in RAY
- /// @param timeDifference Time elapsed since last update, in seconds
- function calcLinearIndex_RAY(uint256 cumulativeIndex_RAY, uint256 currentBorrowRate_RAY, uint256 timeDifference)
- public
- pure
- returns (uint256)
- {
- // / currentBorrowRate * timeDifference \
- // newIndex = currentIndex * | 1 + ------------------------------------ |
- // \ SECONDS_PER_YEAR /
- //
- uint256 linearAccumulated_RAY = RAY + (currentBorrowRate_RAY * timeDifference) / SECONDS_PER_YEAR;
- // T:[GM-2]
-
- return (cumulativeIndex_RAY * linearAccumulated_RAY) / RAY; // T:[GM-2]
- }
-
- /// @dev Updates the borrow rate when liquidity parameters are changed
- /// @param loss The loss incurred by the pool on last parameter update, if any
- function _updateBorrowRate(uint256 loss) internal {
- // Update total _expectedLiquidityLU
-
- _expectedLiquidityLU = expectedLiquidity() - loss; // T:[PS-27]
-
- // Update cumulativeIndex
- _cumulativeIndex_RAY = calcLinearCumulative_RAY(); // T:[PS-27]
-
- // update borrow APY
- borrowAPY_RAY = interestRateModel.calcBorrowRate(_expectedLiquidityLU, availableLiquidity()); // T:[PS-27]
- _timestampLU = block.timestamp; // T:[PS-27]
- }
-
- //
- // DIESEL TOKEN MGMT
- //
-
- /// @dev Returns the current exchange rate of Diesel tokens to underlying
- /// More info: https://dev.gearbox.fi/developers/pools/economy#diesel-rate
- function getDieselRate_RAY() public view override returns (uint256) {
- uint256 dieselSupply = IERC20(dieselToken).totalSupply();
- if (dieselSupply == 0) return RAY; // T:[PS-1]
- return (expectedLiquidity() * RAY) / dieselSupply; // T:[PS-6]
- }
-
- /// @dev Converts a quantity of the underlying to Diesel tokens
- /// @param amount Amount in underlyingToken tokens to be converted to diesel tokens
- function toDiesel(uint256 amount) public view override returns (uint256) {
- return (amount * RAY) / getDieselRate_RAY(); // T:[PS-24]
- }
-
- /// @dev Converts a quantity of Diesel tokens to the underlying
- /// @param amount Amount in diesel tokens to be converted to diesel tokens
- function fromDiesel(uint256 amount) public view override returns (uint256) {
- return (amount * getDieselRate_RAY()) / RAY; // T:[PS-24]
- }
-
- //
- // CONFIGURATION
- //
-
- /// @dev Connects a new Credit manager to pool
- /// @param _creditManager Address of the Credit Manager
- function connectCreditManager(address _creditManager)
- external
- configuratorOnly // T:[PS-9]
- {
- require(
- address(this) == ICreditManagerV2(_creditManager).poolService(),
- Errors.POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER
- ); // T:[PS-10]
-
- require(!creditManagersCanRepay[_creditManager], Errors.POOL_CANT_ADD_CREDIT_MANAGER_TWICE); // T:[PS-35]
-
- creditManagersCanBorrow[_creditManager] = true; // T:[PS-11]
- creditManagersCanRepay[_creditManager] = true; // T:[PS-11]
- creditManagers.push(_creditManager); // T:[PS-11]
- emit NewCreditManagerConnected(_creditManager); // T:[PS-11]
- }
-
- /// @dev Forbids a Credit Manager to borrow
- /// @param _creditManager Address of the Credit Manager
- function forbidCreditManagerToBorrow(address _creditManager)
- external
- configuratorOnly // T:[PS-9]
- {
- creditManagersCanBorrow[_creditManager] = false; // T:[PS-13]
- emit BorrowForbidden(_creditManager); // T:[PS-13]
- }
-
- /// @dev Sets the new interest rate model for the pool
- /// @param _interestRateModel Address of the new interest rate model contract
- /// #limit {:msg "Disallow updating the interest rate model after the constructor"} address(interestRateModel) == address(0x0);
- function updateInterestRateModel(address _interestRateModel)
- public
- configuratorOnly // T:[PS-9]
- {
- _updateInterestRateModel(_interestRateModel);
- }
-
- /// @dev IMPLEMENTATION: updateInterestRateModel
- function _updateInterestRateModel(address _interestRateModel) internal {
- require(_interestRateModel != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED);
- interestRateModel = IInterestRateModel(_interestRateModel); // T:[PS-25]
- _updateBorrowRate(0); // T:[PS-26]
- emit NewInterestRateModel(_interestRateModel); // T:[PS-25]
- }
-
- /// @dev Sets a new expected liquidity limit
- /// @param newLimit New expected liquidity limit
- function setExpectedLiquidityLimit(uint256 newLimit)
- external
- configuratorOnly // T:[PS-9]
- {
- expectedLiquidityLimit = newLimit; // T:[PS-30]
- emit NewExpectedLiquidityLimit(newLimit); // T:[PS-30]
- }
-
- /// @dev Sets a new withdrawal fee
- /// @param fee The new fee amount, in bp
- function setWithdrawFee(uint256 fee)
- public
- configuratorOnly // T:[PS-9]
- {
- require(fee <= MAX_WITHDRAW_FEE, Errors.POOL_INCORRECT_WITHDRAW_FEE); // T:[PS-32]
- withdrawFee = fee; // T:[PS-33]
- emit NewWithdrawFee(fee); // T:[PS-33]
- }
-
- /// @dev Returns the number of connected Credit Managers
- function creditManagersCount() external view override returns (uint256) {
- return creditManagers.length; // T:[PS-11]
- }
-}
diff --git a/contracts/support/BotList.sol b/contracts/support/BotList.sol
index 28bdfe00..6988bcb1 100644
--- a/contracts/support/BotList.sol
+++ b/contracts/support/BotList.sol
@@ -8,10 +8,10 @@ import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
import {IBotList, BotFunding} from "../interfaces/IBotList.sol";
-import {IAddressProvider} from "../interfaces/IAddressProvider.sol";
+import {IAddressProvider} from "@gearbox-protocol/core-v2/contracts/interfaces/IAddressProvider.sol";
import {ZeroAddressException, AddressIsNotContractException} from "../interfaces/IErrors.sol";
-import {PERCENTAGE_FACTOR} from "../libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
uint256 constant SECONDS_PER_WEEK = 3600 * 24 * 7;
diff --git a/contracts/support/ContractUpgrader.sol b/contracts/support/ContractUpgrader.sol
deleted file mode 100644
index 9a42e69a..00000000
--- a/contracts/support/ContractUpgrader.sol
+++ /dev/null
@@ -1,48 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox. Generalized leverage protocol that allows to take leverage and then use it across other DeFi protocols and platforms in a composable way.
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-pragma abicoder v2;
-
-import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
-
-import {AddressProvider} from "../core/AddressProvider.sol";
-import {ACL} from "../core/ACL.sol";
-
-abstract contract ContractUpgrader is Ownable {
- AddressProvider public immutable addressProvider;
- address public immutable root;
-
- error RootSelfDestoyException();
-
- constructor(address _addressProvider) {
- addressProvider = AddressProvider(_addressProvider);
-
- root = ACL(addressProvider.getACL()).owner();
- }
-
- function configure() external virtual onlyOwner {
- _configure();
- _returnRootBack();
- }
-
- function _configure() internal virtual;
-
- // Will be used in case of configure() revert
- function getRootBack() external onlyOwner {
- _returnRootBack();
- }
-
- function _returnRootBack() internal {
- ACL acl = ACL(addressProvider.getACL()); // T:[PD-3]
- acl.transferOwnership(root);
- }
-
- function destoy() external onlyOwner {
- if (ACL(addressProvider.getACL()).owner() == address(this)) {
- revert RootSelfDestoyException();
- }
- selfdestruct(payable(msg.sender));
- }
-}
diff --git a/contracts/tokens/GearStaking.sol b/contracts/support/GearStaking.sol
similarity index 97%
rename from contracts/tokens/GearStaking.sol
rename to contracts/support/GearStaking.sol
index 3beb1bea..1bee8a69 100644
--- a/contracts/tokens/GearStaking.sol
+++ b/contracts/support/GearStaking.sol
@@ -3,10 +3,10 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.17;
+import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
-import {IGearToken} from "../interfaces/IGearToken.sol";
-import {IAddressProvider} from "../interfaces/IAddressProvider.sol";
+import {IAddressProvider} from "@gearbox-protocol/core-v2/contracts/interfaces/IAddressProvider.sol";
import {IVotingContract} from "../interfaces/IVotingContract.sol";
import {
IGearStaking,
@@ -24,7 +24,7 @@ contract GearStaking is ACLNonReentrantTrait, IGearStaking {
using SafeCast for uint256;
/// @dev Address of the GEAR token
- IGearToken public immutable gear;
+ IERC20 public immutable gear;
/// @dev Mapping of user address to their total staked tokens and tokens available for voting
mapping(address => UserVoteLockData) internal voteLockData;
@@ -39,7 +39,7 @@ contract GearStaking is ACLNonReentrantTrait, IGearStaking {
uint256 immutable firstEpochTimestamp;
constructor(address _addressProvider, uint256 _firstEpochTimestamp) ACLNonReentrantTrait(_addressProvider) {
- gear = IGearToken(IAddressProvider(_addressProvider).getGearToken());
+ gear = IERC20(IAddressProvider(_addressProvider).getGearToken());
firstEpochTimestamp = _firstEpochTimestamp;
}
diff --git a/contracts/support/PauseMulticall.sol b/contracts/support/PauseMulticall.sol
deleted file mode 100644
index 96b1c3fe..00000000
--- a/contracts/support/PauseMulticall.sol
+++ /dev/null
@@ -1,63 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
-import {IAddressProvider} from "../interfaces/IAddressProvider.sol";
-import {ACL} from "../core/ACL.sol";
-import {ContractsRegister} from "../core/ContractsRegister.sol";
-import {CallerNotPausableAdminException} from "../interfaces/IErrors.sol";
-
-contract PauseMulticall is ACLNonReentrantTrait {
- ACL public immutable acl;
- ContractsRegister public immutable cr;
-
- modifier pausableAdminOnly() {
- if (!acl.isPausableAdmin(msg.sender)) {
- revert CallerNotPausableAdminException();
- } // F:[PM-05]
- _;
- }
-
- constructor(address _addressProvider) ACLNonReentrantTrait(_addressProvider) {
- IAddressProvider ap = IAddressProvider(_addressProvider);
- acl = ACL(ap.getACL()); // F: [PM-01]
-
- cr = ContractsRegister(ap.getContractsRegister()); // F: [PM-01]
- }
-
- function pauseAllCreditManagers()
- external
- pausableAdminOnly // F:[PM-05]
- {
- // F: [PM-05]
- _pauseBatchOfContractrs(cr.getCreditManagers()); // F: [PM-02]
- }
-
- function pauseAllPools()
- external
- pausableAdminOnly // F:[PM-05]
- {
- _pauseBatchOfContractrs(cr.getPools()); // F: [PM-03]
- }
-
- function pauseAllContracts()
- external
- pausableAdminOnly // F:[PM-05]
- {
- _pauseBatchOfContractrs(cr.getPools()); // F: [PM-04]
- _pauseBatchOfContractrs(cr.getCreditManagers()); // F: [PM-04]
- }
-
- function _pauseBatchOfContractrs(address[] memory contractsToPause) internal {
- uint256 len = contractsToPause.length;
- for (uint256 i = 0; i < len;) {
- // try-catch block to ignore some contracts which are already paused
- try ACLNonReentrantTrait(contractsToPause[i]).pause() {} catch {}
- unchecked {
- ++i;
- }
- }
- }
-}
diff --git a/contracts/test/adapters/AbstractAdapter.t.sol b/contracts/test/adapters/AbstractAdapter.t.sol
index 448b69f4..b0729b5f 100644
--- a/contracts/test/adapters/AbstractAdapter.t.sol
+++ b/contracts/test/adapters/AbstractAdapter.t.sol
@@ -5,11 +5,11 @@ pragma solidity ^0.8.17;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {AccountFactory} from "../../core/AccountFactory.sol";
+import {AccountFactory} from "@gearbox-protocol/core-v2/contracts/core/AccountFactory.sol";
import {CreditFacade} from "../../credit/CreditFacade.sol";
-import {ICreditAccount} from "../../interfaces/ICreditAccount.sol";
-import {ICreditFacade, MultiCall} from "../../interfaces/ICreditFacade.sol";
+import {ICreditAccount} from "@gearbox-protocol/core-v2/contracts/interfaces/ICreditAccount.sol";
+import {ICreditFacade, MultiCall} from "@gearbox-protocol/core-v2/contracts/interfaces/ICreditFacade.sol";
import {ICreditManagerV2, ICreditManagerV2Events} from "../../interfaces/ICreditManagerV2.sol";
import {ICreditFacadeEvents, ICreditFacadeExceptions} from "../../interfaces/ICreditFacade.sol";
@@ -23,7 +23,7 @@ import {ICreditManagerV2Exceptions} from "../../interfaces/ICreditManagerV2.sol"
// MOCKS
import {AdapterMock} from "../mocks/adapters/AdapterMock.sol";
-import {TargetContractMock} from "../mocks/adapters/TargetContractMock.sol";
+import {TargetContractMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/adapters/TargetContractMock.sol";
// SUITES
import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
diff --git a/contracts/test/config/CreditConfig.sol b/contracts/test/config/CreditConfig.sol
index a1cfdb8d..72ac416a 100644
--- a/contracts/test/config/CreditConfig.sol
+++ b/contracts/test/config/CreditConfig.sol
@@ -8,7 +8,7 @@ import {Tokens} from "./Tokens.sol";
import {CreditManagerOpts, CollateralToken} from "../../credit/CreditConfigurator.sol";
-import {PriceFeedConfig} from "../../oracles/PriceOracle.sol";
+import {PriceFeedConfig} from "@gearbox-protocol/core-v2/contracts/oracles/PriceOracle.sol";
import {ICreditConfig} from "../interfaces/ICreditConfig.sol";
import {ITokenTestSuite} from "../interfaces/ITokenTestSuite.sol";
diff --git a/contracts/test/core/ACL.t.sol b/contracts/test/core/ACL.t.sol
deleted file mode 100644
index 81101e9b..00000000
--- a/contracts/test/core/ACL.t.sol
+++ /dev/null
@@ -1,149 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {ACL} from "../../core/ACL.sol";
-
-import {IACLEvents, IACLExceptions} from "../../interfaces/IACL.sol";
-
-// TEST
-import "../lib/constants.sol";
-
-/// @title AccessControlList
-/// @notice Maintains the list of admin addresses
-contract ACLTest is DSTest, IACLEvents, IACLExceptions {
- CheatCodes evm = CheatCodes(HEVM_ADDRESS);
-
- ACL acl;
-
- function setUp() public {
- evm.prank(CONFIGURATOR);
- acl = new ACL();
- }
-
- // [ACL-1]: addPausableAdmin, addUnpausableAdmin, removePausableAdmin, removeUnpausableAdmin reverts if called by non-owner
- function test_ACL_01_add_remove_reverts_on_non_owner() public {
- evm.startPrank(USER);
-
- evm.expectRevert(bytes(OWNABLE_ERROR));
- acl.addPausableAdmin(DUMB_ADDRESS);
-
- evm.expectRevert(bytes(OWNABLE_ERROR));
- acl.addUnpausableAdmin(DUMB_ADDRESS);
-
- evm.expectRevert(bytes(OWNABLE_ERROR));
- acl.removePausableAdmin(DUMB_ADDRESS);
-
- evm.expectRevert(bytes(OWNABLE_ERROR));
- acl.removeUnpausableAdmin(DUMB_ADDRESS);
-
- evm.stopPrank();
- }
-
- // [ACL-2]: addPausableAdmin correctly adds pool
- function test_ACL_02_addPausableAdmin_adds_pool() public {
- assertTrue(!acl.isPausableAdmin(DUMB_ADDRESS));
-
- evm.expectEmit(true, false, false, false);
- emit PausableAdminAdded(DUMB_ADDRESS);
-
- evm.prank(CONFIGURATOR);
- acl.addPausableAdmin(DUMB_ADDRESS);
-
- assertTrue(acl.isPausableAdmin(DUMB_ADDRESS));
- }
-
- // [ACL-3]: removePausableAdmin removes pausable admin
- function test_ACL_03_removePausableAdmin_removes_admin() public {
- evm.startPrank(CONFIGURATOR);
-
- acl.addPausableAdmin(DUMB_ADDRESS);
- assertTrue(acl.isPausableAdmin(DUMB_ADDRESS));
-
- evm.expectEmit(true, false, false, false);
- emit PausableAdminRemoved(DUMB_ADDRESS);
-
- acl.removePausableAdmin(DUMB_ADDRESS);
-
- assertTrue(!acl.isPausableAdmin(DUMB_ADDRESS));
-
- evm.stopPrank();
- }
-
- // [ACL-3A]: removePausableAdmin reverts for non-admins
- function test_ACL_03A_removePausable_admin_reverts_for_non_admins() public {
- evm.startPrank(CONFIGURATOR);
-
- evm.expectRevert(abi.encodeWithSelector(AddressNotPausableAdminException.selector, DUMB_ADDRESS));
- acl.removePausableAdmin(DUMB_ADDRESS);
-
- evm.stopPrank();
- }
-
- // [ACL-4]: addUnpausableAdmin correctly adds pool
- function test_ACL_04_addUnpausableAdmin_adds_pool() public {
- assertTrue(!acl.isUnpausableAdmin(DUMB_ADDRESS));
-
- evm.expectEmit(true, false, false, false);
- emit UnpausableAdminAdded(DUMB_ADDRESS);
-
- evm.prank(CONFIGURATOR);
- acl.addUnpausableAdmin(DUMB_ADDRESS);
-
- assertTrue(acl.isUnpausableAdmin(DUMB_ADDRESS));
- }
-
- // [ACL-5]: removeUnpausableAdmin removes unpausable admin
- function test_ACL_05_removeUnpausableAdmin_removes_admin() public {
- evm.startPrank(CONFIGURATOR);
-
- acl.addUnpausableAdmin(DUMB_ADDRESS);
- assertTrue(acl.isUnpausableAdmin(DUMB_ADDRESS));
-
- evm.expectEmit(true, false, false, false);
- emit UnpausableAdminRemoved(DUMB_ADDRESS);
-
- acl.removeUnpausableAdmin(DUMB_ADDRESS);
-
- assertTrue(!acl.isUnpausableAdmin(DUMB_ADDRESS));
-
- evm.stopPrank();
- }
-
- // [ACL-5A]: removeUnpausableAdmin reverts for non-admins
- function test_ACL_05A_removeUnpausable_admin_reverts_for_non_admins() public {
- evm.startPrank(CONFIGURATOR);
-
- evm.expectRevert(abi.encodeWithSelector(AddressNotUnpausableAdminException.selector, DUMB_ADDRESS));
- acl.removeUnpausableAdmin(DUMB_ADDRESS);
-
- evm.stopPrank();
- }
-
- // [ACL-6]: isConfigurator works properly
- function test_ACL_06_isConfigurator_correct() public {
- assertTrue(acl.isConfigurator(CONFIGURATOR));
- assertTrue(!acl.isConfigurator(DUMB_ADDRESS));
- }
-
- // [ACL-7]: transferOwnership/claimOwnership functions work correctly
- function test_ACL_07_claimable_functions_work_correctly() public {
- assertEq(acl.pendingOwner(), address(0), "Incorrect pending owner");
-
- evm.prank(CONFIGURATOR);
- acl.transferOwnership(DUMB_ADDRESS);
-
- assertEq(acl.pendingOwner(), DUMB_ADDRESS, "Incorrect pending owner");
-
- evm.expectRevert("Claimable: Sender is not pending owner");
- evm.prank(USER);
- acl.claimOwnership();
-
- evm.prank(DUMB_ADDRESS);
- acl.claimOwnership();
-
- assertEq(acl.pendingOwner(), address(0), "Incorrect pending owner");
- assertEq(acl.owner(), DUMB_ADDRESS, "Incorrect owner");
- }
-}
diff --git a/contracts/test/core/AddressProvider.t.sol b/contracts/test/core/AddressProvider.t.sol
deleted file mode 100644
index 5072c852..00000000
--- a/contracts/test/core/AddressProvider.t.sol
+++ /dev/null
@@ -1,163 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {AddressProvider} from "../../core/AddressProvider.sol";
-import {IAddressProviderEvents} from "../../interfaces/IAddressProvider.sol";
-
-import {Errors} from "../../libraries/Errors.sol";
-
-// TEST
-import "../lib/constants.sol";
-
-/// @title AddressRepository
-/// @notice Stores addresses of deployed contracts
-contract AddressProviderTest is DSTest, IAddressProviderEvents {
- CheatCodes evm = CheatCodes(HEVM_ADDRESS);
-
- AddressProvider ap;
-
- function setUp() public {
- evm.prank(CONFIGURATOR);
- ap = new AddressProvider();
- }
-
- // [AP-1]: getAddress reverts if contact not found
- function test_AP_01_getAddress_reverts_if_contact_not_found() public {
- evm.expectRevert(bytes(Errors.AS_ADDRESS_NOT_FOUND));
- ap.getAccountFactory();
- }
-
- // [AP-2]: _setAddress emits event correctly
- function test_AP_02_setAddress_emits_event_correctly() public {
- evm.expectEmit(true, true, false, false);
- emit AddressSet("CONTRACTS_REGISTER", DUMB_ADDRESS);
-
- evm.prank(CONFIGURATOR);
- ap.setContractsRegister(DUMB_ADDRESS);
-
- // Checks that constructor emits event. Can't predict event, btw checks the fact only
- evm.expectEmit(true, false, false, false);
- emit AddressSet("ADDRESS_PROVIDER", DUMB_ADDRESS);
-
- new AddressProvider();
- }
-
- // [AP-3]: setACL correctly sets ACL
- function test_AP_03_setACL_correctly_sets_ACL() public {
- evm.prank(CONFIGURATOR);
- ap.setACL(DUMB_ADDRESS);
- assertEq(ap.getACL(), DUMB_ADDRESS);
- }
-
- // [AP-4]: setContractsRegister correctly sets ContractsRegister
- function test_AP_04_setContractsRegister_correctly_sets_ContractsRegister() public {
- evm.prank(CONFIGURATOR);
- ap.setContractsRegister(DUMB_ADDRESS);
- assertEq(ap.getContractsRegister(), DUMB_ADDRESS);
- }
-
- // [AP-5]: setPriceOracle correctly sets PriceOracle
- function test_AP_05_setPriceOracle_correctly_sets_PriceOracle() public {
- evm.prank(CONFIGURATOR);
- ap.setPriceOracle(DUMB_ADDRESS);
- assertEq(ap.getPriceOracle(), DUMB_ADDRESS);
- }
-
- // [AP-6]: setAccountFactory correctly sets AccountFactory
- function test_AP_06_setAccountFactory_correctly_sets_AccountFactory() public {
- evm.prank(CONFIGURATOR);
- ap.setAccountFactory(DUMB_ADDRESS);
- assertEq(ap.getAccountFactory(), DUMB_ADDRESS);
- }
-
- // [AP-7]: setDataCompressor correctly sets DataCompressor
- function test_AP_07_setDataCompressor_correctly_sets_DataCompressor() public {
- evm.prank(CONFIGURATOR);
- ap.setDataCompressor(DUMB_ADDRESS);
- assertEq(ap.getDataCompressor(), DUMB_ADDRESS);
- }
-
- // [AP-8]: setTreasuryContract correctly sets TreasuryContract
- function test_AP_08_setTreasuryContract_correctly_sets_TreasuryContract() public {
- evm.prank(CONFIGURATOR);
- ap.setTreasuryContract(DUMB_ADDRESS);
- assertEq(ap.getTreasuryContract(), DUMB_ADDRESS);
- }
-
- // [AP-9]: setGearToken correctly sets GearToken
- function test_AP_09_setGearToken_correctly_sets_GearToken() public {
- evm.prank(CONFIGURATOR);
- ap.setGearToken(DUMB_ADDRESS);
- assertEq(ap.getGearToken(), DUMB_ADDRESS);
- }
-
- // [AP-10]: setWethToken correctly sets WethToken
- function test_AP_10_setWethToken_correctly_sets_WethToken() public {
- evm.prank(CONFIGURATOR);
- ap.setWethToken(DUMB_ADDRESS);
- assertEq(ap.getWethToken(), DUMB_ADDRESS);
- }
-
- // [AP-11]: setWETHGateway correctly sets WethGateway
- function test_AP_11_setWETHGateway_correctly_sets_WethGateway() public {
- evm.prank(CONFIGURATOR);
- ap.setWETHGateway(DUMB_ADDRESS);
- assertEq(ap.getWETHGateway(), DUMB_ADDRESS);
- }
-
- // [AP-12]: set functions revert if called by non-owner
- function test_AP_12_set_functions_revert_if_called_by_non_owner() public {
- evm.startPrank(USER);
-
- bytes memory OWNABLE_ERROR_BYTES = bytes(OWNABLE_ERROR);
-
- evm.expectRevert(OWNABLE_ERROR_BYTES);
- ap.setACL(DUMB_ADDRESS);
-
- evm.expectRevert(OWNABLE_ERROR_BYTES);
- ap.setContractsRegister(DUMB_ADDRESS);
-
- evm.expectRevert(OWNABLE_ERROR_BYTES);
- ap.setPriceOracle(DUMB_ADDRESS);
-
- evm.expectRevert(OWNABLE_ERROR_BYTES);
- ap.setAccountFactory(DUMB_ADDRESS);
-
- evm.expectRevert(OWNABLE_ERROR_BYTES);
- ap.setDataCompressor(DUMB_ADDRESS);
-
- evm.expectRevert(OWNABLE_ERROR_BYTES);
- ap.setTreasuryContract(DUMB_ADDRESS);
-
- evm.expectRevert(OWNABLE_ERROR_BYTES);
- ap.setGearToken(DUMB_ADDRESS);
-
- evm.expectRevert(OWNABLE_ERROR_BYTES);
- ap.setWethToken(DUMB_ADDRESS);
-
- evm.expectRevert(OWNABLE_ERROR_BYTES);
- ap.setWETHGateway(DUMB_ADDRESS);
- }
-
- // [AP-13]: transferOwnership/claimOwnership functions work correctly
- function test_AP_13_claimable_functions_work_correctly() public {
- assertEq(ap.pendingOwner(), address(0), "Incorrect pending owner");
-
- evm.prank(CONFIGURATOR);
- ap.transferOwnership(DUMB_ADDRESS);
-
- assertEq(ap.pendingOwner(), DUMB_ADDRESS, "Incorrect pending owner");
-
- evm.expectRevert("Claimable: Sender is not pending owner");
- evm.prank(USER);
- ap.claimOwnership();
-
- evm.prank(DUMB_ADDRESS);
- ap.claimOwnership();
-
- assertEq(ap.pendingOwner(), address(0), "Incorrect pending owner");
- assertEq(ap.owner(), DUMB_ADDRESS, "Incorrect owner");
- }
-}
diff --git a/contracts/test/credit/CreditConfigurator.t.sol b/contracts/test/credit/CreditConfigurator.t.sol
index 53a13adf..c8eb5325 100644
--- a/contracts/test/credit/CreditConfigurator.t.sol
+++ b/contracts/test/credit/CreditConfigurator.t.sol
@@ -9,14 +9,14 @@ import {CreditManager} from "../../credit/CreditManager.sol";
import {CreditConfigurator, CreditManagerOpts, CollateralToken} from "../../credit/CreditConfigurator.sol";
import {ICreditManagerV2, ICreditManagerV2Events} from "../../interfaces/ICreditManagerV2.sol";
import {ICreditConfiguratorEvents} from "../../interfaces/ICreditConfigurator.sol";
-import {IAdapter} from "../../interfaces/adapters/IAdapter.sol";
+import {IAdapter} from "@gearbox-protocol/core-v2/contracts/interfaces/adapters/IAdapter.sol";
import {UniversalAdapter} from "../../adapters/UniversalAdapter.sol";
import {BotList} from "../../support/BotList.sol";
//
-import {PERCENTAGE_FACTOR} from "../../libraries/Constants.sol";
-import "../../libraries/Constants.sol";
-import {AddressList} from "../../libraries/AddressList.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
+import "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
+import {AddressList} from "@gearbox-protocol/core-v2/contracts/libraries/AddressList.sol";
// EXCEPTIONS
import {ICreditConfiguratorExceptions} from "../../interfaces/ICreditConfigurator.sol";
@@ -37,7 +37,7 @@ import "../lib/constants.sol";
// MOCKS
import {AdapterMock} from "../mocks/adapters/AdapterMock.sol";
-import {TargetContractMock} from "../mocks/adapters/TargetContractMock.sol";
+import {TargetContractMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/adapters/TargetContractMock.sol";
// SUITES
import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
diff --git a/contracts/test/credit/CreditFacade.t.sol b/contracts/test/credit/CreditFacade.t.sol
index 6f007ed7..87956ad0 100644
--- a/contracts/test/credit/CreditFacade.t.sol
+++ b/contracts/test/credit/CreditFacade.t.sol
@@ -4,32 +4,35 @@
pragma solidity ^0.8.10;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {IWETH} from "../../interfaces/external/IWETH.sol";
+import {IWETH} from "@gearbox-protocol/core-v2/contracts/interfaces/external/IWETH.sol";
import {CreditFacade} from "../../credit/CreditFacade.sol";
import {CreditManager} from "../../credit/CreditManager.sol";
-import {CreditAccount} from "../../credit/CreditAccount.sol";
-import {AccountFactory} from "../../core/AccountFactory.sol";
+import {CreditAccount} from "@gearbox-protocol/core-v2/contracts/credit/CreditAccount.sol";
+import {AccountFactory} from "@gearbox-protocol/core-v2/contracts/core/AccountFactory.sol";
import {BotList} from "../../support/BotList.sol";
import {ICreditFacade, ICreditFacadeExtended} from "../../interfaces/ICreditFacade.sol";
import {ICreditManagerV2, ICreditManagerV2Events, ClosureAction} from "../../interfaces/ICreditManagerV2.sol";
import {ICreditFacadeEvents, ICreditFacadeExceptions} from "../../interfaces/ICreditFacade.sol";
-import {IDegenNFT, IDegenNFTExceptions} from "../../interfaces/IDegenNFT.sol";
+import {IDegenNFT, IDegenNFTExceptions} from "@gearbox-protocol/core-v2/contracts/interfaces/IDegenNFT.sol";
import {IBlacklistHelper} from "../../interfaces/IBlacklistHelper.sol";
// DATA
-import {MultiCall, MultiCallOps} from "../../libraries/MultiCall.sol";
-import {Balance} from "../../libraries/Balances.sol";
+import {MultiCall, MultiCallOps} from "@gearbox-protocol/core-v2/contracts/libraries/MultiCall.sol";
+import {Balance} from "@gearbox-protocol/core-v2/contracts/libraries/Balances.sol";
-import {CreditFacadeMulticaller, CreditFacadeCalls} from "../../multicall/CreditFacadeCalls.sol";
+import {
+ CreditFacadeMulticaller,
+ CreditFacadeCalls
+} from "@gearbox-protocol/core-v2/contracts/multicall/CreditFacadeCalls.sol";
// CONSTANTS
-import {LEVERAGE_DECIMALS} from "../../libraries/Constants.sol";
-import {PERCENTAGE_FACTOR} from "../../libraries/Constants.sol";
+import {LEVERAGE_DECIMALS} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
// TESTS
@@ -43,7 +46,7 @@ import {ICreditManagerV2Exceptions} from "../../interfaces/ICreditManagerV2.sol"
// MOCKS
import {AdapterMock} from "../mocks/adapters/AdapterMock.sol";
-import {TargetContractMock} from "../mocks/adapters/TargetContractMock.sol";
+import {TargetContractMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/adapters/TargetContractMock.sol";
import {ERC20BlacklistableMock} from "../mocks/token/ERC20Blacklistable.sol";
// SUITES
diff --git a/contracts/test/credit/CreditManager.t.sol b/contracts/test/credit/CreditManager.t.sol
index f49eef4b..5c179ce4 100644
--- a/contracts/test/credit/CreditManager.t.sol
+++ b/contracts/test/credit/CreditManager.t.sol
@@ -3,11 +3,11 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {IAddressProvider} from "../../interfaces/IAddressProvider.sol";
-import {ACL} from "../../core/ACL.sol";
+import {IAddressProvider} from "@gearbox-protocol/core-v2/contracts/interfaces/IAddressProvider.sol";
+import {ACL} from "@gearbox-protocol/core-v2/contracts/core/ACL.sol";
-import {AccountFactory} from "../../core/AccountFactory.sol";
-import {ICreditAccount} from "../../interfaces/ICreditAccount.sol";
+import {AccountFactory} from "@gearbox-protocol/core-v2/contracts/core/AccountFactory.sol";
+import {ICreditAccount} from "@gearbox-protocol/core-v2/contracts/interfaces/ICreditAccount.sol";
import {
ICreditManagerV2,
ICreditManagerV2Events,
@@ -16,16 +16,16 @@ import {
CollateralTokenData
} from "../../interfaces/ICreditManagerV2.sol";
-import {IPriceOracleV2, IPriceOracleV2Ext} from "../../interfaces/IPriceOracle.sol";
+import {IPriceOracleV2, IPriceOracleV2Ext} from "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol";
import {CreditManager, UNIVERSAL_CONTRACT} from "../../credit/CreditManager.sol";
-import {IPoolService} from "../../interfaces/IPoolService.sol";
+import {IPoolService} from "@gearbox-protocol/core-v2/contracts/interfaces/IPoolService.sol";
-import {IWETH} from "../../interfaces/external/IWETH.sol";
+import {IWETH} from "@gearbox-protocol/core-v2/contracts/interfaces/external/IWETH.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {ERC20Mock} from "../mocks/token/ERC20Mock.sol";
-import {PERCENTAGE_FACTOR} from "../../libraries/Constants.sol";
+import {ERC20Mock} from "@gearbox-protocol/core-v2/contracts/test/mocks/token/ERC20Mock.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
// TESTS
@@ -36,16 +36,19 @@ import {BalanceHelper} from "../helpers/BalanceHelper.sol";
// EXCEPTIONS
// MOCKS
-import {PriceFeedMock} from "../mocks/oracles/PriceFeedMock.sol";
+import {PriceFeedMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/oracles/PriceFeedMock.sol";
import {PoolServiceMock} from "../mocks/pool/PoolServiceMock.sol";
-import {TargetContractMock} from "../mocks/adapters/TargetContractMock.sol";
-import {ERC20ApproveRestrictedRevert, ERC20ApproveRestrictedFalse} from "../mocks/token/ERC20ApproveRestricted.sol";
+import {TargetContractMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/adapters/TargetContractMock.sol";
+import {
+ ERC20ApproveRestrictedRevert,
+ ERC20ApproveRestrictedFalse
+} from "@gearbox-protocol/core-v2/contracts/test/mocks/token/ERC20ApproveRestricted.sol";
// SUITES
import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
import {Tokens} from "../config/Tokens.sol";
import {CreditManagerTestSuite} from "../suites/CreditManagerTestSuite.sol";
-import {GenesisFactory} from "../../factories/GenesisFactory.sol";
+import {GenesisFactory} from "@gearbox-protocol/core-v2/contracts/factories/GenesisFactory.sol";
import {CreditManagerTestInternal} from "../mocks/credit/CreditManagerTestInternal.sol";
import {CreditConfig} from "../config/CreditConfig.sol";
diff --git a/contracts/test/credit/CreditManager_Quotas.t.sol b/contracts/test/credit/CreditManager_Quotas.t.sol
index 40a32a24..d8d7cfa7 100644
--- a/contracts/test/credit/CreditManager_Quotas.t.sol
+++ b/contracts/test/credit/CreditManager_Quotas.t.sol
@@ -3,11 +3,11 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {IAddressProvider} from "../../interfaces/IAddressProvider.sol";
-import {ACL} from "../../core/ACL.sol";
+import {IAddressProvider} from "@gearbox-protocol/core-v2/contracts/interfaces/IAddressProvider.sol";
+import {ACL} from "@gearbox-protocol/core-v2/contracts/core/ACL.sol";
-import {AccountFactory} from "../../core/AccountFactory.sol";
-import {ICreditAccount} from "../../interfaces/ICreditAccount.sol";
+import {AccountFactory} from "@gearbox-protocol/core-v2/contracts/core/AccountFactory.sol";
+import {ICreditAccount} from "@gearbox-protocol/core-v2/contracts/interfaces/ICreditAccount.sol";
import {
ICreditManagerV2,
ICreditManagerV2Events,
@@ -23,16 +23,16 @@ import {
IPoolQuotaKeeperExceptions,
AccountQuota
} from "../../interfaces/IPoolQuotaKeeper.sol";
-import {IPriceOracleV2, IPriceOracleV2Ext} from "../../interfaces/IPriceOracle.sol";
+import {IPriceOracleV2, IPriceOracleV2Ext} from "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol";
import {CreditManager, UNIVERSAL_CONTRACT} from "../../credit/CreditManager.sol";
-import {IPoolService} from "../../interfaces/IPoolService.sol";
+import {IPoolService} from "@gearbox-protocol/core-v2/contracts/interfaces/IPoolService.sol";
-import {IWETH} from "../../interfaces/external/IWETH.sol";
+import {IWETH} from "@gearbox-protocol/core-v2/contracts/interfaces/external/IWETH.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {ERC20Mock} from "../mocks/token/ERC20Mock.sol";
-import {PERCENTAGE_FACTOR} from "../../libraries/Constants.sol";
+import {ERC20Mock} from "@gearbox-protocol/core-v2/contracts/test/mocks/token/ERC20Mock.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
// TESTS
@@ -43,17 +43,16 @@ import {BalanceHelper} from "../helpers/BalanceHelper.sol";
// EXCEPTIONS
// MOCKS
-import {PriceFeedMock} from "../mocks/oracles/PriceFeedMock.sol";
+import {PriceFeedMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/oracles/PriceFeedMock.sol";
import {PoolServiceMock} from "../mocks/pool/PoolServiceMock.sol";
import {PoolQuotaKeeper} from "../../pool/PoolQuotaKeeper.sol";
-import {TargetContractMock} from "../mocks/adapters/TargetContractMock.sol";
-import {ERC20ApproveRestrictedRevert, ERC20ApproveRestrictedFalse} from "../mocks/token/ERC20ApproveRestricted.sol";
+import {TargetContractMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/adapters/TargetContractMock.sol";
// SUITES
import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
import {Tokens} from "../config/Tokens.sol";
import {CreditManagerTestSuite} from "../suites/CreditManagerTestSuite.sol";
-import {GenesisFactory} from "../../factories/GenesisFactory.sol";
+import {GenesisFactory} from "@gearbox-protocol/core-v2/contracts/factories/GenesisFactory.sol";
import {CreditManagerTestInternal} from "../mocks/credit/CreditManagerTestInternal.sol";
import {CreditConfig} from "../config/CreditConfig.sol";
diff --git a/contracts/test/interfaces/ICreditConfig.sol b/contracts/test/interfaces/ICreditConfig.sol
index 6f9595cd..22717ccd 100644
--- a/contracts/test/interfaces/ICreditConfig.sol
+++ b/contracts/test/interfaces/ICreditConfig.sol
@@ -4,7 +4,7 @@
pragma solidity ^0.8.10;
import {ITokenTestSuite} from "./ITokenTestSuite.sol";
-import {PriceFeedConfig} from "../../oracles/PriceOracle.sol";
+import {PriceFeedConfig} from "@gearbox-protocol/core-v2/contracts/oracles/PriceOracle.sol";
import {CreditManagerOpts, CollateralToken} from "../../credit/CreditConfigurator.sol";
interface ICreditConfig {
diff --git a/contracts/test/lib/constants.sol b/contracts/test/lib/constants.sol
index a0715dcf..0ed795dd 100644
--- a/contracts/test/lib/constants.sol
+++ b/contracts/test/lib/constants.sol
@@ -1,7 +1,12 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;
-import {WAD, RAY, DEFAULT_FEE_LIQUIDATION, DEFAULT_LIQUIDATION_PREMIUM} from "../../libraries/Constants.sol";
+import {
+ WAD,
+ RAY,
+ DEFAULT_FEE_LIQUIDATION,
+ DEFAULT_LIQUIDATION_PREMIUM
+} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
import "../lib/test.sol";
import {CheatCodes, HEVM_ADDRESS} from "../lib/cheatCodes.sol";
diff --git a/contracts/test/mocks/adapters/TargetContractMock.sol b/contracts/test/mocks/adapters/TargetContractMock.sol
deleted file mode 100644
index 1daaaae3..00000000
--- a/contracts/test/mocks/adapters/TargetContractMock.sol
+++ /dev/null
@@ -1,15 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-/// @title Target Contract Mock
-contract TargetContractMock {
- bytes public callData;
-
- constructor() {}
-
- fallback() external {
- callData = msg.data;
- }
-}
diff --git a/contracts/test/mocks/credit/CreditManagerTestInternal.sol b/contracts/test/mocks/credit/CreditManagerTestInternal.sol
index d8c5a5b4..5db5fe68 100644
--- a/contracts/test/mocks/credit/CreditManagerTestInternal.sol
+++ b/contracts/test/mocks/credit/CreditManagerTestInternal.sol
@@ -7,7 +7,7 @@ import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {CreditManager, ClosureAction} from "../../../credit/CreditManager.sol";
-import {IPriceOracleV2} from "../../../interfaces/IPriceOracle.sol";
+import {IPriceOracleV2} from "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol";
import {IPoolQuotaKeeper, QuotaUpdate, TokenLT, QuotaStatusChange} from "../../../interfaces/IPoolQuotaKeeper.sol";
import {CollateralTokenData} from "../../../interfaces/ICreditManagerV2.sol";
diff --git a/contracts/test/mocks/dao/TreasuryMock.sol b/contracts/test/mocks/dao/TreasuryMock.sol
deleted file mode 100644
index 93370f60..00000000
--- a/contracts/test/mocks/dao/TreasuryMock.sol
+++ /dev/null
@@ -1,18 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-/**
- * @title TreasuryMock
- * @notice Just keeps money, used for test purpodes only
- * @author Gearbox
- */
-contract TreasuryMock {
- // emits each time when money come
- event NewDonation(uint256 amount);
-
- receive() external payable {
- emit NewDonation(msg.value);
- }
-}
diff --git a/contracts/test/mocks/oracles/LPPriceFeedMock.sol b/contracts/test/mocks/oracles/LPPriceFeedMock.sol
deleted file mode 100644
index dfc6a16a..00000000
--- a/contracts/test/mocks/oracles/LPPriceFeedMock.sol
+++ /dev/null
@@ -1,47 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {PriceFeedType} from "../../../interfaces/IPriceFeedType.sol";
-import {LPPriceFeed} from "../../../oracles/LPPriceFeed.sol";
-
-// EXCEPTIONS
-
-/// @title PPriceFeedMock pricefeed adapter
-contract LPPriceFeedMock is LPPriceFeed {
- PriceFeedType public constant override priceFeedType = PriceFeedType.YEARN_ORACLE;
- uint256 public constant override version = 1;
-
- // This pricefeed doesn't need sanity check, cause we check priceFeed for underlying token and set bounds for pricePerShare value
- bool public constant override skipPriceCheck = true;
-
- constructor(address addressProvider, uint256 range, string memory descrition)
- LPPriceFeed(
- addressProvider,
- range, // F:[LPF-1]
- descrition
- )
- {}
-
- function latestRoundData()
- external
- view
- override
- returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
- {
- roundId = 1;
- answer = 0;
- startedAt = block.timestamp;
- updatedAt = block.timestamp;
- answeredInRound = 1;
- }
-
- function checkAndUpperBoundValue(uint256 value) external view returns (uint256) {
- return _checkAndUpperBoundValue(value);
- }
-
- function _checkCurrentValueInBounds(uint256, uint256) internal pure override returns (bool) {
- return true;
- }
-}
diff --git a/contracts/test/mocks/oracles/PriceFeedMock.sol b/contracts/test/mocks/oracles/PriceFeedMock.sol
deleted file mode 100644
index 7b4a447b..00000000
--- a/contracts/test/mocks/oracles/PriceFeedMock.sol
+++ /dev/null
@@ -1,117 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
-import {IPriceFeedType, PriceFeedType} from "../../../interfaces/IPriceFeedType.sol";
-
-enum FlagState {
- FALSE,
- TRUE,
- REVERT
-}
-
-/// @title Price feed mock
-/// @notice Used for test purposes only
-contract PriceFeedMock is AggregatorV3Interface, IPriceFeedType {
- int256 private price;
- uint8 public immutable override decimals;
-
- uint80 internal roundId;
- uint256 startedAt;
- uint256 updatedAt;
- uint80 internal answerInRound;
-
- PriceFeedType internal _priceFeedType;
-
- FlagState internal _skipPriceCheck;
-
- bool internal revertOnLatestRound;
-
- constructor(int256 _price, uint8 _decimals) {
- price = _price;
- decimals = _decimals;
- roundId = 80;
- answerInRound = 80;
- startedAt = uint256(block.timestamp) + 1;
- updatedAt = uint256(block.timestamp) + 1;
- }
-
- function setParams(uint80 _roundId, uint256 _startedAt, uint256 _updatedAt, uint80 _answerInRound) external {
- roundId = _roundId;
- startedAt = _startedAt;
- updatedAt = _updatedAt;
- answerInRound = _answerInRound;
-
- _skipPriceCheck = FlagState.REVERT;
- }
-
- function description() external pure override returns (string memory) {
- return "price oracle";
- }
-
- function version() external pure override returns (uint256) {
- return 1;
- }
-
- function setPrice(int256 newPrice) external {
- price = newPrice;
- }
-
- // getRoundData and latestRoundData should both raise "No data present"
- // if they do not have data to report, instead of returning unset values
- // which could be misinterpreted as actual reported values.
- function getRoundData(uint80)
- external
- view
- override
- returns (
- uint80, // roundId,
- int256, // answer,
- uint256, // startedAt,
- uint256, // updatedAt,
- uint80 // answeredInRound
- )
- {
- return (roundId, price, startedAt, updatedAt, answerInRound);
- }
-
- function latestRoundData()
- external
- view
- override
- returns (
- uint80, // roundId,
- int256, // answer,
- uint256, // startedAt,
- uint256, // updatedAt,
- uint80 //answeredInRound
- )
- {
- if (revertOnLatestRound) revert();
-
- return (roundId, price, startedAt, updatedAt, answerInRound);
- }
-
- function priceFeedType() external view override returns (PriceFeedType) {
- return _priceFeedType;
- }
-
- function skipPriceCheck() external view override returns (bool) {
- return flagState(_skipPriceCheck);
- }
-
- function flagState(FlagState f) internal pure returns (bool value) {
- if (f == FlagState.REVERT) revert();
- return f == FlagState.TRUE;
- }
-
- function setSkipPriceCheck(FlagState f) external {
- _skipPriceCheck = f;
- }
-
- function setRevertOnLatestRound(bool value) external {
- revertOnLatestRound = value;
- }
-}
diff --git a/contracts/test/mocks/pool/CreditManagerMockForPoolTest.sol b/contracts/test/mocks/pool/CreditManagerMockForPoolTest.sol
index 90a90549..276351b4 100644
--- a/contracts/test/mocks/pool/CreditManagerMockForPoolTest.sol
+++ b/contracts/test/mocks/pool/CreditManagerMockForPoolTest.sol
@@ -3,7 +3,7 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {IPoolService} from "../../../interfaces/IPoolService.sol";
+import {IPoolService} from "@gearbox-protocol/core-v2/contracts/interfaces/IPoolService.sol";
import "../../lib/constants.sol";
contract CreditManagerMockForPoolTest {
diff --git a/contracts/test/mocks/pool/PoolServiceMock.sol b/contracts/test/mocks/pool/PoolServiceMock.sol
index 683f0cac..347238d2 100644
--- a/contracts/test/mocks/pool/PoolServiceMock.sol
+++ b/contracts/test/mocks/pool/PoolServiceMock.sol
@@ -6,11 +6,11 @@ pragma solidity ^0.8.10;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
-import {RAY} from "../../../libraries/Constants.sol";
+import {RAY} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
-import {IPoolService} from "../../../interfaces/IPoolService.sol";
+import {IPoolService} from "@gearbox-protocol/core-v2/contracts/interfaces/IPoolService.sol";
-import {AddressProvider} from "../../../core/AddressProvider.sol";
+import {AddressProvider} from "@gearbox-protocol/core-v2/contracts/core/AddressProvider.sol";
/**
* @title Mock of pool service for CreditManager constracts testing
diff --git a/contracts/test/mocks/pool/TestPoolService.sol b/contracts/test/mocks/pool/TestPoolService.sol
deleted file mode 100644
index 8c07987b..00000000
--- a/contracts/test/mocks/pool/TestPoolService.sol
+++ /dev/null
@@ -1,53 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IPoolService} from "../../../interfaces/IPoolService.sol";
-
-import {PoolService} from "../../../pool/PoolService.sol";
-
-/**
- * @title Pool Service Test implementation
- * @notice Used for testing Pool Service. Implements some functions to set internal parameters
- * @author Gearbox
- */
-contract TestPoolService is IPoolService, PoolService {
- /**
- * @dev Constructor
- * @param addressProvider Address Repository for upgradable contract model
- * @param _underlying Address of underlying token
- * @param interestRateModelAddress Address of interest rate model
- */
- constructor(
- address addressProvider,
- address _underlying,
- address interestRateModelAddress,
- uint256 _expectedLiquidityLimit
- ) PoolService(addressProvider, _underlying, interestRateModelAddress, _expectedLiquidityLimit) {}
-
- /**
- * @dev Mock function to set _totalLiquidity manually
- * used for test purposes only
- */
-
- function setExpectedLiquidity(uint256 newExpectedLiquidity) external {
- _expectedLiquidityLU = newExpectedLiquidity;
- }
-
- function getCumulativeIndex_RAY() external view returns (uint256) {
- return _cumulativeIndex_RAY;
- }
-
- function getTimestampLU() external view returns (uint256) {
- return _timestampLU;
- }
-
- function getExpectedLU() external view returns (uint256) {
- return _expectedLiquidityLU;
- }
-
- function updateBorrowRate() external {
- _updateBorrowRate(0);
- }
-}
diff --git a/contracts/test/mocks/token/ERC20ApproveRestricted.sol b/contracts/test/mocks/token/ERC20ApproveRestricted.sol
deleted file mode 100644
index 064fb2d1..00000000
--- a/contracts/test/mocks/token/ERC20ApproveRestricted.sol
+++ /dev/null
@@ -1,31 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
-import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
-
-contract ERC20ApproveRestrictedRevert is ERC20, Ownable {
- constructor() ERC20("", "") {}
-
- function approve(address user, uint256 amount) public override returns (bool) {
- if ((allowance(msg.sender, user) > 0) && (amount != 0)) {
- revert("Try to change allowance from non-zero to non-zero");
- }
- _approve(msg.sender, user, amount);
- return true;
- }
-}
-
-contract ERC20ApproveRestrictedFalse is ERC20, Ownable {
- constructor() ERC20("", "") {}
-
- function approve(address user, uint256 amount) public override returns (bool) {
- if ((allowance(msg.sender, user) > 0) && (amount != 0)) {
- return false;
- }
- _approve(msg.sender, user, amount);
- return true;
- }
-}
diff --git a/contracts/test/mocks/token/ERC20Blocking.sol b/contracts/test/mocks/token/ERC20Blocking.sol
deleted file mode 100644
index 5670f2be..00000000
--- a/contracts/test/mocks/token/ERC20Blocking.sol
+++ /dev/null
@@ -1,29 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
-import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
-
-contract ERC20BlockingMock is ERC20, Ownable {
- bool public isBlocked;
-
- constructor(string memory name_, string memory symbol_) ERC20(name_, symbol_) {
- _mint(msg.sender, 1e24);
- isBlocked = false;
- }
-
- function blockToken() external {
- isBlocked = true;
- }
-
- function mint(address to, uint256 amount) external onlyOwner {
- _mint(to, amount);
- }
-
- function transfer(address recipient, uint256 amount) public override returns (bool) {
- _transfer(_msgSender(), recipient, amount);
- return !isBlocked;
- }
-}
diff --git a/contracts/test/mocks/token/ERC20FeeMock.sol b/contracts/test/mocks/token/ERC20FeeMock.sol
index 5c6de9dc..9f4f114e 100644
--- a/contracts/test/mocks/token/ERC20FeeMock.sol
+++ b/contracts/test/mocks/token/ERC20FeeMock.sol
@@ -4,8 +4,8 @@
pragma solidity ^0.8.10;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
-import {ERC20Mock} from "./ERC20Mock.sol";
-import {PERCENTAGE_FACTOR} from "../../../libraries/Constants.sol";
+import {ERC20Mock} from "@gearbox-protocol/core-v2/contracts/test/mocks/token/ERC20Mock.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
import {IUSDT} from "../../../interfaces/external/IUSDT.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
diff --git a/contracts/test/mocks/token/ERC20Mock.sol b/contracts/test/mocks/token/ERC20Mock.sol
deleted file mode 100644
index 4134c516..00000000
--- a/contracts/test/mocks/token/ERC20Mock.sol
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
-import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
-
-contract ERC20Mock is ERC20, Ownable {
- uint8 private immutable _decimals;
- address public minter;
-
- constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_) {
- _decimals = decimals_;
- minter = msg.sender;
- // _mint(msg.sender, 1e24);
- }
-
- modifier minterOnly() {
- require(msg.sender == minter, "Minter calls only");
- _;
- }
-
- function decimals() public view override returns (uint8) {
- return _decimals;
- }
-
- function mint(address to, uint256 amount) external minterOnly returns (bool) {
- _mint(to, amount);
- return true;
- }
-
- function burnFrom(address to, uint256 amount) external minterOnly returns (bool) {
- _burn(to, amount);
- return true;
- }
-
- function burn(address to, uint256 amount) external returns (bool) {
- _burn(to, amount);
- return true;
- }
-
- function set_minter(address _minter) external {
- minter = _minter;
- }
-}
diff --git a/contracts/test/mocks/token/ERC20NonCompliant.sol b/contracts/test/mocks/token/ERC20NonCompliant.sol
deleted file mode 100644
index 062d8f2e..00000000
--- a/contracts/test/mocks/token/ERC20NonCompliant.sol
+++ /dev/null
@@ -1,8 +0,0 @@
-pragma solidity ^0.8.10;
-
-//Non ERC20 compliant token which do not have a return value on approve/transfer (e.g. TUSD, OMG)
-contract NonCompliantERC20 {
- function approve(address, uint256) external pure returns (bool) {
- return false;
- }
-}
diff --git a/contracts/test/mocks/token/ERC721ReceiverMock.sol b/contracts/test/mocks/token/ERC721ReceiverMock.sol
deleted file mode 100644
index 10d69edc..00000000
--- a/contracts/test/mocks/token/ERC721ReceiverMock.sol
+++ /dev/null
@@ -1,19 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-pragma solidity ^0.8.10;
-
-interface IERC721Receiver {
- function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
- external
- returns (bytes4);
-}
-
-contract ERC721ReceiverMock is IERC721Receiver {
- function onERC721Received(
- address, // operator,
- address, // from,
- uint256, // tokenId,
- bytes calldata // data
- ) external pure returns (bytes4) {
- return IERC721Receiver.onERC721Received.selector;
- }
-}
diff --git a/contracts/test/mocks/token/WETHMock.sol b/contracts/test/mocks/token/WETHMock.sol
deleted file mode 100644
index be922bd4..00000000
--- a/contracts/test/mocks/token/WETHMock.sol
+++ /dev/null
@@ -1,68 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-pragma solidity ^0.8.10;
-
-import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-
-contract WETHMock is IERC20 {
- string public name = "Wrapped Ether";
- string public symbol = "WETH";
- uint8 public decimals = 18;
-
- // event Approval(address indexed src, address indexed guy, uint256 wad);
- // event Transfer(address indexed src, address indexed dst, uint256 wad);
- event Deposit(address indexed dst, uint256 wad);
- event Withdrawal(address indexed src, uint256 wad);
-
- mapping(address => uint256) public balanceOf;
- mapping(address => mapping(address => uint256)) public allowance;
-
- function mint(address to, uint256 amount) external {
- balanceOf[to] += amount;
- }
-
- receive() external payable {
- deposit(); // T:[WM-1]
- }
-
- function deposit() public payable {
- balanceOf[msg.sender] += msg.value; // T:[WM-1]
- emit Deposit(msg.sender, msg.value); // T:[WM-1]
- }
-
- function withdraw(uint256 wad) public {
- require(balanceOf[msg.sender] >= wad); // T:[WM-2]
- balanceOf[msg.sender] -= wad; // T:[WM-2]
- payable(msg.sender).transfer(wad); // T:[WM-3]
- emit Withdrawal(msg.sender, wad); // T:[WM-4]
- }
-
- function totalSupply() public view returns (uint256) {
- return address(this).balance; // T:[WM-1, 2]
- }
-
- function approve(address guy, uint256 wad) public returns (bool) {
- allowance[msg.sender][guy] = wad; // T:[WM-3]
- emit Approval(msg.sender, guy, wad); // T:[WM-3]
- return true;
- }
-
- function transfer(address dst, uint256 wad) public returns (bool) {
- return transferFrom(msg.sender, dst, wad); // T:[WM-4,5,6]
- }
-
- function transferFrom(address src, address dst, uint256 wad) public returns (bool) {
- require(balanceOf[src] >= wad); // T:[WM-4]
-
- if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) {
- require(allowance[src][msg.sender] >= wad); // T:[WM-4]
- allowance[src][msg.sender] -= wad; // T:[WM-7]
- }
-
- balanceOf[src] -= wad; // T:[WM-5]
- balanceOf[dst] += wad; // T:[WM-5]
-
- emit Transfer(src, dst, wad); // T:[WM-6]
-
- return true;
- }
-}
diff --git a/contracts/test/oracles/BoundedPriceFeed.t.sol b/contracts/test/oracles/BoundedPriceFeed.t.sol
deleted file mode 100644
index e7b35f47..00000000
--- a/contracts/test/oracles/BoundedPriceFeed.t.sol
+++ /dev/null
@@ -1,87 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {BoundedPriceFeed} from "../../oracles/BoundedPriceFeed.sol";
-import {PriceFeedMock} from "../mocks/oracles/PriceFeedMock.sol";
-import {AddressProviderACLMock} from "../mocks/core/AddressProviderACLMock.sol";
-
-import {CheatCodes, HEVM_ADDRESS} from "../lib/cheatCodes.sol";
-import "../lib/test.sol";
-import "../lib/constants.sol";
-
-// SUITES
-import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
-
-// EXCEPTIONS
-import {NotImplementedException, CallerNotConfiguratorException} from "../../interfaces/IErrors.sol";
-
-/// @title BoundedPriceFeedTest
-/// @notice Designed for unit test purposes only
-contract BoundedPriceFeedTest is DSTest {
- CheatCodes evm = CheatCodes(HEVM_ADDRESS);
-
- PriceFeedMock public targetPf;
- BoundedPriceFeed public pf;
-
- TokensTestSuite tokenTestSuite;
-
- function setUp() public {
- targetPf = new PriceFeedMock(8 * 10**8, 8);
- pf = new BoundedPriceFeed(address(targetPf), 10 * 10**8);
- }
-
- ///
- ///
- /// TESTS
- ///
- ///
-
- /// @dev [BPF-1]: constructor sets correct values
- function test_BPF_01_constructor_sets_correct_values() public {
- assertEq(pf.description(), "price oracle Bounded", "Incorrect description");
-
- assertEq(pf.decimals(), 8, "Incorrect decimals");
-
- assertTrue(!pf.skipPriceCheck(), "Incorrect skipPriceCheck");
- }
-
- /// @dev [BPF-2]: getRoundData reverts
- function test_BPF_02_getRoundData_reverts() public {
- evm.expectRevert(NotImplementedException.selector);
-
- pf.getRoundData(1);
- }
-
- /// @dev [BPF-3]: latestRoundData works correctly
- function test_BPF_03_latestRoundData_works_correctly() public {
- (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) =
- pf.latestRoundData();
- (
- uint80 roundIdTarget,
- int256 answerTarget,
- uint256 startedAtTarget,
- uint256 updatedAtTarget,
- uint80 answeredInRoundTarget
- ) = targetPf.latestRoundData();
-
- assertEq(roundId, roundIdTarget, "Incorrect round Id #1");
- assertEq(answer, answerTarget, "Incorrect answer #1");
- assertEq(startedAt, startedAtTarget, "Incorrect startedAt #1");
- assertEq(updatedAt, updatedAtTarget, "Incorrect updatedAt #1");
- assertEq(answeredInRound, answeredInRoundTarget, "Incorrect answeredInRound #1");
-
- targetPf.setPrice(15 * 10 ** 8);
-
- (roundId, answer, startedAt, updatedAt, answeredInRound) = pf.latestRoundData();
- (roundIdTarget, answerTarget, startedAtTarget, updatedAtTarget, answeredInRoundTarget) =
- targetPf.latestRoundData();
-
- assertEq(roundId, roundIdTarget, "Incorrect round Id #2");
- assertEq(answer, int256(pf.upperBound()), "Incorrect answer #2");
- assertEq(startedAt, startedAtTarget, "Incorrect startedAt #2");
- assertEq(updatedAt, updatedAtTarget, "Incorrect updatedAt #2");
- assertEq(answeredInRound, answeredInRoundTarget, "Incorrect answeredInRound #2");
- }
-}
diff --git a/contracts/test/oracles/CompositePriceFeed.t.sol b/contracts/test/oracles/CompositePriceFeed.t.sol
deleted file mode 100644
index 8b6cd995..00000000
--- a/contracts/test/oracles/CompositePriceFeed.t.sol
+++ /dev/null
@@ -1,132 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {CompositePriceFeed} from "../../oracles/CompositePriceFeed.sol";
-import {PriceFeedMock} from "../mocks/oracles/PriceFeedMock.sol";
-import {IPriceOracleV2Exceptions} from "../../interfaces/IPriceOracle.sol";
-
-import {CheatCodes, HEVM_ADDRESS} from "../lib/cheatCodes.sol";
-import "../lib/test.sol";
-import "../lib/constants.sol";
-
-// SUITES
-import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
-
-// EXCEPTIONS
-import {NotImplementedException, CallerNotConfiguratorException} from "../../interfaces/IErrors.sol";
-
-/// @title CompositePriceFeedTest
-/// @notice Designed for unit test purposes only
-contract CompositePriceFeedTest is DSTest, IPriceOracleV2Exceptions {
- CheatCodes evm = CheatCodes(HEVM_ADDRESS);
-
- PriceFeedMock public targetPf;
- PriceFeedMock public baseUsdPf;
- CompositePriceFeed public pf;
-
- TokensTestSuite tokenTestSuite;
-
- function setUp() public {
- targetPf = new PriceFeedMock(99 * 10**16, 18);
- baseUsdPf = new PriceFeedMock(1000 * 10**8, 8);
- pf = new CompositePriceFeed(address(targetPf), address(baseUsdPf));
- }
-
- ///
- ///
- /// TESTS
- ///
- ///
-
- /// @dev [CPF-1]: constructor sets correct values
- function test_CPF_01_constructor_sets_correct_values() public {
- assertEq(pf.description(), "price oracle to USD Composite", "Incorrect description");
-
- assertEq(pf.decimals(), 8, "Incorrect decimals");
-
- assertEq(pf.answerDenominator(), int256(10 ** 18), "Incorrect ETH price feed decimals");
-
- assertTrue(pf.skipPriceCheck(), "Incorrect skipPriceCheck");
- }
-
- /// @dev [CPF-2]: getRoundData reverts
- function test_CPF_02_getRoundData_reverts() public {
- evm.expectRevert(NotImplementedException.selector);
-
- pf.getRoundData(1);
- }
-
- /// @dev [CPF-3]: latestRoundData works correctly
- function test_CPF_03_latestRoundData_works_correctly(int256 answer1, int256 answer2) public {
- evm.assume(answer1 > 0);
- evm.assume(answer2 > 0);
- evm.assume(answer1 < int256(RAY));
- evm.assume(answer2 < int256(RAY));
-
- targetPf.setPrice(answer1);
- baseUsdPf.setPrice(answer2);
-
- (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) =
- pf.latestRoundData();
- (, int256 answerTarget,,,) = targetPf.latestRoundData();
- (
- uint80 roundIdBase,
- int256 answerBase,
- uint256 startedAtBase,
- uint256 updatedAtBase,
- uint80 answeredInRoundBase
- ) = baseUsdPf.latestRoundData();
-
- assertEq(roundId, roundIdBase, "Incorrect round Id #1");
- assertEq(answer, (answerTarget * answerBase) / int256(10 ** targetPf.decimals()), "Incorrect answer #1");
- assertEq(startedAt, startedAtBase, "Incorrect startedAt #1");
- assertEq(updatedAt, updatedAtBase, "Incorrect updatedAt #1");
- assertEq(answeredInRound, answeredInRoundBase, "Incorrect answeredInRound #1");
- }
-
- /// @dev [CEPF-4]: latestRoundData reverts on failing sanity checks
- function test_CEPF_04_latestRoundData_reverts_on_incorrect_answers() public {
- (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) =
- targetPf.latestRoundData();
-
- targetPf.setParams(roundId, startedAt, 0, answeredInRound);
-
- evm.expectRevert(ChainPriceStaleException.selector);
- pf.latestRoundData();
-
- targetPf.setParams(roundId, startedAt, updatedAt, roundId - 1);
-
- evm.expectRevert(ChainPriceStaleException.selector);
- pf.latestRoundData();
-
- targetPf.setParams(roundId, startedAt, updatedAt, answeredInRound);
-
- targetPf.setPrice(0);
-
- evm.expectRevert(ZeroPriceException.selector);
- pf.latestRoundData();
-
- targetPf.setPrice(99 * 10 ** 16);
-
- (roundId, answer, startedAt, updatedAt, answeredInRound) = baseUsdPf.latestRoundData();
-
- baseUsdPf.setParams(roundId, startedAt, 0, answeredInRound);
-
- evm.expectRevert(ChainPriceStaleException.selector);
- pf.latestRoundData();
-
- baseUsdPf.setParams(roundId, startedAt, updatedAt, roundId - 1);
-
- evm.expectRevert(ChainPriceStaleException.selector);
- pf.latestRoundData();
-
- baseUsdPf.setParams(roundId, startedAt, updatedAt, answeredInRound);
-
- baseUsdPf.setPrice(0);
-
- evm.expectRevert(ZeroPriceException.selector);
- pf.latestRoundData();
- }
-}
diff --git a/contracts/test/oracles/LPPriceFeed.t.sol b/contracts/test/oracles/LPPriceFeed.t.sol
deleted file mode 100644
index d0235022..00000000
--- a/contracts/test/oracles/LPPriceFeed.t.sol
+++ /dev/null
@@ -1,113 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {ILPPriceFeedExceptions, ILPPriceFeedEvents} from "../../interfaces/ILPPriceFeed.sol";
-import {PERCENTAGE_FACTOR} from "../../libraries/Constants.sol";
-
-// TEST
-import "../lib/constants.sol";
-
-// MOCKS
-import {LPPriceFeedMock} from "../mocks/oracles/LPPriceFeedMock.sol";
-import {AddressProviderACLMock} from "../mocks/core/AddressProviderACLMock.sol";
-
-// SUITES
-import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
-
-// EXCEPTIONS
-
-import {
- ZeroAddressException, CallerNotConfiguratorException, NotImplementedException
-} from "../../interfaces/IErrors.sol";
-
-import {IPriceOracleV2Exceptions} from "../../interfaces/IPriceOracle.sol";
-
-uint256 constant RANGE_WIDTH = 200; // 2%
-
-/// @title LPPriceFeedTest
-/// @notice Designed for unit test purposes only
-contract LPPriceFeedTest is DSTest, ILPPriceFeedEvents, ILPPriceFeedExceptions, IPriceOracleV2Exceptions {
- CheatCodes evm = CheatCodes(HEVM_ADDRESS);
-
- AddressProviderACLMock public addressProvider;
-
- LPPriceFeedMock public pf;
-
- TokensTestSuite tokenTestSuite;
-
- function setUp() public {
- evm.prank(CONFIGURATOR);
- addressProvider = new AddressProviderACLMock();
-
- pf = new LPPriceFeedMock(address(addressProvider), RANGE_WIDTH, "MOCK");
-
- evm.label(address(pf), "LP_PRICE_FEED");
- }
-
- ///
- ///
- /// TESTS
- ///
- ///
-
- /// @dev [LPF-1]: constructor sets correct values
- function test_LPF_01_constructor_sets_correct_values() public {
- // LP2
-
- assertEq(pf.description(), "MOCK");
-
- assertEq(pf.delta(), RANGE_WIDTH, "Incorrect delta");
- }
-
- /// @dev [LPF-2]: getRoundData reverts
- function test_LPF_02_getRoundData_reverts() public {
- evm.expectRevert(NotImplementedException.selector);
-
- pf.getRoundData(1);
- }
-
- /// @dev [LPF-3]: _checkAndUpperBoundValue reverts if below bounds and returns upperBound if above bounds
- function test_LPF_03_latestRoundData_works_correctly(uint256 value) public {
- evm.assume(value > 0 && value < type(uint256).max >> 16);
-
- evm.prank(CONFIGURATOR);
- pf.setLimiter(value);
-
- evm.expectRevert(ValueOutOfRangeException.selector);
- pf.checkAndUpperBoundValue(value - 1);
-
- uint256 val = pf.checkAndUpperBoundValue((value * (PERCENTAGE_FACTOR + RANGE_WIDTH)) / PERCENTAGE_FACTOR + 1);
-
- assertEq(
- val, (value * (PERCENTAGE_FACTOR + RANGE_WIDTH)) / PERCENTAGE_FACTOR, "Upper bounded value is incorrect"
- );
- }
-
- /// @dev [LPF-4]: setLimiter reverts for non-configurator or value = 0
- function test_LPF_04_setLimiter_reverts_for_non_configurator_or_with_zero_value() public {
- evm.expectRevert(CallerNotConfiguratorException.selector);
- pf.setLimiter(44);
-
- evm.expectRevert(IncorrectLimitsException.selector);
- evm.prank(CONFIGURATOR);
- pf.setLimiter(0);
- }
-
- /// @dev [LPF-5]: setLimiter sets bounds correctly
- function test_LPF_05_setLimiter_sets_bounds_correctly(uint256 value) public {
- evm.assume(value > 0 && value < type(uint256).max >> 16);
-
- uint256 expectedUpperBound = (value * (PERCENTAGE_FACTOR + RANGE_WIDTH)) / PERCENTAGE_FACTOR;
-
- evm.expectEmit(false, false, false, true);
- emit NewLimiterParams(value, expectedUpperBound);
-
- evm.prank(CONFIGURATOR);
- pf.setLimiter(value);
-
- assertEq(pf.lowerBound(), value, "Incorrect lower bound");
- assertEq(pf.upperBound(), expectedUpperBound, "Incorrect upper bound");
- }
-}
diff --git a/contracts/test/oracles/PriceOracle.t.sol b/contracts/test/oracles/PriceOracle.t.sol
deleted file mode 100644
index 86157412..00000000
--- a/contracts/test/oracles/PriceOracle.t.sol
+++ /dev/null
@@ -1,345 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IPriceOracleV2Events} from "../../interfaces/IPriceOracle.sol";
-import {PriceOracle, PriceFeedConfig} from "../../oracles/PriceOracle.sol";
-
-import {AddressProvider} from "../../core/AddressProvider.sol";
-import {ACL} from "../../core/ACL.sol";
-
-// LIBRARIES
-
-// TEST
-import "../lib/constants.sol";
-
-// MOCKS
-import {ERC20Mock} from "../mocks/token/ERC20Mock.sol";
-import {PriceFeedMock, FlagState} from "../mocks/oracles/PriceFeedMock.sol";
-
-// SUITES
-import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
-import {Tokens} from "../config/Tokens.sol";
-
-// EXCEPTIONS
-import {
- ZeroAddressException,
- AddressIsNotContractException,
- IncorrectPriceFeedException,
- IncorrectTokenContractException
-} from "../../interfaces/IErrors.sol";
-import {IPriceOracleV2Exceptions} from "../../interfaces/IPriceOracle.sol";
-
-/// @title PriceOracleTest
-/// @notice Designed for unit test purposes only
-contract PriceOracleTest is DSTest, IPriceOracleV2Events, IPriceOracleV2Exceptions {
- CheatCodes evm = CheatCodes(HEVM_ADDRESS);
-
- TokensTestSuite tokenTestSuite;
-
- AddressProvider public addressProvider;
- ACL public acl;
-
- PriceOracle public priceOracle;
-
- function setUp() public {
- tokenTestSuite = new TokensTestSuite();
- tokenTestSuite.topUpWETH{value: 100 * WAD}();
-
- evm.startPrank(CONFIGURATOR);
- addressProvider = new AddressProvider();
- addressProvider.setWethToken(tokenTestSuite.wethToken());
-
- acl = new ACL();
-
- addressProvider.setACL(address(acl));
-
- priceOracle = new PriceOracle(
- address(addressProvider),
- tokenTestSuite.getPriceFeeds()
- );
-
- evm.stopPrank();
- }
-
- ///
- ///
- /// TESTS
- ///
- ///
-
- /// @dev [PO-1]: constructor sets correct values
- function test_PO_01_constructor_sets_correct_values() public {
- Tokens[4] memory tokensAdded = [Tokens.DAI, Tokens.USDC, Tokens.WETH, Tokens.LINK];
-
- uint256 len = tokensAdded.length;
-
- for (uint256 i = 0; i < len; i++) {
- address token = tokenTestSuite.addressOf(tokensAdded[i]);
- address priceFeed = tokenTestSuite.priceFeedsMap(tokensAdded[i]);
-
- assertEq(
- priceOracle.priceFeeds(token),
- priceFeed,
- string(abi.encodePacked("Incorrect pricefeed ", tokenTestSuite.symbols(tokensAdded[i])))
- );
- }
- }
-
- /// @dev [PO-2]: addPriceFeed reverts for zero address and incorrect digitals
- function test_PO_02_addPriceFeed_reverts_for_zero_address_and_incorrect_contracts() public {
- evm.startPrank(CONFIGURATOR);
-
- evm.expectRevert(ZeroAddressException.selector);
- priceOracle.addPriceFeed(address(0), DUMB_ADDRESS);
-
- evm.expectRevert(ZeroAddressException.selector);
- priceOracle.addPriceFeed(DUMB_ADDRESS, address(0));
-
- // Checks that it reverts for non-contract addresses
- evm.expectRevert(abi.encodeWithSelector(AddressIsNotContractException.selector, DUMB_ADDRESS));
-
- priceOracle.addPriceFeed(DUMB_ADDRESS, address(this));
-
- evm.expectRevert(abi.encodeWithSelector(AddressIsNotContractException.selector, DUMB_ADDRESS2));
- priceOracle.addPriceFeed(address(this), DUMB_ADDRESS2);
-
- // Checks that it reverts if token has no .decimals() method
- PriceFeedMock priceFeed = new PriceFeedMock(8 * 10**8, 8);
- evm.expectRevert(IncorrectTokenContractException.selector);
- priceOracle.addPriceFeed(address(this), address(priceFeed));
-
- // 19 digits case
- ERC20Mock token19decimals = new ERC20Mock("19-19", "19-19", 19);
-
- evm.expectRevert(IncorrectTokenContractException.selector);
- priceOracle.addPriceFeed(address(token19decimals), address(priceFeed));
-
- address daiToken = tokenTestSuite.addressOf(Tokens.DAI);
-
- evm.expectRevert(IncorrectPriceFeedException.selector);
- // Checks that it reverts if priceFeed has no .decimals() method
- priceOracle.addPriceFeed(daiToken, address(this));
-
- PriceFeedMock pfMock9decimals = new PriceFeedMock(10, 9);
-
- evm.expectRevert(IncorrectPriceFeedException.selector);
- priceOracle.addPriceFeed(daiToken, address(pfMock9decimals));
-
- priceFeed.setRevertOnLatestRound(true);
-
- evm.expectRevert(IncorrectPriceFeedException.selector);
- priceOracle.addPriceFeed(daiToken, address(priceFeed));
-
- priceFeed.setPrice(0);
- priceFeed.setParams(80, block.timestamp, block.timestamp, 80);
-
- evm.expectRevert(IncorrectPriceFeedException.selector);
- priceOracle.addPriceFeed(daiToken, address(priceFeed));
-
- priceFeed.setRevertOnLatestRound(false);
- priceFeed.setPrice(0);
- priceFeed.setParams(80, block.timestamp, block.timestamp, 80);
-
- evm.expectRevert(ZeroPriceException.selector);
- priceOracle.addPriceFeed(daiToken, address(priceFeed));
-
- priceFeed.setPrice(10);
- priceFeed.setParams(80, block.timestamp, block.timestamp, 78);
-
- evm.expectRevert(ChainPriceStaleException.selector);
- priceOracle.addPriceFeed(daiToken, address(priceFeed));
-
- priceFeed.setRevertOnLatestRound(false);
- priceFeed.setPrice(10);
- priceFeed.setParams(80, block.timestamp, block.timestamp, 78);
-
- evm.expectRevert(ChainPriceStaleException.selector);
- priceOracle.addPriceFeed(daiToken, address(priceFeed));
-
- priceFeed.setParams(80, block.timestamp, 0, 80);
-
- evm.expectRevert(ChainPriceStaleException.selector);
- priceOracle.addPriceFeed(daiToken, address(priceFeed));
- }
-
- /// @dev [PO-3]: addPriceFeed adds pricefeed and emits event
- function test_PO_03_addPriceFeed_adds_pricefeed_and_emits_event() public {
- for (uint256 sc = 0; sc < 2; sc++) {
- bool skipCheck = sc != 0;
-
- setUp();
-
- ERC20Mock token = new ERC20Mock("Token", "Token", 17);
-
- PriceFeedMock priceFeed = new PriceFeedMock(8 * 10**8, 8);
-
- priceFeed.setSkipPriceCheck(skipCheck ? FlagState.TRUE : FlagState.FALSE);
-
- evm.expectEmit(true, true, false, false);
- emit NewPriceFeed(address(token), address(priceFeed));
-
- evm.prank(CONFIGURATOR);
-
- priceOracle.addPriceFeed(address(token), address(priceFeed));
-
- (address newPriceFeed, bool sc_flag, uint256 decimals) = priceOracle.priceFeedsWithFlags(address(token));
-
- assertEq(newPriceFeed, address(priceFeed), "Incorrect pricefeed");
-
- assertEq(priceOracle.priceFeeds(address(token)), address(priceFeed), "Incorrect pricefeed");
-
- assertEq(decimals, 17, "Incorrect decimals");
-
- assertTrue(sc_flag == skipCheck, "Incorrect skipCheck");
- }
- }
-
- /// @dev [PO-4]: getPrice reverts if depends on address but address(0) was provided
- function test_PO_04_getPrice_reverts_if_depends_on_address_but_zero_address_was_provided() public {
- ERC20Mock token = new ERC20Mock("Token", "Token", 17);
-
- PriceFeedMock priceFeed = new PriceFeedMock(8 * 10**8, 8);
-
- evm.prank(CONFIGURATOR);
- priceOracle.addPriceFeed(address(token), address(priceFeed));
-
- priceOracle.getPrice(address(token));
- }
-
- /// @dev [PO-5]: getPrice reverts if not passed skipCheck when it's enabled
- function test_PO_05_getPrice_reverts_if_not_passed_skipCheck_when_its_enabled() public {
- for (uint256 sc = 0; sc < 2; sc++) {
- bool skipForCheck = sc != 0;
-
- setUp();
-
- ERC20Mock token = new ERC20Mock("Token", "Token", 17);
-
- PriceFeedMock priceFeed = new PriceFeedMock(8 * 10**8, 8);
-
- priceFeed.setSkipPriceCheck(skipForCheck ? FlagState.TRUE : FlagState.FALSE);
-
- evm.prank(CONFIGURATOR);
- priceOracle.addPriceFeed(address(token), address(priceFeed));
-
- priceFeed.setPrice(0);
- priceFeed.setParams(80, block.timestamp, block.timestamp, 80);
-
- if (!skipForCheck) {
- evm.expectRevert(ZeroPriceException.selector);
- }
- priceOracle.getPrice(address(token));
-
- priceFeed.setPrice(10);
- priceFeed.setParams(80, block.timestamp, block.timestamp, 78);
-
- if (!skipForCheck) {
- evm.expectRevert(ChainPriceStaleException.selector);
- }
- priceOracle.getPrice(address(token));
-
- priceFeed.setParams(80, block.timestamp, 0, 80);
-
- if (!skipForCheck) {
- evm.expectRevert(ChainPriceStaleException.selector);
- }
-
- priceOracle.getPrice(address(token));
- }
- }
-
- /// @dev [PO-6]: getPrice returs correct price getting through correct method
- function test_PO_06_getPrice_returns_correct_price(int256 price) public {
- setUp();
-
- evm.assume(price > 0);
- ERC20Mock token = new ERC20Mock("Token", "Token", 17);
-
- PriceFeedMock priceFeed = new PriceFeedMock(8 * 10**8, 8);
-
- evm.prank(CONFIGURATOR);
- priceOracle.addPriceFeed(address(token), address(priceFeed));
-
- priceFeed.setPrice(price);
-
- evm.expectCall(address(priceFeed), abi.encodeWithSignature("latestRoundData()"));
-
- uint256 actualPrice = priceOracle.getPrice(address(token));
-
- assertEq(actualPrice, uint256(price), "Incorrect price");
- }
-
- /// @dev [PO-7]: convertToUSD and convertFromUSD computes correctly
- /// All prices are taken from tokenTestSuite
- function test_PO_07_convertFromUSD_and_convertToUSD_computes_correctly(uint128 amount) public {
- address wethToken = tokenTestSuite.wethToken();
- address linkToken = tokenTestSuite.addressOf(Tokens.LINK);
-
- uint256 decimalsDifference = WAD / 10 ** 8;
-
- assertEq(
- priceOracle.convertToUSD(amount, wethToken),
- (uint256(amount) * DAI_WETH_RATE) / decimalsDifference,
- "Incorrect ETH/USD conversation"
- );
-
- assertEq(
- priceOracle.convertToUSD(amount, linkToken),
- (uint256(amount) * 15) / decimalsDifference,
- "Incorrect LINK/USD conversation"
- );
-
- assertEq(
- priceOracle.convertFromUSD(amount, wethToken),
- (uint256(amount) * decimalsDifference) / DAI_WETH_RATE,
- "Incorrect USDC/ETH conversation"
- );
-
- assertEq(
- priceOracle.convertFromUSD(amount, linkToken),
- (uint256(amount) * decimalsDifference) / 15,
- "Incorrect USD/LINK conversation"
- );
- }
-
- /// @dev [PO-8]: convert computes correctly
- /// All prices are taken from tokenTestSuite
- function test_PO_08_convert_computes_correctly() public {
- assertEq(
- priceOracle.convert(WAD, tokenTestSuite.addressOf(Tokens.WETH), tokenTestSuite.addressOf(Tokens.USDC)),
- DAI_WETH_RATE * 10 ** 6,
- "Incorrect WETH/USDC conversation"
- );
-
- assertEq(
- priceOracle.convert(WAD, tokenTestSuite.addressOf(Tokens.WETH), tokenTestSuite.addressOf(Tokens.LINK)),
- (DAI_WETH_RATE * WAD) / 15,
- "Incorrect WETH/LINK conversation"
- );
-
- assertEq(
- priceOracle.convert(WAD, tokenTestSuite.addressOf(Tokens.LINK), tokenTestSuite.addressOf(Tokens.DAI)),
- 15 * WAD,
- "Incorrect LINK/DAI conversation"
- );
-
- assertEq(
- priceOracle.convert(10 ** 8, tokenTestSuite.addressOf(Tokens.USDC), tokenTestSuite.addressOf(Tokens.DAI)),
- 100 * WAD,
- "Incorrect USDC/DAI conversation"
- );
- }
-
- /// @dev [PO-9]: fastCheck computes correctly
- /// All prices are taken from tokenTestSuite
- function test_PO_09_fastCheck_computes_correctly() public {
- (uint256 collateralWETH, uint256 collateralUSDC) = priceOracle.fastCheck(
- 5 * WAD, tokenTestSuite.addressOf(Tokens.WETH), 10 * 10 ** 6, tokenTestSuite.addressOf(Tokens.USDC)
- );
-
- assertEq(collateralWETH, 5 * DAI_WETH_RATE * 10 ** 8, "Incorrect collateral WETH");
- assertEq(collateralUSDC, 10 * 10 ** 8, "Incorrect collateral USDC");
- }
-}
diff --git a/contracts/test/oracles/ZeroPriceFeed.t.sol b/contracts/test/oracles/ZeroPriceFeed.t.sol
deleted file mode 100644
index 6ee55ec6..00000000
--- a/contracts/test/oracles/ZeroPriceFeed.t.sol
+++ /dev/null
@@ -1,77 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {ILPPriceFeedExceptions} from "../../interfaces/ILPPriceFeed.sol";
-import {ZeroPriceFeed} from "../../oracles/ZeroPriceFeed.sol";
-
-// LIBRARIES
-
-// TEST
-
-import {CheatCodes, HEVM_ADDRESS} from "../lib/cheatCodes.sol";
-import "../lib/test.sol";
-
-// MOCKS
-
-// SUITES
-import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
-
-// EXCEPTIONS
-import {ZeroAddressException, NotImplementedException} from "../../interfaces/IErrors.sol";
-import {IPriceOracleV2Exceptions} from "../../interfaces/IPriceOracle.sol";
-
-/// @title ZeroFeedTest
-/// @notice Designed for unit test purposes only
-contract ZeroFeedTest is DSTest, ILPPriceFeedExceptions, IPriceOracleV2Exceptions {
- CheatCodes evm = CheatCodes(HEVM_ADDRESS);
-
- ZeroPriceFeed public pf;
-
- TokensTestSuite tokenTestSuite;
-
- function setUp() public {
- pf = new ZeroPriceFeed();
-
- evm.label(address(pf), "ZERO_PRICE_FEED");
- }
-
- ///
- ///
- /// TESTS
- ///
- ///
-
- /// @dev [ZPF-1]: constructor sets correct values
- function test_ZPF_01_constructor_sets_correct_values() public {
- assertEq(pf.description(), "Zero pricefeed", "Incorrect description");
-
- assertEq(
- pf.decimals(),
- 8, // Decimals divider for DAI
- "Incorrect decimals"
- );
-
- assertTrue(pf.skipPriceCheck() == true, "Incorrect deepencds for address");
- }
-
- /// @dev [ZPF-2]: getRoundData reverts
- function test_ZPF_02_getRoundData_reverts() public {
- evm.expectRevert(NotImplementedException.selector);
-
- pf.getRoundData(1);
- }
-
- /// @dev [ZPF-3]: latestRoundData works correctly
- function test_ZPF_03_latestRoundData_works_correctly() public {
- (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) =
- pf.latestRoundData();
-
- assertEq(roundId, 1, "Incorrect round Id #1");
- assertEq(answer, 0, "Incorrect answer #1");
- assertEq(startedAt, block.timestamp, "Incorrect startedAt #1");
- assertEq(updatedAt, block.timestamp, "Incorrect updatedAt #1");
- assertEq(answeredInRound, 1, "Incorrect answeredInRound #1");
- }
-}
diff --git a/contracts/test/pool/Pool4626.t.sol b/contracts/test/pool/Pool4626.t.sol
index 7653d683..a9b65a71 100644
--- a/contracts/test/pool/Pool4626.t.sol
+++ b/contracts/test/pool/Pool4626.t.sol
@@ -9,13 +9,12 @@ import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Pool4626} from "../../pool/Pool4626.sol";
-import {IERC4626Events} from "../../interfaces/IERC4626.sol";
import {IPool4626Events, Pool4626Opts, IPool4626Exceptions} from "../../interfaces/IPool4626.sol";
import {IERC4626Events} from "../../interfaces/IERC4626.sol";
import {IInterestRateModel} from "../../interfaces/IInterestRateModel.sol";
-import {ACL} from "../../core/ACL.sol";
+import {ACL} from "@gearbox-protocol/core-v2/contracts/core/ACL.sol";
import {CreditManagerMockForPoolTest} from "../mocks/pool/CreditManagerMockForPoolTest.sol";
import {
liquidityProviderInitBalance,
@@ -25,7 +24,7 @@ import {
PoolServiceTestSuite
} from "../suites/PoolServiceTestSuite.sol";
-import "../../libraries/Errors.sol";
+import "@gearbox-protocol/core-v2/contracts/libraries/Errors.sol";
import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
import {Tokens} from "../config/Tokens.sol";
@@ -35,7 +34,7 @@ import {ERC20FeeMock} from "../mocks/token/ERC20FeeMock.sol";
// TEST
import "../lib/constants.sol";
import "../lib/StringUtils.sol";
-import {PERCENTAGE_FACTOR} from "../../libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
import "forge-std/console.sol";
diff --git a/contracts/test/pool/PoolService.t.sol b/contracts/test/pool/PoolService.t.sol
deleted file mode 100644
index a7e334f8..00000000
--- a/contracts/test/pool/PoolService.t.sol
+++ /dev/null
@@ -1,744 +0,0 @@
-// SPDX-License-Identifier: UNLICENSED
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-
-import {TestPoolService} from "../mocks/pool/TestPoolService.sol";
-import {IPoolServiceEvents} from "../../interfaces/IPoolService.sol";
-import {LinearInterestRateModel} from "../../pool/LinearInterestRateModel.sol";
-import {DieselToken} from "../../tokens/DieselToken.sol";
-
-import {ACL} from "../../core/ACL.sol";
-import {CreditManagerMockForPoolTest} from "../mocks/pool/CreditManagerMockForPoolTest.sol";
-import {
- liquidityProviderInitBalance,
- addLiquidity,
- removeLiquidity,
- referral,
- PoolServiceTestSuite
-} from "../suites/PoolServiceTestSuite.sol";
-
-import "../../libraries/Errors.sol";
-
-import {TokensTestSuite} from "../suites/TokensTestSuite.sol";
-import {Tokens} from "../config/Tokens.sol";
-import {BalanceHelper} from "../helpers/BalanceHelper.sol";
-
-// TEST
-import "../lib/constants.sol";
-
-// EXCEPTIONS
-import {CallerNotConfiguratorException} from "../../interfaces/IErrors.sol";
-
-/// @title PoolService
-/// @notice Business logic for borrowing liquidity pools
-contract PoolServiceTest is DSTest, BalanceHelper, IPoolServiceEvents {
- CheatCodes evm = CheatCodes(HEVM_ADDRESS);
-
- PoolServiceTestSuite psts;
-
- ACL acl;
- TestPoolService poolService;
- DieselToken dieselToken;
- address underlying;
- CreditManagerMockForPoolTest cmMock;
-
- function setUp() public {
- tokenTestSuite = new TokensTestSuite();
- psts = new PoolServiceTestSuite(
- tokenTestSuite,
- tokenTestSuite.addressOf(Tokens.DAI),
- false,
- false
- );
-
- poolService = psts.poolService();
- dieselToken = psts.dieselToken();
- underlying = address(psts.underlying());
- cmMock = psts.cmMock();
- acl = psts.acl();
- }
-
- // [PS-1]: getDieselRate_RAY=RAY, withdrawFee=0 and expectedLiquidityLimit as expected at start
- function test_PS_01_start_parameters_correct() public {
- assertEq(poolService.getDieselRate_RAY(), RAY);
- assertEq(poolService.withdrawFee(), 0);
- assertEq(poolService.expectedLiquidityLimit(), type(uint256).max);
- }
-
- // [PS-2]: addLiquidity correctly adds liquidity
- function test_PS_02_add_liquidity_adds_correctly() public {
- evm.expectEmit(true, true, false, true);
- emit AddLiquidity(USER, FRIEND, addLiquidity, referral);
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, FRIEND, referral);
-
- expectBalance(address(dieselToken), FRIEND, addLiquidity);
- expectBalance(underlying, USER, liquidityProviderInitBalance - addLiquidity);
- assertEq(poolService.expectedLiquidity(), addLiquidity);
- assertEq(poolService.availableLiquidity(), addLiquidity);
- }
-
- // [PS-3]: removeLiquidity correctly removes liquidity
- function test_PS_03_remove_liquidity_removes_correctly() public {
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, FRIEND, referral);
-
- evm.expectEmit(true, true, false, true);
- emit RemoveLiquidity(FRIEND, USER, removeLiquidity);
-
- evm.prank(FRIEND);
- poolService.removeLiquidity(removeLiquidity, USER);
-
- expectBalance(address(dieselToken), FRIEND, addLiquidity - removeLiquidity);
- expectBalance(underlying, USER, liquidityProviderInitBalance - addLiquidity + removeLiquidity);
- assertEq(poolService.expectedLiquidity(), addLiquidity - removeLiquidity);
- assertEq(poolService.availableLiquidity(), addLiquidity - removeLiquidity);
- }
-
- // [PS-4]: addLiquidity, removeLiquidity, lendCreditAccount, repayCreditAccount reverts if contract is paused
- function test_PS_04_cannot_be_used_while_paused() public {
- evm.startPrank(CONFIGURATOR);
- acl.addPausableAdmin(CONFIGURATOR);
- poolService.pause();
- evm.stopPrank();
-
- evm.startPrank(USER);
-
- evm.expectRevert(bytes(PAUSABLE_ERROR));
- poolService.addLiquidity(addLiquidity, FRIEND, referral);
-
- evm.expectRevert(bytes(PAUSABLE_ERROR));
- poolService.removeLiquidity(removeLiquidity, FRIEND);
-
- evm.expectRevert(bytes(PAUSABLE_ERROR));
- poolService.lendCreditAccount(1, FRIEND);
-
- evm.expectRevert(bytes(PAUSABLE_ERROR));
- poolService.repayCreditAccount(1, 0, 0);
-
- evm.stopPrank();
- }
-
- // [PS-5]: constructor set correct cumulative index to 1 at start
- function test_PS_05_starting_cumulative_index_correct() public {
- assertEq(poolService.getCumulativeIndex_RAY(), RAY);
- }
-
- // [PS-6]: getDieselRate_RAY correctly computes rate
- function test_PS_06_diesel_rate_computes_correctly() public {
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, FRIEND, referral);
-
- poolService.setExpectedLiquidity(addLiquidity * 2);
-
- assertEq(poolService.expectedLiquidity(), addLiquidity * 2);
- assertEq(poolService.getDieselRate_RAY(), RAY * 2);
- }
-
- // [PS-7]: addLiquidity correctly adds liquidity with DieselRate != 1
- function test_PS_07_correctly_adds_liquidity_at_new_diesel_rate() public {
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- poolService.setExpectedLiquidity(addLiquidity * 2);
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, FRIEND, referral);
-
- assertEq(dieselToken.balanceOf(FRIEND), addLiquidity / 2);
- }
-
- // [PS-8]: removeLiquidity correctly removes liquidity if diesel rate != 1
- function test_PS_08_correctly_removes_liquidity_at_new_diesel_rate() public {
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, FRIEND, referral);
-
- poolService.setExpectedLiquidity(addLiquidity * 2);
-
- evm.prank(FRIEND);
- poolService.removeLiquidity(removeLiquidity, USER);
-
- expectBalance(address(dieselToken), FRIEND, addLiquidity - removeLiquidity);
- expectBalance(underlying, USER, liquidityProviderInitBalance - addLiquidity + 2 * removeLiquidity);
- assertEq(poolService.expectedLiquidity(), (addLiquidity - removeLiquidity) * 2);
- assertEq(poolService.availableLiquidity(), addLiquidity - removeLiquidity * 2);
- }
-
- // [PS-9]: connectCreditManager, forbidCreditManagerToBorrow, newInterestRateModel, setExpecetedLiquidityLimit reverts if called with non-configurator
- function test_PS_09_admin_functions_revert_on_non_admin() public {
- evm.startPrank(USER);
-
- evm.expectRevert(CallerNotConfiguratorException.selector);
- poolService.connectCreditManager(DUMB_ADDRESS);
-
- evm.expectRevert(CallerNotConfiguratorException.selector);
- poolService.forbidCreditManagerToBorrow(DUMB_ADDRESS);
-
- evm.expectRevert(CallerNotConfiguratorException.selector);
- poolService.updateInterestRateModel(DUMB_ADDRESS);
-
- evm.expectRevert(CallerNotConfiguratorException.selector);
- poolService.setExpectedLiquidityLimit(0);
-
- evm.stopPrank();
- }
-
- // [PS-10]: connectCreditManager reverts if another pool is setup in CreditManager
- function test_PS_10_connectCreditManager_fails_on_incompatible_CM() public {
- cmMock.changePoolService(DUMB_ADDRESS);
-
- evm.expectRevert(bytes(Errors.POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER));
-
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
- }
-
- // [PS-11]: connectCreditManager adds CreditManager correctly and emits event
- function test_PS_11_CM_is_connected_correctly() public {
- assertEq(poolService.creditManagersCount(), 0);
-
- evm.expectEmit(true, false, false, false);
- emit NewCreditManagerConnected(address(cmMock));
-
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- assertEq(poolService.creditManagersCount(), 1);
- assertTrue(poolService.creditManagersCanBorrow(address(cmMock)));
- assertTrue(poolService.creditManagersCanRepay(address(cmMock)));
- }
-
- // [PS-12]: lendCreditAccount, repayCreditAccount reverts if called non-CreditManager
- function test_PS_12_CA_can_be_lent_repaid_only_by_CM() public {
- evm.startPrank(USER);
-
- evm.expectRevert(bytes(Errors.POOL_CONNECTED_CREDIT_MANAGERS_ONLY));
- poolService.lendCreditAccount(0, DUMB_ADDRESS);
-
- evm.expectRevert(bytes(Errors.POOL_CONNECTED_CREDIT_MANAGERS_ONLY));
- poolService.repayCreditAccount(0, 0, 0);
-
- evm.stopPrank();
- }
-
- // [PS-13]: lendCreditAccount reverts of creditManagers was disallowed by forbidCreditManagerToBorrow
- function test_PS_13_lendCreditAccount_reverts_on_forbidden_CM() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- cmMock.lendCreditAccount(addLiquidity / 2, DUMB_ADDRESS);
-
- evm.expectEmit(false, false, false, true);
- emit BorrowForbidden(address(cmMock));
-
- evm.prank(CONFIGURATOR);
- poolService.forbidCreditManagerToBorrow(address(cmMock));
-
- evm.expectRevert(bytes(Errors.POOL_CONNECTED_CREDIT_MANAGERS_ONLY));
- cmMock.lendCreditAccount(addLiquidity / 2, DUMB_ADDRESS);
- }
-
- // [PS-14]: lendCreditAccount transfers tokens correctly
- function test_PS_14_lendCreditAccount_correctly_transfers_tokens() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- expectBalance(underlying, ca, 0);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- expectBalance(underlying, ca, addLiquidity / 2);
- }
-
- // [PS-15]: lendCreditAccount emits Borrow event
- function test_PS_15_lendCreditAccount_emits_event() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- evm.expectEmit(false, false, false, true);
- emit Borrow(address(cmMock), ca, addLiquidity / 2);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
- }
-
- // [PS-16]: lendCreditAccount correctly updates parameters
- function test_PS_16_lendCreditAccount_correctly_updates_parameters() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- uint256 totalBorrowed = poolService.totalBorrowed();
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- assertEq(poolService.totalBorrowed(), totalBorrowed + addLiquidity / 2, "Incorrect new borrow amount");
- }
-
- // [PS-17]: lendCreditAccount correctly updates borrow rate
- function test_PS_17_lendCreditAccount_correctly_updates_borrow_rate() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 expectedLiquidity = addLiquidity;
- uint256 expectedAvailable = expectedLiquidity - addLiquidity / 2;
-
- uint256 expectedBorrowRate = psts.linearIRModel().calcBorrowRate(expectedLiquidity, expectedAvailable);
-
- assertEq(expectedBorrowRate, poolService.borrowAPY_RAY(), "Borrow rate is incorrect");
- }
-
- // [PS-18]: repayCreditAccount emits Repay event
- function test_PS_18_repayCreditAccount_emits_event() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- evm.expectEmit(true, false, false, true);
- emit Repay(address(cmMock), addLiquidity / 2, 1, 0);
-
- cmMock.repayCreditAccount(addLiquidity / 2, 1, 0);
- }
-
- // [PS-19]: repayCreditAccount correctly updates params on loss accrued: treasury < loss
- function test_PS_19_repayCreditAccount_correctly_updates_on_uncovered_loss() public {
- address treasury = psts.treasury();
-
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- evm.prank(address(poolService));
- dieselToken.mint(treasury, 1e4);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 borrowRate = poolService.borrowAPY_RAY();
- uint256 timeWarp = 365 days;
-
- uint256 expectedInterest = ((addLiquidity / 2) * borrowRate) / RAY;
- uint256 expectedLiquidity = addLiquidity + expectedInterest - 1e6;
-
- uint256 expectedBorrowRate =
- psts.linearIRModel().calcBorrowRate(expectedLiquidity, addLiquidity + expectedInterest - 1e6);
-
- evm.warp(block.timestamp + timeWarp);
-
- uint256 treasuryUnderlying = poolService.fromDiesel(dieselToken.balanceOf(treasury));
-
- tokenTestSuite.mint(Tokens.DAI, address(poolService), addLiquidity / 2 + expectedInterest - 1e6);
-
- evm.expectEmit(true, false, false, true);
- emit UncoveredLoss(address(cmMock), 1e6 - treasuryUnderlying);
-
- cmMock.repayCreditAccount(addLiquidity / 2, 0, 1e6);
-
- assertEq(poolService.expectedLiquidity(), expectedLiquidity, "Expected liquidity was not updated correctly");
-
- assertEq(dieselToken.balanceOf(treasury), 0, "dToken remains in the treasury");
-
- assertEq(poolService.borrowAPY_RAY(), expectedBorrowRate, "Borrow rate was not updated correctly");
- }
-
- // [PS-20]: repayCreditAccount correctly updates params on loss accrued: treasury >= loss; and emits event
- function test_PS_20_repayCreditAccount_correctly_updates_on_covered_loss() public {
- address treasury = psts.treasury();
-
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- uint256 dieselSupply = dieselToken.totalSupply();
-
- evm.prank(address(poolService));
- dieselToken.mint(treasury, dieselSupply);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 borrowRate = poolService.borrowAPY_RAY();
- uint256 timeWarp = 365 days;
-
- evm.warp(block.timestamp + timeWarp);
-
- uint256 treasuryUnderlying = poolService.fromDiesel(dieselToken.balanceOf(treasury));
-
- uint256 expectedInterest = ((addLiquidity / 2) * borrowRate) / RAY;
- uint256 expectedLiquidity = addLiquidity + expectedInterest - (treasuryUnderlying / 2);
-
- uint256 expectedBorrowRate = psts.linearIRModel().calcBorrowRate(expectedLiquidity, addLiquidity);
-
- tokenTestSuite.mint(Tokens.DAI, address(poolService), addLiquidity / 2);
-
- cmMock.repayCreditAccount(addLiquidity / 2, 0, treasuryUnderlying / 2);
-
- assertEq(poolService.expectedLiquidity(), expectedLiquidity, "Expected liquidity was not updated correctly");
-
- assertEq(
- dieselToken.balanceOf(treasury),
- poolService.toDiesel(treasuryUnderlying - treasuryUnderlying / 2),
- "dToken balance incorrect"
- );
-
- assertEq(poolService.borrowAPY_RAY(), expectedBorrowRate, "Borrow rate was not updated correctly");
- }
-
- // [PS-21]: repayCreditAccount correctly updates params on profit
- function test_PS_21_repayCreditAccount_correctly_updates_on_profit() public {
- address treasury = psts.treasury();
-
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 borrowRate = poolService.borrowAPY_RAY();
- uint256 timeWarp = 365 days;
-
- evm.warp(block.timestamp + timeWarp);
-
- uint256 expectedInterest = ((addLiquidity / 2) * borrowRate) / RAY;
- uint256 expectedLiquidity = addLiquidity + expectedInterest + 100;
-
- uint256 expectedBorrowRate =
- psts.linearIRModel().calcBorrowRate(expectedLiquidity, addLiquidity + expectedInterest + 100);
-
- tokenTestSuite.mint(Tokens.DAI, address(poolService), addLiquidity / 2 + expectedInterest + 100);
-
- cmMock.repayCreditAccount(addLiquidity / 2, 100, 0);
-
- assertEq(poolService.expectedLiquidity(), expectedLiquidity, "Expected liquidity was not updated correctly");
-
- assertEq(dieselToken.balanceOf(treasury), poolService.toDiesel(100), "dToken balance incorrect");
-
- assertEq(poolService.borrowAPY_RAY(), expectedBorrowRate, "Borrow rate was not updated correctly");
- }
-
- // [PS-22]: repayCreditAccount does not change the diesel rate outside margin of error
- function test_PS_22_repayCreditAccount_does_not_change_diesel_rate() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 borrowRate = poolService.borrowAPY_RAY();
- uint256 timeWarp = 365 days;
-
- evm.warp(block.timestamp + timeWarp);
-
- uint256 expectedInterest = ((addLiquidity / 2) * borrowRate) / RAY;
- uint256 expectedLiquidity = addLiquidity + expectedInterest;
-
- tokenTestSuite.mint(Tokens.DAI, address(poolService), addLiquidity / 2 + expectedInterest);
-
- cmMock.repayCreditAccount(addLiquidity / 2, 100, 0);
-
- assertEq(
- (RAY * expectedLiquidity) / addLiquidity / 1e8,
- poolService.getDieselRate_RAY() / 1e8,
- "Expected liquidity was not updated correctly"
- );
- }
-
- // [PS-23]: fromDiesel / toDiesel works correctly
- function test_PS_23_diesel_conversion_is_correct() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 timeWarp = 365 days;
-
- evm.warp(block.timestamp + timeWarp);
-
- uint256 dieselRate = poolService.getDieselRate_RAY();
-
- assertEq(
- poolService.toDiesel(addLiquidity), (addLiquidity * RAY) / dieselRate, "ToDiesel does not compute correctly"
- );
-
- assertEq(
- poolService.fromDiesel(addLiquidity),
- (addLiquidity * dieselRate) / RAY,
- "ToDiesel does not compute correctly"
- );
- }
-
- // [PS-24]: updateInterestRateModel changes interest rate model & emit event
- function test_PS_24_updateInterestRateModel_works_correctly_and_emits_event() public {
- LinearInterestRateModel newIR = new LinearInterestRateModel(
- 8000,
- 9000,
- 200,
- 500,
- 4000,
- 7500,
- false
- );
-
- evm.expectEmit(true, false, false, false);
- emit NewInterestRateModel(address(newIR));
-
- evm.prank(CONFIGURATOR);
- poolService.updateInterestRateModel(address(newIR));
-
- assertEq(address(poolService.interestRateModel()), address(newIR), "Interest rate model was not set correctly");
- }
-
- // [PS-25]: updateInterestRateModel correctly computes new borrow rate
- function test_PS_25_updateInterestRateModel_correctly_computes_new_borrow_rate() public {
- LinearInterestRateModel newIR = new LinearInterestRateModel(
- 8000,
- 9000,
- 200,
- 500,
- 4000,
- 7500,
- false
- );
-
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 expectedLiquidity = poolService.expectedLiquidity();
- uint256 availableLiquidity = poolService.availableLiquidity();
-
- evm.prank(CONFIGURATOR);
- poolService.updateInterestRateModel(address(newIR));
-
- assertEq(
- newIR.calcBorrowRate(expectedLiquidity, availableLiquidity),
- poolService.borrowAPY_RAY(),
- "Borrow rate does not match"
- );
- }
-
- // [PS-26]: updateBorrowRate correctly updates parameters
- function test_PS_26_updateBorrowRate_correct() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 borrowRate = poolService.borrowAPY_RAY();
- uint256 timeWarp = 365 days;
-
- evm.warp(block.timestamp + timeWarp);
-
- uint256 expectedInterest = ((addLiquidity / 2) * borrowRate) / RAY;
- uint256 expectedLiquidity = addLiquidity + expectedInterest;
-
- uint256 expectedBorrowRate = psts.linearIRModel().calcBorrowRate(expectedLiquidity, addLiquidity / 2);
-
- poolService.updateBorrowRate();
-
- assertEq(poolService.expectedLiquidity(), expectedLiquidity, "Expected liquidity was not updated correctly");
-
- assertEq(poolService._timestampLU(), block.timestamp, "Timestamp was not updated correctly");
-
- assertEq(poolService.borrowAPY_RAY(), expectedBorrowRate, "Borrow rate was not updated correctly");
-
- assertEq(
- poolService.calcLinearCumulative_RAY(),
- poolService.getCumulativeIndex_RAY(),
- "Index value was not updated correctly"
- );
- }
-
- // [PS-27]: calcLinearCumulative_RAY computes correctly
- function test_PS_27_calcLinearCumulative_RAY_correct() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 timeWarp = 180 days;
-
- evm.warp(block.timestamp + timeWarp);
-
- uint256 borrowRate = poolService.borrowAPY_RAY();
-
- uint256 expectedLinearRate = RAY + (borrowRate * timeWarp) / 365 days;
-
- assertEq(poolService.calcLinearCumulative_RAY(), expectedLinearRate, "Index value was not updated correctly");
- }
-
- // [PS-28]: expectedLiquidity() computes correctly
- function test_PS_28_expectedLiquidity_correct() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- address ca = cmMock.getCreditAccountOrRevert(DUMB_ADDRESS);
-
- cmMock.lendCreditAccount(addLiquidity / 2, ca);
-
- uint256 borrowRate = poolService.borrowAPY_RAY();
- uint256 timeWarp = 365 days;
-
- evm.warp(block.timestamp + timeWarp);
-
- uint256 expectedInterest = ((addLiquidity / 2) * borrowRate) / RAY;
- uint256 expectedLiquidity = poolService._expectedLiquidityLU() + expectedInterest;
-
- assertEq(poolService.expectedLiquidity(), expectedLiquidity, "Index value was not updated correctly");
- }
-
- // [PS-29]: setExpectedLiquidityLimit() sets limit & emits event
- function test_PS_29_setExpectedLiquidityLimit_correct_and_emits_event() public {
- evm.expectEmit(false, false, false, true);
- emit NewExpectedLiquidityLimit(10000);
-
- evm.prank(CONFIGURATOR);
- poolService.setExpectedLiquidityLimit(10000);
-
- assertEq(poolService.expectedLiquidityLimit(), 10000, "expectedLiquidityLimit not set correctly");
- }
-
- // [PS-30]: addLiquidity reverts above expectedLiquidityLimit
- function test_PS_30_addLiquidity_reverts_above_liquidity_limit() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.prank(CONFIGURATOR);
- poolService.setExpectedLiquidityLimit(10000);
-
- evm.expectRevert(bytes(Errors.POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT));
-
- evm.prank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
- }
-
- // [PS-31]: setWithdrawFee reverts on fee > 1%
- function test_PS_31_setWithdrawFee_reverts_on_fee_too_lage() public {
- evm.expectRevert(bytes(Errors.POOL_INCORRECT_WITHDRAW_FEE));
-
- evm.prank(CONFIGURATOR);
- poolService.setWithdrawFee(101);
- }
-
- // [PS-32]: setWithdrawFee changes fee and emits event
- function test_PS_32_setWithdrawFee_correct_and_emits_event() public {
- evm.expectEmit(false, false, false, true);
- emit NewWithdrawFee(50);
-
- evm.prank(CONFIGURATOR);
- poolService.setWithdrawFee(50);
-
- assertEq(poolService.withdrawFee(), 50, "withdrawFee not set correctly");
- }
-
- // [PS-33]: removeLiqudity correctly takes withdrawal fee
- function test_PS_33_removeLiquidity_takes_withdrawal_fee() public {
- address treasury = psts.treasury();
-
- evm.startPrank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
- poolService.setWithdrawFee(50);
- evm.stopPrank();
-
- evm.startPrank(USER);
- poolService.addLiquidity(addLiquidity, USER, referral);
-
- uint256 balanceBefore = IERC20(underlying).balanceOf(USER);
-
- poolService.removeLiquidity(addLiquidity, USER);
- evm.stopPrank();
-
- expectBalance(underlying, treasury, (addLiquidity * 50) / 10000, "Incorrect balance in treasury");
-
- expectBalance(underlying, USER, balanceBefore + (addLiquidity * 9950) / 10000, "Incorrect balance for user");
- }
-
- // [PS-34]: connectCreditManager reverts on adding a manager twice
- function test_PS_34_connectCreditManager_reverts_on_duplicate() public {
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
-
- evm.expectRevert(bytes(Errors.POOL_CANT_ADD_CREDIT_MANAGER_TWICE));
-
- evm.prank(CONFIGURATOR);
- poolService.connectCreditManager(address(cmMock));
- }
-
- // [PS-35]: updateInterestRateModel reverts on zero address
- function test_PS_35_updateInterestRateModel_reverts_on_zero_address() public {
- evm.expectRevert(bytes(Errors.ZERO_ADDRESS_IS_NOT_ALLOWED));
- evm.prank(CONFIGURATOR);
- poolService.updateInterestRateModel(address(0));
- }
-}
diff --git a/contracts/test/suites/CreditFacadeTestSuite.sol b/contracts/test/suites/CreditFacadeTestSuite.sol
index e7fa9e66..5466fa3e 100644
--- a/contracts/test/suites/CreditFacadeTestSuite.sol
+++ b/contracts/test/suites/CreditFacadeTestSuite.sol
@@ -11,7 +11,7 @@ import {CreditManagerFactoryBase} from "../../factories/CreditManagerFactoryBase
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {DegenNFT} from "../../tokens/DegenNFT.sol";
+import {DegenNFT} from "@gearbox-protocol/core-v2/contracts/tokens/DegenNFT.sol";
import {BlacklistHelper} from "../../support/BlacklistHelper.sol";
import "../lib/constants.sol";
diff --git a/contracts/test/suites/CreditManagerTestSuite.sol b/contracts/test/suites/CreditManagerTestSuite.sol
index e9cc76e8..7b3023bf 100644
--- a/contracts/test/suites/CreditManagerTestSuite.sol
+++ b/contracts/test/suites/CreditManagerTestSuite.sol
@@ -6,12 +6,12 @@ pragma solidity ^0.8.10;
import {CreditManager} from "../../credit/CreditManager.sol";
import {CreditManagerOpts, CollateralToken} from "../../credit/CreditConfigurator.sol";
-import {IWETH} from "../../interfaces/external/IWETH.sol";
+import {IWETH} from "@gearbox-protocol/core-v2/contracts/interfaces/external/IWETH.sol";
import {QuotaRateUpdate} from "../../interfaces/IPoolQuotaKeeper.sol";
-import {PERCENTAGE_FACTOR} from "../../libraries/Constants.sol";
+import {PERCENTAGE_FACTOR} from "@gearbox-protocol/core-v2/contracts/libraries/PercentageMath.sol";
-import "../../libraries/Constants.sol";
+import "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
import "../lib/constants.sol";
import {CreditManagerTestInternal} from "../mocks/credit/CreditManagerTestInternal.sol";
diff --git a/contracts/test/suites/PoolDeployer.sol b/contracts/test/suites/PoolDeployer.sol
index f11caf42..a57f8c2d 100644
--- a/contracts/test/suites/PoolDeployer.sol
+++ b/contracts/test/suites/PoolDeployer.sol
@@ -3,14 +3,14 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {AddressProvider} from "../../core/AddressProvider.sol";
-import {IPriceOracleV2Ext} from "../../interfaces/IPriceOracle.sol";
-import {PriceFeedConfig} from "../../oracles/PriceOracle.sol";
-import {ACL} from "../../core/ACL.sol";
-import {ContractsRegister} from "../../core/ContractsRegister.sol";
-import {AccountFactory} from "../../core/AccountFactory.sol";
-import {GenesisFactory} from "../../factories/GenesisFactory.sol";
-import {PoolFactory, PoolOpts} from "../../factories/PoolFactory.sol";
+import {AddressProvider} from "@gearbox-protocol/core-v2/contracts/core/AddressProvider.sol";
+import {IPriceOracleV2Ext} from "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol";
+import {PriceFeedConfig} from "@gearbox-protocol/core-v2/contracts/oracles/PriceOracle.sol";
+import {ACL} from "@gearbox-protocol/core-v2/contracts/core/ACL.sol";
+import {ContractsRegister} from "@gearbox-protocol/core-v2/contracts/core/ContractsRegister.sol";
+import {AccountFactory} from "@gearbox-protocol/core-v2/contracts/core/AccountFactory.sol";
+import {GenesisFactory} from "@gearbox-protocol/core-v2/contracts/factories/GenesisFactory.sol";
+import {PoolFactory, PoolOpts} from "@gearbox-protocol/core-v2/contracts/factories/PoolFactory.sol";
import {CreditManagerOpts, CollateralToken} from "../../credit/CreditConfigurator.sol";
import {PoolServiceMock} from "../mocks/pool/PoolServiceMock.sol";
diff --git a/contracts/test/suites/PoolServiceTestSuite.sol b/contracts/test/suites/PoolServiceTestSuite.sol
index ad2658c4..f7008888 100644
--- a/contracts/test/suites/PoolServiceTestSuite.sol
+++ b/contracts/test/suites/PoolServiceTestSuite.sol
@@ -3,20 +3,20 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {AddressProvider} from "../../core/AddressProvider.sol";
-import {ContractsRegister} from "../../core/ContractsRegister.sol";
-import {ACL} from "../../core/ACL.sol";
-import {DieselToken} from "../../tokens/DieselToken.sol";
+import {AddressProvider} from "@gearbox-protocol/core-v2/contracts/core/AddressProvider.sol";
+import {ContractsRegister} from "@gearbox-protocol/core-v2/contracts/core/ContractsRegister.sol";
+import {ACL} from "@gearbox-protocol/core-v2/contracts/core/ACL.sol";
+import {DieselToken} from "@gearbox-protocol/core-v2/contracts/tokens/DieselToken.sol";
import {IPool4626, Pool4626Opts} from "../../interfaces/IPool4626.sol";
-import {TestPoolService} from "../mocks/pool/TestPoolService.sol";
+import {TestPoolService} from "@gearbox-protocol/core-v2/contracts/test/mocks/pool/TestPoolService.sol";
import {Tokens} from "../config/Tokens.sol";
import {LinearInterestRateModel} from "../../pool/LinearInterestRateModel.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {CreditManagerMockForPoolTest} from "../mocks/pool/CreditManagerMockForPoolTest.sol";
-import {WETHMock} from "../mocks/token/WETHMock.sol";
+import {WETHMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/token/WETHMock.sol";
import {ERC20FeeMock} from "../mocks/token/ERC20FeeMock.sol";
import "../lib/constants.sol";
diff --git a/contracts/test/suites/TokensTestSuite.sol b/contracts/test/suites/TokensTestSuite.sol
index c4af5f60..282afc96 100644
--- a/contracts/test/suites/TokensTestSuite.sol
+++ b/contracts/test/suites/TokensTestSuite.sol
@@ -5,17 +5,17 @@ pragma solidity ^0.8.10;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {WETHMock} from "../mocks/token/WETHMock.sol";
+import {WETHMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/token/WETHMock.sol";
import {ERC20BlacklistableMock} from "../mocks/token/ERC20Blacklistable.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
-import {PriceFeedConfig} from "../../oracles/PriceOracle.sol";
+import {PriceFeedConfig} from "@gearbox-protocol/core-v2/contracts/oracles/PriceOracle.sol";
// MOCKS
-import {ERC20Mock} from "../mocks/token/ERC20Mock.sol";
+import {ERC20Mock} from "@gearbox-protocol/core-v2/contracts/test/mocks/token/ERC20Mock.sol";
import {ERC20FeeMock} from "../mocks/token/ERC20FeeMock.sol";
-import {PriceFeedMock} from "../mocks/oracles/PriceFeedMock.sol";
+import {PriceFeedMock} from "@gearbox-protocol/core-v2/contracts/test/mocks/oracles/PriceFeedMock.sol";
import "../lib/test.sol";
diff --git a/contracts/test/suites/TokensTestSuiteHelper.sol b/contracts/test/suites/TokensTestSuiteHelper.sol
index d15afb3c..04c19fc4 100644
--- a/contracts/test/suites/TokensTestSuiteHelper.sol
+++ b/contracts/test/suites/TokensTestSuiteHelper.sol
@@ -5,12 +5,12 @@ pragma solidity ^0.8.10;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
-import {IWETH} from "../../interfaces/external/IWETH.sol";
+import {IWETH} from "@gearbox-protocol/core-v2/contracts/interfaces/external/IWETH.sol";
import {ITokenTestSuite} from "../interfaces/ITokenTestSuite.sol";
// MOCKS
-import {ERC20Mock} from "../mocks/token/ERC20Mock.sol";
+import {ERC20Mock} from "@gearbox-protocol/core-v2/contracts/test/mocks/token/ERC20Mock.sol";
import "../lib/constants.sol";
contract TokensTestSuiteHelper is DSTest, ITokenTestSuite {
diff --git a/contracts/test/support/GearStaking.t.sol b/contracts/test/support/GearStaking.t.sol
deleted file mode 100644
index 8b137891..00000000
--- a/contracts/test/support/GearStaking.t.sol
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/contracts/test/support/PauseMulticall.t.sol b/contracts/test/support/PauseMulticall.t.sol
index 3b474843..09e8b509 100644
--- a/contracts/test/support/PauseMulticall.t.sol
+++ b/contracts/test/support/PauseMulticall.t.sol
@@ -3,9 +3,9 @@
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
-import {IAddressProvider} from "../../interfaces/IAddressProvider.sol";
-import {ContractsRegister} from "../../core/ContractsRegister.sol";
-import {PauseMulticall} from "../../support/PauseMulticall.sol";
+import {IAddressProvider} from "@gearbox-protocol/core-v2/contracts/interfaces/IAddressProvider.sol";
+import {ContractsRegister} from "@gearbox-protocol/core-v2/contracts/core/ContractsRegister.sol";
+import {PauseMulticall} from "@gearbox-protocol/core-v2/contracts/support/PauseMulticall.sol";
import {CreditManager, UNIVERSAL_CONTRACT} from "../../credit/CreditManager.sol";
// TESTS
diff --git a/contracts/test/tokens/DegenNFT.t.sol b/contracts/test/tokens/DegenNFT.t.sol
index 2883b458..ffb600b5 100644
--- a/contracts/test/tokens/DegenNFT.t.sol
+++ b/contracts/test/tokens/DegenNFT.t.sol
@@ -6,13 +6,13 @@ pragma solidity ^0.8.10;
import {CreditManager} from "../../credit/CreditManager.sol";
import {CreditFacade} from "../../credit/CreditFacade.sol";
-import {AccountFactory} from "../../core/AccountFactory.sol";
+import {AccountFactory} from "@gearbox-protocol/core-v2/contracts/core/AccountFactory.sol";
import {ICreditManagerV2, ICreditManagerV2Events} from "../../interfaces/ICreditManagerV2.sol";
-import {AddressProvider} from "../../core/AddressProvider.sol";
-import {IDegenNFT, IDegenNFTExceptions} from "../../interfaces/IDegenNFT.sol";
-import {DegenNFT} from "../../tokens/DegenNFT.sol";
+import {AddressProvider} from "@gearbox-protocol/core-v2/contracts/core/AddressProvider.sol";
+import {IDegenNFT, IDegenNFTExceptions} from "@gearbox-protocol/core-v2/contracts/interfaces/IDegenNFT.sol";
+import {DegenNFT} from "@gearbox-protocol/core-v2/contracts/tokens/DegenNFT.sol";
import "../lib/constants.sol";
import {CreditFacadeTestHelper} from "../helpers/CreditFacadeTestHelper.sol";
diff --git a/contracts/tokens/DegenNFT.sol b/contracts/tokens/DegenNFT.sol
deleted file mode 100644
index 4ec28751..00000000
--- a/contracts/tokens/DegenNFT.sol
+++ /dev/null
@@ -1,203 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-
-pragma solidity ^0.8.10;
-
-import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
-import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
-import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
-import {Address} from "@openzeppelin/contracts/utils/Address.sol";
-
-import {AddressProvider} from "../core/AddressProvider.sol";
-import {ContractsRegister} from "../core/ContractsRegister.sol";
-
-import {ACLNonReentrantTrait} from "../core/ACLNonReentrantTrait.sol";
-import {NotImplementedException} from "../interfaces/IErrors.sol";
-
-import {ICreditManagerV2} from "../interfaces/ICreditManagerV2.sol";
-import {ICreditFacade} from "../interfaces/ICreditFacade.sol";
-import {IDegenNFT} from "../interfaces/IDegenNFT.sol";
-
-contract DegenNFT is ERC721, ACLNonReentrantTrait, IDegenNFT {
- using Address for address;
-
- /// @dev Stores the total number of tokens on holder accounts
- uint256 public override totalSupply;
-
- /// @dev address of Contracts register
- ContractsRegister internal immutable contractsRegister;
-
- /// @dev address of the current minter
- address public minter;
-
- /// @dev mapping from address to supported Credit Facade status
- mapping(address => bool) public isSupportedCreditFacade;
-
- /// @dev Stores the base URI for NFT metadata
- string public override baseURI;
-
- /// @dev contract version
- uint256 public constant override version = 1;
-
- /// @dev Restricts calls to this contract's minter
- modifier onlyMinter() {
- if (msg.sender != minter) {
- revert MinterOnlyException();
- }
- _;
- }
-
- /// @dev Restricts calls to the configurator or Credit Facades
- modifier creditFacadeOrConfiguratorOnly() {
- if (!isSupportedCreditFacade[msg.sender] && !_acl.isConfigurator(msg.sender)) {
- revert CreditFacadeOrConfiguratorOnlyException();
- }
- _;
- }
-
- constructor(address _addressProvider, string memory _name, string memory _symbol)
- ACLNonReentrantTrait(_addressProvider)
- ERC721(_name, _symbol) // F:[DNFT-1]
- {
- contractsRegister = ContractsRegister(AddressProvider(_addressProvider).getContractsRegister());
- }
-
- function setMinter(address minter_)
- external
- configuratorOnly // F:[DNFT-2B]
- {
- minter = minter_; // F: [DNFT-5A]
- emit NewMinterSet(minter);
- }
-
- function addCreditFacade(address creditFacade_)
- external
- configuratorOnly // F: [DNFT-2C]
- {
- if (!isSupportedCreditFacade[creditFacade_]) {
- if (!creditFacade_.isContract()) {
- revert InvalidCreditFacadeException(); // F:[DNFT-6]
- }
-
- address creditManager;
- try ICreditFacade(creditFacade_).creditManager() returns (ICreditManagerV2 cm) {
- creditManager = address(cm);
- } catch {
- revert InvalidCreditFacadeException(); // F:[DNFT-6]
- }
-
- if (
- !contractsRegister.isCreditManager(creditManager)
- || ICreditFacade(creditFacade_).degenNFT() != address(this)
- || ICreditManagerV2(creditManager).creditFacade() != creditFacade_
- ) revert InvalidCreditFacadeException(); // F:[DNFT-6]
-
- isSupportedCreditFacade[creditFacade_] = true; // F: [DNFT-10]
- emit NewCreditFacadeAdded(creditFacade_);
- }
- }
-
- function removeCreditFacade(address creditFacade_)
- external
- configuratorOnly // F: [DNFT-2D]
- {
- if (isSupportedCreditFacade[creditFacade_]) {
- isSupportedCreditFacade[creditFacade_] = false; // F: [DNFT-9]
- emit NewCreditFacadeRemoved(creditFacade_);
- }
- }
-
- function setBaseUri(string calldata baseURI_)
- external
- configuratorOnly // F:[DNFT-2A]
- {
- baseURI = baseURI_; // F:[DNFT-5]
- }
-
- function _baseURI() internal view override returns (string memory) {
- return baseURI; // F:[DNFT-5]
- }
-
- /**
- * @dev See {IERC721Metadata-tokenURI}.
- */
- function tokenURI(uint256 tokenId) public view override (IERC721Metadata, ERC721) returns (string memory) {
- require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
-
- return _baseURI();
- }
-
- /// @dev Mints a specified amount of tokens to the address
- /// @param to Address the tokens are minted to
- /// @param amount The number of tokens to mint
- function mint(address to, uint256 amount)
- external
- override
- onlyMinter // F:[DNFT-3]
- {
- uint256 balanceBefore = balanceOf(to); // F:[DNFT-7]
-
- for (uint256 i; i < amount;) {
- uint256 tokenId = (uint256(uint160(to)) << 40) + balanceBefore + i; // F:[DNFT-7]
- _mint(to, tokenId); // F:[DNFT-7]
-
- unchecked {
- ++i; // F:[DNFT-7]
- }
- }
-
- totalSupply += amount; // F:[DNFT-7]
- }
-
- /// @dev Burns a number of tokens from a specified address
- /// @param from The address a token will be burnt from
- /// @param amount The number of tokens to burn
- function burn(address from, uint256 amount)
- external
- override
- creditFacadeOrConfiguratorOnly // F:[DNFT-4]
- {
- uint256 balance = balanceOf(from); // F:[DNFT-8,8A]
-
- if (balance < amount) {
- revert InsufficientBalanceException(); // F:[DNFT-8A]
- }
-
- for (uint256 i; i < amount;) {
- uint256 tokenId = (uint256(uint160(from)) << 40) + balance - i - 1; // F:[DNFT-8]
- _burn(tokenId); // F:[DNFT-8]
-
- unchecked {
- ++i; // F:[DNFT-8]
- }
- }
-
- totalSupply -= amount; // F:[DNFT-8]
- }
-
- /// @dev Not implemented as the token is not transferrable
- function approve(address, uint256) public pure virtual override (IERC721, ERC721) {
- revert NotImplementedException(); // F:[DNFT-11]
- }
-
- /// @dev Not implemented as the token is not transferrable
- function setApprovalForAll(address, bool) public pure virtual override (IERC721, ERC721) {
- revert NotImplementedException(); // F:[DNFT-11]
- }
-
- /// @dev Not implemented as the token is not transferrable
- function transferFrom(address, address, uint256) public pure virtual override (IERC721, ERC721) {
- revert NotImplementedException(); // F:[DNFT-11]
- }
-
- /// @dev Not implemented as the token is not transferrable
- function safeTransferFrom(address, address, uint256) public pure virtual override (IERC721, ERC721) {
- revert NotImplementedException(); // F:[DNFT-11]
- }
-
- /// @dev Not implemented as the token is not transferrable
- function safeTransferFrom(address, address, uint256, bytes memory) public pure virtual override (IERC721, ERC721) {
- revert NotImplementedException(); // F:[DNFT-11]
- }
-}
diff --git a/contracts/tokens/DieselToken.sol b/contracts/tokens/DieselToken.sol
deleted file mode 100644
index 50a63fcf..00000000
--- a/contracts/tokens/DieselToken.sol
+++ /dev/null
@@ -1,37 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
-import {IDieselToken} from "../interfaces/IDieselToken.sol";
-
-/// @dev DieselToken is LP token for Gearbox pools
-contract DieselToken is ERC20, IDieselToken {
- uint8 private immutable _decimals;
- address public immutable poolService;
-
- modifier onlyPoolService() {
- if (msg.sender != poolService) {
- revert PoolServiceOnlyException();
- }
- _;
- }
-
- constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_) {
- _decimals = decimals_;
- poolService = msg.sender;
- }
-
- function mint(address to, uint256 amount) external onlyPoolService {
- _mint(to, amount);
- }
-
- function burn(address to, uint256 amount) external onlyPoolService {
- _burn(to, amount);
- }
-
- function decimals() public view override returns (uint8) {
- return _decimals;
- }
-}
diff --git a/contracts/tokens/GearToken.sol b/contracts/tokens/GearToken.sol
deleted file mode 100644
index 28ae33fd..00000000
--- a/contracts/tokens/GearToken.sol
+++ /dev/null
@@ -1,400 +0,0 @@
-// SPDX-License-Identifier: BSD-3-Clause
-pragma solidity ^0.8.10;
-
-pragma experimental ABIEncoderV2;
-
-/// @dev Governance Gearbox token
-/// based on https://github.com/Uniswap/governance/blob/master/contracts/Uni.sol
-contract GearToken {
- /// @notice EIP-20 token name for this token
- string public constant name = "Gearbox";
-
- /// @notice EIP-20 token symbol for this token
- string public constant symbol = "GEAR";
-
- /// @notice EIP-20 token decimals for this token
- uint8 public constant decimals = 18;
-
- /// @notice Total number of tokens in circulation
- uint256 public constant totalSupply = 10_000_000_000e18; // 10 billion Gear
-
- // Allowance amounts on behalf of others
- mapping(address => mapping(address => uint96)) internal allowances;
-
- // Official record of token balances for each account
- mapping(address => uint96) internal balances;
-
- /// @notice A record of each accounts delegate
- mapping(address => address) public delegates;
-
- /// @notice A checkpoint for marking number of votes from a given block
- struct Checkpoint {
- uint32 fromBlock;
- uint96 votes;
- }
-
- /// @notice A record of votes checkpoints for each account, by index
- mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
-
- /// @notice The number of checkpoints for each account
- mapping(address => uint32) public numCheckpoints;
-
- /// @notice The EIP-712 typehash for the contract's domain
- bytes32 public constant DOMAIN_TYPEHASH =
- keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
-
- /// @notice The EIP-712 typehash for the delegation struct used by the contract
- bytes32 public constant DELEGATION_TYPEHASH =
- keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
-
- /// @notice The EIP-712 typehash for the permit struct used by the contract
- bytes32 public constant PERMIT_TYPEHASH =
- keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
-
- // A record of states for signing / validating signatures
- mapping(address => uint256) public nonces;
-
- /// @notice Flag which allows token transfers
- bool public transfersAllowed;
-
- /// @notice Contract owner which can allow token transfers
- address public manager;
-
- /// @notice Miner address which can send tokens during account mining
- address public miner;
-
- /// @notice An event thats emitted when an account changes its delegate
- event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
-
- /// @notice An event thats emitted when a delegate account's vote balance changes
- event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
-
- /// @notice The standard EIP-20 transfer event
- event Transfer(address indexed from, address indexed to, uint256 amount);
-
- /// @notice The standard EIP-20 approval event
- event Approval(address indexed owner, address indexed spender, uint256 amount);
-
- event OwnershipTransferred(address indexed owner, address indexed newOwner);
-
- event MinerSet(address indexed miner);
-
- event TransferAllowed();
-
- modifier managerOnly() {
- require(msg.sender == manager, "Gear::caller is not the manager");
- _;
- }
-
- /**
- * @notice Construct a new Gear token
- * @param account The initial account to grant all the tokens
- */
- constructor(address account) {
- require(account != address(0), "Zero address is not allowed");
- balances[account] = uint96(totalSupply);
- emit Transfer(address(0), account, totalSupply);
- manager = msg.sender;
- transfersAllowed = false;
- }
-
- function transferOwnership(address newManager)
- external
- managerOnly // T:[GT-3]
- {
- require(newManager != address(0), "Zero address is not allowed"); // T:[GT-5]
- emit OwnershipTransferred(manager, newManager); // T:[GT-6]
- manager = newManager; // T:[GT-6]
- }
-
- function setMiner(address _miner)
- external
- managerOnly // T:[GT-3]
- {
- require(_miner != address(0), "Zero address is not allowed");
- miner = _miner; // T:[GT-4]
- emit MinerSet(miner); // T:[GT-4]
- }
-
- function allowTransfers()
- external
- managerOnly // T:[GT-3]
- {
- transfersAllowed = true; // T:[GT-1]
- emit TransferAllowed();
- }
-
- /**
- * @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
- * @param account The address of the account holding the funds
- * @param spender The address of the account spending the funds
- * @return The number of tokens approved
- */
- function allowance(address account, address spender) external view returns (uint256) {
- return allowances[account][spender];
- }
-
- /**
- * @notice Approve `spender` to transfer up to `amount` from `src`
- * @dev This will overwrite the approval amount for `spender`
- * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
- * @param spender The address of the account which may transfer tokens
- * @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
- * @return Whether or not the approval succeeded
- */
- function approve(address spender, uint256 rawAmount) external returns (bool) {
- uint96 amount;
- if (rawAmount == type(uint256).max) {
- amount = type(uint96).max;
- } else {
- amount = safe96(rawAmount, "Gear::approve: amount exceeds 96 bits");
- }
-
- allowances[msg.sender][spender] = amount;
-
- emit Approval(msg.sender, spender, amount);
- return true;
- }
-
- /**
- * @notice Triggers an approval from owner to spends
- * @param owner The address to approve from
- * @param spender The address to be approved
- * @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
- * @param deadline The time at which to expire the signature
- * @param v The recovery byte of the signature
- * @param r Half of the ECDSA signature pair
- * @param s Half of the ECDSA signature pair
- */
- function permit(address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
- external
- {
- uint96 amount;
- if (rawAmount == type(uint256).max) {
- amount = type(uint96).max;
- } else {
- amount = safe96(rawAmount, "Gear::permit: amount exceeds 96 bits");
- }
-
- bytes32 domainSeparator =
- keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
- bytes32 structHash =
- keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
- bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
- address signatory = ecrecover(digest, v, r, s);
- require(signatory != address(0), "Gear::permit: invalid signature");
- require(signatory == owner, "Gear::permit: unauthorized");
- require(block.timestamp <= deadline, "Gear::permit: signature expired");
-
- allowances[owner][spender] = amount;
-
- emit Approval(owner, spender, amount);
- }
-
- /**
- * @notice Get the number of tokens held by the `account`
- * @param account The address of the account to get the balance of
- * @return The number of tokens held
- */
- function balanceOf(address account) external view returns (uint256) {
- return balances[account];
- }
-
- /**
- * @notice Transfer `amount` tokens from `msg.sender` to `dst`
- * @param dst The address of the destination account
- * @param rawAmount The number of tokens to transfer
- * @return Whether or not the transfer succeeded
- */
- function transfer(address dst, uint256 rawAmount) external returns (bool) {
- uint96 amount = safe96(rawAmount, "Gear::transfer: amount exceeds 96 bits");
- _transferTokens(msg.sender, dst, amount);
- return true;
- }
-
- /**
- * @notice Transfer `amount` tokens from `src` to `dst`
- * @param src The address of the source account
- * @param dst The address of the destination account
- * @param rawAmount The number of tokens to transfer
- * @return Whether or not the transfer succeeded
- */
- function transferFrom(address src, address dst, uint256 rawAmount) external returns (bool) {
- address spender = msg.sender;
- uint96 spenderAllowance = allowances[src][spender];
- uint96 amount = safe96(rawAmount, "Gear::approve: amount exceeds 96 bits");
-
- if (spender != src && spenderAllowance != type(uint96).max) {
- uint96 newAllowance =
- sub96(spenderAllowance, amount, "Gear::transferFrom: transfer amount exceeds spender allowance");
- allowances[src][spender] = newAllowance;
-
- emit Approval(src, spender, newAllowance);
- }
-
- _transferTokens(src, dst, amount);
- return true;
- }
-
- /**
- * @notice Delegate votes from `msg.sender` to `delegatee`
- * @param delegatee The address to delegate votes to
- */
- function delegate(address delegatee) external {
- return _delegate(msg.sender, delegatee);
- }
-
- /**
- * @notice Delegates votes from signatory to `delegatee`
- * @param delegatee The address to delegate votes to
- * @param nonce The contract state required to match the signature
- * @param expiry The time at which to expire the signature
- * @param v The recovery byte of the signature
- * @param r Half of the ECDSA signature pair
- * @param s Half of the ECDSA signature pair
- */
- function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external {
- bytes32 domainSeparator =
- keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
- bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
- bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
- address signatory = ecrecover(digest, v, r, s);
- require(signatory != address(0), "Gear::delegateBySig: invalid signature");
- require(nonce == nonces[signatory]++, "Gear::delegateBySig: invalid nonce");
- require(block.timestamp <= expiry, "Gear::delegateBySig: signature expired");
- return _delegate(signatory, delegatee);
- }
-
- /**
- * @notice Gets the current votes balance for `account`
- * @param account The address to get votes balance
- * @return The number of current votes for `account`
- */
- function getCurrentVotes(address account) external view returns (uint96) {
- uint32 nCheckpoints = numCheckpoints[account];
- return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
- }
-
- /**
- * @notice Determine the prior number of votes for an account as of a block number
- * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
- * @param account The address of the account to check
- * @param blockNumber The block number to get the vote balance at
- * @return The number of votes the account had as of the given block
- */
- function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96) {
- require(blockNumber < block.number, "Gear::getPriorVotes: not yet determined");
-
- uint32 nCheckpoints = numCheckpoints[account];
- if (nCheckpoints == 0) {
- return 0;
- }
-
- // First check most recent balance
- if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
- return checkpoints[account][nCheckpoints - 1].votes;
- }
-
- // Next check implicit zero balance
- if (checkpoints[account][0].fromBlock > blockNumber) {
- return 0;
- }
-
- uint32 lower;
- uint32 upper = nCheckpoints - 1;
- while (upper > lower) {
- uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
- Checkpoint memory cp = checkpoints[account][center];
- if (cp.fromBlock == blockNumber) {
- return cp.votes;
- } else if (cp.fromBlock < blockNumber) {
- lower = center;
- } else {
- upper = center - 1;
- }
- }
- return checkpoints[account][lower].votes;
- }
-
- function _delegate(address delegator, address delegatee) internal {
- address currentDelegate = delegates[delegator];
- uint96 delegatorBalance = balances[delegator];
- delegates[delegator] = delegatee;
-
- emit DelegateChanged(delegator, currentDelegate, delegatee);
-
- _moveDelegates(currentDelegate, delegatee, delegatorBalance);
- }
-
- function _transferTokens(address src, address dst, uint96 amount) internal {
- require(transfersAllowed || msg.sender == manager || msg.sender == miner, "Gear::transfers are forbidden");
- require(src != address(0), "Gear::_transferTokens: cannot transfer from the zero address");
- require(dst != address(0), "Gear::_transferTokens: cannot transfer to the zero address");
-
- balances[src] = sub96(balances[src], amount, "Gear::_transferTokens: transfer amount exceeds balance");
- balances[dst] = add96(balances[dst], amount, "Gear::_transferTokens: transfer amount overflows");
- emit Transfer(src, dst, amount);
-
- _moveDelegates(delegates[src], delegates[dst], amount);
- }
-
- function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
- if (srcRep != dstRep && amount > 0) {
- if (srcRep != address(0)) {
- uint32 srcRepNum = numCheckpoints[srcRep];
- uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
- uint96 srcRepNew = sub96(srcRepOld, amount, "Gear::_moveVotes: vote amount underflows");
- _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
- }
-
- if (dstRep != address(0)) {
- uint32 dstRepNum = numCheckpoints[dstRep];
- uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
- uint96 dstRepNew = add96(dstRepOld, amount, "Gear::_moveVotes: vote amount overflows");
- _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
- }
- }
- }
-
- function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
- uint32 blockNumber = safe32(block.number, "Gear::_writeCheckpoint: block number exceeds 32 bits");
-
- if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
- checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
- } else {
- checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
- numCheckpoints[delegatee] = nCheckpoints + 1;
- }
-
- emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
- }
-
- function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
- require(n < 2 ** 32, errorMessage);
- return uint32(n);
- }
-
- function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
- require(n < 2 ** 96, errorMessage);
- return uint96(n);
- }
-
- function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
- uint96 c = a + b;
- require(c >= a, errorMessage);
- return c;
- }
-
- function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
- require(b <= a, errorMessage);
- return a - b;
- }
-
- function getChainId() internal view returns (uint256) {
- uint256 chainId;
- assembly {
- chainId := chainid()
- }
- return chainId;
- }
-}
diff --git a/contracts/tokens/LICENSE b/contracts/tokens/LICENSE
deleted file mode 100644
index 398e36ff..00000000
--- a/contracts/tokens/LICENSE
+++ /dev/null
@@ -1,13 +0,0 @@
-The 3-Clause BSD License
-
-Copyright 2020 Compound Labs, Inc.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-
-3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/contracts/tokens/PhantomERC20.sol b/contracts/tokens/PhantomERC20.sol
deleted file mode 100644
index 55dd04d5..00000000
--- a/contracts/tokens/PhantomERC20.sol
+++ /dev/null
@@ -1,44 +0,0 @@
-// SPDX-License-Identifier: BUSL-1.1
-// Gearbox Protocol. Generalized leverage for DeFi protocols
-// (c) Gearbox Holdings, 2022
-pragma solidity ^0.8.10;
-
-import {IPhantomERC20} from "../interfaces/IPhantomERC20.sol";
-
-/// @dev PhantomERC20 is a pseudo-ERC20 that only implements totalSupply and balanceOf
-/// @notice Used to track positions that do not issue an explicit share token
-/// This is an abstract contract and balanceOf is implemented by concrete instances
-abstract contract PhantomERC20 is IPhantomERC20 {
- address public immutable underlying;
-
- string public override symbol;
- string public override name;
- uint8 public immutable override decimals;
-
- constructor(address _underlying, string memory _name, string memory _symbol, uint8 _decimals) {
- symbol = _symbol;
- name = _name;
- decimals = _decimals;
- underlying = _underlying;
- }
-
- function totalSupply() external view virtual override returns (uint256) {
- return IPhantomERC20(underlying).totalSupply();
- }
-
- function transfer(address, uint256) external pure override returns (bool) {
- return false;
- }
-
- function allowance(address, address) external pure override returns (uint256) {
- return 0;
- }
-
- function approve(address, uint256) external pure override returns (bool) {
- return false;
- }
-
- function transferFrom(address, address, uint256) external pure override returns (bool) {
- return false;
- }
-}
diff --git a/foundry.toml b/foundry.toml
index 69aa5179..4fc44d9c 100644
--- a/foundry.toml
+++ b/foundry.toml
@@ -7,6 +7,7 @@ remappings = [
'@openzeppelin/=node_modules/@openzeppelin/',
'@chainlink/=node_modules/@chainlink/',
'hardhat/=node_modules/hardhat/',
+ '@gearbox-protocol=node_modules/@gearbox-protocol/'
]
solc_version = '0.8.17'
src = 'contracts'
diff --git a/package.json b/package.json
index 3bbd0c4c..b81555fa 100644
--- a/package.json
+++ b/package.json
@@ -36,5 +36,8 @@
"lint-staged": {
"*.sol": "forge fmt",
"*.{json,md}": "prettier --write"
+ },
+ "dependencies": {
+ "@gearbox-protocol/core-v2": "^1.7.2"
}
}
diff --git a/yarn.lock b/yarn.lock
index 9e1b3bda..9005908f 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -467,6 +467,11 @@
"@ethersproject/properties" "^5.7.0"
"@ethersproject/strings" "^5.7.0"
+"@gearbox-protocol/core-v2@^1.7.2":
+ version "1.7.2"
+ resolved "https://registry.yarnpkg.com/@gearbox-protocol/core-v2/-/core-v2-1.7.2.tgz#a116672ab9d04a8f29bc15f3104bed15f6f853b8"
+ integrity sha512-mxFxHXqROg1tutki3MbBiff5rbZsO/ephzqdeOcVbpEYPTouHD+tYablOFf2dPX2mVQhLbR2Ccj6Yh1IRWUzMw==
+
"@gearbox-protocol/prettier-config@^1.5.0":
version "1.5.0"
resolved "https://registry.yarnpkg.com/@gearbox-protocol/prettier-config/-/prettier-config-1.5.0.tgz#4df8e9fd2305fee6ab8c1417a02e31343836932a"