Verified contractPartialAGPL-3.0-or-later
Coordinator
Address0x2a6070558151d47410ce9e72f8a3483946e5cf35
- Balance
0 ETH
- Transactions
2,178
- Compiler
solc 0.8.24
- Same code
9 more contracts
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- Via IR
- yes
- License
- AGPL-3.0-or-later
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,342,609
- Creation transaction
- 0x93efbde102…63a8b1b673
73 files
- lib/blockchainManager/evm/v1/contracts/v2/Coordinator.solmain59.76 KB
- @chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol645 B
- @chainlink/contracts0.8.0/src/v0.8/Denominations.sol1.13 KB
- @chainlink/contracts0.8.0/src/v0.8/interfaces/AggregatorInterface.sol599 B
- @chainlink/contracts0.8.0/src/v0.8/interfaces/AggregatorV2V3Interface.sol215 B
- @chainlink/contracts0.8.0/src/v0.8/interfaces/AggregatorV3Interface.sol592 B
- @chainlink/contracts0.8.0/src/v0.8/interfaces/FeedRegistryInterface.sol3.77 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.17 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.64 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol9.38 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.48 KB
- @openzeppelin/contracts/access/Ownable.sol2.62 KB
- @openzeppelin/contracts/interfaces/IERC1271.sol666 B
- @openzeppelin/contracts/interfaces/IERC1967.sol667 B
- @openzeppelin/contracts/interfaces/draft-IERC1822.sol879 B
- @openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol6.04 KB
- @openzeppelin/contracts/proxy/Proxy.sol3.25 KB
- @openzeppelin/contracts/proxy/beacon/BeaconProxy.sol2.1 KB
- @openzeppelin/contracts/proxy/beacon/IBeacon.sol450 B
- @openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol2.04 KB
- @openzeppelin/contracts/security/ReentrancyGuard.sol3.13 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol12.85 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol6.94 KB
- @openzeppelin/contracts/utils/Address.sol9.36 KB
- @openzeppelin/contracts/utils/Context.sol962 B
- @openzeppelin/contracts/utils/StorageSlot.sol4.11 KB
- @openzeppelin/contracts/utils/Strings.sol2.78 KB
- @openzeppelin/contracts/utils/cryptography/ECDSA.sol9.13 KB
- @openzeppelin/contracts/utils/cryptography/SignatureChecker.sol2.26 KB
- @openzeppelin/contracts/utils/math/Math.sol12.79 KB
- @openzeppelin/contracts/utils/math/SignedMath.sol1.26 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IEscrow.sol1.52 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IEscrowedLine.sol1.07 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IInterestRateCredit.sol2.26 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ILineFactory.sol1.95 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ILineOfCredit.sol12.47 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IModuleFactory.sol1.06 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IOracle.sol352 B
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ISecuredLine.sol902 B
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ISpigot.sol3.07 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ISpigotedLine.sol6.65 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/credit/EscrowedLine.sol3.28 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/credit/LineOfCredit.sol19.4 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/credit/SecuredLine.sol3.93 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/credit/SpigotedLine.sol11.26 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/escrow/Escrow.sol6.36 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/factories/LineFactory.sol6.5 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/factories/ModuleFactory.sol1.71 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/interest-rate/InterestRateCredit.sol3.45 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/oracle/Oracle.sol5.33 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/oracle/PolygonOracle.sol6 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/modules/spigot/Spigot.sol9.32 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/utils/CreditLib.sol9.89 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/utils/CreditListLib.sol2.87 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/utils/EscrowLib.sol8.89 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/utils/LibRegistry.sol1.07 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/utils/LineFactoryLib.sol2.12 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/utils/LineLib.sol4.25 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/utils/MutualConsent.sol4.58 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/utils/SpigotLib.sol11.58 KB
- lib/blockchainManager/evm/v1/contracts/Spigot/utils/SpigotedLineLib.sol11.22 KB
- lib/blockchainManager/evm/v1/contracts/mock/SimpleAccount.sol2.2 KB
- lib/blockchainManager/evm/v1/contracts/utils/MultiCall.sol2.36 KB
- lib/blockchainManager/evm/v1/contracts/utils/interfaces/IERC20Decimals.sol224 B
- lib/blockchainManager/evm/v1/contracts/v2/Beacon.sol3.11 KB
- lib/blockchainManager/evm/v1/contracts/v2/Collateral.sol20.42 KB
- lib/blockchainManager/evm/v1/contracts/v2/Factory.sol9.88 KB
- lib/blockchainManager/evm/v1/contracts/v2/interfaces/ICollateral.sol1.88 KB
- lib/blockchainManager/evm/v1/contracts/v2/interfaces/IERC20Decimals.sol728 B
- lib/blockchainManager/evm/v1/contracts/v2/interfaces/IFactory.sol462 B
lib/blockchainManager/evm/v1/contracts/v2/Coordinator.sol
// SPDX-FileCopyrightText: Copyright (C) 2024 Signify Holdings, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.24;
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import {ICollateral} from "./interfaces/ICollateral.sol";
import {IERC20Decimals} from "./interfaces/IERC20Decimals.sol";
/**
* @title Coordinator Contract
* @notice Smart contract for managing funds in collateral contracts: due balance tracking, payments, and liquidation
*
* @dev Core functionalities:
* 1. Statement Management
* - Publishers create expense statements for teams
* - Each statement tracks total owed amount and payments
* - Statements have liquidation timelock
*
* 2. Payment Processing
* - Users can pay from their account or collateral contract
* - Supports both native chain assets (ETH/AVAX) and ERC20 assets
* - Two payment routes:
* a) Direct payment from user account
* b) Payment from collateral contract
* - Automatic fee calculation and collection
* - Price conversion using Chainlink oracles
* - Payment can be made for a statement or not
*
* 3. Liquidation Processing
* - Liquidation can be made for unpaid statements amount only
* - Liquidation can be made by authorized executors only
* - Multi-asset support for collateral
*
* 4. Fee Collection
* - Fee is collected from payment amount
* - Fee is paid to treasury
* - feeBps is in basis points (1/100th of 1%)
* - Example: 30 basis points = 0.3%
*
* 5. Collateral Management
* - Signature-based withdrawals (EIP-712)
* - Liquidation of unpaid statements
* - Multi-asset support for collateral
*
* 6. Role-Based Access
* - Publishers: Create/update statements
* - Executors: Process liquidations
* - Admins: Manage collateral contracts
* - Owner: System configuration
*
* 6. Asset Handling
* - Native assets (ETH/AVAX)
* - ERC20 assets
* - Stablecoins (1:1 USD peg)
* - Price-volatile assets (via Chainlink)
*
* 7. Security Features
* - Reentrancy protection
* - EIP-712 signatures
* - Nonce-based replay protection
* - Price staleness checks
* - Safe math operations
*
* @dev Technical Details:
* - Version: 2 (EIP712_DOMAIN_VERSION)
* - Required OpenZeppelin: Ownable, ReentrancyGuard, ECDSA, SafeERC20
* - External Dependencies: Chainlink Price Feeds
* - All amounts stored in cents (USD)
* - Withdraw and payment are processed in asset's native amount
* - Fees configured in basis points (1/100th of 1%)
*
* @dev Key State Variables:
* - treasury: Recipient of all payments and fees
* - statements: Maps statement IDs to their details
* - supportedAssets: Configuration for supported payment assets
* - publishers[]: Authorized statement creators
* - executors[]: Authorized liquidation processors
* - nonce: Prevents signature replay attacks
*
* @dev Main Workflows:
* 1. Statement Creation:
* Publisher -> createStatement -> Statement stored
*
* 2. Payment Process:
* User wallet -> makePayment -> Treasury
* OR
* Collateral -> signedPayment -> Treasury
*
* 3. Liquidation Process:
* Executor -> liquidateAsset -> Treasury
* (Only after liquidatableAfter timestamp)
*
* @notice Important Constraints:
* - Payments cannot exceed remaining statement balance
* - Excessive payments are returned to the user/collateral
* - Assets must be pre-configured before use
* - Price feeds must be fresh for non-stablecoin assets
* - Ownership cannot be renounced
*/
contract Coordinator is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20Decimals;
/// @dev Elliptic Curve Digital Signature Algorithm to validate signature
using ECDSA for bytes32;
/// @dev closingAccountBalanceCents - paidAmountCents = amount represents the outstanding balance that can be liquidated by the executor
/// @dev Statement represents a financial record for a team with the following properties:
/// All amounts are stored in USD cents (1/100th of a dollar)
struct Statement {
// Unique identifier for this statement, used as key in statements mapping
string id;
// Identifier for the team this statement belongs to, used for tracking and events
string teamId;
// Total amount owed by the team in USD cents, must be greater than 0
uint256 closingAccountBalanceCents;
// Running total of all payments made against this statement in USD cents
// Must always be <= closingAccountBalanceCents
uint256 paidAmountCents;
// Smart contract holding the team's collateral, must be non-zero address
// Used for liquidation and payment processing
address collateralProxy;
// Unix timestamp after which unpaid amounts can be liquidated
// Liquidation can only occur if block.timestamp >= liquidatableAfter
uint256 liquidatableAfter;
}
/// @dev Supported asset struct, supporting both ERC-20 and native assets with or without Chainlink oracle
struct SupportedAsset {
// Asset ERC-20 contract address. Zero address for native asset such as ETH and AVAX
// Must be non-zero for ERC20 tokens
address asset;
// Chainlink oracle address to get asset to USD exchange rate
// If not set (address(0)), asset is treated as a stablecoin with 1:1 USD peg
// Must be set for native assets and volatile tokens
address oracle;
// Threshold in seconds to consider the price feed as stale
// If 0, staleness check is disabled
// If >0, price updates older than threshold will revert
uint256 staleThreshold;
// Minimum price to consider the price feed as valid
// Price lower than min price will revert
int256 minPrice;
// Maximum price to consider the price feed as valid
// Price higher than max price will revert
int256 maxPrice;
// Fee in basis points (1/100th of 1%)
// Example: 30 = 0.3%, 100 = 1%
// Must be <= 10000 (100%)
uint16 feeBps;
}
/// @dev User readable name of signing domain
string public constant EIP712_DOMAIN_NAME = "Coordinator";
/// @dev Current major version of signing domain
string public constant EIP712_DOMAIN_VERSION = "2";
/// @dev Type hash to check EIP712 domain separator validity in signature
bytes32 public constant EIP712_DOMAIN_TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)");
/// @dev Type hash to check pay signature validity
bytes32 public constant PAY_TYPE_HASH =
keccak256(
"Pay(address user,address collateral,address asset,uint256 amount,uint256 nonce,uint256 expiresAt,string teamId,string statementId)"
);
/// @dev Type hash to check withdraw signature validity
bytes32 public constant WITHDRAW_TYPE_HASH =
keccak256(
"Withdraw(address user,address collateral,address asset,uint256 amount,address recipient,uint256 nonce,uint256 expiresAt)"
);
/// @dev Treasury contract address for the service provider.
/// Payment and liqudation moves assets to this address.
address public treasury;
/// @dev A counter to prevent duplicate transaction with same signature.
/// Using single nonce for all type of transactions to ensure their order.
/// key: address of Collateral contract
/// Value: increasing counter
mapping(address => uint256) public nonce;
/// @dev Addresses that can publish statements
address[] public publishers;
/// @dev Addresses that can liquidate
address[] public executors;
/// @dev Statement mapping
/// Key: statement's uuid
/// Value: a statement data of a team
mapping(string => Statement) public statements;
/// @dev Keeping track of supported assets
mapping(address => SupportedAsset) public supportedAssets;
event Withdrawal(address indexed collateralProxy, address asset, address recipient, uint256 amountNative);
event PaymentFromCollateral(
address user,
address indexed collateralProxy,
address asset,
uint256 amountsNative,
uint256 amountsCents,
uint256 feeNative,
uint8 assetDecimals,
uint256 nonce,
uint256 expiresAt,
string indexed indexedTeamId,
string teamId
);
event PaymentFromCollateralForStatement(
address user,
address indexed collateralProxy,
address asset,
uint256 amountsNative,
uint256 amountsCents,
uint256 feeNative,
uint8 assetDecimals,
uint256 nonce,
uint256 expiresAt,
string indexed indexedTeamId,
string teamId,
string indexed indexedStatementId,
string statementId
);
event PaymentFromUserAccount(
address user,
address asset,
uint256 amountNative,
uint256 amountCents,
uint256 feeNative,
uint8 assetDecimals,
string indexed indexedTeamId,
string teamId
);
event PaymentFromUserAccountForStatement(
address user,
address asset,
uint256 amountNative,
uint256 amountCents,
uint256 feeNative,
uint8 assetDecimals,
string indexed indexedTeamId,
string teamId,
string indexed indexedStatementId,
string statementId
);
event Liquidation(
address indexed collateralProxy,
address[] assets,
uint256[] amountsNative,
uint256[] amountsCents,
uint8[] assetDecimals,
uint256 netAmountCents,
uint256[] feeNative,
string indexed indexedTeamId,
string teamId,
string indexed indexedStatementId,
string statementId
);
event PublisherAdded(address indexed publisher);
event PublisherRemoved(address indexed publisher);
event ExecutorAdded(address indexed executor);
event ExecutorRemoved(address indexed executor);
event NewTreasury(address indexed newTreasury, address oldTreasury);
event StatementPublished(
string indexed indexedStatementId,
string statementId,
string indexed indexedTeamId,
string teamId,
uint256 closingAccountBalanceCents,
address collateralProxy,
uint256 liquidatableAfter
);
event StatementUpdated(
string indexed indexedStatementId,
string statementId,
string indexed indexedTeamId,
string teamId,
uint256 closingAccountBalanceCents,
address collateralProxy,
uint256 liquidatableAfter
);
event SupportedAssetAdded(
address indexed asset,
address oracle,
uint256 staleThreshold,
int256 minPrice,
int256 maxPrice,
uint16 feeBps
);
event SupportedAssetRemoved(
address indexed asset,
address oracle,
uint256 staleThreshold,
int256 minPrice,
int256 maxPrice,
uint16 feeBps
);
event NonceIncreased(address indexed collateralProxy, uint256 newNonce);
event StatementMarkedPaid(string indexed indexedStatementId, string statementId, uint256 amountCents);
event ExtraNativeAssetReturned(address indexed recipient, uint256 amountsNative, uint8 assetDecimals);
error Unauthorized(address unauthorizedAddress);
error UnsupportedAsset(address asset);
error InconsistentInputLength();
error InvalidTeamId();
error DisabledOwnershipRenouncement();
error BalanceMustBeGreaterOrEqualToZero();
error BalanceAlreadyPaid();
error NoAssets();
error StatementNotFound();
error CannotOverwriteStatement();
error AmountTooBig();
error AmountTooSmall();
error InvalidSignature();
error ZeroAddress();
error SupportedAssetAlreadyExists();
error TooEarlyToLiquidate();
error InvalidPrice(int256 price);
error StalePrice();
error CannotSendNativeAsset();
error InvalidFeeBps();
error PublisherAlreadyExists(address publisher);
error ExecutorAlreadyExists(address executor);
error LastPublisher(address publisher);
error LastExecutor(address executor);
error PublisherNotFound(address publisher);
error ExecutorNotFound(address executor);
error TeamIdMismatch();
/// @dev Revert if caller is not the publisher
modifier onlyPublisher() {
(bool found, ) = _getAddressIndex(publishers, msg.sender);
if (!found) {
revert Unauthorized(msg.sender);
}
_;
}
/// @dev Revert if caller is not the executor
modifier onlyExecutor() {
(bool found, ) = _getAddressIndex(executors, msg.sender);
if (!found) {
revert Unauthorized(msg.sender);
}
_;
}
/// @dev Revert if the signature is expired
modifier activeSignature(uint256 _expiresAt) {
if (block.timestamp > _expiresAt) {
revert InvalidSignature();
}
_;
}
/// @dev Revert if asset is not supported
modifier onlySupportedAsset(address _asset) {
if (!isSupportedAsset(_asset)) {
revert UnsupportedAsset(_asset);
}
_;
}
/**
* @notice Initialize Coordinator contract
* @param _owner Owner address
* @param _publisher Publisher address
* @param _executor Executor address
* @param _treasury Treasury address
*/
constructor(address _owner, address _publisher, address _executor, address _treasury) {
transferOwnership(_owner);
// Check if publisher is zero address
if (_publisher == address(0)) {
revert ZeroAddress();
}
publishers.push(_publisher);
// Check if executor is zero address
if (_executor == address(0)) {
revert ZeroAddress();
}
executors.push(_executor);
// Check if treasury is zero address
if (_treasury == address(0)) {
revert ZeroAddress();
}
treasury = _treasury;
}
/**
* @notice Add a publisher
* @dev only owner can call this function
* @param _publisher publisher address to add
*/
function addPublisher(address _publisher) external onlyOwner {
if (_publisher == address(0)) {
revert ZeroAddress();
}
// Check if publisher already exists
(bool found, ) = _getAddressIndex(publishers, _publisher);
if (found) {
revert PublisherAlreadyExists(_publisher);
}
publishers.push(_publisher);
emit PublisherAdded(_publisher);
}
/**
* @notice Remove a publisher
* @dev only owner can call this function
* @param _publisher publisher address to remove
*/
function removePublisher(address _publisher) external onlyOwner {
// Minimum one publisher is required
if (publishers.length == 1) {
revert LastPublisher(_publisher);
}
// Check if publisher exists
(bool found, uint256 index) = _getAddressIndex(publishers, _publisher);
if (!found) {
revert PublisherNotFound(_publisher);
}
// Remove publisher by moving last element to removed index then pop the last element
publishers[index] = publishers[publishers.length - 1];
publishers.pop();
emit PublisherRemoved(_publisher);
}
/**
* @notice Add an executor
* @dev only owner can call this function
* @param _executor executor address to add
*/
function addExecutor(address _executor) external onlyOwner {
// Check if executor is zero address
if (_executor == address(0)) {
revert ZeroAddress();
}
// Check if executor already exists
(bool found, ) = _getAddressIndex(executors, _executor);
if (found) {
revert ExecutorAlreadyExists(_executor);
}
executors.push(_executor);
emit ExecutorAdded(_executor);
}
/**
* @notice Remove an executor
* @dev only owner can call this function
* @param _executor executor address to remove
*/
function removeExecutor(address _executor) external onlyOwner {
// Minimum one executor is required
if (executors.length == 1) {
revert LastExecutor(_executor);
}
// Check if executor exists
(bool found, uint256 index) = _getAddressIndex(executors, _executor);
if (!found) {
revert ExecutorNotFound(_executor);
}
// Remove executor by moving last element to removed index then pop the last element
executors[index] = executors[executors.length - 1];
executors.pop();
emit ExecutorRemoved(_executor);
}
/**
* @notice Get an index of an address in an array
* @param _array array to search
* @param _address address to find
*/
function _getAddressIndex(address[] memory _array, address _address) private pure returns (bool, uint256) {
// It is expected that the number of admins would be around 1~5
for (uint256 i = 0; i < _array.length; i++) {
if (_array[i] == _address) {
return (true, i);
}
}
// Index value 0 is meaningless here as not found
return (false, 0);
}
/**
* @notice Update treasury contract address
* @dev only owner can call this function
* @param _treasury new treasury contract address
* Requirements:
* - `_newAddress` should not be NullAddress.
*/
function updateTreasury(address _treasury) external onlyOwner {
// Check if treasury is zero address
if (_treasury == address(0)) {
revert ZeroAddress();
}
address oldTreasury = treasury;
treasury = _treasury;
emit NewTreasury(_treasury, oldTreasury);
}
/**
* @notice Add a supported asset
* @dev only owner can call this function
* Requirements:
* - ERC20 tokens must have their contract address
* - Native chain asset (address(0)) must have price oracle
* - Stablecoins can be configured without price oracle
* - Price-volatile assets must have valid Chainlink oracle
* @param _asset asset's contract address, zero address for native asset such as ETH and AVAX
* @param _oracle Chainlink price oracle address to get asset to USD exchange rate
* If not set, the asset is considered to be stable.
* @param _staleThreshold threshold in seconds to consider the price feed as stale
* @param _feeBps fee in basis points
*/
function addSupportedAsset(
address _asset,
address _oracle,
uint256 _staleThreshold,
int256 _minPrice,
int256 _maxPrice,
uint16 _feeBps
) external onlyOwner {
// Check if asset already exists
if (isSupportedAsset(_asset)) {
revert SupportedAssetAlreadyExists();
}
// Native asset should be set with price oracle
if (_asset == address(0) && _oracle == address(0)) {
revert ZeroAddress();
}
// Check if feeBps is valid
if (_feeBps > 10000) {
revert InvalidFeeBps();
}
supportedAssets[_asset] = SupportedAsset(_asset, _oracle, _staleThreshold, _minPrice, _maxPrice, _feeBps);
emit SupportedAssetAdded(_asset, _oracle, _staleThreshold, _minPrice, _maxPrice, _feeBps);
}
/**
* @notice Remove a supported asset
* @dev only owner can call this function
* @param _asset asset's contract address
*/
function removeSupportedAsset(address _asset) external onlyOwner {
// Check if asset is supported
if (!isSupportedAsset(_asset)) {
revert UnsupportedAsset(_asset);
}
SupportedAsset memory asset = supportedAssets[_asset];
delete supportedAssets[_asset];
emit SupportedAssetRemoved(
asset.asset,
asset.oracle,
asset.staleThreshold,
asset.minPrice,
asset.maxPrice,
asset.feeBps
);
}
/**
* @notice Check if an asset is supported
* @param _asset asset's contract address, zero address for native asset
* @return true if asset is supported
*/
function isSupportedAsset(address _asset) public view returns (bool) {
SupportedAsset memory asset = supportedAssets[_asset];
// Asset is supported if it is not zero address
// or zero address with a price oracle(native asset)
return asset.asset != address(0) || asset.oracle != address(0);
}
/**
* @notice Convert amounts in cents to native
* @param _asset asset's contract address
* @param _amountCents asset amount in cents
* @return amountNative converted amount in native asset
* @return assetDecimals asset's smallest unit
*/
function getAssetAmountNative(
address _asset,
uint256 _amountCents
) public view returns (uint256 amountNative, uint8 assetDecimals) {
// Check if asset is supported
if (!isSupportedAsset(_asset)) {
revert UnsupportedAsset(_asset);
}
SupportedAsset memory asset = supportedAssets[_asset];
assetDecimals = _asset == address(0)
? 18 // All EVM chains should implement 18 decimals in its native asset
: IERC20Decimals(_asset).decimals();
if (asset.oracle == address(0)) {
// asset is considered to be stable to USD
amountNative = (_amountCents * (10 ** (assetDecimals - 2)));
} else {
(int256 price, uint8 priceDecimals) = _getCurrentAssetPrice(asset);
amountNative = (_amountCents * (10 ** (uint256(priceDecimals) - 2 + assetDecimals))) / uint256(price);
}
}
/**
* @notice Convert amounts in native to cents
* @param _asset asset's contract address
* @param _amountNative asset amount in native decimals
* @return amountCents converted amount in cents
*/
function getAssetAmountCents(
address _asset,
uint256 _amountNative
) public view returns (uint256 amountCents, uint8 assetDecimals) {
// Check if asset is supported
if (!isSupportedAsset(_asset)) {
revert UnsupportedAsset(_asset);
}
SupportedAsset memory asset = supportedAssets[_asset];
assetDecimals = _asset == address(0)
? 18 // All EVM chains should implement 18 decimals in its native asset
: IERC20Decimals(_asset).decimals();
if (asset.oracle == address(0)) {
// asset is considered to be stable to USD
uint256 divisor = 10 ** (assetDecimals - 2);
// Floor cents amount
amountCents = _amountNative / divisor;
} else {
(int256 price, uint8 priceDecimals) = _getCurrentAssetPrice(asset);
uint256 divisor = 10 ** (uint256(priceDecimals) - 2 + assetDecimals);
// Floor cents amount
amountCents = (_amountNative * uint256(price)) / divisor;
}
}
/**
* @notice Get current price of an asset
* @dev Price validation:
* 1. Price must be > 0 (reverts on zero/negative)
* 2. If staleThreshold > 0, price timestamp must be recent
* 3. Decimals are retrieved from oracle for proper scaling
* @param _asset asset information
* @return price current price of the asset
* @return decimals price's decimals
*/
function _getCurrentAssetPrice(SupportedAsset memory _asset) private view returns (int256 price, uint8 decimals) {
// Get price from Chainlink oracle
AggregatorV3Interface priceOracle = AggregatorV3Interface(_asset.oracle);
// Get price and updated at from Chainlink oracle
uint256 updatedAt;
(, price, , updatedAt, ) = priceOracle.latestRoundData();
// 0 or negative price is invalid
if (price <= 0) {
revert InvalidPrice(price);
}
// Check if price is within the allowed range
if (price < _asset.minPrice) {
revert InvalidPrice(price);
}
if (price > _asset.maxPrice) {
revert InvalidPrice(price);
}
// Get price decimals from Chainlink oracle
decimals = priceOracle.decimals();
// Check if price from oracle is stale
if (_asset.staleThreshold != 0 && updatedAt + _asset.staleThreshold < block.timestamp) {
revert StalePrice();
}
}
/**
* @notice Increase nonce of a collateral proxy by owner
* It can be used to invalidate a signature issued by executor or publisher
* @dev only executor can call this function
* @param _collateralProxy collateral proxy address
*/
function increaseNonce(address _collateralProxy) external onlyExecutor {
nonce[_collateralProxy]++;
emit NonceIncreased(_collateralProxy, nonce[_collateralProxy]);
}
/**
* @notice Publish closing account balance of multiple teams
* @param _statementIds array of statement's uuid
* @param _teamIds array of team's uuid in the same order as _statementIds
* @param _closingAccountBalanceCents array of closing account balance in cents in the same order as _statementIds
* @param _collateralProxies array of Collateral contract addresses in the same order as _statementIds
*/
function publishStatements(
string[] calldata _statementIds,
string[] calldata _teamIds,
uint256[] calldata _closingAccountBalanceCents,
address[] calldata _collateralProxies,
uint256[] calldata _liquidatableAfters
) public onlyPublisher {
// Check if input lengths are consistent
if (
_teamIds.length != _statementIds.length ||
_teamIds.length != _closingAccountBalanceCents.length ||
_teamIds.length != _collateralProxies.length ||
_teamIds.length != _liquidatableAfters.length
) {
revert InconsistentInputLength();
}
for (uint256 i = 0; i < _teamIds.length; i++) {
// Check if teamId is valid
if (bytes(_teamIds[i]).length == 0) {
revert InvalidTeamId();
}
// Closing account balance must be greater or equal to zero
if (_closingAccountBalanceCents[i] <= 0) {
revert BalanceMustBeGreaterOrEqualToZero();
}
// Collateral proxy address must be valid
if (_collateralProxies[i] == address(0)) {
revert ZeroAddress();
}
Statement storage statement = statements[_statementIds[i]];
// Statement should not be published yet
if (statement.closingAccountBalanceCents > 0) {
revert CannotOverwriteStatement();
}
// Create a new statement
statements[_statementIds[i]] = Statement(
_statementIds[i],
_teamIds[i],
_closingAccountBalanceCents[i],
0,
_collateralProxies[i],
_liquidatableAfters[i]
);
emit StatementPublished(
_statementIds[i],
_statementIds[i],
_teamIds[i],
_teamIds[i],
_closingAccountBalanceCents[i],
_collateralProxies[i],
_liquidatableAfters[i]
);
}
}
/**
* @notice Update statement after publishing
* @param _statementId statement's uuid
* @param _teamId team's uuid
* @param _closingAccountBalanceCent closing account balance in cents
* @param _collateralProxy Collateral contract address
*/
function updateStatement(
string calldata _statementId,
string calldata _teamId,
uint256 _closingAccountBalanceCent,
address _collateralProxy,
uint256 _liquidatableAfter
) public onlyPublisher {
Statement storage statement = statements[_statementId];
// Statement should be published
if (bytes(statement.teamId).length == 0) {
revert StatementNotFound();
}
// Closing account balance must be greater than or equal to paid amount
if (_closingAccountBalanceCent < statement.paidAmountCents) {
revert BalanceAlreadyPaid();
}
// Collateral proxy address must be valid
if (_collateralProxy == address(0)) {
revert ZeroAddress();
}
// Update statement
statement.teamId = _teamId;
statement.closingAccountBalanceCents = _closingAccountBalanceCent;
statement.collateralProxy = _collateralProxy;
statement.liquidatableAfter = _liquidatableAfter;
emit StatementUpdated(
_statementId,
_statementId,
_teamId,
_teamId,
_closingAccountBalanceCent,
_collateralProxy,
_liquidatableAfter
);
}
/**
* @notice Mark a statement as paid in case it was paid outside the chain
* @dev Validation checks:
* 1. Verify statement exists
* 2. Check that new payment won't exceed remaining balance
* 3. Safely add payment to running total
* All amounts are in cents to maintain consistency
* @param _statementId statement's uuid
* @param _amountCents amount in cents
*/
function markStatementPaid(string calldata _statementId, uint256 _amountCents) public onlyExecutor {
_markStatementPaid(statements[_statementId], _amountCents);
}
/**
* @notice Liquidate assets of multiple teams
* @dev Liquidation flow:
* 1. Verify statement exists and liquidation timelock has passed
* 2. Calculate outstanding balance (closing - paid amounts)
* 3. For each asset:
* - Convert desired cents to native asset amount
* - Transfer from collateral to treasury
* - Track running total of liquidated value
* 4. Stop when full amount is covered or assets exhausted
* 5. Update statement's paid amount
* @param _statementIds array of statement's uuid in the same order as _teamIds
* @param _assets array of assets' contract addresses in the same order as _teamIds
*/
function liquidateAsset(string[] calldata _statementIds, address[][] calldata _assets) public onlyExecutor {
// Check if input lengths are consistent
if (_statementIds.length != _assets.length) {
revert InconsistentInputLength();
}
for (uint256 i = 0; i < _statementIds.length; i++) {
// Check if assets array is not empty
if (_assets[i].length == 0) {
revert NoAssets();
}
Statement storage statement = statements[_statementIds[i]];
// Statement should be published
if (statement.closingAccountBalanceCents == 0) {
revert StatementNotFound();
}
// Statement should be liquidatable after the specified time
if (block.timestamp < statement.liquidatableAfter) {
revert TooEarlyToLiquidate();
}
// Calculate pending amount and net amount
uint256 pendingAmountCents = statement.closingAccountBalanceCents - statement.paidAmountCents;
uint256 netAmountCents = 0; // Sum of cents amount without fee
uint256[] memory amountsNativeFinal = new uint256[](_assets[i].length);
uint256[] memory amountsCentsFinal = new uint256[](_assets[i].length);
uint8[] memory assetDecimals = new uint8[](_assets[i].length);
uint256[] memory feeNative = new uint256[](_assets[i].length);
for (uint256 j = 0; j < _assets[i].length; j++) {
// Stop if pending amount is already liquidated
if (netAmountCents >= pendingAmountCents) {
break;
}
// Check if asset is supported
if (!isSupportedAsset(_assets[i][j])) {
revert UnsupportedAsset(_assets[i][j]);
}
// Transfer asset from collateral to treasury
(
amountsNativeFinal[j],
amountsCentsFinal[j],
feeNative[j],
assetDecimals[j]
) = _transferCollateralCents(
statement.collateralProxy,
_assets[i][j],
pendingAmountCents - netAmountCents,
treasury,
supportedAssets[_assets[i][j]].feeBps,
true
);
netAmountCents += amountsCentsFinal[j];
}
// Update paid amount
statement.paidAmountCents += netAmountCents;
string memory teamId = statements[_statementIds[i]].teamId;
emit Liquidation(
statement.collateralProxy,
_assets[i],
amountsNativeFinal,
amountsCentsFinal,
assetDecimals,
netAmountCents,
feeNative,
teamId,
teamId,
_statementIds[i],
_statementIds[i]
);
}
}
/**
* @notice Withdraw assets from a Collateral contract with multi-signature verification
* @dev Requires signatures from both an executor/publisher AND collateral admins
* @dev Withdrawal flow:
* 1. Verify signature from executor/publisher
* 2. Verify signatures from collateral admins
* 3. Transfer assets from collateral to recipient
* @param _collateralProxy The Collateral contract to withdraw from
* @param _asset Asset address (or zero address for native asset)
* @param _amountNative Amount to withdraw in asset's native decimals
* @param _recipient Address to receive the withdrawn assets
* @param _expiresAt Timestamp after which the signatures become invalid
* @param _executorPublisherSalt Salt for executor/publisher signature domain separator
* @param _executorPublisherSignature Signature from either an executor or publisher
* @param _adminSalts Array of salts for admin signatures
* @param _adminSignatures Array of signatures from collateral admins
* @param _directTransfer If true, transfers directly to recipient. If false, routes through coordinator
*/
function withdrawAsset(
address _collateralProxy,
address _asset,
uint256 _amountNative,
address _recipient,
uint256 _expiresAt,
bytes32 _executorPublisherSalt,
bytes calldata _executorPublisherSignature,
bytes32[] calldata _adminSalts,
bytes[] calldata _adminSignatures,
bool _directTransfer
) external activeSignature(_expiresAt) {
// Create message hash for executor/publisher signature verification
// Includes user address, collateral details, asset info, and withdrawal params
bytes32 messageHash = keccak256(
bytes.concat(
abi.encode(WITHDRAW_TYPE_HASH, msg.sender, _collateralProxy, _asset, _amountNative),
abi.encode(_recipient, nonce[_collateralProxy], _expiresAt)
)
);
// Verify signature from executor or publisher
_verifySignature(_collateralProxy, messageHash, _executorPublisherSalt, _executorPublisherSignature);
// Verify signatures from collateral admins
ICollateral collateral = ICollateral(_collateralProxy);
collateral.verifyWithdrawAdminSignatures(
msg.sender,
_asset,
_amountNative,
_recipient,
_adminSalts,
_adminSignatures
);
// Transfer assets from collateral to recipient
// No fee is charged for withdrawals
_transferCollateralCommon(_collateralProxy, _asset, _recipient, _amountNative, 0, _directTransfer);
// Emit withdrawal event with final details
emit Withdrawal(_collateralProxy, _asset, _recipient, _amountNative);
}
/**
* @notice Make payment from Collateral contract
* The payment is not tied to any statement
* @dev Payment flow:
* 1. Get current nonce for the collateral proxy
* 2. Verify signature from executor or publisher
* 3. Transfer assets from collateral to treasury
* @param _collateralProxy targeting Collateral proxy address
* @param _asset asset's contract address
* @param _amountNative asset amount to pay in native decimals
* @param _expiresAt expiry time of the signature
* @param _salt disambiguating salt for signature
* @param _signature signature generated by either executor or publisher
* @param _teamId team's uuid
*/
function makePaymentFromCollateral(
address _collateralProxy,
address _asset,
uint256 _amountNative,
uint256 _expiresAt,
bytes32 _salt,
bytes calldata _signature,
string calldata _teamId
) external {
uint256 _nonce = nonce[_collateralProxy];
// Transfer asset from collateral to treasury
(
uint256 amountNativeFinal,
uint256 amountCentsFinal,
uint256 feeNative,
uint8 assetDecimals
) = _makePaymentFromCollateral(
_collateralProxy,
_asset,
_amountNative,
_nonce,
_expiresAt,
_teamId,
"",
_salt,
_signature
);
emit PaymentFromCollateral(
msg.sender,
_collateralProxy,
_asset,
amountNativeFinal,
amountCentsFinal,
feeNative,
assetDecimals,
_nonce,
_expiresAt,
_teamId,
_teamId
);
}
/**
* @notice Make payment from Collateral contract and mark statement as paid
* @dev Payment flow:
* 1. Get current nonce for the collateral proxy
* 2. Verify signature from executor or publisher
* 3. Transfer assets from collateral to treasury
* 4. Mark statement as paid
* @param _collateralProxy targeting Collateral proxy address
* @param _asset asset's contract address
* @param _amountNative asset amount to pay in native decimals
* @param _expiresAt expiry time of the signature
* @param _salt disambiguating salt for signature
* @param _signature signature generated by either executor or publisher
* @param _statementId statement's uuid
*/
function makePaymentFromCollateralForStatement(
address _collateralProxy,
address _asset,
uint256 _amountNative,
uint256 _expiresAt,
bytes32 _salt,
bytes calldata _signature,
string calldata _teamId,
string calldata _statementId
) external {
uint256 _nonce = nonce[_collateralProxy];
Statement storage statement = statements[_statementId];
// Check if the teamId of the statement matches the teamId of the payment
if (keccak256(bytes(statement.teamId)) != keccak256(bytes(_teamId))) {
revert TeamIdMismatch();
}
// Transfer asset from collateral to treasury
(
uint256 amountNativeFinal,
uint256 amountCentsFinal,
uint256 feeNative,
uint8 assetDecimals
) = _makePaymentFromCollateral(
_collateralProxy,
_asset,
_amountNative,
_nonce,
_expiresAt,
_teamId,
_statementId,
_salt,
_signature
);
// Mark statement as paid
_markStatementPaid(statement, amountCentsFinal);
emit PaymentFromCollateralForStatement(
msg.sender,
_collateralProxy,
_asset,
amountNativeFinal,
amountCentsFinal,
feeNative,
assetDecimals,
_nonce,
_expiresAt,
statement.teamId,
statement.teamId,
_statementId,
_statementId
);
}
/**
* @notice Sub function to verify signature and transfer asset from Collateral contract to treasury
* @dev Payment flow:
* 1. Verify signature is valid and from authorized signer
* 2. Create EIP-712 compliant message hash
* 3. Verify signature matches message and increment nonce
* 4. Calculate payment amount and fee in native decimals
* 5. Transfer asset from collateral to treasury:
* - For native assets (ETH/AVAX): Direct transfer
* - For ERC20: Use safe transfer after approval
* 6. Return final amounts in native and cents
* @param _collateralProxy targeting Collateral proxy address
* @param _asset asset's contract address
* @param _amountNative asset amount to pay in native decimals
* @param _nonce nonce of the transaction
* @param _expiresAt expiry time of the signature
* @param _teamId team's uuid
* @param _statementId statement's uuid. If empty, the payment is not tied to any statement
* @param _salt disambiguating salt for signature
* @param _signature signature generated by either executor or publisher
* @return amountNativeFinal amount that was actually transferred in native decimals including fee
* @return amountCentsFinal amount that was actually transferred in cents
* @return feeNative fee paid in native decimals
* @return assetDecimals asset's smallest unit
*/
function _makePaymentFromCollateral(
address _collateralProxy,
address _asset,
uint256 _amountNative,
uint256 _nonce,
uint256 _expiresAt,
string calldata _teamId,
string memory _statementId,
bytes32 _salt,
bytes calldata _signature
)
internal
onlySupportedAsset(_asset)
activeSignature(_expiresAt)
returns (uint256 amountNativeFinal, uint256 amountCentsFinal, uint256 feeNative, uint8 assetDecimals)
{
// Create message hash for signature verification
bytes32 messageHash = keccak256(
bytes.concat(
abi.encode(PAY_TYPE_HASH, msg.sender, _collateralProxy, _asset, _amountNative),
abi.encode(_nonce, _expiresAt, keccak256(bytes(_teamId)), keccak256(bytes(_statementId)))
)
);
_verifySignature(_collateralProxy, messageHash, _salt, _signature);
// Transfer asset from collateral to treasury
(amountNativeFinal, amountCentsFinal, feeNative, assetDecimals) = _transferCollateralNative(
_collateralProxy,
_asset,
_amountNative,
treasury,
supportedAssets[_asset].feeBps,
true
);
}
/**
* @notice Make payment from user account without marking statement as paid
* @dev Payment flow:
* 1. Calculate fee based on configured basis points
* 2. For native assets:
* - Verify sufficient msg.value
* - Transfer to treasury
* 3. For ERC20:
* - Transfer from user to coordinator
* - Transfer from coordinator to treasury
* @param _asset asset's contract address
* @param _amountNative asset amount to pay in native decimals
* @param _teamId team's uuid
*/
function makePaymentFromUserAccount(
address _asset,
uint256 _amountNative,
string calldata _teamId
) external payable {
// Transfer asset from user account to treasury
(uint256 amountCents, uint256 feeNative, uint8 assetDecimals) = _makePaymentFromUserAccount(
_asset,
_amountNative
);
emit PaymentFromUserAccount(
msg.sender,
_asset,
_amountNative,
amountCents,
feeNative,
assetDecimals,
_teamId,
_teamId
);
}
/**
* @notice Make payment from user account and mark statement as paid
* @dev Payment flow:
* 1. Transfer asset from user account to treasury:
* - For native assets: verify msg.value and transfer to treasury
* - For ERC20: transfer from user to coordinator then to treasury
* 2. Calculate payment amount in cents
* 3. Mark statement as paid with the cents amount
* @param _asset asset's contract address
* @param _amountNative asset amount to pay in native decimals
* @param _statementId statement's uuid
*/
function makePaymentFromUserAccountForStatement(
address _asset,
uint256 _amountNative,
string calldata _statementId
) external payable {
// Transfer asset from user account to treasury
(uint256 amountCents, uint256 feeNative, uint8 assetDecimals) = _makePaymentFromUserAccount(
_asset,
_amountNative
);
_markStatementPaid(statements[_statementId], amountCents);
emit PaymentFromUserAccountForStatement(
msg.sender,
_asset,
_amountNative,
amountCents,
feeNative,
assetDecimals,
statements[_statementId].teamId,
statements[_statementId].teamId,
_statementId,
_statementId
);
}
/**
* @notice Sub function to transfer asset from user account to treasury
* @dev Payment flow:
* 1. Calculate fee based on configured basis points (feeBps)
* 2. Calculate total amount including fee
* 3. Convert payment amount to cents for statement tracking
* 4. For native assets (ETH/AVAX):
* - Verify msg.value covers amount + fee
* - Transfer to treasury
* - Return any excess ETH to sender
* 5. For ERC20 tokens:
* - Transfer tokens from user to coordinator (requires prior approval)
* - Transfer tokens from coordinator to treasury
* @param _asset asset's contract address
* @param _amountNative asset amount to pay in native decimals
* @return amountCents converted amount in cents
* @return feeNative fee paid in native decimals
* @return assetDecimals asset's smallest unit
*/
function _makePaymentFromUserAccount(
address _asset,
uint256 _amountNative
)
internal
nonReentrant
onlySupportedAsset(_asset)
returns (uint256 amountCents, uint256 feeNative, uint8 assetDecimals)
{
// Calculate fee by flooring
feeNative = (_amountNative * supportedAssets[_asset].feeBps) / 10000;
uint256 amountWithFeeNative = _amountNative + feeNative;
// Convert amount to cents
(amountCents, assetDecimals) = getAssetAmountCents(_asset, _amountNative);
// Transfer native asset from user account to treasury
if (_asset == address(0)) {
if (msg.value < amountWithFeeNative) {
revert AmountTooSmall();
}
// Send native asset to treasury
(bool sentToTreasury, ) = treasury.call{value: amountWithFeeNative}("");
// Check if the transfer was successful
if (!sentToTreasury) {
revert CannotSendNativeAsset();
}
// Return excessive amount to sender
uint256 extraAsset = msg.value - amountWithFeeNative;
if (extraAsset > 0) {
(bool sentBackToSender, ) = msg.sender.call{value: extraAsset}("");
// Check if the transfer was successful
if (!sentBackToSender) {
revert CannotSendNativeAsset();
}
emit ExtraNativeAssetReturned(msg.sender, extraAsset, assetDecimals);
}
} else {
IERC20Decimals asset = IERC20Decimals(_asset);
// Using two steps expecting user to approve coordinator
// to transfer asset before calling this function.
asset.safeTransferFrom(msg.sender, address(this), amountWithFeeNative);
asset.safeTransfer(treasury, amountWithFeeNative);
}
}
/**
* @notice Sub function mark statement as paid
* @param _statement statement to mark as paid
* @param _amountCents asset amount to pay in cents
*/
function _markStatementPaid(Statement storage _statement, uint256 _amountCents) internal {
if (bytes(_statement.teamId).length == 0) {
revert StatementNotFound();
}
// Check if the amount to be paid is greater than the remaining balance
if (_amountCents > _statement.closingAccountBalanceCents - _statement.paidAmountCents) {
revert AmountTooBig();
}
// Update paid amount
_statement.paidAmountCents += _amountCents;
emit StatementMarkedPaid(_statement.id, _statement.id, _amountCents);
}
/**
* @notice Transfer native amount of assets from Collateral contract to recipient
* @param _collateralProxy targeting Collateral proxy address
* @param _asset asset's contract address
* @param _amountNative asset amount to transfer in native decimals
* @param _recipient address to receive asset
* @param _feeBps fee in basis points
* @param _directTransfer if false, transfer asset to coordinator first then to recipient
* @return amountNativeFinal amount that was actually transferred in native decimals
* @return amountCentsFinal amount that was actually transferred in cents
* @return feeNative fee in native decimals
* @return assetDecimals asset's smallest unit
*/
function _transferCollateralNative(
address _collateralProxy,
address _asset,
uint256 _amountNative,
address _recipient,
uint16 _feeBps,
bool _directTransfer
) internal returns (uint256 amountNativeFinal, uint256 amountCentsFinal, uint256 feeNative, uint8 assetDecimals) {
// Get current collateral balance
uint256 currentCollateralBalanceNative = _asset == address(0)
? _collateralProxy.balance
: IERC20Decimals(_asset).balanceOf(_collateralProxy);
// Calculate fee by flooring
feeNative = (_amountNative * _feeBps) / 10000;
// Check if the amount to be transferred is greater than the collateral balance
if (currentCollateralBalanceNative < _amountNative + feeNative) {
// Calculate amount and fee with the remaining collateral balance
amountNativeFinal = (currentCollateralBalanceNative * 10000) / (10000 + _feeBps);
// Convert amount to cents
(amountCentsFinal, assetDecimals) = getAssetAmountCents(_asset, amountNativeFinal);
// Calculate fee with the remaining collateral balance
feeNative = currentCollateralBalanceNative - amountNativeFinal;
} else {
// Transfer full amount in parameter
amountNativeFinal = _amountNative;
// Convert amount to cents
(amountCentsFinal, assetDecimals) = getAssetAmountCents(_asset, _amountNative);
}
_transferCollateralCommon(_collateralProxy, _asset, _recipient, amountNativeFinal, feeNative, _directTransfer);
}
/**
* @notice Transfer cents amount of assets from Collateral contract to recipient
* @param _collateralProxy targeting Collateral proxy address
* @param _asset asset's contract address
* @param _amountCents asset amount to transfer in cents
* @param _recipient address to receive asset
* @param _feeBps fee in basis points
* @param _directTransfer if false, transfer asset to coordinator first then to recipient
* @return amountNativeFinal amount that was actually transferred in native asset
* @return amountCentsFinal amount that was actually transferred in cents
* @return feeNative fee in native asset
* @return assetDecimals asset's smallest unit
*/
function _transferCollateralCents(
address _collateralProxy,
address _asset,
uint256 _amountCents,
address _recipient,
uint16 _feeBps,
bool _directTransfer
) internal returns (uint256 amountNativeFinal, uint256 amountCentsFinal, uint256 feeNative, uint8 assetDecimals) {
// Convert amount to native
uint256 amountNative;
(amountNative, assetDecimals) = getAssetAmountNative(_asset, _amountCents);
// Calculate fee by flooring
feeNative = (amountNative * _feeBps) / 10000;
// Get current collateral balance
uint256 currentCollateralBalanceNative = _asset == address(0)
? _collateralProxy.balance
: IERC20Decimals(_asset).balanceOf(_collateralProxy);
// Check if the amount to be transferred is greater than the collateral balance
if (currentCollateralBalanceNative < amountNative + feeNative) {
// Calculate amount and fee with the remaining collateral balance
amountNativeFinal = (currentCollateralBalanceNative * 10000) / (10000 + _feeBps);
// Convert amount to cents
(amountCentsFinal, assetDecimals) = getAssetAmountCents(_asset, amountNativeFinal);
// Calculate fee with the remaining collateral balance
feeNative = currentCollateralBalanceNative - amountNativeFinal;
} else {
// Transfer full amount in parameter
amountNativeFinal = amountNative;
amountCentsFinal = _amountCents;
}
_transferCollateralCommon(_collateralProxy, _asset, _recipient, amountNativeFinal, feeNative, _directTransfer);
}
/**
* @notice Sub function to transfer asset from Collateral contract to recipient
* @dev Transfer flows:
* 1. Direct transfer (_directTransfer = true):
* collateral -> recipient
* 2. Indirect transfer (_directTransfer = false):
* collateral -> coordinator -> recipient
* The indirect flow allows the coordinator to handle ERC20
* approvals and native asset conversions if needed
* @param _collateralProxy targeting Collateral proxy address
* @param _asset asset's contract address
* @param _recipient address to receive asset
* @param _amountNativeFinal amount that was actually transferred in native decimals
* @param _feeNative fee in native decimals
* @param _directTransfer if true, transfer asset to recipient directly.
* if false, transfer asset to coordinator first then to recipient
* so that coordinator address can be allowed to withdraw asset by ERC-20 allowance function
*/
function _transferCollateralCommon(
address _collateralProxy,
address _asset,
address _recipient,
uint256 _amountNativeFinal,
uint256 _feeNative,
bool _directTransfer
) internal {
// Transfer native asset(ETH, AVAX, etc.)
if (_asset == address(0)) {
if (_directTransfer) {
// Transfer asset to recipient directly
ICollateral(_collateralProxy).withdrawNativeAsset(_recipient, _amountNativeFinal + _feeNative);
} else {
// Transfer asset to coordinator first then to
ICollateral(_collateralProxy).withdrawNativeAsset(address(this), _amountNativeFinal + _feeNative);
// Transfer asset to recipient
(bool sentToRecipient, ) = _recipient.call{value: _amountNativeFinal + _feeNative}("");
if (!sentToRecipient) {
revert CannotSendNativeAsset();
}
}
} else {
// Transfer ERC-20 asset
if (_directTransfer) {
// Transfer asset to recipient directly
ICollateral(_collateralProxy).withdrawERC20Asset(_asset, _recipient, _amountNativeFinal + _feeNative);
} else {
// Transfer asset to coordinator first then to recipient
ICollateral(_collateralProxy).withdrawERC20Asset(
_asset,
address(this),
_amountNativeFinal + _feeNative
);
IERC20Decimals asset = IERC20Decimals(_asset);
asset.safeTransfer(_recipient, _amountNativeFinal + _feeNative);
}
}
}
/**
* @notice Sub function of _verifyPaymentSignature and _verifyWithdrawal
* used to verify signature is from either executor or publisher
* @dev Verification flow:
* 1. Create domain separator with contract-specific data
* 2. Hash the typed data according to EIP-712 standard
* 3. Recover signer address from signature
* 4. Verify signer is authorized (executor or publisher)
* 5. Increment nonce to prevent signature reuse
* @param _collateralProxy targeting Collateral proxy address
* @param _messageHash keccak256 hashed message
* @param _salt disambiguating salt for signature
* @param _signature signature generated by either executor or publisher
*/
function _verifySignature(
address _collateralProxy,
bytes32 _messageHash,
bytes32 _salt,
bytes calldata _signature
) internal {
// Create domain separator
bytes32 domainSeparator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPE_HASH,
keccak256(bytes(EIP712_DOMAIN_NAME)),
keccak256(bytes(EIP712_DOMAIN_VERSION)),
block.chainid,
address(this),
_salt
)
);
// Create digest
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, _messageHash));
// Verify that the signature was generated by either executor or publisher
address recoveredAddress = digest.recover(_signature);
(bool isExecutor, ) = _getAddressIndex(executors, recoveredAddress);
(bool isPublisher, ) = _getAddressIndex(publishers, recoveredAddress);
if (!isExecutor && !isPublisher) {
revert InvalidSignature();
}
// Update nonce
nonce[_collateralProxy] += 1;
}
/**
* @notice Block renounceOwnership
*/
function renounceOwnership() public virtual override onlyOwner {
revert DisabledOwnershipRenouncement();
}
/**
* @notice Receive native asset(ETH, AVAX, etc.)
*/
receive() external payable {}
}
@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
@chainlink/contracts0.8.0/src/v0.8/Denominations.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Denominations {
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant BTC = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;
// Fiat currencies follow https://en.wikipedia.org/wiki/ISO_4217
address public constant USD = address(840);
address public constant GBP = address(826);
address public constant EUR = address(978);
address public constant JPY = address(392);
address public constant KRW = address(410);
address public constant CNY = address(156);
address public constant AUD = address(36);
address public constant CAD = address(124);
address public constant CHF = address(756);
address public constant ARS = address(32);
address public constant PHP = address(608);
address public constant NZD = address(554);
address public constant SGD = address(702);
address public constant NGN = address(566);
address public constant ZAR = address(710);
address public constant RUB = address(643);
address public constant INR = address(356);
address public constant BRL = address(986);
}
@chainlink/contracts0.8.0/src/v0.8/interfaces/AggregatorInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
@chainlink/contracts0.8.0/src/v0.8/interfaces/AggregatorV2V3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}
@chainlink/contracts0.8.0/src/v0.8/interfaces/AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
@chainlink/contracts0.8.0/src/v0.8/interfaces/FeedRegistryInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "./AggregatorV2V3Interface.sol";
interface FeedRegistryInterface {
struct Phase {
uint16 phaseId;
uint80 startingAggregatorRoundId;
uint80 endingAggregatorRoundId;
}
event FeedProposed(
address indexed asset,
address indexed denomination,
address indexed proposedAggregator,
address currentAggregator,
address sender
);
event FeedConfirmed(
address indexed asset,
address indexed denomination,
address indexed latestAggregator,
address previousAggregator,
uint16 nextPhaseId,
address sender
);
// V3 AggregatorV3Interface
function decimals(address base, address quote) external view returns (uint8);
function description(address base, address quote) external view returns (string memory);
function version(address base, address quote) external view returns (uint256);
function latestRoundData(
address base,
address quote
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function getRoundData(
address base,
address quote,
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
// V2 AggregatorInterface
function latestAnswer(address base, address quote) external view returns (int256 answer);
function latestTimestamp(address base, address quote) external view returns (uint256 timestamp);
function latestRound(address base, address quote) external view returns (uint256 roundId);
function getAnswer(address base, address quote, uint256 roundId) external view returns (int256 answer);
function getTimestamp(address base, address quote, uint256 roundId) external view returns (uint256 timestamp);
// Registry getters
function getFeed(address base, address quote) external view returns (AggregatorV2V3Interface aggregator);
function getPhaseFeed(
address base,
address quote,
uint16 phaseId
) external view returns (AggregatorV2V3Interface aggregator);
function isFeedEnabled(address aggregator) external view returns (bool);
function getPhase(address base, address quote, uint16 phaseId) external view returns (Phase memory phase);
// Round helpers
function getRoundFeed(
address base,
address quote,
uint80 roundId
) external view returns (AggregatorV2V3Interface aggregator);
function getPhaseRange(
address base,
address quote,
uint16 phaseId
) external view returns (uint80 startingRoundId, uint80 endingRoundId);
function getPreviousRoundId(
address base,
address quote,
uint80 roundId
) external view returns (uint80 previousRoundId);
function getNextRoundId(address base, address quote, uint80 roundId) external view returns (uint80 nextRoundId);
// Feed management
function proposeFeed(address base, address quote, address aggregator) external;
function confirmFeed(address base, address quote, address aggregator) external;
// Proposed aggregator
function getProposedFeed(
address base,
address quote
) external view returns (AggregatorV2V3Interface proposedAggregator);
function proposedGetRoundData(
address base,
address quote,
uint80 roundId
) external view returns (uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function proposedLatestRoundData(
address base,
address quote
) external view returns (uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
// Phases
function getCurrentPhaseId(address base, address quote) external view returns (uint16 currentPhaseId);
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
@openzeppelin/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*
* _Available since v4.8.3._
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
@openzeppelin/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/IERC1967.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*/
abstract contract ERC1967Upgrade is IERC1967 {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
@openzeppelin/contracts/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overridden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../Proxy.sol";
import "../ERC1967/ERC1967Upgrade.sol";
/**
* @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.
*
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
* conflict with the storage layout of the implementation behind the proxy.
*
* _Available since v3.4._
*/
contract BeaconProxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
*/
constructor(address beacon, bytes memory data) payable {
_upgradeBeaconToAndCall(beacon, data, false);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address) {
return _getBeacon();
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_getBeacon()).implementation();
}
/**
* @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
*
* Requirements:
*
* - `beacon` must be a contract.
* - The implementation returned by `beacon` must be a contract.
*/
function _setBeacon(address beacon, bytes memory data) internal virtual {
_upgradeBeaconToAndCall(beacon, data, false);
}
}
@openzeppelin/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../../access/Ownable.sol";
import "../../utils/Address.sol";
/**
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
* implementation contract, which is where they will delegate all function calls.
*
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
*/
contract UpgradeableBeacon is IBeacon, Ownable {
address private _implementation;
/**
* @dev Emitted when the implementation returned by the beacon is changed.
*/
event Upgraded(address indexed implementation);
/**
* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
* beacon.
*/
constructor(address implementation_) {
_setImplementation(implementation_);
}
/**
* @dev Returns the current implementation address.
*/
function implementation() public view virtual override returns (address) {
return _implementation;
}
/**
* @dev Upgrades the beacon to a new implementation.
*
* Emits an {Upgraded} event.
*
* Requirements:
*
* - msg.sender must be the owner of the contract.
* - `newImplementation` must be a contract.
*/
function upgradeTo(address newImplementation) public virtual onlyOwner {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation contract address for this beacon
*
* Requirements:
*
* - `newImplementation` must be a contract.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract");
_implementation = newImplementation;
}
}
@openzeppelin/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
* Argent and Gnosis Safe.
*
* _Available since v4.1._
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
return
(error == ECDSA.RecoverError.NoError && recovered == signer) ||
isValidERC1271SignatureNow(signer, hash, signature);
}
/**
* @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
* against the signer smart contract using ERC1271.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidERC1271SignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success &&
result.length >= 32 &&
abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
}
}
@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
@openzeppelin/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IEscrow.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
interface IEscrow {
struct Deposit {
uint amount;
bool isERC4626;
address asset; // eip4626 asset else the erc20 token itself
uint8 assetDecimals;
}
event AddCollateral(address indexed token, uint indexed amount);
event RemoveCollateral(address indexed token, uint indexed amount);
event EnableCollateral(address indexed token);
error InvalidCollateral();
error CallerAccessDenied();
error UnderCollateralized();
error NotLiquidatable();
// State var getters.
function line() external returns (address);
function oracle() external returns (address);
function borrower() external returns (address);
function minimumCollateralRatio() external returns (uint32);
// Functions
function isLiquidatable() external returns (bool);
function updateLine(address line_) external returns (bool);
function getCollateralRatio() external returns (uint);
function getCollateralValue() external returns (uint);
function enableCollateral(address token) external returns (bool);
function addCollateral(uint amount, address token) external payable returns (uint);
function releaseCollateral(uint amount, address token, address to) external returns (uint);
function liquidate(uint amount, address token, address to) external returns (bool);
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IEscrowedLine.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {IEscrow} from "./IEscrow.sol";
interface IEscrowedLine {
event Liquidate(bytes32 indexed id, uint256 indexed amount, address indexed token, address escrow);
/**
* @notice - Forcefully take collateral from Escrow and repay debt for lender
* - current implementation just sends "liquidated" tokens to Arbiter to sell off how the deem fit and then manually repay with DepositAndRepay
* @dev - only callable by Arbiter
* @dev - Line status MUST be LIQUIDATABLE
* @dev - callable by `arbiter`
* @param amount - amount of `targetToken` expected to be sold off in _liquidate
* @param targetToken - token in escrow that will be sold of to repay position
*/
function liquidate(uint256 amount, address targetToken) external returns (uint256);
/// @notice the escrow contract backing this Line
function escrow() external returns (IEscrow);
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IInterestRateCredit.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
interface IInterestRateCredit {
struct Rate {
// The interest rate charged to a Borrower on borrowed / drawn down funds
// in bps, 4 decimals
uint128 dRate;
// The interest rate charged to a Borrower on the remaining funds available, but not yet drawn down (rate charged on the available headroom)
// in bps, 4 decimals
uint128 fRate;
// The time stamp at which accrued interest was last calculated on an ID and then added to the overall interestAccrued (interest due but not yet repaid)
uint256 lastAccrued;
}
/**
* @notice - allows `lineContract to calculate how much interest is owed since it was last calculated charged at time `lastAccrued`
* @dev - pure function that only calculates interest owed. Line is responsible for actually updating credit balances with returned value
* @dev - callable by `lineContract`
* @param id - position id on Line to look up interest rates for
* @param drawnBalance the balance of funds that a Borrower has drawn down on the credit line
* @param facilityBalance the remaining balance of funds that a Borrower can still drawn down on a credit line (aka headroom)
*
* @return - the amount of interest to be repaid for this interest period
*/
function accrueInterest(bytes32 id, uint256 drawnBalance, uint256 facilityBalance) external returns (uint256);
/**
* @notice - updates interest rates on a lender's position. Updates lastAccrued time to block.timestamp
* @dev - MUST call accrueInterest() on Line before changing rates. If not, lender will not accrue interest over previous interest period.
* @dev - callable by `line`
* @return - if call was successful or not
*/
function setRate(bytes32 id, uint128 dRate, uint128 fRate) external returns (bool);
function getInterestAccrued(
bytes32 id,
uint256 drawnBalance,
uint256 facilityBalance
) external view returns (uint256);
function getRates(bytes32 id) external view returns (uint128, uint128);
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ILineFactory.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
interface ILineFactory {
struct CoreLineParams {
address borrower;
uint256 ttl;
uint32 cratio;
uint8 revenueSplit;
}
event DeployedSecuredLine(
address indexed deployedAt,
address indexed escrow,
address indexed spigot,
address swapTarget,
uint8 revenueSplit
);
event RegisteredSecuredLine(
address indexed deployedAt,
address indexed escrow,
address indexed spigot,
address swapTarget,
uint8 revenueSplit
);
event RegisteredUpdatedStatus(address indexed line, uint256 indexed status); // store as normal uint so it can be indexed in subgraph
event RegisteredLine(address indexed line, address indexed oracle, address indexed arbiter, address borrower, address operator);
error ModuleTransferFailed(address line, address spigot, address escrow);
error InvalidRevenueSplit();
error InvalidOracleAddress();
error InvalidSwapTargetAddress();
error InvalidArbiterAddress();
error InvalidEscrowAddress();
error InvalidSpigotAddress();
function deployEscrow(uint32 minCRatio, address owner, address borrower) external returns (address);
function deploySpigot(address owner, address operator) external returns (address);
function deploySecuredLine(address borrower, uint256 ttl) external returns (address);
function deploySecuredLineWithConfig(CoreLineParams calldata coreParams) external returns (address);
function deploySecuredLineWithModules(
CoreLineParams calldata coreParams,
address mSpigot,
address mEscrow
) external returns (address);
function rolloverSecuredLine(address payable oldLine, address borrower, uint256 ttl) external returns (address);
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ILineOfCredit.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {LineLib} from "../utils/LineLib.sol";
import {IOracle} from "../interfaces/IOracle.sol";
interface ILineOfCredit {
// Lender data
struct Credit {
// all denominated in token, not USD
uint256 deposit; // The total liquidity provided by a Lender in a given token on a Line of Credit
uint256 principal; // The amount of a Lender's Deposit on a Line of Credit that has actually been drawn down by the Borrower (in Tokens)
uint256 interestAccrued; // Interest due by a Borrower but not yet repaid to the Line of Credit contract
uint256 interestRepaid; // Interest repaid by a Borrower to the Line of Credit contract but not yet withdrawn by a Lender
uint8 decimals; // Decimals of Credit Token for calcs
address token; // The token being lent out (Credit Token)
address lender; // The person to repay
bool isOpen; // Status of position
}
// General Events
event UpdateStatus(uint256 indexed status); // store as normal uint so it can be indexed in subgraph
event DeployLine(address indexed oracle, address indexed arbiter, address indexed borrower);
event SortedIntoQ(bytes32 indexed id, uint256 indexed newIdx, uint256 indexed oldIdx, bytes32 oldId);
// MutualConsent borrower/lender events
event AddCredit(address indexed lender, address indexed token, uint256 indexed deposit, bytes32 id);
// can only reference id once AddCredit is emitted because it will be indexed offchain
event SetRates(bytes32 indexed id, uint128 indexed dRate, uint128 indexed fRate);
event IncreaseCredit(bytes32 indexed id, uint256 indexed deposit);
// Lender Events
// Emits data re Lender removes funds (principal) - there is no corresponding function, just withdraw()
event WithdrawDeposit(bytes32 indexed id, uint256 indexed amount);
// Emits data re Lender withdraws interest - there is no corresponding function, just withdraw()
event WithdrawProfit(bytes32 indexed id, uint256 indexed amount);
// Emitted when any credit line is closed by the line's borrower or the position's lender
event CloseCreditPosition(bytes32 indexed id);
// After accrueInterest runs, emits the amount of interest added to a Borrower's outstanding balance of interest due
// but not yet repaid to the Line of Credit contract
event InterestAccrued(bytes32 indexed id, uint256 indexed amount);
// Borrower Events
// receive full line or drawdown on credit
event Borrow(bytes32 indexed id, uint256 indexed amount);
// Emits that a Borrower has repaid an amount of interest Results in an increase in interestRepaid, i.e. interest not yet withdrawn by a Lender). There is no corresponding function
event RepayInterest(bytes32 indexed id, uint256 indexed amount);
// Emits that a Borrower has repaid an amount of principal - there is no corresponding function
event RepayPrincipal(bytes32 indexed id, uint256 indexed amount);
event Default(bytes32 indexed id);
// Access Errors
error NotActive();
error NotBorrowing();
error CallerAccessDenied();
// Tokens
error TokenTransferFailed();
error NoTokenPrice();
// Line
error BadModule(address module);
error NoLiquidity();
error PositionExists();
error CloseFailedWithPrincipal();
error NotInsolvent(address module);
error NotLiquidatable();
error AlreadyInitialized();
error PositionIsClosed();
error RepayAmountExceedsDebt(uint256 totalAvailable);
error CantStepQ();
error EthSupportDisabled();
error BorrowFailed();
// Fully public functions
/**
* @notice - Runs logic to ensure Line owns all modules are configured properly - collateral, interest rates, arbiter, etc.
* - Changes `status` from UNINITIALIZED to ACTIVE
* @dev - Reverts on failure to update status
*/
function init() external;
// MutualConsent functions
/**
* @notice - On first call, creates proposed terms and emits MutualConsentRegistsered event. No position is created.
- On second call, creates position and stores in Line contract, sets interest rates, and starts accruing facility rate fees.
* @dev - Requires mutualConsent participants send EXACT same params when calling addCredit
* @dev - Fully executes function after a Borrower and a Lender have agreed terms, both Lender and borrower have agreed through mutualConsent
* @dev - callable by `lender` and `borrower`
* @param drate - The interest rate charged to a Borrower on borrowed / drawn down funds. In bps, 4 decimals.
* @param frate - The interest rate charged to a Borrower on the remaining funds available, but not yet drawn down
(rate charged on the available headroom). In bps, 4 decimals.
* @param amount - The amount of Credit Token to initially deposit by the Lender
* @param token - The Credit Token, i.e. the token to be lent out
* @param lender - The address that will manage credit line
* @return id - Lender's position id to look up in `credits`
*/
function addCredit(
uint128 drate,
uint128 frate,
uint256 amount,
address token,
address lender
) external payable returns (bytes32);
/**
* @notice - lets Lender and Borrower update rates on the lender's position
* - accrues interest before updating terms, per InterestRate docs
* - can do so even when LIQUIDATABLE for the purpose of refinancing and/or renego
* @dev - callable by Borrower or Lender
* @param id - position id that we are updating
* @param drate - new drawn rate. In bps, 4 decimals
* @param frate - new facility rate. In bps, 4 decimals
*/
function setRates(bytes32 id, uint128 drate, uint128 frate) external;
/**
* @notice - Lets a Lender and a Borrower increase the credit limit on a position
* @dev - line status must be ACTIVE
* @dev - callable by borrower
* @dev - The function retains the `payable` designation, despite not accepting Eth via mutualConsent modifier, as a gas-optimization
* @param id - position id that we are updating
* @param amount - amount to deposit by the Lender
*/
function increaseCredit(bytes32 id, uint256 amount) external payable;
// Borrower functions
/**
* @notice - Borrower chooses which lender position draw down on and transfers tokens from Line contract to Borrower
* @dev - callable by borrower
* @param id - the position to draw down on
* @param amount - amount of tokens the borrower wants to withdraw
*/
function borrow(bytes32 id, uint256 amount) external;
/**
* @notice - Transfers token used in position id from msg.sender to Line contract.
* @dev - Available for anyone to deposit Credit Tokens to be available to be withdrawn by Lenders
* @dev - The function retains the `payable` designation, despite reverting with a non-zero msg.value, as a gas-optimization
* @notice - see LineOfCredit._repay() for more details
* @param amount - amount of `token` in `id` to pay back
*/
function depositAndRepay(uint256 amount) external payable;
/**
* @notice - A Borrower deposits enough tokens to repay and close a credit line.
* @dev - callable by borrower
* @dev - The function retains the `payable` designation, despite reverting with a non-zero msg.value, as a gas-optimization
*/
function depositAndClose() external payable;
/**
* @notice - Removes and deletes a position, preventing any more borrowing or interest.
* - Requires that the position principal has already been repais in full
* @dev - MUST repay accrued interest from facility fee during call
* @dev - callable by `borrower` or Lender
* @dev - The function retains the `payable` designation, despite reverting with a non-zero msg.value, as a gas-optimization
* @param id -the position id to be closed
*/
function close(bytes32 id) external payable;
// Lender functions
/**
* @notice - Withdraws liquidity from a Lender's position available to the Borrower.
* - Lender is only allowed to withdraw tokens not already lent out
* - Withdraws from repaid interest (profit) first and then deposit is reduced
* @dev - can only withdraw tokens from their own position. If multiple lenders lend DAI, the lender1 can't withdraw using lender2's tokens
* @dev - callable by Lender on `id`
* @param id - the position id that Lender is withdrawing from
* @param amount - amount of tokens the Lender would like to withdraw (withdrawn amount may be lower)
*/
function withdraw(bytes32 id, uint256 amount) external;
// Arbiter functions
/**
* @notice - Allow the Arbiter to signify that the Borrower is incapable of repaying debt permanently.
* - Recoverable funds for Lender after declaring insolvency = deposit + interestRepaid - principal
* @dev - Needed for onchain impairment accounting e.g. updating ERC4626 share price
* - MUST NOT have collateral left for call to succeed. Any collateral must already have been liquidated.
* @dev - Callable only by Arbiter.
*/
function declareInsolvent() external;
/**
*
* @notice - Updates accrued interest for the whole Line of Credit facility (i.e. for all credit lines)
* @dev - Loops over all position ids and calls related internal functions during which InterestRateCredit.sol
* is called with the id data and then 'interestAccrued' is updated.
* @dev - The related internal function _accrue() is called by other functions any time the balance on an individual
* credit line changes or if the interest rates of a credit line are changed by mutual consent
* between a Borrower and a Lender.
*/
function accrueInterest() external;
function healthcheck() external returns (LineLib.STATUS);
/**
* @notice - Cycles through position ids andselects first position with non-null principal to the zero index
* @dev - Only works if the first element in the queue is null
*/
function stepQ() external;
/**
* @notice - Returns the total debt of a Borrower across all positions for all Lenders.
* @dev - Denominated in USD, 8 decimals.
* @dev - callable by anyone
* @return totalPrincipal - total amount of principal, in USD, owed across all positions
* @return totalInterest - total amount of interest, in USD, owed across all positions
*/
function updateOutstandingDebt() external returns (uint256, uint256);
// State getters
function status() external returns (LineLib.STATUS);
function borrower() external returns (address);
function arbiter() external returns (address);
function oracle() external returns (IOracle);
/**
* @notice - getter for amount of active ids + total ids in list
* @return - (uint256, uint256) - active credit lines, total length
*/
function counts() external view returns (uint256, uint256);
/**
* @notice - getter for amount of active ids + total ids in list
* @return - (uint256, uint256) - active credit lines, total length
*/
function interestAccrued(bytes32 id) external returns (uint256);
/**
* @notice - info on the next lender position that must be repaid
* @return - (bytes32, address, address, uint, uint) - id, lender, token, principal, interestAccrued
*/
function nextInQ() external view returns (bytes32, address, address, uint256, uint256, uint256, uint128, uint128);
/**
* @notice - how many tokens can be withdrawn from positions by borrower or lender
* @return - (uint256, uint256) - remaining deposit, claimable interest
*/
function available(bytes32 id) external returns (uint256, uint256);
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IModuleFactory.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
interface IModuleFactory {
event DeployedSpigot(address indexed deployedAt, address indexed owner, address operator);
event DeployedEscrow(address indexed deployedAt, uint32 indexed minCRatio, address indexed oracle, address owner);
event RegisteredSpigot(address indexed deployedAt, address indexed owner, address borrower, address operator);
event RegisteredEscrow(address indexed deployedAt, uint32 indexed minCRatio, address indexed oracle, address owner);
function deploySpigot(address owner, address operator) external returns (address);
function deployEscrow(uint32 minCRatio, address oracle, address owner, address borrower) external returns (address);
function registerEscrow(uint32 minCRatio, address oracle, address owner, address escrow) external;
function registerSpigot(address spigot, address owner, address borrower, address operator) external;
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/IOracle.sol
pragma solidity ^0.8.16;
interface IOracle {
/** current price for token asset. denominated in USD */
function getLatestAnswer(address token) external returns (int256);
/** Readonly function providing the current price for token asset. denominated in USD */
function _getLatestAnswer(address token) external view returns (int256);
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ISecuredLine.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {IEscrowedLine} from "./IEscrowedLine.sol";
import {ISpigotedLine} from "./ISpigotedLine.sol";
interface ISecuredLine is IEscrowedLine, ISpigotedLine {
// Rollover
error DebtOwed();
error BadNewLine();
error BadRollover();
// Borrower functions
/**
* @notice - helper function to allow Borrower to easily transfer settings and collateral from this line to a new line
* - usefull after ttl has expired and want to renew Line with minimal effort
* @dev - transfers Spigot and Escrow ownership to newLine. Arbiter functions on this Line will no longer work
* @param newLine - the new, uninitialized Line deployed by borrower
*/
function rollover(address newLine) external;
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ISpigot.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
interface ISpigot {
struct Setting {
uint8 ownerSplit; // x/100 % to Owner, rest to Operator
bytes4 claimFunction; // function signature on contract to call and claim revenue
bytes4 transferOwnerFunction; // function signature on contract to call and transfer ownership
}
// Spigot Events
event AddSpigot(address indexed revenueContract, uint256 ownerSplit, bytes4 claimFnSig, bytes4 trsfrFnSig);
event RemoveSpigot(address indexed revenueContract, address token);
event UpdateWhitelistFunction(bytes4 indexed func, bool indexed allowed);
event UpdateOwnerSplit(address indexed revenueContract, uint8 indexed split);
event ClaimRevenue(address indexed token, uint256 indexed amount, uint256 escrowed, address revenueContract);
event ClaimOwnerTokens(address indexed token, uint256 indexed amount, address owner);
event ClaimOperatorTokens(address indexed token, uint256 indexed amount, address operator);
// Stakeholder Events
event UpdateOwner(address indexed newOwner);
event UpdateOperator(address indexed newOperator);
// Errors
error BadFunction();
error OperatorFnNotWhitelisted();
error OperatorFnNotValid();
error OperatorFnCallFailed();
error ClaimFailed();
error NoRevenue();
error UnclaimedRevenue();
error CallerAccessDenied();
error BadSetting();
error InvalidRevenueContract();
// ops funcs
function claimRevenue(
address revenueContract,
address token,
bytes calldata data
) external returns (uint256 claimed);
function operate(address revenueContract, bytes calldata data) external returns (bool);
// owner funcs
function claimOwnerTokens(address token) external returns (uint256 claimed);
function claimOperatorTokens(address token) external returns (uint256 claimed);
function addSpigot(address revenueContract, Setting memory setting) external returns (bool);
function removeSpigot(address revenueContract) external returns (bool);
// stakeholder funcs
function updateOwnerSplit(address revenueContract, uint8 ownerSplit) external returns (bool);
function updateOwner(address newOwner) external returns (bool);
function updateOperator(address newOperator) external returns (bool);
function updateWhitelistedFunction(bytes4 func, bool allowed) external returns (bool);
// Getters
function owner() external view returns (address);
function operator() external view returns (address);
function isWhitelisted(bytes4 func) external view returns (bool);
function getOwnerTokens(address token) external view returns (uint256);
function getOperatorTokens(address token) external view returns (uint256);
function getSetting(
address revenueContract
) external view returns (uint8 split, bytes4 claimFunc, bytes4 transferFunc);
}
lib/blockchainManager/evm/v1/contracts/Spigot/interfaces/ISpigotedLine.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {ISpigot} from "./ISpigot.sol";
interface ISpigotedLine {
/**
* @notice - Log how many revenue tokens are used to repay debt after claimAndRepay
* - dont need to track value like other events because _repay already emits that
* - Mainly used to log debt that is paid via Spigot directly vs other sources. Without this event it's a lot harder to parse that offchain.
*/
event RevenuePayment(address indexed token, uint256 indexed amount);
error ReservesOverdrawn(address token, uint256 amountAvailable);
/**
* @notice - Log how many revenue tokens were traded for credit tokens.
* - Differs from RevenuePayment because we trade revenue at different times from repaying with revenue
* @dev - Can you use to figure out price of revenue tokens offchain since we only have an oracle for credit tokens
* @dev - Revenue tokens may be from reserves or from Spigot revenue.
*/
event TradeSpigotRevenue(
address indexed revenueToken,
uint256 revenueTokenAmount,
address indexed debtToken,
uint256 indexed debtTokensBought
);
event ReservesChanged(
address indexed token,
int256 indexed diff,
uint256 tokenType // 0 for revenue token, 1 for credit token
);
// Borrower functions
/**
* @notice - Directly repays a Lender using unused tokens already held by Line with no trading
* @dev - callable by `borrower` or first lender in repayment queue
* @param amount - amount of unused tokens to use to repay Lender
* @return - if function executed successfully
*/
function useAndRepay(uint256 amount) external returns (bool);
/**
* @notice - Claims revenue tokens from the Spigot, trades them for credit tokens via a Dex aggregator (Ox protocol) and uses the bought credit tokens to repay debt.
* - see SpigotedLine._claimAndTrade and SpigotedLineLib.claimAndTrade for more details on Spigot and trading logic
* - see LineOfCredit._repay() for more details on repayment logic
* @dev - does not trade asset if claimToken = credit.token
* @dev - callable by `arbiter`
* @param claimToken - The Revenue Token escrowed by Spigot to claim and use to repay debt
* @param zeroExTradeData - data generated by the 0x dex API to trade `claimToken` against their exchange contract
* @return newTokens - amount of credit tokens claimed or bought during call
*/
function claimAndRepay(address claimToken, bytes calldata zeroExTradeData) external returns (uint256);
/**
*
* @notice - allows borrower to trade revenue to credit tokens at a favorable price without repaying debt
* - sends all bought tokens to `unused` to be repaid later
* - see SpigotedLine._claimAndTrade and SpigotedLineLib.claimAndTrade for more details
* @dev - ensures first token in repayment queue is being bought
* @dev - callable by `arbiter`
* @param claimToken - The revenue token escrowed in the Spigot to sell in trade
* @param zeroExTradeData - 0x API data to use in trade to sell `claimToken` for `credits[ids[0]]`
* @return tokensBought - amount of credit tokens bought
*/
function claimAndTrade(address claimToken, bytes calldata zeroExTradeData) external returns (uint256 tokensBought);
// Spigot management functions
/**
* @notice - allow Line (aka Owner on Spigot) to add new revenue streams to repay credit
* @dev - see Spigot.addSpigot()
* @dev - callable `arbiter` ONLY
* @return - if function call was successful
*/
function addSpigot(address revenueContract, ISpigot.Setting calldata setting) external returns (bool);
/**
* @notice - Sets or resets the whitelisted functions that a Borrower [Operator] is allowed to perform on the revenue generating contracts
* @dev - see Spigot.updateWhitelistedFunction()
* @dev - callable `arbiter` ONLY
* @return - if function call was successful
*/
function updateWhitelist(bytes4 func, bool allowed) external returns (bool);
/**
* @notice - Changes the revenue split between the Treasury and the Line (Owner) based upon the status of the Line of Credit
* @dev - callable by anyone
* @param revenueContract - spigot to update
* @return didUpdate - whether or not split was updated
*/
function updateOwnerSplit(address revenueContract) external returns (bool);
/**
* @notice - Transfers ownership of the entire Spigot from its then Owner to either the Borrower (if a Line of Credit has been been fully repaid)
* - or to the Arbiter (if the Line of Credit is liquidatable).
* @dev - callable by borrower + arbiter
* @param to - address that caller wants to transfer Spigot ownership to
* @return bool - whether or not a Spigot was released
*/
function releaseSpigot(address to) external returns (bool);
/**
* @notice - sends unused tokens to borrower if REPAID or arbiter if LIQUIDATABLE or INSOLVENT
* - does not send tokens out if line is ACTIVE
* @dev - callable by `borrower` or `arbiter`
* @param to - address to send swept tokens to
* @param token - revenue or credit token to sweep
* @param amount - amount of reserve tokens to withdraw/liquidate
*/
function sweep(address to, address token, uint256 amount) external returns (uint256);
// getters
/**
* @notice - getter for `unusedTokens` mapping which is a private var
* @param token - address for an ERC20
* @return amount - amount of revenue tokens available to trade for credit tokens or credit tokens availble to repay debt with
*/
function unused(address token) external returns (uint256);
/**
* @notice - Looksup `unusedTokens` + spigot.getOwnerTokens` for how many tokens arbiter must sell in claimAndTrade/Repay
* @param token - address for an ERC20 earned as revenue
* @return amount - amount of unused + claimable revenue tokens available to trade for credit tokens or credit tokens availble to repay debt with
*/
function tradeable(address token) external returns (uint256);
function spigot() external returns (ISpigot);
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/credit/EscrowedLine.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {IEscrow} from "../../interfaces/IEscrow.sol";
import {LineLib} from "../../utils/LineLib.sol";
import {IEscrowedLine} from "../../interfaces/IEscrowedLine.sol";
import {ILineOfCredit} from "../../interfaces/ILineOfCredit.sol";
// used for importing NATSPEC docs, not used
import {LineOfCredit} from "./LineOfCredit.sol";
// import { SecuredLine } from "./SecuredLine.sol";
abstract contract EscrowedLine is IEscrowedLine, ILineOfCredit {
// contract holding all collateral for borrower
IEscrow public immutable escrow;
constructor(address _escrow) {
escrow = IEscrow(_escrow);
}
/**
* see LineOfCredit._init and SecuredLine.init
* @notice requires this Line is owner of the Escrowed collateral else Line will not init
*/
function _init() internal virtual {
if (escrow.line() != address(this)) revert BadModule(address(escrow));
}
/**
* see LineOfCredit._healthcheck and SecuredLine._healthcheck
* @notice returns LIQUIDATABLE if Escrow contract is undercollateralized, else returns ACTIVE
*/
function _healthcheck() internal virtual returns (LineLib.STATUS) {
if (escrow.isLiquidatable()) {
return LineLib.STATUS.LIQUIDATABLE;
}
return LineLib.STATUS.ACTIVE;
}
/**
* see SecuredlLine.liquidate
* @notice sends escrowed tokens to liquidation.
* @dev priviliegad function. Do checks before calling.
*
* @param id - The credit line being repaid via the liquidation
* @param amount - amount of tokens to take from escrow and liquidate
* @param targetToken - the token to take from escrow
* @param to - the liquidator to send tokens to. could be OTC address or smart contract
*
* @return amount - the total amount of `targetToken` sold to repay credit
*/
function _liquidate(
bytes32 id,
uint256 amount,
address targetToken,
address to
) internal virtual returns (uint256) {
IEscrow escrow_ = escrow; // gas savings
require(escrow_.liquidate(amount, targetToken, to));
emit Liquidate(id, amount, targetToken, address(escrow_));
return amount;
}
/**
* see SecuredLine.declareInsolvent
* @notice require all collateral sold off before declaring insolvent
*(@dev priviliegad internal function.
* @return isInsolvent - if Escrow contract is currently insolvent or not
*/
function _canDeclareInsolvent() internal virtual returns (bool) {
if (escrow.getCollateralValue() != 0) {
revert NotInsolvent(address(escrow));
}
return true;
}
/**
* see SecuredlLine.rollover
* @notice helper function to allow borrower to easily swithc collateral to a new Line after repyment
*(@dev priviliegad internal function.
* @dev MUST only be callable if line is REPAID
* @return - if function successfully executed
*/
function _rollover(address newLine) internal virtual returns (bool) {
require(escrow.updateLine(newLine));
return true;
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/credit/LineOfCredit.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {Denominations} from "@chainlink/contracts0.8.0/src/v0.8/Denominations.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {LineLib} from "../../utils/LineLib.sol";
import {CreditLib} from "../../utils/CreditLib.sol";
import {CreditListLib} from "../../utils/CreditListLib.sol";
import {MutualConsent} from "../../utils/MutualConsent.sol";
import {InterestRateCredit} from "../interest-rate/InterestRateCredit.sol";
import {IOracle} from "../../interfaces/IOracle.sol";
import {ILineOfCredit} from "../../interfaces/ILineOfCredit.sol";
/**
* @title - Credit Cooperative Unsecured Line of Credit
* @notice - Core credit facility logic for proposing, depositing, borrowing, and repaying debt.
* - Contains core financial covnenants around term length (`deadline`), collateral ratios, liquidations, etc.
* @dev - contains internal functions overwritten by SecuredLine, SpigotedLine, and EscrowedLine
*/
contract LineOfCredit is ILineOfCredit, MutualConsent, ReentrancyGuard {
using SafeERC20 for IERC20;
using CreditListLib for bytes32[];
/// @notice - the timestamp that all creditors must be repaid by
uint256 public immutable deadline;
/// @notice - the account that can drawdown and manage debt positions
address public immutable borrower;
/// @notice - neutral 3rd party that mediates btw borrower and all lenders
address public immutable arbiter;
/// @notice - price feed to use for valuing credit tokens
IOracle public immutable oracle;
/// @notice - contract responsible for calculating interest owed on debt positions
InterestRateCredit public immutable interestRate;
/// @notice - current amount of active positions (aka non-null ids) in `ids` list
uint256 private count;
/// @notice - positions ids of all open credit lines.
/// @dev - may contain null elements
bytes32[] public ids;
/// @notice id -> position data
mapping(bytes32 => Credit) public credits;
/// @notice - current health status of line
LineLib.STATUS public status;
/**
* @notice - How to deploy a Line of Credit
* @dev - A Borrower and a first Lender agree on terms. Then the Borrower deploys the contract using the constructor below.
* Later, both Lender and Borrower must call _mutualConsent() during addCredit() to actually enable funds to be deposited.
* @param oracle_ - The price oracle to use for getting all token values.
* @param arbiter_ - A neutral party with some special priviliges on behalf of Borrower and Lender.
* @param borrower_ - The debitor for all credit lines in this contract.
* @param ttl_ - The time to live for all credit lines for the Line of Credit facility (sets the maturity/term of the Line of Credit)
*/
constructor(address oracle_, address arbiter_, address borrower_, uint256 ttl_) {
oracle = IOracle(oracle_);
arbiter = arbiter_;
borrower = borrower_;
deadline = block.timestamp + ttl_; //the deadline is the term/maturity/expiry date of the Line of Credit facility
interestRate = new InterestRateCredit();
emit DeployLine(oracle_, arbiter_, borrower_);
}
function init() external virtual {
if (status != LineLib.STATUS.UNINITIALIZED) {
revert AlreadyInitialized();
}
_init();
_updateStatus(LineLib.STATUS.ACTIVE);
}
function _init() internal virtual {
// If no collateral or Spigot then Line of Credit is immediately active
return;
}
///////////////
// MODIFIERS //
///////////////
modifier whileActive() {
if (status != LineLib.STATUS.ACTIVE) {
revert NotActive();
}
_;
}
modifier whileBorrowing() {
if (count == 0 || credits[ids[0]].principal == 0) {
revert NotBorrowing();
}
_;
}
modifier onlyBorrower() {
if (msg.sender != borrower) {
revert CallerAccessDenied();
}
_;
}
/**
* @notice - mutualConsent() but hardcodes borrower address and uses the position id to
get Lender address instead of passing it in directly
* @param id - position to pull lender address from for mutual consent agreement
*/
modifier mutualConsentById(bytes32 id) {
if (_mutualConsent(borrower, credits[id].lender)) {
// Run whatever code is needed for the 2/2 consent
_;
}
}
/**
* @notice - evaluates all covenants encoded in _healthcheck from different Line variants
* @dev - updates `status` variable in storage if current status is diferent from existing status
* @return - current health status of Line
*/
function healthcheck() external returns (LineLib.STATUS) {
// can only check if the line has been initialized
require(uint256(status) >= uint256(LineLib.STATUS.ACTIVE));
return _updateStatus(_healthcheck());
}
function _healthcheck() internal virtual returns (LineLib.STATUS) {
// if line is in a final end state then do not run _healthcheck()
LineLib.STATUS s = status;
if (
s == LineLib.STATUS.REPAID || // end state - good
s == LineLib.STATUS.INSOLVENT // end state - bad
) {
return s;
}
// Liquidate if all credit lines aren't closed by deadline
if (block.timestamp >= deadline && count != 0) {
emit Default(ids[0]); // can query all defaulted positions offchain once event picked up
return LineLib.STATUS.LIQUIDATABLE;
}
// if nothing wrong, return to healthy ACTIVE state
return LineLib.STATUS.ACTIVE;
}
/// see ILineOfCredit.declareInsolvent
function declareInsolvent() external {
if (arbiter != msg.sender) {
revert CallerAccessDenied();
}
if (LineLib.STATUS.LIQUIDATABLE != _updateStatus(_healthcheck())) {
revert NotLiquidatable();
}
if (_canDeclareInsolvent()) {
_updateStatus(LineLib.STATUS.INSOLVENT);
}
}
function _canDeclareInsolvent() internal virtual returns (bool) {
// logic updated in Spigoted and Escrowed lines
return true;
}
/// see ILineOfCredit.updateOutstandingDebt
function updateOutstandingDebt() external override returns (uint256, uint256) {
return _updateOutstandingDebt();
}
function _updateOutstandingDebt() internal returns (uint256 principal, uint256 interest) {
// use full length not count because positions might not be packed in order
uint256 len = ids.length;
if (len == 0) return (0, 0);
bytes32 id;
for (uint256 i; i < len; ++i) {
id = ids[i];
// null element in array from closing a position. skip for gas savings
if (id == bytes32(0)) {
continue;
}
(Credit memory c, uint256 _p, uint256 _i) = CreditLib.getOutstandingDebt(
credits[id],
id,
address(oracle),
address(interestRate)
);
// update total outstanding debt
principal += _p;
interest += _i;
// save changes to storage
credits[id] = c;
}
}
/// see ILineOfCredit.accrueInterest
function accrueInterest() external override {
uint256 len = ids.length;
bytes32 id;
for (uint256 i; i < len; ++i) {
id = ids[i];
Credit memory credit = credits[id];
credits[id] = _accrue(credit, id);
}
}
/// see ILineOfCredit.addCredit
function addCredit(
uint128 drate,
uint128 frate,
uint256 amount,
address token,
address lender
) external payable override nonReentrant whileActive mutualConsent(lender, borrower) returns (bytes32) {
bytes32 id = _createCredit(lender, token, amount);
_setRates(id, drate, frate);
LineLib.receiveTokenOrETH(token, lender, amount);
return id;
}
/// see ILineOfCredit.setRates
function setRates(bytes32 id, uint128 drate, uint128 frate) external override mutualConsentById(id) {
credits[id] = _accrue(credits[id], id);
_setRates(id, drate, frate);
}
/// see ILineOfCredit.setRates
function _setRates(bytes32 id, uint128 drate, uint128 frate) internal {
interestRate.setRate(id, drate, frate);
emit SetRates(id, drate, frate);
}
/// see ILineOfCredit.increaseCredit
function increaseCredit(
bytes32 id,
uint256 amount
) external payable override nonReentrant whileActive mutualConsentById(id) {
Credit memory credit = _accrue(credits[id], id);
credit.deposit += amount;
credits[id] = credit;
LineLib.receiveTokenOrETH(credit.token, credit.lender, amount);
emit IncreaseCredit(id, amount);
}
///////////////
// REPAYMENT //
///////////////
/// see ILineOfCredit.depositAndClose
function depositAndClose() external payable override nonReentrant whileBorrowing onlyBorrower {
bytes32 id = ids[0];
Credit memory credit = _accrue(credits[id], id);
// Borrower deposits the outstanding balance not already repaid
uint256 totalOwed = credit.principal + credit.interestAccrued;
// Borrower clears the debt then closes the credit line
credits[id] = _close(_repay(credit, id, totalOwed, borrower), id);
}
/// see ILineOfCredit.close
function close(bytes32 id) external payable override nonReentrant onlyBorrower {
Credit memory credit = _accrue(credits[id], id);
uint256 facilityFee = credit.interestAccrued;
// clear facility fees and close position
credits[id] = _close(_repay(credit, id, facilityFee, borrower), id);
}
/// see ILineOfCredit.depositAndRepay
function depositAndRepay(uint256 amount) external payable override nonReentrant whileBorrowing {
bytes32 id = ids[0];
Credit memory credit = _accrue(credits[id], id);
if (amount > credit.principal + credit.interestAccrued) {
revert RepayAmountExceedsDebt(credit.principal + credit.interestAccrued);
}
credits[id] = _repay(credit, id, amount, msg.sender);
}
////////////////////
// FUND TRANSFERS //
////////////////////
/// see ILineOfCredit.borrow
function borrow(bytes32 id, uint256 amount) external override nonReentrant whileActive onlyBorrower {
Credit memory credit = _accrue(credits[id], id);
if (!credit.isOpen) {
revert PositionIsClosed();
}
if (amount > credit.deposit - credit.principal) {
revert NoLiquidity();
}
credit.principal += amount;
// save new debt before healthcheck and token transfer
credits[id] = credit;
// ensure that borrowing doesnt cause Line to be LIQUIDATABLE
if (_updateStatus(_healthcheck()) != LineLib.STATUS.ACTIVE) {
revert BorrowFailed();
}
LineLib.sendOutTokenOrETH(credit.token, borrower, amount);
emit Borrow(id, amount);
_sortIntoQ(id);
}
/// see ILineOfCredit.withdraw
function withdraw(bytes32 id, uint256 amount) external override nonReentrant {
// accrues interest and transfer funds to Lender addres
credits[id] = CreditLib.withdraw(_accrue(credits[id], id), id, msg.sender, amount);
}
/**
* @notice - Steps the Queue be replacing the first element with the next valid credit line's ID
* @dev - Only works if the first element in the queue is null
*/
function stepQ() external {
ids.stepQ();
}
//////////////////////
// Internal funcs //
//////////////////////
/**
* @notice - updates `status` variable in storage if current status is diferent from existing status.
* @dev - privileged internal function. MUST check params and logic flow before calling
* @dev - does not save new status if it is the same as current status
* @return status - the current status of the line after updating
*/
function _updateStatus(LineLib.STATUS status_) internal returns (LineLib.STATUS) {
if (status == status_) return status_;
emit UpdateStatus(uint256(status_));
return (status = status_);
}
/**
* @notice - Generates position id and stores lender's position
* @dev - positions have unique composite-index on [lineAddress, lenderAddress, tokenAddress]
* @dev - privileged internal function. MUST check params and logic flow before calling
* @param lender - address that will own and manage position
* @param token - ERC20 token that is being lent and borrower
* @param amount - amount of tokens lender will initially deposit
*/
function _createCredit(address lender, address token, uint256 amount) internal returns (bytes32 id) {
id = CreditLib.computeId(address(this), lender, token);
// MUST not double add the credit line. once lender is set it cant be deleted even if position is closed.
if (credits[id].lender != address(0)) {
revert PositionExists();
}
credits[id] = CreditLib.create(id, amount, lender, token, address(oracle));
ids.push(id); // add lender to end of repayment queue
unchecked {
++count;
}
return id;
}
/**
* @dev - Reduces `principal` and/or `interestAccrued` on a credit line.
Expects checks for conditions of repaying and param sanitizing before calling
e.g. early repayment of principal, tokens have actually been paid by borrower, etc.
* @dev - privileged internal function. MUST check params and logic flow before calling
* @dev syntatic sugar
* @param id - position id with all data pertaining to line
* @param amount - amount of Credit Token being repaid on credit line
* @return credit - position struct in memory with updated values
*/
function _repay(Credit memory credit, bytes32 id, uint256 amount, address payer) internal returns (Credit memory) {
return CreditLib.repay(credit, id, amount, payer);
}
/**
* @notice - accrues token demoninated interest on a lender's position.
* @dev MUST call any time a position balance or interest rate changes
* @dev syntatic sugar
* @param credit - the lender position that is accruing interest
* @param id - the position id for credit position
*/
function _accrue(Credit memory credit, bytes32 id) internal returns (Credit memory) {
return CreditLib.accrue(credit, id, address(interestRate));
}
/**
* @notice - checks that a credit line is fully repaid and removes it
* @dev deletes credit storage. Store any data u might need later in call before _close()
* @dev - privileged internal function. MUST check params and logic flow before calling
* @dev - when the line being closed is at the 0-index in the ids array, the null index is replaced using `.stepQ`
* @return credit - position struct in memory with updated values
*/
function _close(Credit memory credit, bytes32 id) internal virtual returns (Credit memory) {
// update position data in state
if (!credit.isOpen) {
revert PositionIsClosed();
}
if (credit.principal != 0) {
revert CloseFailedWithPrincipal();
}
credit.isOpen = false;
// nullify the element for `id`
ids.removePosition(id);
// if positions was 1st in Q, cycle to next valid position
if (ids[0] == bytes32(0)) ids.stepQ();
unchecked {
--count;
}
// If all credit lines are closed the the overall Line of Credit facility is declared 'repaid'.
if (count == 0) {
_updateStatus(LineLib.STATUS.REPAID);
}
emit CloseCreditPosition(id);
return credit;
}
/**
* @notice - Insert `p` into the next availble FIFO position in the repayment queue
- once earliest slot is found, swap places with `p` and position in slot.
* @dev - privileged internal function. MUST check params and logic flow before calling
* @param p - position id that we are trying to find appropriate place for
*/
function _sortIntoQ(bytes32 p) internal {
uint256 lastSpot = ids.length - 1;
uint256 nextQSpot = lastSpot;
bytes32 id;
for (uint256 i; i <= lastSpot; ++i) {
id = ids[i];
if (p != id) {
if (
id == bytes32(0) || // deleted element. In the middle of the q because it was closed.
nextQSpot != lastSpot || // position already found. skip to find `p` asap
credits[id].principal != 0 //`id` should be placed before `p`
) continue;
nextQSpot = i; // index of first undrawn line found
} else {
// nothing to update
if (nextQSpot == lastSpot) return; // nothing to update
// get id value being swapped with `p`
bytes32 oldPositionId = ids[nextQSpot];
// swap positions
ids[i] = oldPositionId; // id put into old `p` position
ids[nextQSpot] = p; // p put at target index
emit SortedIntoQ(p, nextQSpot, i, oldPositionId);
}
}
}
/* GETTERS */
/// see ILineOfCredit.interestAccrued
function interestAccrued(bytes32 id) external view returns (uint256) {
return CreditLib.interestAccrued(credits[id], id, address(interestRate));
}
/// see ILineOfCredit.counts
function counts() external view returns (uint256, uint256) {
return (count, ids.length);
}
/// see ILineOfCredit.available
function available(bytes32 id) external view returns (uint256, uint256) {
return (credits[id].deposit - credits[id].principal, credits[id].interestRepaid);
}
function nextInQ() external view returns (bytes32, address, address, uint256, uint256, uint256, uint128, uint128) {
bytes32 next = ids[0];
Credit memory credit = credits[next];
// Add to docs that this view revertts if no queue
(uint128 dRate, uint128 fRate) = CreditLib.getNextRateInQ(credit.principal, next, address(interestRate));
return (
next,
credit.lender,
credit.token,
credit.principal,
credit.deposit,
CreditLib.interestAccrued(credit, next, address(interestRate)),
dRate,
fRate
);
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/credit/SecuredLine.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {LineLib} from "../../utils/LineLib.sol";
import {EscrowedLine} from "./EscrowedLine.sol";
import {SpigotedLine} from "./SpigotedLine.sol";
import {SpigotedLineLib} from "../../utils/SpigotedLineLib.sol";
import {LineOfCredit} from "./LineOfCredit.sol";
import {ILineOfCredit} from "../../interfaces/ILineOfCredit.sol";
import {ISecuredLine} from "../../interfaces/ISecuredLine.sol";
/**
* @title - Credit Cooperative Secured Line of Credit
* @notice - The SecuredLine combines both collateral modules (SpigotedLine + EscrowedLine) with core lending functionality from LineOfCredit
* - to create a fully secured lending facility backed by revenue via Spigot or tokens via Escrow.
* @dev - modifies _liquidate(), _healthcheck(), _init(), and _declareInsolvent() functionality
*/
contract SecuredLine is SpigotedLine, EscrowedLine, ISecuredLine {
constructor(
address oracle_,
address arbiter_,
address borrower_,
address payable swapTarget_,
address spigot_,
address escrow_,
uint ttl_,
uint8 defaultSplit_
) SpigotedLine(oracle_, arbiter_, borrower_, spigot_, swapTarget_, ttl_, defaultSplit_) EscrowedLine(escrow_) {}
/**
* @dev requires both Spigot and Escrow to pass _init to succeed
*/
function _init() internal virtual override(SpigotedLine, EscrowedLine) {
SpigotedLine._init();
EscrowedLine._init();
}
/// see ISecuredLine.rollover
function rollover(address newLine) external override onlyBorrower {
// require all debt successfully paid already
if (status != LineLib.STATUS.REPAID) {
revert DebtOwed();
}
// require new line isn't activated yet
if (ILineOfCredit(newLine).status() != LineLib.STATUS.UNINITIALIZED) {
revert BadNewLine();
}
// we dont check borrower is same on both lines because borrower might want new address managing new line
EscrowedLine._rollover(newLine);
SpigotedLineLib.rollover(address(spigot), newLine);
// ensure that line we are sending can accept them. There is no recovery option.
try ILineOfCredit(newLine).init() {} catch {
revert BadRollover();
}
}
// see IEscrowedLine.liquidate
function liquidate(uint256 amount, address targetToken) external returns (uint256) {
if (msg.sender != arbiter) {
revert CallerAccessDenied();
}
if (_updateStatus(_healthcheck()) != LineLib.STATUS.LIQUIDATABLE) {
revert NotLiquidatable();
}
// send tokens to arbiter for OTC sales
return _liquidate(ids[0], amount, targetToken, msg.sender);
}
function _healthcheck() internal override(EscrowedLine, LineOfCredit) returns (LineLib.STATUS) {
// check core (also cheap & internal) covenants before checking collateral conditions
LineLib.STATUS s = LineOfCredit._healthcheck();
if (s != LineLib.STATUS.ACTIVE) {
// return early if non-default answer
return s;
}
// check collateral ratio and return ACTIVE
return EscrowedLine._healthcheck();
}
/**
* @notice Wrapper for SpigotedLine and EscrowedLine internal functions
* @dev - both underlying calls MUST return true for Line status to change to INSOLVENT
* @return isInsolvent - if the entire Line including all collateral sources is fuly insolvent.
*/
function _canDeclareInsolvent() internal virtual override(EscrowedLine, SpigotedLine) returns (bool) {
return (EscrowedLine._canDeclareInsolvent() && SpigotedLine._canDeclareInsolvent());
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/credit/SpigotedLine.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {Denominations} from "@chainlink/contracts0.8.0/src/v0.8/Denominations.sol";
import {LineOfCredit} from "./LineOfCredit.sol";
import {LineLib} from "../../utils/LineLib.sol";
import {CreditLib} from "../../utils/CreditLib.sol";
import {SpigotedLineLib} from "../../utils/SpigotedLineLib.sol";
import {MutualConsent} from "../../utils/MutualConsent.sol";
import {ISpigot} from "../../interfaces/ISpigot.sol";
import {ISpigotedLine} from "../../interfaces/ISpigotedLine.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title - Credit Cooperative Spigoted Line of Credit
* @notice - Line of Credit contract with additional functionality for integrating with a Spigot and revenue based collateral.
- Allows Arbiter to repay debt using collateralized revenue streams onbehalf of Borrower and Lender(s)
* @dev - Inherits LineOfCredit functionality
*/
contract SpigotedLine is ISpigotedLine, LineOfCredit {
using SafeERC20 for IERC20;
/// @notice see Spigot
ISpigot public immutable spigot;
/// @notice - maximum revenue we want to be able to take from spigots if Line is in default
uint8 constant MAX_SPLIT = 100;
/// @notice % of revenue tokens to take from Spigot if the Line of Credit is healthy. 0 decimals
uint8 public immutable defaultRevenueSplit;
/// @notice exchange aggregator (mainly 0x router) to trade revenue tokens from a Spigot for credit tokens owed to lenders
address payable public immutable swapTarget;
/**
* @notice - excess unsold revenue claimed from Spigot to be sold later or excess credit tokens bought from revenue but not yet used to repay debt
* - needed because the Line of Credit might have the same token being lent/borrower as being bought/sold so need to separate accounting.
* @dev - private variable so other Line modules do not interfer with Spigot functionality
*/
mapping(address => uint256) private unusedTokens;
/**
* @notice - The SpigotedLine is a LineofCredit contract with additional functionality for integrating with a Spigot.
- allows Borrower or Lender to repay debt using collateralized revenue streams
* @param oracle_ - price oracle to use for getting all token values
* @param arbiter_ - neutral party with some special priviliges on behalf of borrower and lender
* @param borrower_ - the debitor for all credit positions in this contract
* @param spigot_ - Spigot smart contract that is owned by this Line
* @param swapTarget_ - 0x protocol exchange address to send calldata for trades to exchange revenue tokens for credit tokens
* @param ttl_ - time to live for line of credit contract across all lenders set at deployment in order to set the term/expiry date
* @param defaultRevenueSplit_ - The % of Revenue Tokens that the Spigot escrows for debt repayment if the Line is healthy.
*/
constructor(
address oracle_,
address arbiter_,
address borrower_,
address spigot_,
address payable swapTarget_,
uint256 ttl_,
uint8 defaultRevenueSplit_
) LineOfCredit(oracle_, arbiter_, borrower_, ttl_) {
require(defaultRevenueSplit_ <= MAX_SPLIT);
spigot = ISpigot(spigot_);
defaultRevenueSplit = defaultRevenueSplit_;
swapTarget = swapTarget_;
}
/**
* see LineOfCredit._init and Securedline.init
* @notice requires this Line is owner of the Escrowed collateral else Line will not init
*/
function _init() internal virtual override(LineOfCredit) {
if (spigot.owner() != address(this)) revert BadModule(address(spigot));
}
/**
* see SecuredLine.declareInsolvent
* @notice requires Spigot contract itselgf to be transfered to Arbiter and sold off to a 3rd party before declaring insolvent
*(@dev priviliegad internal function.
* @return isInsolvent - if Spigot contract is currently insolvent or not
*/
function _canDeclareInsolvent() internal virtual override returns (bool) {
return SpigotedLineLib.canDeclareInsolvent(address(spigot), arbiter);
}
/// see ISpigotedLine.claimAndRepay
function claimAndRepay(
address claimToken,
bytes calldata zeroExTradeData
) external whileBorrowing nonReentrant returns (uint256) {
bytes32 id = ids[0];
Credit memory credit = _accrue(credits[id], id);
if (msg.sender != arbiter) {
revert CallerAccessDenied();
}
uint256 newTokens = _claimAndTrade(claimToken, credit.token, zeroExTradeData);
uint256 repaid = newTokens + unusedTokens[credit.token];
uint256 debt = credit.interestAccrued + credit.principal;
// cap payment to debt value
if (repaid > debt) repaid = debt;
// update reserves based on usage
if (repaid > newTokens) {
// if using `unusedTokens` to repay line, reduce reserves
uint256 diff = repaid - newTokens;
emit ReservesChanged(credit.token, -int256(diff), 1);
unusedTokens[credit.token] -= diff;
} else {
// else high revenue and bought more credit tokens than owed, fill reserves
uint256 diff = newTokens - repaid;
emit ReservesChanged(credit.token, int256(diff), 1);
unusedTokens[credit.token] += diff;
}
credits[id] = _repay(credit, id, repaid, address(0)); // no payer, we already have funds
emit RevenuePayment(claimToken, repaid);
return newTokens;
}
/// see ISpigotedLine.useAndRepay
function useAndRepay(uint256 amount) external whileBorrowing returns (bool) {
bytes32 id = ids[0];
Credit memory credit = credits[id];
if (msg.sender != borrower && msg.sender != credit.lender) {
revert CallerAccessDenied();
}
if (amount > credit.principal + credit.interestAccrued) {
revert RepayAmountExceedsDebt(credit.principal + credit.interestAccrued);
}
if (amount > unusedTokens[credit.token]) {
revert ReservesOverdrawn(credit.token, unusedTokens[credit.token]);
}
// reduce reserves before _repay calls token to prevent reentrancy
unusedTokens[credit.token] -= amount;
emit ReservesChanged(credit.token, -int256(amount), 0);
credits[id] = _repay(_accrue(credit, id), id, amount, address(0)); // no payer, we already have funds
emit RevenuePayment(credit.token, amount);
return true;
}
/// see ISpigotedLine.claimAndTrade
function claimAndTrade(
address claimToken,
bytes calldata zeroExTradeData
) external whileBorrowing nonReentrant returns (uint256) {
if (msg.sender != arbiter) {
revert CallerAccessDenied();
}
address targetToken = credits[ids[0]].token;
uint256 newTokens = _claimAndTrade(claimToken, targetToken, zeroExTradeData);
// add bought tokens to unused balance
unusedTokens[targetToken] += newTokens;
emit ReservesChanged(targetToken, int256(newTokens), 1);
return newTokens;
}
/**
* @notice - Claims revenue tokens escrowed in Spigot and trades them for credit tokens.
* - MUST trade all available claim tokens to target credit token.
* - Excess credit tokens not used to repay dent are stored in `unused`
* @dev - priviliged internal function
* @param claimToken - The revenue token escrowed in the Spigot to sell in trade
* @param targetToken - The credit token that needs to be bought in order to pat down debt. Always `credits[ids[0]].token`
* @param zeroExTradeData - 0x API data to use in trade to sell `claimToken` for target
*
* @return - amount of target tokens bought
*/
function _claimAndTrade(
address claimToken,
address targetToken,
bytes calldata zeroExTradeData
) internal returns (uint256) {
if (claimToken == targetToken) {
// same asset. dont trade
return spigot.claimOwnerTokens(claimToken);
} else {
// trade revenue token for debt obligation
(uint256 tokensBought, uint256 totalUnused) = SpigotedLineLib.claimAndTrade(
claimToken,
targetToken,
swapTarget,
address(spigot),
unusedTokens[claimToken],
zeroExTradeData
);
// we dont use revenue after this so can store now
/// @dev ReservesChanged event for claim token is emitted in SpigotedLineLib.claimAndTrade
unusedTokens[claimToken] = totalUnused;
// the target tokens purchased
return tokensBought;
}
}
// SPIGOT OWNER FUNCTIONS
/// see ISpigotedLine.updateOwnerSplit
function updateOwnerSplit(address revenueContract) external returns (bool) {
return
SpigotedLineLib.updateSplit(
address(spigot),
revenueContract,
_updateStatus(_healthcheck()),
defaultRevenueSplit
);
}
/// see ISpigotedLine.addSpigot
function addSpigot(address revenueContract, ISpigot.Setting calldata setting) external returns (bool) {
if (msg.sender != arbiter) {
revert CallerAccessDenied();
}
return spigot.addSpigot(revenueContract, setting);
}
/// see ISpigotedLine.updateWhitelist
function updateWhitelist(bytes4 func, bool allowed) external returns (bool) {
if (msg.sender != arbiter) {
revert CallerAccessDenied();
}
return spigot.updateWhitelistedFunction(func, allowed);
}
/// see ISpigotedLine.releaseSpigot
function releaseSpigot(address to) external returns (bool) {
return SpigotedLineLib.releaseSpigot(address(spigot), _updateStatus(_healthcheck()), borrower, arbiter, to);
}
/// see ISpigotedLine.sweep
function sweep(address to, address token, uint256 amount) external nonReentrant returns (uint256) {
uint256 swept = SpigotedLineLib.sweep(
to,
token,
amount,
unusedTokens[token],
_updateStatus(_healthcheck()),
borrower,
arbiter
);
if (swept != 0) {
unusedTokens[token] -= swept;
emit ReservesChanged(token, -int256(swept), 1);
}
return swept;
}
/// see ILineOfCredit.tradeable
function tradeable(address token) external view returns (uint256) {
return unusedTokens[token] + spigot.getOwnerTokens(token);
}
/// see ILineOfCredit.unused
function unused(address token) external view returns (uint256) {
return unusedTokens[token];
}
// allow claiming/trading in ETH
receive() external payable {}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/escrow/Escrow.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {Denominations} from "@chainlink/contracts0.8.0/src/v0.8/Denominations.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IEscrow} from "../../interfaces/IEscrow.sol";
import {IOracle} from "../../interfaces/IOracle.sol";
import {ILineOfCredit} from "../../interfaces/ILineOfCredit.sol";
import {CreditLib} from "../../utils/CreditLib.sol";
import {LineLib} from "../../utils/LineLib.sol";
import {EscrowState, EscrowLib} from "../../utils/EscrowLib.sol";
/**
* @title - Credit Cooperative Escrow
* @notice - Ownable contract that allows someone to deposit ERC20 and ERC4626 tokens as collateral to back a Line of Credit
*/
contract Escrow is IEscrow, ReentrancyGuard {
using SafeERC20 for IERC20;
using EscrowLib for EscrowState;
/// @notice the minimum value of the collateral in relation to the outstanding debt e.g. 10% of outstanding debt
uint32 public immutable minimumCollateralRatio;
/// @notice Stakeholders and contracts used in Escrow
address public immutable oracle;
/// @notice borrower on line contract
address public immutable borrower;
/// @notice all data around terms for collateral and current deposits
EscrowState private state;
/**
* @notice - Initiates immutable terms for a Line of Credit agreement related to collateral requirements
* @param _minimumCollateralRatio - In bps, 3 decimals. Cratio threshold where liquidations begin. see Escrow.isLiquidatable()
* @param _oracle - address to call for collateral token prices
* @param _line - Initial owner of Escrow contract. May be non-Line contract at construction before transferring to a Line.
- also is the oracle providing current total outstanding debt value.
* @param _borrower - borrower on the _line contract. Cannot pull from _line because _line might not be a Line at construction.
*/
constructor(uint32 _minimumCollateralRatio, address _oracle, address _line, address _borrower) {
minimumCollateralRatio = _minimumCollateralRatio;
oracle = _oracle;
borrower = _borrower;
state.line = _line;
}
/**
* @notice the current controller of the Escrow contract.
*/
function line() external view override returns (address) {
return state.line;
}
/**
* @notice - Checks Line's outstanding debt value and current Escrow collateral value to compute collateral ratio and checks that against minimum.
* @return isLiquidatable - returns true if Escrow.getCollateralRatio is lower than minimumCollateralRatio else false
*/
function isLiquidatable() external returns (bool) {
return state.isLiquidatable(oracle, minimumCollateralRatio);
}
/**
* @notice - Allows current owner to transfer ownership to another address
* @dev - Used if we setup Escrow before Line exists. Line has no way to interface with this function so once transfered `line` is set forever
* @return didUpdate - if function successfully executed or not
*/
function updateLine(address _line) external returns (bool) {
return state.updateLine(_line);
}
/**
* @notice add collateral to your position
* @dev requires that the token deposited by the depositor has been enabled by `line.Arbiter`
* @dev - callable by anyone
* @param amount - the amount of collateral to add
* @param token - the token address of the deposited token
* @return - the updated cratio
*/
function addCollateral(uint256 amount, address token) external payable nonReentrant returns (uint256) {
return state.addCollateral(oracle, amount, token);
}
/**
* @notice - allows the lines arbiter to enable thdeposits of an asset
* - gives better risk segmentation forlenders
* @dev - whitelisting protects against malicious 4626 tokens and DoS attacks
* - only need to allow once. Can not disable collateral once enabled.
* @param token - the token to all borrow to deposit as collateral
*/
function enableCollateral(address token) external returns (bool) {
return state.enableCollateral(oracle, token);
}
/**
* @notice remove collateral from your position. Must remain above min collateral ratio
* @dev callable by `borrower`
* @dev updates cratio
* @param amount - the amount of collateral to release
* @param token - the token address to withdraw
* @param to - who should receive the funds
* @return - the updated cratio
*/
function releaseCollateral(uint256 amount, address token, address to) external nonReentrant returns (uint256) {
return state.releaseCollateral(borrower, oracle, minimumCollateralRatio, amount, token, to);
}
/**
* @notice calculates the cratio
* @dev callable by anyone
* @return - the calculated cratio
*/
function getCollateralRatio() external returns (uint256) {
return state.getCollateralRatio(oracle);
}
/**
* @notice calculates the collateral value in USD to 8 decimals
* @dev callable by anyone
* @return - the calculated collateral value to 8 decimals
*/
function getCollateralValue() external returns (uint256) {
return state.getCollateralValue(oracle);
}
/**
* @notice liquidates borrowers collateral by token and amount
* line can liquidate at anytime based off other covenants besides cratio
* @dev requires that the cratio is at or below the liquidation threshold
* @dev callable by `line`
* @param amount - the amount of tokens to liquidate
* @param token - the address of the token to draw funds from
* @param to - the address to receive the funds
* @return - true if successful
*/
function liquidate(uint256 amount, address token, address to) external nonReentrant returns (bool) {
return state.liquidate(amount, token, to);
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/factories/LineFactory.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {ILineFactory} from "../../interfaces/ILineFactory.sol";
import {IModuleFactory} from "../../interfaces/IModuleFactory.sol";
import {LineLib} from "../../utils/LineLib.sol";
import {LineFactoryLib} from "../../utils/LineFactoryLib.sol";
import {ISecuredLine} from "../../interfaces/ISecuredLine.sol";
import {ILineOfCredit} from "../../interfaces/ILineOfCredit.sol";
/**
* @title - Credit Cooperative Line Factory
* @notice - Facotry contract to deploy SecuredLine, Spigot, and Escrow contracts.
* @dev - Have immutable default values for Credit Cooperative system external dependencies.
*/
contract LineFactory is ILineFactory {
IModuleFactory immutable factory;
uint8 constant defaultRevenueSplit = 90; // 90% to debt repayment
uint8 constant MAX_SPLIT = 100; // max % to take
uint32 constant defaultMinCRatio = 3000; // 30.00% minimum collateral ratio
address public immutable arbiter;
address public immutable oracle;
address payable public immutable swapTarget;
constructor(address moduleFactory, address arbiter_, address oracle_, address payable swapTarget_) {
factory = IModuleFactory(moduleFactory);
if (arbiter_ == address(0)) {
revert InvalidArbiterAddress();
}
if (oracle_ == address(0)) {
revert InvalidOracleAddress();
}
if (swapTarget_ == address(0)) {
revert InvalidSwapTargetAddress();
}
arbiter = arbiter_;
oracle = oracle_;
swapTarget = swapTarget_;
}
/// see ModuleFactory.deployEscrow.
function deployEscrow(uint32 minCRatio, address owner, address borrower) external returns (address) {
return factory.deployEscrow(minCRatio, oracle, owner, borrower);
}
/// see ModuleFactory.deploySpigot.
function deploySpigot(address owner, address operator) external returns (address) {
return factory.deploySpigot(owner, operator);
}
function deploySecuredLine(address borrower, uint256 ttl) external returns (address line) {
// deploy new modules
address s = factory.deploySpigot(address(this), borrower);
address e = factory.deployEscrow(defaultMinCRatio, oracle, address(this), borrower);
uint8 split = defaultRevenueSplit; // gas savings
line = LineFactoryLib.deploySecuredLine(oracle, arbiter, borrower, payable(swapTarget), s, e, ttl, split);
// give modules from address(this) to line so we can run line.init()
LineFactoryLib.transferModulesToLine(address(line), s, e);
emit DeployedSecuredLine(address(line), s, e, swapTarget, split);
}
function deploySecuredLineWithConfig(CoreLineParams calldata coreParams) external returns (address line) {
if (coreParams.revenueSplit > MAX_SPLIT) {
revert InvalidRevenueSplit();
}
// deploy new modules
address s = factory.deploySpigot(address(this), coreParams.borrower);
address e = factory.deployEscrow(coreParams.cratio, oracle, address(this), coreParams.borrower);
line = LineFactoryLib.deploySecuredLine(
oracle,
arbiter,
coreParams.borrower,
payable(swapTarget),
s,
e,
coreParams.ttl,
coreParams.revenueSplit
);
// give modules from address(this) to line so we can run line.init()
LineFactoryLib.transferModulesToLine(address(line), s, e);
emit DeployedSecuredLine(address(line), s, e, swapTarget, coreParams.revenueSplit);
}
/**
* @dev We don't transfer the ownership of Escrow and Spigot internally
* because they aren't owned by the factory, the responsibility falls
* on the [owner of the line]
* @dev The `cratio` in the CoreParams are not used, due to the fact
* they're passed in when the Escrow is created separately.
*/
function deploySecuredLineWithModules(
CoreLineParams calldata coreParams,
address mSpigot,
address mEscrow
) external returns (address line) {
if (mSpigot == address(0)) {
revert InvalidSpigotAddress();
}
if (mEscrow == address(0)) {
revert InvalidEscrowAddress();
}
line = LineFactoryLib.deploySecuredLine(
oracle,
arbiter,
coreParams.borrower,
payable(swapTarget),
mSpigot,
mEscrow,
coreParams.ttl,
coreParams.revenueSplit
);
emit DeployedSecuredLine(address(line), mEscrow, mSpigot, swapTarget, coreParams.revenueSplit);
}
function registerSecuredLine(
address line,
address spigot,
address escrow,
address borrower,
address operator,
uint8 revenueSplit,
uint32 minCRatio
) external {
if (msg.sender != arbiter){
revert InvalidArbiterAddress();
}
factory.registerEscrow(minCRatio, oracle, line, escrow);
factory.registerSpigot(spigot, line, borrower, operator);
emit RegisteredLine(line, oracle, arbiter, borrower, operator);
emit RegisteredUpdatedStatus(line, uint256(ILineOfCredit(line).status()));
emit RegisteredSecuredLine(line, escrow, spigot, swapTarget, revenueSplit);
}
/**
@notice sets up new line based of config of old line. Old line does not need to have REPAID status for this call to succeed.
@dev borrower must call rollover() on `oldLine` with newly created line address
@param oldLine - line to copy config from for new line.
@param borrower - borrower address on new line
@param ttl - set total term length of line
@return line - address of newly deployed line with oldLine config
*/
function rolloverSecuredLine(
address payable oldLine,
address borrower,
uint256 ttl
) external returns (address line) {
address s = address(ISecuredLine(oldLine).spigot());
address e = address(ISecuredLine(oldLine).escrow());
line = LineFactoryLib.deploySecuredLine(oracle, arbiter, borrower, swapTarget, s, e, ttl, defaultRevenueSplit);
emit DeployedSecuredLine(line, s, e, swapTarget, defaultRevenueSplit);
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/factories/ModuleFactory.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {IModuleFactory} from "../../interfaces/IModuleFactory.sol";
import {Spigot} from "../spigot/Spigot.sol";
import {Escrow} from "../escrow/Escrow.sol";
/**
* @title - Credit Cooperative Module Factory
* @notice - Facotry contract to deploy Spigot, and Escrow contracts.
*/
contract ModuleFactory is IModuleFactory {
/**
* see Spigot.constructor
* @notice - Deploys a Spigot module that can be used in a LineOfCredit
*/
function deploySpigot(
address owner,
address operator
) external returns (address module) {
module = address(new Spigot(owner, operator));
emit DeployedSpigot(module, owner, operator);
}
/**
* see Escrow.constructor
* @notice - Deploys an Escrow module that can be used in a LineOfCredit
*/
function deployEscrow(
uint32 minCRatio,
address oracle,
address owner,
address borrower
) external returns (address module) {
module = address(new Escrow(minCRatio, oracle, owner, borrower));
emit DeployedEscrow(module, minCRatio, oracle, owner);
}
function registerEscrow(
uint32 minCRatio,
address oracle,
address owner,
address escrow
) external {
emit RegisteredEscrow(escrow, minCRatio, oracle, owner);
}
function registerSpigot(
address spigot,
address owner,
address borrower, //
address operator
) external {
emit RegisteredSpigot(spigot, owner, borrower, operator);
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/interest-rate/InterestRateCredit.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {IInterestRateCredit} from "../../interfaces/IInterestRateCredit.sol";
contract InterestRateCredit is IInterestRateCredit {
// 1 Julian astronomical year in seconds to use in calculations for rates = 31557600 seconds
uint256 constant ONE_YEAR = 365.25 days;
// Must divide by 100 too offset bps in numerator and divide by another 100 to offset % and get actual token amount
uint256 constant BASE_DENOMINATOR = 10000;
// = 31557600 * 10000 = 315576000000;
uint256 constant INTEREST_DENOMINATOR = ONE_YEAR * BASE_DENOMINATOR;
address immutable lineContract;
mapping(bytes32 => Rate) public rates; // position id -> lending rates
/**
* @notice Interest rate / acrrued interest calculation contract for Line of Credit contracts
*/
constructor() {
lineContract = msg.sender;
}
/////////// MODIFIERS ///////////
modifier onlyLineContract() {
require(msg.sender == lineContract, "InterestRateCred: only line contract.");
_;
}
/// see IInterestRateCredit.accrueInterest
function accrueInterest(
bytes32 id,
uint256 drawnBalance,
uint256 facilityBalance
) external override onlyLineContract returns (uint256 accrued) {
accrued = _accrueInterest(id, drawnBalance, facilityBalance);
// update last timestamp in storage
rates[id].lastAccrued = block.timestamp;
}
function getInterestAccrued(
bytes32 id,
uint256 drawnBalance,
uint256 facilityBalance
) external view returns (uint256) {
return _accrueInterest(id, drawnBalance, facilityBalance);
}
function _accrueInterest(
bytes32 id,
uint256 drawnBalance,
uint256 facilityBalance
) internal view returns (uint256) {
Rate memory rate = rates[id];
// get time since interest was last accrued iwth these balances
uint256 timespan = block.timestamp - rate.lastAccrued;
return (_calculateInterestOwed(rate.dRate, drawnBalance, timespan) +
_calculateInterestOwed(rate.fRate, (facilityBalance - drawnBalance), timespan));
}
/**
* @notice - total interest to accrue based on apr, balance, and length of time
* @dev - r = APR in bps, x = # tokens, t = time
* - interest = (r * x * t) / 1yr / 100
* @param bpsRate - interest rate (APR) to charge against balance in bps (4 decimals)
* @param balance - current balance for interest rate tier to charge interest against
* @param timespan - total amount of time that interest should be charged for
*
* @return interestOwed
*/
function _calculateInterestOwed(
uint256 bpsRate,
uint256 balance,
uint256 timespan
) internal pure returns (uint256) {
return (bpsRate * balance * timespan) / INTEREST_DENOMINATOR;
}
/// see IInterestRateCredit.setRate
function setRate(bytes32 id, uint128 dRate, uint128 fRate) external onlyLineContract returns (bool) {
rates[id] = Rate({dRate: dRate, fRate: fRate, lastAccrued: block.timestamp});
return true;
}
function getRates(bytes32 id) external view returns (uint128, uint128) {
return (rates[id].dRate, rates[id].fRate);
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/oracle/Oracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import "@chainlink/contracts0.8.0/src/v0.8/interfaces/FeedRegistryInterface.sol";
import {Denominations} from "@chainlink/contracts0.8.0/src/v0.8/Denominations.sol";
import {LineLib} from "../../utils/LineLib.sol";
import "../../interfaces/IOracle.sol";
/**
* @title - Chainlink Feed Registry Wrapper
* @notice - simple contract that wraps Chainlink's Feed Registry to get asset prices for any tokens without needing to know the specific oracle address
* - only makes request for USD prices and returns results in standard 8 decimals for Chainlink USD feeds
*/
contract Oracle is IOracle {
/// @notice registry - Chainlink Feed Registry with aggregated prices across
FeedRegistryInterface public immutable registry;
/// @notice NULL_PRICE - null price when asset price feed is deemed invalid
int256 public constant NULL_PRICE = 0;
/// @notice PRICE_DECIMALS - the normalized amount of decimals for returned prices in USD
uint8 public constant PRICE_DECIMALS = 8;
/// @notice MAX_PRICE_LATENCY - amount of time between oracle responses until an asset is determined toxiz
/// Assumes Chainlink updates price minimum of once every 24hrs and 1 hour buffer for network issues
uint256 public constant MAX_PRICE_LATENCY = 25 hours;
event StalePrice(address indexed token, uint256 answerTimestamp);
event NullPrice(address indexed token);
event NoDecimalData(address indexed token, bytes errData);
event NoRoundData(address indexed token, bytes errData);
constructor(address _registry) {
registry = FeedRegistryInterface(_registry);
}
/**
* @param token_ - ERC20 token to get USD price for
* @dev - Native ETH is not supported, but there is no WETH oracle. Use ETH price for WETH token.
* @return price - the latest price in USD to 8 decimals
*/
function getLatestAnswer(address token_) external returns (int256) {
address token = token_ == LineLib.WETH ? Denominations.ETH : token_;
try registry.latestRoundData(token, Denominations.USD) returns (
uint80 /* uint80 roundID */,
int256 _price,
uint256 /* uint256 roundStartTime */,
uint256 answerTimestamp /* uint80 answeredInRound */,
uint80
) {
// no price for asset if price is stale. Asset is toxic
if (answerTimestamp == 0 || block.timestamp - answerTimestamp > MAX_PRICE_LATENCY) {
emit StalePrice(token, answerTimestamp);
return NULL_PRICE;
}
if (_price <= NULL_PRICE) {
emit NullPrice(token);
return NULL_PRICE;
}
try registry.decimals(token, Denominations.USD) returns (uint8 decimals) {
// if already at target decimals then return price
if (decimals == PRICE_DECIMALS) return _price;
// transform decimals to target value. disregard rounding errors
return
decimals < PRICE_DECIMALS
? _price * int256(10 ** (PRICE_DECIMALS - decimals))
: _price / int256(10 ** (decimals - PRICE_DECIMALS));
} catch (bytes memory msg_) {
emit NoDecimalData(token, msg_);
return NULL_PRICE;
}
// another try catch for decimals call
} catch (bytes memory msg_) {
emit NoRoundData(token, msg_);
return NULL_PRICE;
}
}
/**
* @notice - View function for oracle pricing that can be used off-chain.
* @dev - Can be used onchain for less gas than `getLatestAnswer` (no event emission).
* @param token - ERC20 token to get USD price for
* @return price - the latest price in USD to 8 decimals
*/
function _getLatestAnswer(address token) external view returns (int256) {
try registry.latestRoundData(token, Denominations.USD) returns (
uint80 /* uint80 roundID */,
int256 _price,
uint256 /* uint256 roundStartTime */,
uint256 answerTimestamp /* uint80 answeredInRound */,
uint80
) {
// no price for asset if price is stale. Asset is toxic
if (answerTimestamp == 0 || block.timestamp - answerTimestamp > MAX_PRICE_LATENCY) {
return NULL_PRICE;
}
if (_price <= NULL_PRICE) {
return NULL_PRICE;
}
try registry.decimals(token, Denominations.USD) returns (uint8 decimals) {
// if already at target decimals then return price
if (decimals == PRICE_DECIMALS) return _price;
// transform decimals to target value. disregard rounding errors
return
decimals < PRICE_DECIMALS
? _price * int256(10 ** (PRICE_DECIMALS - decimals))
: _price / int256(10 ** (decimals - PRICE_DECIMALS));
} catch (bytes memory) {
return NULL_PRICE;
}
// another try catch for decimals call
} catch (bytes memory) {
return NULL_PRICE;
}
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/oracle/PolygonOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
// import 'forge-std/console.sol';
import "@chainlink/contracts0.8.0/src/v0.8/interfaces/FeedRegistryInterface.sol";
import "@chainlink/contracts0.8.0/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {Denominations} from "@chainlink/contracts0.8.0/src/v0.8/Denominations.sol";
import {LineLib} from "../../utils/LineLib.sol";
import "../../interfaces/IOracle.sol";
/**
* @title - Chainlink Feed Registry Wrapper
* @notice - simple contract that wraps Chainlink's Feed Registry to get asset prices for any tokens without needing to know the specific oracle address
* - only makes request for USD prices and returns results in standard 8 decimals for Chainlink USD feeds
*/
contract PolygonOracle is IOracle {
/// @notice Price Feeds - Chainlink Feed Registry with aggregated prices across
mapping(address => address) public priceFeed; // token => chainlink price feed
/// @notice NULL_PRICE - null price when asset price feed is deemed invalid
int256 public constant NULL_PRICE = 0;
/// @notice PRICE_DECIMALS - the normalized amount of decimals for returned prices in USD
uint8 public constant PRICE_DECIMALS = 8;
/// @notice MAX_PRICE_LATENCY - amount of time between oracle responses until an asset is determined toxiz
/// Assumes Chainlink updates price minimum of once every 24hrs and 1 hour buffer for network issues
uint256 public constant MAX_PRICE_LATENCY = 25 hours;
event StalePrice(address indexed token, uint256 answerTimestamp);
event NullPrice(address indexed token);
event NoDecimalData(address indexed token, bytes errData);
event NoRoundData(address indexed token, bytes errData);
// TODO: Add DAI and USDC pricefeeds to mapping in constructor
// DAI/USD: 0x4746DeC9e833A82EC7C2C1356372CcF2cfcD2F3D
// USDC/USD: 0xfE4A8cc5b5B2366C1B58Bea3858e81843581b2F7
constructor() {
priceFeed[0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063] = 0x4746DeC9e833A82EC7C2C1356372CcF2cfcD2F3D; // DAI
priceFeed[0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174] = 0xfE4A8cc5b5B2366C1B58Bea3858e81843581b2F7; // USDC
}
/**
* @param token_ - ERC20 token to get USD price for
* @dev - Native ETH is not supported, but there is no WETH oracle. Use ETH price for WETH token.
* @return price - the latest price in USD to 8 decimals
*/
function getLatestAnswer(address token_) external returns (int256) {
require(priceFeed[token_] != address(0), "UNSUPPORTED");
address token = token_ == LineLib.WETH ? Denominations.ETH : token_;
try AggregatorV3Interface(priceFeed[token_]).latestRoundData() returns (
uint80 /* uint80 roundID */,
int256 _price,
uint256 /* uint256 roundStartTime */,
uint256 answerTimestamp /* uint80 answeredInRound */,
uint80
) {
// no price for asset if price is stale. Asset is toxic
// console.log("answerTimestamp: %s", answerTimestamp);
if (answerTimestamp == 0 || block.timestamp - answerTimestamp > MAX_PRICE_LATENCY) {
emit StalePrice(token, answerTimestamp);
return NULL_PRICE;
}
if (_price <= NULL_PRICE) {
emit NullPrice(token);
return NULL_PRICE;
}
try AggregatorV3Interface(priceFeed[token_]).decimals() returns (uint8 decimals) {
// if already at target decimals then return price
if (decimals == PRICE_DECIMALS) return _price;
// transform decimals to target value. disregard rounding errors
return
decimals < PRICE_DECIMALS
? _price * int256(10 ** (PRICE_DECIMALS - decimals))
: _price / int256(10 ** (decimals - PRICE_DECIMALS));
} catch (bytes memory msg_) {
emit NoDecimalData(token, msg_);
return NULL_PRICE;
}
// another try catch for decimals call
} catch (bytes memory msg_) {
emit NoRoundData(token, msg_);
return NULL_PRICE;
}
}
/**
* @notice - View function for oracle pricing that can be used off-chain.
* @dev - Can be used onchain for less gas than `getLatestAnswer` (no event emission).
* @param token - ERC20 token to get USD price for
* @return price - the latest price in USD to 8 decimals
*/
function _getLatestAnswer(address token) external view returns (int256) {
try AggregatorV3Interface(priceFeed[token]).latestRoundData() returns (
uint80 /* uint80 roundID */,
int256 _price,
uint256 /* uint256 roundStartTime */,
uint256 answerTimestamp /* uint80 answeredInRound */,
uint80
) {
// no price for asset if price is stale. Asset is toxic
if (answerTimestamp == 0 || block.timestamp - answerTimestamp > MAX_PRICE_LATENCY) {
return NULL_PRICE;
}
if (_price <= NULL_PRICE) {
return NULL_PRICE;
}
try AggregatorV3Interface(priceFeed[token]).decimals() returns (uint8 decimals) {
// if already at target decimals then return price
if (decimals == PRICE_DECIMALS) return _price;
// transform decimals to target value. disregard rounding errors
return
decimals < PRICE_DECIMALS
? _price * int256(10 ** (PRICE_DECIMALS - decimals))
: _price / int256(10 ** (decimals - PRICE_DECIMALS));
} catch (bytes memory) {
return NULL_PRICE;
}
// another try catch for decimals call
} catch (bytes memory) {
return NULL_PRICE;
}
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/modules/spigot/Spigot.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {LineLib} from "../../utils/LineLib.sol";
import {SpigotState, SpigotLib} from "../../utils/SpigotLib.sol";
import {ISpigot} from "../../interfaces/ISpigot.sol";
/**
* @title Credit Cooperative Spigot
* @notice - a contract allowing the revenue stream of a smart contract to be split between two parties, Owner and Treasury
- operational control of revenue generating contract belongs to Spigot's Owner and delegated to Operator.
* @dev - Should be deployed once per agreement. Multiple revenue contracts can be attached to a Spigot.
*/
contract Spigot is ISpigot, ReentrancyGuard {
using SpigotLib for SpigotState;
// Stakeholder variables
SpigotState private state;
/**
* @notice - Configure data for Spigot stakeholders
* - Owner/operator/treasury can all be the same address when setting up a Spigot
* @param _owner - An address that controls the Spigot and owns rights to some or all tokens earned by owned revenue contracts
* @param _operator - An active address for non-Owner that can execute whitelisted functions to manage and maintain product operations
* - on revenue generating contracts controlled by the Spigot.
*/
constructor(address _owner, address _operator) {
state.owner = _owner;
state.operator = _operator;
}
function owner() external view returns (address) {
return state.owner;
}
function operator() external view returns (address) {
return state.operator;
}
// ##########################
// ##### Claimoooor #####
// ##########################
/**
* @notice - Claims revenue tokens from the Spigoted revenue contract and stores them for the Owner and Operator to withdraw later.
* - Accepts both push (tokens sent directly to Spigot) and pull payments (Spigot calls revenue contract to claim tokens)
* - Calls predefined function in contract settings to claim revenue.
* - Automatically sends portion to Treasury and then stores Owner and Operator shares
* - There is no conversion or trade of revenue tokens.
* @dev - Assumes the only side effect of calling claimFunc on revenueContract is we receive new tokens.
* - Any other side effects could be dangerous to the Spigot or upstream contracts.
* @dev - callable by anyone
* @param revenueContract - Contract with registered settings to claim revenue from
* @param data - Transaction data, including function signature, to properly claim revenue on revenueContract
* @return claimed - The amount of revenue tokens claimed from revenueContract and split between `owner` and `treasury`
*/
function claimRevenue(
address revenueContract,
address token,
bytes calldata data
) external nonReentrant returns (uint256 claimed) {
return state.claimRevenue(revenueContract, token, data);
}
/**
* @notice - Allows Spigot Owner to claim escrowed revenue tokens
* @dev - callable by `owner`
* @param token - address of revenue token that is being escrowed by spigot
* @return claimed - The amount of tokens claimed by the `owner`
*/
function claimOwnerTokens(address token) external nonReentrant returns (uint256 claimed) {
return state.claimOwnerTokens(token);
}
/**
* @notice - Allows Spigot Operqtor to claim escrowed revenue tokens
* @dev - callable by `operator`
* @param token - address of revenue token that is being escrowed by spigot
* @return claimed - The amount of tokens claimed by the `operator`
*/
function claimOperatorTokens(address token) external nonReentrant returns (uint256 claimed) {
return state.claimOperatorTokens(token);
}
// ##########################
// ##### *ring* *ring* #####
// ##### OPERATOOOR #####
// ##### OPERATOOOR #####
// ##########################
/**
* @notice - Allows Operator to call whitelisted functions on revenue contracts to maintain their product
* - while still allowing Spigot Owner to receive its revenue stream
* @dev - cannot call revenueContracts claim or transferOwner functions
* @dev - callable by `operator`
* @param revenueContract - contract to call. Must have existing settings added by Owner
* @param data - tx data, including function signature, to call contract with
*/
function operate(address revenueContract, bytes calldata data) external returns (bool) {
return state.operate(revenueContract, data);
}
// ##########################
// ##### Maintainooor #####
// ##########################
/**
* @notice - allows Owner to add a new revenue stream to the Spigot
* @dev - revenueContract cannot be address(this)
* @dev - callable by `owner`
* @param revenueContract - smart contract to claim tokens from
* @param setting - Spigot settings for smart contract
*/
function addSpigot(address revenueContract, Setting memory setting) external returns (bool) {
return state.addSpigot(revenueContract, setting);
}
/**
* @notice - Uses predefined function in revenueContract settings to transfer complete control and ownership from this Spigot to the Operator
* @dev - revenuContract's transfer func MUST only accept one paramteter which is the new owner's address.
* @dev - callable by `owner`
* @param revenueContract - smart contract to transfer ownership of
*/
function removeSpigot(address revenueContract) external returns (bool) {
return state.removeSpigot(revenueContract);
}
/**
* @notice - Changes the revenue split between the Treasury and the Owner based upon the status of the Line of Credit
* - or otherwise if the Owner and Borrower wish to change the split.
* @dev - callable by `owner`
* @param revenueContract - Address of spigoted revenue generating contract
* @param ownerSplit - new % split to give owner
*/
function updateOwnerSplit(address revenueContract, uint8 ownerSplit) external returns (bool) {
return state.updateOwnerSplit(revenueContract, ownerSplit);
}
/**
* @notice - Update Owner role of Spigot contract.
* - New Owner receives revenue stream split and can control Spigot
* @dev - callable by `owner`
* @param newOwner - Address to give control to
*/
function updateOwner(address newOwner) external returns (bool) {
return state.updateOwner(newOwner);
}
/**
* @notice - Update Operator role of Spigot contract.
* - New Operator can interact with revenue contracts.
* @dev - callable by `operator`
* @param newOperator - Address to give control to
*/
function updateOperator(address newOperator) external returns (bool) {
return state.updateOperator(newOperator);
}
/**
* @notice - Allows Owner to whitelist function methods across all revenue contracts for Operator to call.
* - Can whitelist "transfer ownership" functions on revenue contracts
* - allowing Spigot to give direct control back to Operator.
* @dev - callable by `owner`
* @param func - smart contract function signature to whitelist
* @param allowed - true/false whether to allow this function to be called by Operator
*/
function updateWhitelistedFunction(bytes4 func, bool allowed) external returns (bool) {
return state.updateWhitelistedFunction(func, allowed);
}
// ##########################
// ##### GETTOOOORS #####
// ##########################
/**
* @notice - Retrieve amount of revenue tokens escrowed waiting for claim
* @param token - Revenue token that is being garnished from spigots
*/
function getOwnerTokens(address token) external view returns (uint256) {
return state.ownerTokens[token];
}
/**
* @notice - Retrieve amount of revenue tokens escrowed waiting for claim
* @param token - Revenue token that is being garnished from spigots
*/
function getOperatorTokens(address token) external view returns (uint256) {
return state.operatorTokens[token];
}
/**
* @notice - Returns if the function is whitelisted for an Operator to call
- on the spigoted revenue generating smart contracts.
* @param func - Function signature to check on whitelist
*/
function isWhitelisted(bytes4 func) external view returns (bool) {
return state.isWhitelisted(func);
}
function getSetting(address revenueContract) external view returns (uint8, bytes4, bytes4) {
return state.getSetting(revenueContract);
}
receive() external payable {
return;
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/utils/CreditLib.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {Denominations} from "@chainlink/contracts0.8.0/src/v0.8/Denominations.sol";
import {ILineOfCredit} from "../interfaces/ILineOfCredit.sol";
import {IOracle} from "../interfaces/IOracle.sol";
import {IInterestRateCredit} from "../interfaces/IInterestRateCredit.sol";
import {ILineOfCredit} from "../interfaces/ILineOfCredit.sol";
import {LineLib} from "./LineLib.sol";
/**
* @title Credit Cooperative Line of Credit Library
* @notice Core logic and variables to be reused across all Credit Cooperative Marketplace Line of Credit contracts
*/
library CreditLib {
event AddCredit(address indexed lender, address indexed token, uint256 indexed deposit, bytes32 id);
/// @notice Emitted when Lender withdraws from their initial deposit
event WithdrawDeposit(bytes32 indexed id, uint256 indexed amount);
/// @notice Emitted when Lender withdraws interest paid by borrower
event WithdrawProfit(bytes32 indexed id, uint256 indexed amount);
/// @notice Emits amount of interest (denominated in credit token) added to a Borrower's outstanding balance
event InterestAccrued(bytes32 indexed id, uint256 indexed amount);
// Borrower Events
/// @notice Emits when Borrower has drawn down an amount (denominated in credit.token) on a credit line
event Borrow(bytes32 indexed id, uint256 indexed amount);
/// @notice Emits that a Borrower has repaid some amount of interest (denominated in credit.token)
event RepayInterest(bytes32 indexed id, uint256 indexed amount);
/// @notice Emits that a Borrower has repaid some amount of principal (denominated in credit.token)
event RepayPrincipal(bytes32 indexed id, uint256 indexed amount);
// Errors
error NoTokenPrice();
error PositionExists();
error RepayAmountExceedsDebt(uint256 totalAvailable);
error InvalidTokenDecimals();
error NoQueue();
error PositionIsClosed();
error NoLiquidity();
error CloseFailedWithPrincipal();
error CallerAccessDenied();
/**
* @dev - Creates a deterministic hash id for a credit line provided by a single Lender for a given token on a Line of Credit facility
* @param line - The Line of Credit facility concerned
* @param lender - The address managing the credit line concerned
* @param token - The token being lent out on the credit line concerned
* @return id
*/
function computeId(address line, address lender, address token) external pure returns (bytes32) {
return keccak256(abi.encode(line, lender, token));
}
// getOutstandingDebt() is called by updateOutstandingDebt()
function getOutstandingDebt(
ILineOfCredit.Credit memory credit,
bytes32 id,
address oracle,
address interestRate
) external returns (ILineOfCredit.Credit memory c, uint256 principal, uint256 interest) {
c = accrue(credit, id, interestRate);
int256 price = IOracle(oracle).getLatestAnswer(c.token);
principal = calculateValue(price, c.principal, c.decimals);
interest = calculateValue(price, c.interestAccrued, c.decimals);
return (c, principal, interest);
}
/**
* @notice - Calculates value of tokens. Used for calculating the USD value of principal and of interest during getOutstandingDebt()
* @dev - Assumes Oracle returns answers in USD with 1e8 decimals
* - If price < 0 then we treat it as 0.
* @param price - The Oracle price of the asset. 8 decimals
* @param amount - The amount of tokens being valued.
* @param decimals - Token decimals to remove for USD price
* @return - The total USD value of the amount of tokens being valued in 8 decimals
*/
function calculateValue(int price, uint256 amount, uint8 decimals) public pure returns (uint256) {
return price <= 0 ? 0 : (amount * uint(price)) / (1 * 10 ** decimals);
}
/**
* see ILineOfCredit._createCredit
* @notice called by LineOfCredit._createCredit during every repayment function
* @param oracle - interset rate contract used by line that will calculate interest owed
*/
function create(
bytes32 id,
uint256 amount,
address lender,
address token,
address oracle
) external returns (ILineOfCredit.Credit memory credit) {
int price = IOracle(oracle).getLatestAnswer(token);
if (price <= 0) {
revert NoTokenPrice();
}
(bool passed, bytes memory result) = token.call(abi.encodeWithSignature("decimals()"));
if (!passed || result.length == 0) {
revert InvalidTokenDecimals();
}
uint8 decimals = abi.decode(result, (uint8));
credit = ILineOfCredit.Credit({
lender: lender,
token: token,
decimals: decimals,
deposit: amount,
principal: 0,
interestAccrued: 0,
interestRepaid: 0,
isOpen: true
});
emit AddCredit(lender, token, amount, id);
return credit;
}
/**
* see ILineOfCredit._repay
* @notice called by LineOfCredit._repay during every repayment function
* @dev uses uncheckd math. assumes checks have been done in caller
* @param credit - The lender position being repaid
*/
function repay(
ILineOfCredit.Credit memory credit,
bytes32 id,
uint256 amount,
address payer
) external returns (ILineOfCredit.Credit memory) {
if (!credit.isOpen) {
revert PositionIsClosed();
}
unchecked {
if (amount > credit.principal + credit.interestAccrued) {
revert RepayAmountExceedsDebt(credit.principal + credit.interestAccrued);
}
if (amount <= credit.interestAccrued) {
credit.interestAccrued -= amount;
credit.interestRepaid += amount;
emit RepayInterest(id, amount);
} else {
uint256 interest = credit.interestAccrued;
uint256 principalPayment = amount - interest;
// update individual credit line denominated in token
credit.principal -= principalPayment;
credit.interestRepaid += interest;
credit.interestAccrued = 0;
emit RepayInterest(id, interest);
emit RepayPrincipal(id, principalPayment);
}
}
// if we arent using funds from reserves to repay then pull tokens from target
if(payer != address(0)) {
LineLib.receiveTokenOrETH(credit.token, payer, amount);
}
return credit;
}
/**
* see ILineOfCredit.withdraw
* @notice called by LineOfCredit.withdraw during every repayment function
* @dev uses uncheckd math. assumes checks have been done in caller
* @param credit - The lender position that is being bwithdrawn from
*/
function withdraw(
ILineOfCredit.Credit memory credit,
bytes32 id,
address caller,
uint256 amount
) external returns (ILineOfCredit.Credit memory) {
if (caller != credit.lender) {
revert CallerAccessDenied();
}
unchecked {
if (amount > credit.deposit - credit.principal + credit.interestRepaid) {
revert ILineOfCredit.NoLiquidity();
}
if (amount > credit.interestRepaid) {
uint256 interest = credit.interestRepaid;
credit.deposit -= amount - interest;
credit.interestRepaid = 0;
// emit events before setting to 0
emit WithdrawDeposit(id, amount - interest);
emit WithdrawProfit(id, interest);
} else {
credit.interestRepaid -= amount;
emit WithdrawProfit(id, amount);
}
}
LineLib.sendOutTokenOrETH(credit.token, credit.lender, amount);
return credit;
}
/**
* see ILineOfCredit._accrue
* @notice called by LineOfCredit._accrue during every repayment function
* @dev public to use in `getOutstandingDebt`
* @param interest - interset rate contract used by line that will calculate interest owed
*/
function accrue(
ILineOfCredit.Credit memory credit,
bytes32 id,
address interest
) public returns (ILineOfCredit.Credit memory) {
if (!credit.isOpen) {
return credit;
}
unchecked {
// interest will almost always be less than deposit
// low risk of overflow unless extremely high interest rate
// get token demoninated interest accrued
uint256 accruedToken = IInterestRateCredit(interest).accrueInterest(id, credit.principal, credit.deposit);
// update credit line balance
credit.interestAccrued += accruedToken;
emit InterestAccrued(id, accruedToken);
return credit;
}
}
function interestAccrued(
ILineOfCredit.Credit memory credit,
bytes32 id,
address interest
) external view returns (uint256) {
return
credit.interestAccrued +
IInterestRateCredit(interest).getInterestAccrued(id, credit.principal, credit.deposit);
}
function getNextRateInQ(uint256 principal, bytes32 id, address interest) external view returns (uint128, uint128) {
if (principal == 0) {
revert NoQueue();
} else {
return IInterestRateCredit(interest).getRates(id);
}
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/utils/CreditListLib.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {ILineOfCredit} from "../interfaces/ILineOfCredit.sol";
import {IOracle} from "../interfaces/IOracle.sol";
import {CreditLib} from "./CreditLib.sol";
/**
* @title Credit Cooperative Line of Credit Library
* @notice Core logic and variables to be reused across all Credit Cooperative Marketplace Line of Credit contracts
*/
library CreditListLib {
event QueueCleared();
event SortedIntoQ(bytes32 indexed id, uint256 indexed newIdx, uint256 indexed oldIdx, bytes32 oldId);
error CantStepQ();
/**
* @notice - Removes a position id from the active list of open positions.
* @dev - assumes `id` is stored only once in the `positions` array. if `id` occurs twice, debt would be double counted.
* @param ids - all current credit lines on the Line of Credit facility
* @param id - the hash id of the credit line to be removed from active ids after removePosition() has run
* @return newPositions - all active credit lines on the Line of Credit facility after the `id` has been removed [Bob - consider renaming to newIds
*/
function removePosition(bytes32[] storage ids, bytes32 id) external returns (bool) {
uint256 len = ids.length;
for (uint256 i; i < len; ++i) {
if (ids[i] == id) {
delete ids[i];
return true;
}
}
return true;
}
/**
* @notice - swap the first element in the queue, provided it is null, with the next available valid(non-null) id
* @dev - Must perform check for ids[0] being valid (non-zero) before calling
* @param ids - all current credit lines on the Line of Credit facility
* @return swapped - returns true if the swap has occurred
*/
function stepQ(bytes32[] storage ids) external returns (bool) {
if (ids[0] != bytes32(0)) {
revert CantStepQ();
}
uint256 len = ids.length;
if (len <= 1) return false;
// skip the loop if we don't need
if (len == 2 && ids[1] != bytes32(0)) {
(ids[0], ids[1]) = (ids[1], ids[0]);
emit SortedIntoQ(ids[0], 0, 1, ids[1]);
return true;
}
// we never check the first id, because we already know it's null
for (uint i = 1; i < len; ) {
if (ids[i] != bytes32(0)) {
(ids[0], ids[i]) = (ids[i], ids[0]); // swap the ids in storage
emit SortedIntoQ(ids[0], 0, i, ids[i]);
return true; // if we make the swap, return early
}
unchecked {
++i;
}
}
emit QueueCleared();
return false;
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/utils/EscrowLib.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {Denominations} from "@chainlink/contracts0.8.0/src/v0.8/Denominations.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IOracle} from "../interfaces/IOracle.sol";
import {ILineOfCredit} from "../interfaces/ILineOfCredit.sol";
import {IEscrow} from "../interfaces/IEscrow.sol";
import {CreditLib} from "../utils/CreditLib.sol";
import {LineLib} from "../utils/LineLib.sol";
struct EscrowState {
address line;
address[] collateralTokens;
/// if lenders allow token as collateral. ensures uniqueness in collateralTokens
mapping(address => bool) enabled;
/// tokens used as collateral (must be able to value with oracle)
mapping(address => IEscrow.Deposit) deposited;
}
library EscrowLib {
using SafeERC20 for IERC20;
// return if have collateral but no debt
uint256 constant MAX_INT = type(uint256).max;
/**
* @notice updates the cratio according to the collateral value vs line value
* @dev calls accrue interest on the line contract to update the latest interest payable
* @param oracle - address to call for collateral token prices
* @return cratio - the updated collateral ratio in 4 decimals
*/
function _getLatestCollateralRatio(EscrowState storage self, address oracle) public returns (uint256) {
(uint256 principal, uint256 interest) = ILineOfCredit(self.line).updateOutstandingDebt();
uint256 debtValue = principal + interest;
uint256 collateralValue = _getCollateralValue(self, oracle);
if (debtValue == 0) return MAX_INT;
if (collateralValue == 0) return 0;
uint256 _numerator = collateralValue * 10 ** 5; // scale to 4 decimals
return ((_numerator / debtValue) + 5) / 10;
}
/**
* @notice - Iterates over all enabled tokens and calculates the USD value of all deposited collateral
* @param oracle - address to call for collateral token prices
* @return totalCollateralValue - the collateral's USD value in 8 decimals
*/
function _getCollateralValue(EscrowState storage self, address oracle) public returns (uint256) {
uint256 collateralValue;
// gas savings
uint256 length = self.collateralTokens.length;
IOracle o = IOracle(oracle);
IEscrow.Deposit memory d;
for (uint256 i; i < length; ++i) {
address token = self.collateralTokens[i];
d = self.deposited[token];
// new var so we don't override original deposit amount for 4626 tokens
uint256 deposit = d.amount;
if (deposit != 0) {
if (d.isERC4626) {
// this conversion could shift, hence it is best to get it each time
(bool success, bytes memory assetAmount) = token.call(
abi.encodeWithSignature("previewRedeem(uint256)", deposit)
);
if (!success) continue;
deposit = abi.decode(assetAmount, (uint256));
}
collateralValue += CreditLib.calculateValue(o.getLatestAnswer(d.asset), deposit, d.assetDecimals);
}
}
return collateralValue;
}
/** see Escrow.addCollateral */
function addCollateral(
EscrowState storage self,
address oracle,
uint256 amount,
address token
) external returns (uint256) {
if (amount == 0) {
revert InvalidZeroAmount();
}
if (!self.enabled[token]) {
revert InvalidCollateral();
}
LineLib.receiveTokenOrETH(token, msg.sender, amount);
self.deposited[token].amount += amount;
emit AddCollateral(token, amount);
return _getLatestCollateralRatio(self, oracle);
}
/** see Escrow.enableCollateral */
function enableCollateral(EscrowState storage self, address oracle, address token) external returns (bool) {
if (msg.sender != ILineOfCredit(self.line).arbiter()) {
revert ArbiterOnly();
}
if (token == address(0) || token == Denominations.ETH) {
revert EthSupportDisabled();
}
bool isEnabled = self.enabled[token];
IEscrow.Deposit memory deposit = self.deposited[token]; // gas savings
if (!isEnabled) {
(bool passed, bytes memory tokenAddrBytes) = token.call(abi.encodeWithSignature("asset()"));
bool is4626 = tokenAddrBytes.length != 0 && passed;
deposit.isERC4626 = is4626;
// if 4626 save the underlying token to use for oracle pricing
deposit.asset = !is4626 ? token : abi.decode(tokenAddrBytes, (address));
int256 price = IOracle(oracle).getLatestAnswer(deposit.asset);
if (price <= 0) {
revert InvalidCollateral();
}
(bool successDecimals, bytes memory decimalBytes) = deposit.asset.call(
abi.encodeWithSignature("decimals()")
);
if (!successDecimals || decimalBytes.length == 0) {
revert InvalidTokenDecimals();
}
deposit.assetDecimals = abi.decode(decimalBytes, (uint8));
// update collateral settings
self.enabled[token] = true;
self.deposited[token] = deposit;
self.collateralTokens.push(token);
emit EnableCollateral(deposit.asset);
}
return true;
}
/** see Escrow.releaseCollateral */
function releaseCollateral(
EscrowState storage self,
address borrower,
address oracle,
uint256 minimumCollateralRatio,
uint256 amount,
address token,
address to
) external returns (uint256) {
if (amount == 0) {
revert InvalidZeroAmount();
}
if (msg.sender != borrower) {
revert CallerAccessDenied();
}
if (self.deposited[token].amount < amount) {
revert InvalidCollateral();
}
self.deposited[token].amount -= amount;
LineLib.sendOutTokenOrETH(token, to, amount);
uint256 cratio = _getLatestCollateralRatio(self, oracle);
// fail if reduces cratio below min
// but allow borrower to always withdraw if fully repaid
if (
cratio < minimumCollateralRatio && // if undercollateralized, revert;
ILineOfCredit(self.line).status() != LineLib.STATUS.REPAID // if repaid, skip;
) {
revert UnderCollateralized();
}
emit RemoveCollateral(token, amount);
return cratio;
}
/** see Escrow.getCollateralRatio */
function getCollateralRatio(EscrowState storage self, address oracle) external returns (uint256) {
return _getLatestCollateralRatio(self, oracle);
}
/** see Escrow.getCollateralValue */
function getCollateralValue(EscrowState storage self, address oracle) external returns (uint256) {
return _getCollateralValue(self, oracle);
}
/** see Escrow.liquidate */
function liquidate(EscrowState storage self, uint256 amount, address token, address to) external returns (bool) {
if (amount == 0) {
revert InvalidZeroAmount();
}
if (msg.sender != self.line) {
revert CallerAccessDenied();
}
if (self.deposited[token].amount < amount) {
revert InvalidCollateral();
}
self.deposited[token].amount -= amount;
LineLib.sendOutTokenOrETH(token, to, amount);
return true;
}
/** see Escrow.isLiquidatable */
function isLiquidatable(
EscrowState storage self,
address oracle,
uint256 minimumCollateralRatio
) external returns (bool) {
return _getLatestCollateralRatio(self, oracle) < minimumCollateralRatio;
}
/** see Escrow.updateLine */
function updateLine(EscrowState storage self, address _line) external returns (bool) {
require(msg.sender == self.line);
self.line = _line;
return true;
}
event AddCollateral(address indexed token, uint256 indexed amount);
event RemoveCollateral(address indexed token, uint256 indexed amount);
event EnableCollateral(address indexed token);
event Liquidate(address indexed token, uint256 indexed amount);
error ArbiterOnly();
error InvalidZeroAmount();
error InvalidCollateral();
error EthSupportDisabled();
error CallerAccessDenied();
error UnderCollateralized();
error NotLiquidatable();
error InvalidTokenDecimals();
}
lib/blockchainManager/evm/v1/contracts/Spigot/utils/LibRegistry.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {CreditLib} from "./CreditLib.sol";
import {CreditListLib} from "./CreditListLib.sol";
import {EscrowLib} from "./EscrowLib.sol";
import {LineFactoryLib} from "./LineFactoryLib.sol";
import {LineLib} from "./LineLib.sol";
import {SpigotedLineLib} from "./SpigotedLineLib.sol";
import {SpigotLib} from "./SpigotLib.sol";
contract LibRegistry {
address public creditLib;
address public creditListLib;
address public escrowLib;
address public lineFactoryLib;
address public lineLib;
address public spigotedLineLib;
address public spigotLib;
constructor() {
creditLib = address(CreditLib);
creditListLib = address(CreditListLib);
escrowLib = address(EscrowLib);
lineFactoryLib = address(LineFactoryLib);
lineLib = address(LineLib);
spigotedLineLib = address(SpigotedLineLib);
spigotLib = address(SpigotLib);
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/utils/LineFactoryLib.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {SecuredLine} from "../modules/credit/SecuredLine.sol";
import {LineLib} from "./LineLib.sol";
library LineFactoryLib {
error ModuleTransferFailed(address line, address spigot, address escrow);
error InitNewLineFailed(address line, address spigot, address escrow);
/**
* @notice - transfer ownership of Spigot + Escrow contracts from factory to line contract after all 3 have been deployed
* @param line - the line to transfer modules to
* @param spigot - the module to be transferred to line
* @param escrow - the module to be transferred to line
*/
function transferModulesToLine(address line, address spigot, address escrow) external {
(bool success, bytes memory returnVal) = spigot.call(
abi.encodeWithSignature("updateOwner(address)", address(line))
);
(bool success2, bytes memory returnVal2) = escrow.call(
abi.encodeWithSignature("updateLine(address)", address(line))
);
// ensure all modules were transferred
if (!(success && abi.decode(returnVal, (bool)) && success2 && abi.decode(returnVal2, (bool)))) {
revert ModuleTransferFailed(line, spigot, escrow);
}
SecuredLine(payable(line)).init();
}
/**
* @notice - See SecuredLine.constructor(). Deploys a new SecuredLine contract with params provided by factory.
* @dev - Deploy from lib not factory so we can have multiple factories (aka marketplaces) built on same Line contracts
* @return line - address of newly deployed line
*/
function deploySecuredLine(
address oracle,
address arbiter,
address borrower,
address payable swapTarget,
address s,
address e,
uint256 ttl,
uint8 revenueSplit
) external returns (address) {
return address(new SecuredLine(oracle, arbiter, borrower, swapTarget, s, e, ttl, revenueSplit));
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/utils/LineLib.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {IInterestRateCredit} from "../interfaces/IInterestRateCredit.sol";
import {ILineOfCredit} from "../interfaces/ILineOfCredit.sol";
import {IOracle} from "../interfaces/IOracle.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Denominations} from "@chainlink/contracts0.8.0/src/v0.8/Denominations.sol";
/**
* @title Credit Cooperative Line of Credit Library
* @notice Core logic and variables to be reused across all Credit Cooperative Marketplace Line of Credit contracts
*/
library LineLib {
using SafeERC20 for IERC20;
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet WETH
error EthSentWithERC20();
error TransferFailed();
error SendingEthFailed();
error RefundEthFailed();
error BadToken();
event RefundIssued(address indexed recipient, uint256 value);
enum STATUS {
UNINITIALIZED,
ACTIVE,
LIQUIDATABLE,
REPAID,
INSOLVENT
}
/**
* @notice - Send ETH or ERC20 token from this contract to an external contract
* @param token - address of token to send out. Denominations.ETH for raw ETH
* @param receiver - address to send tokens to
* @param amount - amount of tokens to send
*/
function sendOutTokenOrETH(address token, address receiver, uint256 amount) external returns (bool) {
if (token == address(0)) {
revert TransferFailed();
}
// both branches revert if call failed
if (token != Denominations.ETH) {
// ERC20
IERC20(token).safeTransfer(receiver, amount);
} else {
// ETH
bool success = _safeTransferFunds(receiver, amount);
if (!success) {
revert SendingEthFailed();
}
}
return true;
}
/**
* @notice - Receive ETH or ERC20 token at this contract from an external contract
* @dev - If the sender overpays, the difference will be refunded to the sender
* @dev - If the sender is unable to receive the refund, it will be diverted to the calling contract
* @param token - address of token to receive. Denominations.ETH for raw ETH
* @param sender - address that is sendingtokens/ETH
* @param amount - amount of tokens to send
*/
function receiveTokenOrETH(address token, address sender, uint256 amount) external returns (bool) {
if (token == address(0)) {
revert TransferFailed();
}
if (token != Denominations.ETH) {
// ERC20
if (msg.value != 0) {
revert EthSentWithERC20();
}
IERC20(token).safeTransferFrom(sender, address(this), amount);
} else {
// ETH
if (msg.value < amount) {
revert TransferFailed();
}
if (msg.value > amount) {
uint256 refund = msg.value - amount;
if (_safeTransferFunds(msg.sender, refund)) {
emit RefundIssued(msg.sender, refund);
}
}
}
return true;
}
/**
* @notice - Helper function to get current balance of this contract for ERC20 or ETH
* @param token - address of token to check. Denominations.ETH for raw ETH
*/
function getBalance(address token) external view returns (uint256) {
if (token == address(0)) return 0;
return token != Denominations.ETH ? IERC20(token).balanceOf(address(this)) : address(this).balance;
}
/**
* @notice - Helper function to safely transfer Eth using native call
* @dev - Errors should be handled in the calling function
* @param recipient - address of the recipient
* @param value - value to be sent (in wei)
*/
function _safeTransferFunds(address recipient, uint256 value) internal returns (bool success) {
(success, ) = payable(recipient).call{value: value}("");
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/utils/MutualConsent.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
// forked from https://github.com/IndexCoop/index-coop-smart-contracts/blob/master/contracts/lib/MutualConsent.sol
pragma solidity ^0.8.16;
/**
* @title MutualConsent
* @author Set Protocol
*
* The MutualConsent contract contains a modifier for handling mutual consents between two parties
*/
abstract contract MutualConsent {
/* ============ State Variables ============ */
// equivalent to longest msg.data bytes, ie addCredit
uint256 constant MAX_DATA_LENGTH_BYTES = 164;
// equivalent to any fn with no args, ie just a fn selector
uint256 constant MIN_DATA_LENGTH_BYTES = 4;
// Mapping of upgradable units and if consent has been initialized by other party
mapping(bytes32 => address) public mutualConsentProposals;
error Unauthorized();
error InvalidConsent();
error NotUserConsent();
error NonZeroEthValue();
// causes revert when the msg.data passed in has more data (ie arguments) than the largest known fn signature
error UnsupportedMutualConsentFunction();
/* ============ Events ============ */
event MutualConsentRegistered(bytes32 proposalId, address taker);
event MutualConsentRevoked(bytes32 proposalId);
event MutualConsentAccepted(bytes32 proposalId);
/* ============ Modifiers ============ */
/**
* @notice - allows a function to be called if only two specific stakeholders signoff on the tx data
* - signers can be anyone. only two signers per contract or dynamic signers per tx.
*/
modifier mutualConsent(address _signerOne, address _signerTwo) {
if (_mutualConsent(_signerOne, _signerTwo)) {
// Run whatever code needed 2/2 consent
_;
}
}
/**
* @notice - allows a caller to revoke a previously created consent
* @dev - MAX_DATA_LENGTH_BYTES is set at 164 bytes, which is the length of the msg.data
* - for the addCredit function. Anything over that is not valid and might be used in
* - an attempt to create a hash collision
* @param _reconstrucedMsgData The reconstructed msg.data for the function call for which the
* original consent was created - comprised of the fn selector (bytes4) and abi.encoded
* function arguments.
*
*/
function revokeConsent(bytes calldata _reconstrucedMsgData) external {
if (
_reconstrucedMsgData.length > MAX_DATA_LENGTH_BYTES || _reconstrucedMsgData.length < MIN_DATA_LENGTH_BYTES
) {
revert UnsupportedMutualConsentFunction();
}
bytes32 proposalIdToDelete = keccak256(abi.encodePacked(_reconstrucedMsgData, msg.sender));
address consentor = mutualConsentProposals[proposalIdToDelete];
if (consentor == address(0)) {
revert InvalidConsent();
}
if (consentor != msg.sender) {
revert NotUserConsent();
} // note: cannot test, as no way to know what data (+msg.sender) would cause hash collision
delete mutualConsentProposals[proposalIdToDelete];
emit MutualConsentRevoked(proposalIdToDelete);
}
/* ============ Internal Functions ============ */
function _mutualConsent(address _signerOne, address _signerTwo) internal returns (bool) {
if (msg.sender != _signerOne && msg.sender != _signerTwo) {
revert Unauthorized();
}
address nonCaller = _getNonCaller(_signerOne, _signerTwo);
// The consent hash is defined by the hash of the transaction call data and sender of msg,
// which uniquely identifies the function, arguments, and sender.
bytes32 expectedProposalId = keccak256(abi.encodePacked(msg.data, nonCaller));
if (mutualConsentProposals[expectedProposalId] == address(0)) {
bytes32 newProposalId = keccak256(abi.encodePacked(msg.data, msg.sender));
mutualConsentProposals[newProposalId] = msg.sender; // save caller's consent for nonCaller to accept
emit MutualConsentRegistered(newProposalId, nonCaller);
return false;
}
delete mutualConsentProposals[expectedProposalId];
emit MutualConsentAccepted(expectedProposalId);
return true;
}
function _getNonCaller(address _signerOne, address _signerTwo) internal view returns (address) {
return msg.sender == _signerOne ? _signerTwo : _signerOne;
}
}
lib/blockchainManager/evm/v1/contracts/Spigot/utils/SpigotLib.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {LineLib} from "../utils/LineLib.sol";
import {ISpigot} from "../interfaces/ISpigot.sol";
struct SpigotState {
/// @notice Economic owner of Spigot revenue streams
address owner;
/// @notice account in charge of running onchain ops of spigoted contracts on behalf of owner
address operator;
/// @notice Total amount of revenue tokens help by the Spigot and available to be claimed by owner
mapping(address => uint256) ownerTokens; // token -> claimable
/// @notice Total amount of revenue tokens help by the Spigot and available to be claimed by operator
mapping(address => uint256) operatorTokens; // token -> claimable
/// @notice Functions that the operator is allowed to run on all revenue contracts controlled by the Spigot
mapping(bytes4 => bool) whitelistedFunctions; // function -> allowed
/// @notice Configurations for revenue contracts related to the split of revenue, access control to claiming revenue tokens and transfer of Spigot ownership
mapping(address => ISpigot.Setting) settings; // revenue contract -> settings
}
/**
* @notice - helper lib for Spigot
* @dev see Spigot docs
*/
library SpigotLib {
// Maximum numerator for Setting.ownerSplit param to ensure that the Owner can't claim more than 100% of revenue
uint8 constant MAX_SPLIT = 100;
// cap revenue per claim to avoid overflows on multiplication when calculating percentages
uint256 constant MAX_REVENUE = type(uint256).max / MAX_SPLIT;
function _claimRevenue(
SpigotState storage self,
address revenueContract,
address token,
bytes calldata data
) public returns (uint256 claimed) {
if (self.settings[revenueContract].transferOwnerFunction == bytes4(0)) {
revert InvalidRevenueContract();
}
uint256 existingBalance = LineLib.getBalance(token);
if (self.settings[revenueContract].claimFunction == bytes4(0)) {
// push payments
// claimed = total balance - already accounted for balance
claimed = existingBalance - self.ownerTokens[token] - self.operatorTokens[token];
// underflow revert ensures we have more tokens than we started with and actually claimed revenue
} else {
// pull payments
if (bytes4(data) != self.settings[revenueContract].claimFunction) {
revert BadFunction();
}
(bool claimSuccess, ) = revenueContract.call(data);
if (!claimSuccess) {
revert ClaimFailed();
}
// claimed = total balance - existing balance
claimed = LineLib.getBalance(token) - existingBalance;
// underflow revert ensures we have more tokens than we started with and actually claimed revenue
}
if (claimed == 0) {
revert NoRevenue();
}
// cap so uint doesnt overflow in split calculations.
// can sweep by "attaching" a push payment spigot with same token
if (claimed > MAX_REVENUE) claimed = MAX_REVENUE;
return claimed;
}
/** see Spigot.claimRevenue */
function claimRevenue(
SpigotState storage self,
address revenueContract,
address token,
bytes calldata data
) external returns (uint256 claimed) {
claimed = _claimRevenue(self, revenueContract, token, data);
// splits revenue stream according to Spigot settings
uint256 ownerTokens = (claimed * self.settings[revenueContract].ownerSplit) / 100;
// update escrowed balance
self.ownerTokens[token] = self.ownerTokens[token] + ownerTokens;
// update operator amount
if (claimed > ownerTokens) {
self.operatorTokens[token] = self.operatorTokens[token] + (claimed - ownerTokens);
}
emit ClaimRevenue(token, claimed, ownerTokens, revenueContract);
return claimed;
}
/** see Spigot.operate */
function operate(SpigotState storage self, address revenueContract, bytes calldata data) external returns (bool) {
if (msg.sender != self.operator) {
revert CallerAccessDenied();
}
// extract function signature from tx data and check whitelist
bytes4 func = bytes4(data);
if (!self.whitelistedFunctions[func]) {
revert OperatorFnNotWhitelisted();
}
// cant claim revenue via operate() because that fucks up accounting logic. Owner shouldn't whitelist it anyway but just in case
// also can't transfer ownership so Owner retains control of revenue contract
if (
func == self.settings[revenueContract].claimFunction ||
func == self.settings[revenueContract].transferOwnerFunction
) {
revert OperatorFnNotValid();
}
(bool success, ) = revenueContract.call(data);
if (!success) {
revert OperatorFnCallFailed();
}
return true;
}
/** see Spigot.claimOwnerTokens */
function claimOwnerTokens(SpigotState storage self, address token) external returns (uint256 claimed) {
if (msg.sender != self.owner) {
revert CallerAccessDenied();
}
claimed = self.ownerTokens[token];
if (claimed == 0) {
revert ClaimFailed();
}
self.ownerTokens[token] = 0; // reset before send to prevent reentrancy
LineLib.sendOutTokenOrETH(token, self.owner, claimed);
emit ClaimOwnerTokens(token, claimed, self.owner);
return claimed;
}
/** see Spigot.claimOperatorTokens */
function claimOperatorTokens(SpigotState storage self, address token) external returns (uint256 claimed) {
if (msg.sender != self.operator) {
revert CallerAccessDenied();
}
claimed = self.operatorTokens[token];
if (claimed == 0) {
revert ClaimFailed();
}
self.operatorTokens[token] = 0; // reset before send to prevent reentrancy
LineLib.sendOutTokenOrETH(token, self.operator, claimed);
emit ClaimOperatorTokens(token, claimed, self.operator);
return claimed;
}
/** see Spigot.addSpigot */
function addSpigot(
SpigotState storage self,
address revenueContract,
ISpigot.Setting memory setting
) external returns (bool) {
if (msg.sender != self.owner) {
revert CallerAccessDenied();
}
if (revenueContract == address(this)) {
revert InvalidRevenueContract();
}
// spigot setting already exists
if (self.settings[revenueContract].transferOwnerFunction != bytes4(0)) {
revert SpigotSettingsExist();
}
// must set transfer func
if (setting.transferOwnerFunction == bytes4(0)) {
revert BadSetting();
}
if (setting.ownerSplit > MAX_SPLIT) {
revert BadSetting();
}
self.settings[revenueContract] = setting;
emit AddSpigot(revenueContract, setting.ownerSplit, setting.claimFunction, setting.transferOwnerFunction);
return true;
}
/** see Spigot.removeSpigot */
function removeSpigot(SpigotState storage self, address revenueContract) external returns (bool) {
if (msg.sender != self.owner) {
revert CallerAccessDenied();
}
(bool success, ) = revenueContract.call(
abi.encodeWithSelector(
self.settings[revenueContract].transferOwnerFunction,
self.operator // assume function only takes one param that is new owner address
)
);
require(success);
delete self.settings[revenueContract];
emit RemoveSpigot(revenueContract);
return true;
}
/** see Spigot.updateOwnerSplit */
function updateOwnerSplit(
SpigotState storage self,
address revenueContract,
uint8 ownerSplit
) external returns (bool) {
if (msg.sender != self.owner) {
revert CallerAccessDenied();
}
if (ownerSplit > MAX_SPLIT) {
revert BadSetting();
}
self.settings[revenueContract].ownerSplit = ownerSplit;
emit UpdateOwnerSplit(revenueContract, ownerSplit);
return true;
}
/** see Spigot.updateOwner */
function updateOwner(SpigotState storage self, address newOwner) external returns (bool) {
if (msg.sender != self.owner) {
revert CallerAccessDenied();
}
require(newOwner != address(0));
self.owner = newOwner;
emit UpdateOwner(newOwner);
return true;
}
/** see Spigot.updateOperator */
function updateOperator(SpigotState storage self, address newOperator) external returns (bool) {
if (msg.sender != self.operator && msg.sender != self.owner) {
revert CallerAccessDenied();
}
require(newOperator != address(0));
self.operator = newOperator;
emit UpdateOperator(newOperator);
return true;
}
/** see Spigot.updateWhitelistedFunction*/
function updateWhitelistedFunction(SpigotState storage self, bytes4 func, bool allowed) external returns (bool) {
if (msg.sender != self.owner) {
revert CallerAccessDenied();
}
self.whitelistedFunctions[func] = allowed;
emit UpdateWhitelistFunction(func, allowed);
return true;
}
/** see Spigot.isWhitelisted*/
function isWhitelisted(SpigotState storage self, bytes4 func) external view returns (bool) {
return self.whitelistedFunctions[func];
}
/** see Spigot.getSetting*/
function getSetting(
SpigotState storage self,
address revenueContract
) external view returns (uint8, bytes4, bytes4) {
return (
self.settings[revenueContract].ownerSplit,
self.settings[revenueContract].claimFunction,
self.settings[revenueContract].transferOwnerFunction
);
}
// Spigot Events
event AddSpigot(address indexed revenueContract, uint256 ownerSplit, bytes4 claimFnSig, bytes4 trsfrFnSig);
event RemoveSpigot(address indexed revenueContract);
event UpdateWhitelistFunction(bytes4 indexed func, bool indexed allowed);
event UpdateOwnerSplit(address indexed revenueContract, uint8 indexed split);
event ClaimRevenue(address indexed token, uint256 indexed amount, uint256 ownerTokens, address revenueContract);
event ClaimOwnerTokens(address indexed token, uint256 indexed amount, address owner);
event ClaimOperatorTokens(address indexed token, uint256 indexed amount, address ooperator);
// Stakeholder Events
event UpdateOwner(address indexed newOwner);
event UpdateOperator(address indexed newOperator);
event UpdateTreasury(address indexed newTreasury);
// Errors
error BadFunction();
error OperatorFnNotWhitelisted();
error OperatorFnNotValid();
error OperatorFnCallFailed();
error ClaimFailed();
error NoRevenue();
error UnclaimedRevenue();
error CallerAccessDenied();
error BadSetting();
error InvalidRevenueContract();
error SpigotSettingsExist();
}
lib/blockchainManager/evm/v1/contracts/Spigot/utils/SpigotedLineLib.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright: https://github.com/credit-cooperative/Line-Of-Credit/blob/master/COPYRIGHT.md
pragma solidity ^0.8.16;
import {ISpigot} from "../interfaces/ISpigot.sol";
import {ISpigotedLine} from "../interfaces/ISpigotedLine.sol";
import {LineLib} from "../utils/LineLib.sol";
import {SpigotLib} from "../utils/SpigotLib.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Denominations} from "@chainlink/contracts0.8.0/src/v0.8/Denominations.sol";
library SpigotedLineLib {
/// @notice - maximum revenue we want to be able to take from spigots if Line is in default
uint8 constant MAX_SPLIT = 100;
error NoSpigot();
error TradeFailed();
error BadTradingPair();
error CallerAccessDenied();
error ReleaseSpigotFailed();
error NotInsolvent(address module);
error ReservesOverdrawn(address token, uint256 amountAvailable);
event TradeSpigotRevenue(
address indexed revenueToken,
uint256 revenueTokenAmount,
address indexed debtToken,
uint256 indexed debtTokensBought
);
event ReservesChanged(
address indexed token,
int256 indexed diff,
uint256 tokenType // 0 for revenue token, 1 for credit token
);
/**
* @dev - priviliged internal function!
* @notice - Allows revenue tokens in 'escrowed' to be traded for credit tokens that aren't yet used to repay debt.
- The newly exchanged credit tokens are held in 'unusedTokens' ready for a Lender to withdraw using useAndRepay
- This feature allows a Borrower to take advantage of an increase in the value of the revenue token compared
- to the credit token and to in effect use less revenue tokens to be later used to repay the same amount of debt.
* @dev - MUST trade all available claimTokens (unused + claimed) to targetTokens
* @param claimToken - The revenue token escrowed in the Spigot to sell in trade
* @param targetToken - The credit token that needs to be bought in order to pay down debt. Always `credits[ids[0]].token`
* @param swapTarget - The 0x exchange router address to call for trades
* @param spigot - The Spigot to claim from. Must be owned by adddress(this)
* @param unused - Current amount of unused claimTokens
* @param zeroExTradeData - 0x API data to use in trade to sell `claimToken` for target
* @return (uint, uint) - amount of targetTokens bought, total unused claimTokens after trade
*/
function claimAndTrade(
address claimToken,
address targetToken,
address payable swapTarget,
address spigot,
uint256 unused,
bytes calldata zeroExTradeData
) external returns (uint256, uint256) {
// can't trade into same token. causes double count for unused tokens
if (claimToken == targetToken) {
revert BadTradingPair();
}
// snapshot token balances now to diff after trade executes
uint256 oldClaimTokens = LineLib.getBalance(claimToken);
uint256 oldTargetTokens = LineLib.getBalance(targetToken);
// @dev claim has to be called after we get balance
// reverts if there are no tokens to claim
uint256 claimed = ISpigot(spigot).claimOwnerTokens(claimToken);
trade(claimed + unused, claimToken, swapTarget, zeroExTradeData);
// underflow revert ensures we have more tokens than we started with
uint256 tokensBought = LineLib.getBalance(targetToken) - oldTargetTokens;
if (tokensBought == 0) {
revert TradeFailed();
} // ensure tokens bought
uint256 newClaimTokens = LineLib.getBalance(claimToken);
// ideally we could use oracle here to calculate # of tokens to receive
// but sellToken might not have oracle. buyToken must have oracle
emit TradeSpigotRevenue(claimToken, claimed, targetToken, tokensBought);
// used reserve revenue to repay debt
if (oldClaimTokens > newClaimTokens) {
unchecked {
// we check all values before math so can use unchecked
uint256 diff = oldClaimTokens - newClaimTokens;
emit ReservesChanged(claimToken, -int256(diff), 0);
// used more tokens than we had in revenue reserves.
// prevent borrower from pulling idle lender funds to repay other lenders
if (diff > unused) revert ReservesOverdrawn(claimToken, unused);
// reduce reserves by consumed amount
else return (tokensBought, unused - diff);
}
} else {
unchecked {
// `unused` unlikely to overflow
// excess revenue in trade. store in reserves
uint256 diff = newClaimTokens - oldClaimTokens;
emit ReservesChanged(claimToken, int256(diff), 0);
return (tokensBought, unused + diff);
}
}
}
/**
* @dev - priviliged internal function!
* @notice - dumb func that executes arbitry code against a target contract
* @param amount - amount of revenue tokens to sell
* @param sellToken - revenue token being sold
* @param swapTarget - exchange aggregator to trade against
* @param zeroExTradeData - Trade data to execute against exchange for target token/amount
* @return bool - if trade was successful
*/
function trade(
uint256 amount,
address sellToken,
address payable swapTarget,
bytes calldata zeroExTradeData
) public returns (bool) {
if (sellToken == Denominations.ETH) {
// if claiming/trading eth send as msg.value to dex
(bool success, ) = swapTarget.call{value: amount}(zeroExTradeData); // TODO: test with 0x api data on mainnet fork
if (!success) {
revert TradeFailed();
}
} else {
IERC20(sellToken).approve(swapTarget, amount);
(bool success, ) = swapTarget.call(zeroExTradeData);
if (!success) {
revert TradeFailed();
}
}
return true;
}
/**
* @notice - cleanup function when a Line of Credit facility has expired. Called in SecuredLine.rollover
* - Reuse a Spigot across a single borrower's Line contracts
* @param spigot - The spigot address owned by this SpigotedLine
* @param newLine - The new line to transfer Spigot ownership to
* @return bool - if Spigot ownership was transferred or not
*/
function rollover(address spigot, address newLine) external returns (bool) {
require(ISpigot(spigot).updateOwner(newLine));
return true;
}
function canDeclareInsolvent(address spigot, address arbiter) external view returns (bool) {
// Must have called releaseSpigot() and sold off protocol / revenue streams already
address owner_ = ISpigot(spigot).owner();
if (address(this) == owner_ || arbiter == owner_) {
revert NotInsolvent(spigot);
}
return true;
}
/**
* @notice - Changes the revenue split between a Borrower's treasury and the LineOfCredit based on line health, runs with updateOwnerSplit()
* @dev - callable by anyone
* @param revenueContract - spigoted contract to update
* @return sucesss - whether or not split was updated
*/
function updateSplit(
address spigot,
address revenueContract,
LineLib.STATUS status,
uint8 defaultSplit
) external returns (bool) {
(uint8 split, , bytes4 transferFunc) = ISpigot(spigot).getSetting(revenueContract);
if (transferFunc == bytes4(0)) {
revert NoSpigot();
}
if (status == LineLib.STATUS.ACTIVE && split != defaultSplit) {
// if Line of Credit is healthy then set the split to the prior agreed default split of revenue tokens
return ISpigot(spigot).updateOwnerSplit(revenueContract, defaultSplit);
} else if (status == LineLib.STATUS.LIQUIDATABLE && split != MAX_SPLIT) {
// if the Line of Credit is in distress then take all revenue to repay debt
return ISpigot(spigot).updateOwnerSplit(revenueContract, MAX_SPLIT);
}
return false;
}
/**
* @notice - Transfers ownership of the entire Spigot and its revenuw streams from its then Owner to either
- the Borrower (if a Line of Credit has been been fully repaid) or
- to the Arbiter (if the Line of Credit is liquidatable).
* @dev - callable by `borrower` or `arbiter`
* @return - whether or not Spigot was released
*/
function releaseSpigot(
address spigot,
LineLib.STATUS status,
address borrower,
address arbiter,
address to
) external returns (bool) {
if (status == LineLib.STATUS.REPAID && msg.sender == borrower) {
if (!ISpigot(spigot).updateOwner(to)) {
revert ReleaseSpigotFailed();
}
return true;
}
if (status == LineLib.STATUS.LIQUIDATABLE && msg.sender == arbiter) {
if (!ISpigot(spigot).updateOwner(to)) {
revert ReleaseSpigotFailed();
}
return true;
}
revert CallerAccessDenied();
}
/**
* @notice - Sends any remaining tokens (revenue or credit tokens) in the Spigot to the Borrower after the loan has been repaid.
- In case of a Borrower default (loan status = liquidatable), this is a fallback mechanism to withdraw all the tokens and send them to the Arbiter
- Does not transfer anything if line is healthy
* @dev - callable by `borrower` or `arbiter`
* @return - whether or not spigot was released
*/
function sweep(
address to,
address token,
uint256 amount,
uint256 available,
LineLib.STATUS status,
address borrower,
address arbiter
) external returns (uint256) {
if (available == 0) {
return 0;
}
if (amount == 0) {
// use all tokens if no amount specified specified
amount = available;
} else {
if (amount > available) {
revert ReservesOverdrawn(token, available);
}
}
if (status == LineLib.STATUS.REPAID && msg.sender == borrower) {
LineLib.sendOutTokenOrETH(token, to, amount);
return amount;
}
if ((status == LineLib.STATUS.LIQUIDATABLE || status == LineLib.STATUS.INSOLVENT) && msg.sender == arbiter) {
LineLib.sendOutTokenOrETH(token, to, amount);
return amount;
}
revert CallerAccessDenied();
}
}
lib/blockchainManager/evm/v1/contracts/mock/SimpleAccount.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/// @notice Minimal 1271 wallet with owner + arbitrary execute().
contract SimpleAccount is IERC1271 {
using ECDSA for bytes32;
// bytes4(keccak256("isValidSignature(bytes32,bytes)"))
bytes4 internal constant MAGICVALUE = 0x1626ba7e;
address public immutable OWNER;
// Custom errors (gas efficient)
error NotOwner();
error OwnerZeroAddress();
error ExecuteFailed(bytes revertData);
event Executed(address indexed to, uint256 value, bytes data, bytes result);
modifier onlyOwner() {
if (msg.sender != OWNER) revert NotOwner();
_;
}
constructor(address _owner) {
if (_owner == address(0)) revert OwnerZeroAddress();
OWNER = _owner;
}
/// -----------------------------------------------------------------------
/// EIP-1271
/// -----------------------------------------------------------------------
function isValidSignature(
bytes32 hash,
bytes calldata signature
) external view override returns (bytes4) {
address recovered = hash.recover(signature);
return recovered == OWNER ? MAGICVALUE : bytes4(0);
}
/// -----------------------------------------------------------------------
/// Execute (EOA-triggered)
/// -----------------------------------------------------------------------
/// @notice Arbitrary call initiated by the owner.
/// @param to Target address to call.
/// @param value ETH to send with the call.
/// @param data Calldata for the call.
/// @return result Raw return data from the call.
function execute(
address to,
uint256 value,
bytes calldata data
) external payable onlyOwner returns (bytes memory result) {
(bool ok, bytes memory ret) = to.call{value: value}(data);
if (!ok) revert ExecuteFailed(ret);
emit Executed(to, value, data, ret);
return ret;
}
/// Accept ETH
receive() external payable {}
}
lib/blockchainManager/evm/v1/contracts/utils/MultiCall.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Decimals} from "./interfaces/IERC20Decimals.sol";
/**
* @title MultiCall Contract
* @notice Get balances of multiple assets for multiple owners in a single call
*/
contract MultiCall {
using SafeERC20 for IERC20Decimals;
struct Balance {
address asset;
address owner;
uint256 balance;
uint8 decimals;
}
/**
* @notice Get balances of multiple assets for multiple owners
* @param assets Array of asset addresses
* @param owners Array of owner addresses
* @return balances Array of balances
*/
function getBalances(
address[] calldata assets,
address[] calldata owners
) external view returns (Balance[] memory) {
Balance[] memory balances = new Balance[](
assets.length * owners.length
);
uint256 balanceIndex = 0;
for (uint256 assetIndex = 0; assetIndex < assets.length; assetIndex++) {
if (assets[assetIndex] == address(0)) {
for (
uint256 ownerIndex = 0;
ownerIndex < owners.length;
ownerIndex++
) {
balances[balanceIndex] = Balance(
assets[assetIndex],
owners[ownerIndex],
owners[ownerIndex].balance,
18 // All EVM chains should implement 18 decimals in its native asset
);
balanceIndex++;
}
} else {
IERC20Decimals asset = IERC20Decimals(assets[assetIndex]);
uint8 decimals = asset.decimals();
for (
uint256 ownerIndex = 0;
ownerIndex < owners.length;
ownerIndex++
) {
balances[balanceIndex] = Balance(
assets[assetIndex],
owners[ownerIndex],
asset.balanceOf(owners[ownerIndex]),
decimals
);
balanceIndex++;
}
}
}
return balances;
}
}
lib/blockchainManager/evm/v1/contracts/utils/interfaces/IERC20Decimals.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Decimals is IERC20 {
function decimals() external view returns (uint8);
}
lib/blockchainManager/evm/v1/contracts/v2/Beacon.sol
// SPDX-FileCopyrightText: Copyright (C) 2024 Signify Holdings, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.24;
import {UpgradeableBeacon} from "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
import {IBeacon} from "@openzeppelin/contracts/proxy/beacon/IBeacon.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Beacon Contract
* @notice Proxy implementation pointer for the upgradeable Collateral system
* @dev Wrapper around OpenZeppelin's UpgradeableBeacon for implementation management
*
* @dev Core Purpose:
* - Single source of truth for Collateral implementation
* - Enables atomic upgrades of all Collateral proxies
* - Manages implementation address for all Collateral contracts
*
* @dev Architecture:
* 1. Proxy Pattern Flow:
* Collateral Proxy → Factory → Beacon → Implementation
* - All proxies point to this Beacon
* - Beacon points to current implementation
* - Updating Beacon updates all proxies
*
* 2. Key Components:
* - BEACON: Immutable reference to UpgradeableBeacon
* - Owner: Controls implementation updates
* - Implementation: Target contract for all proxies
*
* @dev Security:
* 1. Access Control:
* - Only owner can update implementation
* - Implementation address is public but immutable
* - Beacon address is immutable once set
*
* 2. Upgrade Pattern:
* - Atomic upgrades for all proxies
* - No individual proxy can be upgraded
* - All proxies share same implementation
*
* @dev Key Functions:
* 1. Constructor:
* - Sets initial implementation
* - Creates UpgradeableBeacon
* - Transfers ownership
*
* 2. updateImplementation:
* - Updates target contract
* - Only owner can call
* - Affects all proxies
*
* 3. implementation:
* - View current implementation
* - Required by IBeacon
* - Used by proxies
*
* @notice System Impact:
* - Central point for all upgrades
* - Modifications affect all Collateral contracts
* - Cannot be replaced once Factory deployed
*/
contract Beacon is IBeacon, Ownable {
/// @notice Holds reference to beacon contract
UpgradeableBeacon public immutable BEACON;
/**
* @notice Initialize
* @param _initialImplementation initial Collateral implementation contract address
* @param _owner owner of this contract
*/
constructor(address _initialImplementation, address _owner) {
BEACON = new UpgradeableBeacon(_initialImplementation);
transferOwnership(_owner);
}
/**
* @notice update Collateral implementation
* @dev will update implementation of multiple Collateral contracts
*/
function updateImplementation(address _newImplementation) public onlyOwner {
BEACON.upgradeTo(_newImplementation);
}
/**
* @notice get RainCollateral implementation contract address
* @return address of implementation contract saved in beacon
*/
function implementation() public view returns (address) {
return BEACON.implementation();
}
}
lib/blockchainManager/evm/v1/contracts/v2/Collateral.sol
// SPDX-FileCopyrightText: Copyright (C) 2024 Signify Holdings, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.24;
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IFactory} from "./interfaces/IFactory.sol";
/**
* @title Collateral Contract
* @notice Smart contract for holding collateral assets with multi-signature control
* @dev Upgradeable contract via beacon pattern
* Works in conjunction with Coordinator contract
*
* @dev Core functionalities:
* 1. Multi-Signature Administration
* - Multiple admins can control the contract (up to 30 admins)
* - Configurable threshold for required signatures
* - EIP-712 compliant signatures for all admin actions
* - Admin management (add/remove)
*
* 2. Asset Management
* - Holds both native chain assets (ETH/AVAX) and ERC20 tokens
* - Controlled withdrawals and payments via Coordinator contract
* - Safe transfer implementations
*
* 3. Team Management
* - Team name and admin updates
* - Contract can be transferred to new set of admins
* - Multi-sig required for team transfers
*
* 4. Security Features
* - Signature replay protection via nonces
* - Admin threshold enforcement
* - Duplicate signer detection
* - Initializable pattern for proxy deployment
*
* @dev Technical Details:
* - Version: 2 (EIP712_DOMAIN_VERSION)
* - Proxy Pattern: Initializable (OpenZeppelin)
* - Dependencies: ECDSA, SafeERC20
* - Factory deployment model
* - Max admins: 30
*
* @dev Key State Variables:
* - admins[]: Array of admin addresses
* - _adminThreshold: Required signatures for operations
* - name: Team identifier
* - factory: Factory contract address
* - adminNonce: Prevents signature replay
*
* @dev Main Workflows:
* 1. Admin Management:
* - Add/Remove admins (requires multi-sig)
* - Update threshold (requires multi-sig)
*
* 2. Asset Management:
* - Receive assets (native via receive())
* - Withdraw assets (via Coordinator only)
* - Verify withdrawal signatures
*
* 3. Team Transfer:
* - Current admins sign transfer
* - New admins and name set
* - All previous admins removed
*
* @dev Access Control:
* 1. Coordinator Only:
* - Asset withdrawals
* - Signature verification
*
* 2. Factory Only:
* - Factory address updates
*
* 3. Admins:
* - Add/remove admins
* - Update threshold
* - Transfer team
*
* @notice Important Constraints:
* - Cannot remove last admin
* - Cannot exceed max admin limit (30)
* - Threshold cannot exceed admin count
* - Cannot have duplicate signers
* - Must maintain minimum admin threshold
* - Zero addresses not allowed
*/
contract Collateral is Initializable {
using SafeERC20 for IERC20;
/// @notice Elliptic Curve Digital Signature Algorithm Used to validate signature
using ECDSA for bytes32;
// Deprecated state variable.
address private owner;
// User readable name of signing domain
string public constant EIP712_DOMAIN_NAME = "Collateral";
// Current major version of signing domain
string public constant EIP712_DOMAIN_VERSION = "2";
// Type hash to check EIP712 domain separator validity in signature
bytes32 public constant EIP712_DOMAIN_TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
);
// Type hash to update admin threshold signature validity
bytes32 public constant UPDATE_ADMIN_THRESHOLD_TYPE_HASH =
keccak256("UpdateAdminThreshold(uint8 threshold,uint256 nonce)");
// Type hash to add admin signature validity
bytes32 public constant ADD_ADMIN_TYPE_HASH =
keccak256("AddAdmin(address admin,uint256 nonce)");
// Type hash to remove admin signature validity
bytes32 public constant REMOVE_ADMIN_TYPE_HASH =
keccak256("RemoveAdmin(address admin,uint256 nonce)");
// Type hash to withdraw signature validity
bytes32 public constant WITHDRAW_TYPE_HASH =
keccak256(
"Withdraw(address user,address asset,uint256 amount,address recipient,uint256 nonce)"
);
// Type hash to transfer team signature validity
bytes32 public constant TRANSFER_TEAM_TYPE_HASH =
keccak256(
"TransferTeam(address[] addingAdmins,string newName,uint256 nonce)"
);
/// @notice name of collateral
string public name;
/// @notice Factory Address
/// It is used to get controller address held in factory
address public factory;
/// @notice Admins of this contracts.
address[] public admins;
/// @notice Maximum number of admins
uint8 public constant MAX_ADMINS = 30;
/// @notice Admin threshold set by user or default(0)
uint8 internal __adminThreshold;
/// @notice Nonce used to validate admin signature
uint256 public adminNonce;
event AdminThresholdUpdated(uint8 threshold);
event AdminAdded(address admin);
event AdminRemoved(address admin);
event TransferTeam(
address[] addingAdmins,
string newName,
uint8 adminThreshold
);
event NativeAssetReceived(address sender, uint256 amount);
error InvalidAdminThreshold();
error InvalidSignature();
error InconsistentInputLength();
error UnderAdminThreshold();
error AboveMaxAdmins();
error Unauthorized();
error AddressZero();
error MinAdmins();
error MaxAdmins();
error AdminAlreadyExists();
error LastAdmin();
error AdminNotFound();
error DuplicateSigner();
error CannotSendNativeAsset();
/// @notice Authorize transactions from Coordinator contract only
modifier onlyCoordinator() {
if (_getCoordinator() != msg.sender) {
revert Unauthorized();
}
_;
}
/// @notice Authorize transactions from Factory contract only
modifier onlyFactory() {
if (factory != msg.sender) {
revert Unauthorized();
}
_;
}
/// @notice Revert if address param is 0x0
modifier validAddress(address _address) {
if (_address == address(0)) {
revert AddressZero();
}
_;
}
/// @notice Prevent the implementation contract from being used
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @notice Initialize this contract
* @param _name name of collateral
* @param _admin address of the first admin
*/
function initialize(
string memory _name,
address _admin
) public validAddress(_admin) initializer {
name = _name;
factory = msg.sender;
admins.push(_admin);
}
/**
* @notice Get admin threshold with some safety logic
* @return threshold admin threshold
*/
function adminThreshold() public view returns (uint8) {
// If threshold is not set, default to 1
if (__adminThreshold == 0) {
return 1;
}
// If threshold is greater than number of admins, cap it at max admins
// This ensures we never require more signatures than available admins
if (__adminThreshold > admins.length) {
return uint8(admins.length);
}
// Return the configured threshold if it's valid
return __adminThreshold;
}
/**
* @notice Update admin threshold
* @param _threshold new admin threshold
* @param _salts disambiguating salts for admin signatures
* @param _signatures signatures generated by admins in the same order with _salts
*/
function updateAdminThreshold(
uint8 _threshold,
bytes32[] calldata _salts,
bytes[] calldata _signatures
) external {
// Cannot set threshold to 0
if (_threshold == 0) {
revert InvalidAdminThreshold();
}
// Cannot set threshold to be greater than current number of admins
if (_threshold > admins.length) {
revert InvalidAdminThreshold();
}
// Create message hash to verify signature
bytes32 messageHash = keccak256(
bytes.concat(
abi.encode(
UPDATE_ADMIN_THRESHOLD_TYPE_HASH,
_threshold,
adminNonce
)
)
);
// Verify signatures
_verifyAdminSignatures(messageHash, _salts, _signatures);
// Update threshold
__adminThreshold = _threshold;
emit AdminThresholdUpdated(__adminThreshold);
}
/**
* @notice Check if _address is admin of this contract
* @param _address address to check
* @return status true if _address is admin
*/
function isAdmin(address _address) public view returns (bool) {
// Check if _address is in admins array
(bool found, ) = _getAdminIndex(_address);
return found;
}
/**
* @notice Add a collateral admin
* @dev only admin can call this function
* @param _admin new admin address
* @param _salts disambiguating salts for admin signatures
* @param _signatures signatures generated by admins in the same order with _salts
*/
function addAdmin(
address _admin,
bytes32[] calldata _salts,
bytes[] calldata _signatures
) public validAddress(_admin) {
// Cannot exceed max admins
if (admins.length >= MAX_ADMINS) {
revert MaxAdmins();
}
// Check if _admin is already in admins array
(bool found, ) = _getAdminIndex(_admin);
if (found) {
revert AdminAlreadyExists();
}
// Create message hash from admin address and nonce for signature verification
bytes32 messageHash = keccak256(
bytes.concat(abi.encode(ADD_ADMIN_TYPE_HASH, _admin, adminNonce))
);
// Verify that enough valid admin signatures were provided
_verifyAdminSignatures(messageHash, _salts, _signatures);
// Add the new admin address to the admins array
admins.push(_admin);
// Emit event to log the admin addition
emit AdminAdded(_admin);
}
/**
* @notice Remove a collateral admin
* @dev only admin can call this function
* @param _admin admin address to be removed
* @param _salts disambiguating salts for admin signatures
* @param _signatures signatures generated by admins in the same order with _salts
*/
function removeAdmin(
address _admin,
bytes32[] calldata _salts,
bytes[] calldata _signatures
) public {
// Cannot remove the last admin
if (admins.length == 1) {
revert LastAdmin();
}
// Check if _admin is in admins array
(bool found, uint256 index) = _getAdminIndex(_admin);
if (!found) {
revert AdminNotFound();
}
// Create message hash from admin address and nonce for signature verification
bytes32 messageHash = keccak256(
bytes.concat(abi.encode(REMOVE_ADMIN_TYPE_HASH, _admin, adminNonce))
);
// Verify that enough valid admin signatures were provided
_verifyAdminSignatures(messageHash, _salts, _signatures);
// Replace the admin to be removed with the last admin in the array
admins[index] = admins[admins.length - 1];
// Remove the last admin from the array
admins.pop();
emit AdminRemoved(_admin);
}
/**
* @notice Withdraw ERC-20 asset that this contract owns.
* @dev only Coordinator can call this function
* @param _asset asset address
* @param _recipient recipient address
* @param _amountNative withdrawed amount
*/
function withdrawERC20Asset(
address _asset,
address _recipient,
uint256 _amountNative
) external onlyCoordinator {
// Transfer the ERC20 asset to the recipient
IERC20(_asset).safeTransfer(_recipient, _amountNative);
}
/**
* @notice Withdraw native asset(e.g. ETH and AVAX) that this contract owns.
* @dev only Coordinator can call this function
* @param _recipient recipient address
* @param _amountNative withdrawed amount
*/
function withdrawNativeAsset(
address _recipient,
uint256 _amountNative
) external onlyCoordinator {
// Transfer the asset to the recipient
(bool sentToRecipient, ) = _recipient.call{value: _amountNative}("");
if (!sentToRecipient) {
revert CannotSendNativeAsset();
}
}
/**
* @notice Verify admin signatures for withdraw
* @param _user user address
* @param _asset asset address
* @param _amount withdrawal amount
* @param _recipient recipient address
* @param _salts disambiguating salts for signatures
* @param _signatures signatures generated by admins in the same order with _salts
*/
function verifyWithdrawAdminSignatures(
address _user,
address _asset,
uint256 _amount,
address _recipient,
bytes32[] calldata _salts,
bytes[] calldata _signatures
) external onlyCoordinator {
// Create message hash from withdrawal details and nonce for signature verification
bytes32 messageHash = keccak256(
bytes.concat(
abi.encode(
WITHDRAW_TYPE_HASH,
_user,
_asset,
_amount,
_recipient,
adminNonce
)
)
);
// Verify that enough valid admin signatures were provided
_verifyAdminSignatures(messageHash, _salts, _signatures);
}
/**
* @notice Transfer the contract to a new team
* @param _addingAdmins new admins to be added
* @param _newName new name of collateral
* @param _transferTeamSalts disambiguating salts for transfer team signatures
* @param _transferTeamSignatures signatures generated by admins in the same order with _transferTeamSalts
*/
function transferTeam(
address[] calldata _addingAdmins,
string calldata _newName,
bytes32[] calldata _transferTeamSalts,
bytes[] calldata _transferTeamSignatures,
uint8 _adminThreshold
) public {
// Cannot add 0 admins
if (_addingAdmins.length == 0) {
revert MinAdmins();
}
// Cannot add more than max admins
if (_addingAdmins.length > MAX_ADMINS) {
revert MaxAdmins();
}
// Create message hash from new admins and nonce for signature verification
bytes32 messageHash = keccak256(
bytes.concat(
abi.encode(
TRANSFER_TEAM_TYPE_HASH,
keccak256(abi.encodePacked(_addingAdmins)),
keccak256(bytes(_newName)),
adminNonce
)
)
);
// Verify that enough valid admin signatures were provided
_verifyAdminSignatures(
messageHash,
_transferTeamSalts,
_transferTeamSignatures
);
// Reset admins array
admins = new address[](0);
// Add new admins to the array
for (uint256 i = 0; i < _addingAdmins.length; i++) {
if (_addingAdmins[i] == address(0)) {
revert AddressZero();
}
// Check if the admin is already in the array
(bool found, ) = _getAdminIndex(_addingAdmins[i]);
if (found) {
revert AdminAlreadyExists();
}
// Add the new admin to the admins array
admins.push(_addingAdmins[i]);
}
name = _newName;
// Cannot set threshold to be 0 or greater than number of admins
if (_adminThreshold == 0 || _adminThreshold > admins.length) {
revert InvalidAdminThreshold();
}
__adminThreshold = _adminThreshold;
emit TransferTeam(_addingAdmins, _newName, _adminThreshold);
}
/**
* @notice Update factory address
* @dev only current factory can call this function
* @param _newFactory new factory address
*/
function updateFactory(
address _newFactory
) external onlyFactory validAddress(_newFactory) {
factory = _newFactory;
}
/**
* @notice Get admin index from admins array
* @dev Internal view function
* @param _admin querying admin address
* @return found if index is found or not
* @return index admin address if found
*/
function _getAdminIndex(
address _admin
) internal view returns (bool, uint256) {
// Iterate through admins array to find _admin
for (uint256 i = 0; i < admins.length; i++) {
if (admins[i] == _admin) {
return (true, i);
}
}
// Return false and 0 if _admin is not found
return (false, 0);
}
/**
* @notice Get Coordinator contract address from Factory contract
* @dev Internal function to interact with Coordinator contract
* @return address Coordinator contract address
*/
function _getCoordinator() internal view returns (address) {
// Controller address is kept in Factory
return IFactory(factory).coordinator();
}
/**
* @notice Sub function of _verifyPaymentSignature and _verifyWithdrawal
* to verify signature is from admins
* @dev increment nonce when signature is valid
* @param _messageHash keccak256 hashed message
* @param _salts disambiguating salts for signatures
* @param _signatures signatures generated by
*/
function _verifyAdminSignatures(
bytes32 _messageHash,
bytes32[] calldata _salts,
bytes[] calldata _signatures
) internal {
// Check if the number of salts and signatures are the same
if (_signatures.length != _salts.length) {
revert InconsistentInputLength();
}
// Check if the number of signatures is greater than or equal to the admin threshold
if (_signatures.length < adminThreshold()) {
revert UnderAdminThreshold();
}
// Check if the number of signatures is greater than max admins
if (_signatures.length > MAX_ADMINS) {
revert AboveMaxAdmins();
}
// Array to store signers
address[] memory signers = new address[](_signatures.length);
for (uint256 i = 0; i < _signatures.length; i++) {
// Create domain separator for EIP712 signature verification
bytes32 domainSeparator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPE_HASH,
keccak256(bytes(EIP712_DOMAIN_NAME)),
keccak256(bytes(EIP712_DOMAIN_VERSION)),
block.chainid,
address(this),
_salts[i]
)
);
// Create digest to verify signature
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, _messageHash)
);
// Verify that the signature was generated by admin
address signer = digest.recover(_signatures[i]);
if (!isAdmin(signer)) {
revert InvalidSignature();
}
// Check if there are any duplicate signers
for (uint256 j = 0; j < i; j++) {
if (signer == signers[j]) {
revert DuplicateSigner();
}
}
// Store the signer
signers[i] = signer;
}
adminNonce++;
}
/**
* @notice Receive native asset(e.g. ETH and AVAX)
*/
receive() external payable {
emit NativeAssetReceived(msg.sender, msg.value);
}
}
lib/blockchainManager/evm/v1/contracts/v2/Factory.sol
// SPDX-FileCopyrightText: Copyright (C) 2024 Signify Holdings, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.24;
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {BeaconProxy} from "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
import {Beacon} from "./Beacon.sol";
import {Collateral} from "./Collateral.sol";
/**
* @title Factory Contract
* @notice Upgradeable contract for deploying and managing Collateral contracts using beacon proxy pattern
*
* @dev Key Features:
* 1. Proxy Pattern Implementation
* - Uses beacon proxy pattern for upgradeable Collateral contracts
* - All deployed Collateral contracts share same implementation
* - Allows future upgrades to all Collateral instances at once
*
* 2. Deployment Management
* - Creates new Collateral contracts via CREATE2 for address predictability
* - Supports batch deployment of multiple contracts
* - Restricted creation rights to designated creator address
*
* 3. System Configuration
* - Manages coordinator address for all Collateral contracts
* - Controls beacon implementation updates
* - Handles factory address updates across all Collateral contracts
*
* @dev Role-Based Access:
* 1. Owner Capabilities
* - Update coordinator address
* - Update creator address
* - Update factory address in Collateral contracts
* - Control beacon implementation
*
* 2. Creator Capabilities
* - Deploy new Collateral contracts
* - Only authorized creator can deploy
*
* @dev Key Components:
* 1. Beacon Contract
* - Holds reference to current Collateral implementation
* - Enables atomic upgrades of all proxies
* - Controlled by factory owner
*
* 2. Proxy Deployment
* - Uses CREATE2 for deterministic addresses
* - Initializes each Collateral with name and owner
* - Emits events for contract creation
*
* 3. Address Management
* - Coordinator address for permissions
* - Creator address for deployment rights
* - Factory address in Collateral contracts
*
* @dev Workflows:
* 1. Contract Deployment:
* Creator -> createCollateralContract -> New Collateral Proxy
* - Validates inputs
* - Creates proxy with CREATE2
* - Initializes contract
* - Emits creation event
*
* 2. Address Prediction:
* - Calculates proxy address before deployment
* - Uses same parameters as deployment
* - Enables frontend address preview
*
* 3. System Updates:
* - Beacon updates affect all proxies
* - Coordinator updates affect permissions
* - Factory updates maintain contract links
*
* @notice Important Aspects:
* - All deployed Collateral contracts share implementation
* - Addresses are predictable via CREATE2
* - Zero addresses not allowed for critical parameters
* - Only authorized creator can deploy contracts
* - Owner retains upgrade and configuration rights
*/
contract Factory is OwnableUpgradeable {
Beacon public beacon;
/// @dev Coordinator address,
/// Collateral contracts can look up Coordinator address to allow function calls.
address public coordinator;
// Deprecated state variable.
address[] private collateralProxies;
/// @dev Address that can create new Collateral contracts
address public creator;
/// @dev Emitted when a new Collateral contract is deployed
event NewCollateralContract(
address indexed _collateralProxy,
string _name,
address _user
);
event CoordinatorUpdated(address coordinator);
event CreatorUpdated(address newCreator, address oldCreator);
event AdminThresholdUpdated(uint8 threshold);
error Unauthorized(address unauthorizedAddress);
error ZeroAddress();
error InconsistentInputLength();
/// @dev Revert if caller is not the creator
modifier onlyCreator() {
if (msg.sender != creator) {
revert Unauthorized(msg.sender);
}
_;
}
/// @dev Revert if address param is 0x0
modifier validAddress(address _address) {
if (_address == address(0)) {
revert ZeroAddress();
}
_;
}
/**
* @notice Initialize
* @param _coordinator coordinator address
* @param _initialImplementation initial Collateral implementation contract address
* @param _owner owner of this contract
* @param _creator address that can create new Collateral contracts
*/
function initialize(
address _coordinator,
address _initialImplementation,
address _owner,
address _creator
)
public
initializer
validAddress(_coordinator)
validAddress(_initialImplementation)
{
// Initialize Ownable contract
__Ownable_init();
// Transfer ownership to the owner
transferOwnership(_owner);
coordinator = _coordinator;
// Create new Beacon contract
beacon = new Beacon(_initialImplementation, owner());
creator = _creator;
}
/**
* @notice Update Coordinator address
* @dev Only owner can call this function
* @param _coordinator new Coordinator address
*/
function updateCoordinator(
address _coordinator
) external onlyOwner validAddress(_coordinator) {
coordinator = _coordinator;
emit CoordinatorUpdated(_coordinator);
}
/**
* @notice Update Creator address
* @dev Only owner can call this function
* @param _creator new Creator address
*/
function updateCreator(
address _creator
) external onlyOwner validAddress(_creator) {
address oldCreator = creator;
creator = _creator;
emit CreatorUpdated(_creator, oldCreator);
}
/**
* @notice Get the address of the beacon contract
* to the Collateral implementation contract
* @dev actual implementation contract address can be retrieved by getImplementation function
* @return address of the becon contract
*/
function getBeacon() public view returns (address) {
return address(beacon);
}
/**
* @notice Get the address of Collateral implementation contract
* @dev Retrived via beacon contract
* @return address of Collateral implementation contract
*/
function getImplementation() public view returns (address) {
return beacon.implementation();
}
/**
* @notice Update factory address in all Collateral contracts
* @dev Only owner can call this function
* @param _newFactory new factory address
* @param _collateralProxies array of Collateral contract addresses
*/
function updateFactoryInCollaterals(
address _newFactory,
address payable[] calldata _collateralProxies
) external onlyOwner validAddress(_newFactory) {
for (uint32 i = 0; i < _collateralProxies.length; i++) {
Collateral(_collateralProxies[i]).updateFactory(_newFactory);
}
}
/**
* @notice Deploy a new Collateral contract as a beacon proxy
* taking arrays as parameters to deploy multiple contracts at once
* @dev Only creator can call this function
* @param _names names of the new Collateral contracts
* @param _owners owners of the new Collateral contracts
* @param _salts salts to use to create the Collateral contracts
*/
function createCollateralContract(
string[] calldata _names,
address[] calldata _owners,
bytes32[] calldata _salts
) external onlyCreator {
// Check if the lengths of the input arrays are consistent
if (_names.length != _owners.length || _names.length != _salts.length) {
revert InconsistentInputLength();
}
// Deploy new Collateral contracts
for (uint32 i = 0; i < _names.length; i++) {
BeaconProxy collateralProxy = new BeaconProxy{salt: _salts[i]}( // create2
address(beacon),
abi.encodeWithSelector(
Collateral.initialize.selector,
_names[i],
_owners[i]
)
);
// Store the address of the new Collateral contract
collateralProxies.push(address(collateralProxy));
// Emit event to log the new Collateral contract creation
emit NewCollateralContract(
address(collateralProxy),
_names[i],
_owners[i]
);
}
}
/**
* @notice Calculate the address of the Collateral contract
* @param _name name of the new Collateral contract
* @param _user owner of the new Collateral contract
* @param _salt salt to use to create the Collateral contract
* @return address of the Collateral contract
*/
function calculateCollateralProxyAddress(
string calldata _name,
address _user,
bytes32 _salt
) external view returns (address) {
// Prepare the bytecode for the new Collateral contract
bytes memory bytecode = abi.encodePacked(
type(BeaconProxy).creationCode,
abi.encode(
address(beacon),
abi.encodeWithSelector(
Collateral.initialize.selector,
_name,
_user
)
)
);
// Create the hash for the new Collateral contract
bytes32 hash = keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
_salt,
keccak256(bytecode)
)
);
// Return the address of the new Collateral contract
return address(uint160(uint256(hash)));
}
}
lib/blockchainManager/evm/v1/contracts/v2/interfaces/ICollateral.sol
// SPDX-FileCopyrightText: Copyright (C) 2024 Signify Holdings, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.24;
/// @title ICollateral Interface
/// @notice Interface for managing collateral assets and admin-controlled withdrawals
interface ICollateral {
/// @notice Checks if an address has admin privileges
/// @param _admin The address to check
/// @return bool True if the address is an admin, false otherwise
function isAdmin(address _admin) external view returns (bool);
/// @notice Withdraws ERC20 tokens from the contract
/// @param _token The address of the ERC20 token to withdraw
/// @param _recipient The address that will receive the tokens
/// @param _amount The amount of tokens to withdraw
function withdrawERC20Asset(
address _token,
address _recipient,
uint256 _amount
) external;
/// @notice Withdraws native blockchain asset (e.g., ETH) from the contract
/// @param _recipient The address that will receive the native tokens
/// @param _amount The amount of native tokens to withdraw
function withdrawNativeAsset(address _recipient, uint256 _amount) external;
/// @notice Verifies admin signatures for a withdrawal request
/// @param _user The user requesting the withdrawal
/// @param _asset The asset address (zero address for native token)
/// @param _amount The amount to withdraw
/// @param _recipient The address that will receive the assets
/// @param _salts Unique identifiers to prevent signature reuse
/// @param _signatures Array of admin signatures authorizing the withdrawal
function verifyWithdrawAdminSignatures(
address _user,
address _asset,
uint256 _amount,
address _recipient,
bytes32[] calldata _salts,
bytes[] calldata _signatures
) external;
}
lib/blockchainManager/evm/v1/contracts/v2/interfaces/IERC20Decimals.sol
// SPDX-FileCopyrightText: Copyright (C) 2024 Signify Holdings, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IERC20Decimals Interface
/// @notice Extension of the IERC20 interface that adds the decimals() function
/// @dev This interface is commonly used to get the number of decimals for an ERC20 token
interface IERC20Decimals is IERC20 {
/// @notice Returns the number of decimals used by the token
/// @return The number of decimals places the token uses
/// @dev Most tokens use 18 decimals, following ETH itself, but this is not required
function decimals() external view returns (uint8);
}
lib/blockchainManager/evm/v1/contracts/v2/interfaces/IFactory.sol
// SPDX-FileCopyrightText: Copyright (C) 2024 Signify Holdings, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.24;
/// @title IFactory Interface
/// @notice Interface for the factory contract that manages coordinator deployment
interface IFactory {
/// @notice Returns the address of the coordinator contract
/// @return The address of the currently set coordinator
function coordinator() external view returns (address);
}
Compiler settingsShow
{
"viaIR": true,
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.