Feature Tip: Add private address tag to any address under My Name Tag !
Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
Latest 25 from a total of 153 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Repay | 20432795 | 95 days ago | IN | 0 ETH | 0.00119036 | ||||
Borrow With On C... | 20341184 | 108 days ago | IN | 0 ETH | 0.00504891 | ||||
Repay | 20133291 | 137 days ago | IN | 0 ETH | 0.00278076 | ||||
Repay | 20063959 | 147 days ago | IN | 0 ETH | 0.00267192 | ||||
Repay | 20037034 | 150 days ago | IN | 0 ETH | 0.00131808 | ||||
Repay | 20034753 | 151 days ago | IN | 0 ETH | 0.00342926 | ||||
Repay | 20031101 | 151 days ago | IN | 0 ETH | 0.00165524 | ||||
Repay | 20030454 | 151 days ago | IN | 0 ETH | 0.00139085 | ||||
Repay | 20025333 | 152 days ago | IN | 0 ETH | 0.00156454 | ||||
Repay | 20024648 | 152 days ago | IN | 0 ETH | 0.0019511 | ||||
Repay | 20024571 | 152 days ago | IN | 0 ETH | 0.00142201 | ||||
Repay | 20024466 | 152 days ago | IN | 0 ETH | 0.00145071 | ||||
Repay | 20021807 | 152 days ago | IN | 0 ETH | 0.0010456 | ||||
Repay | 20018548 | 153 days ago | IN | 0 ETH | 0.00109085 | ||||
Repay | 20016571 | 153 days ago | IN | 0 ETH | 0.00090635 | ||||
Repay | 20016562 | 153 days ago | IN | 0 ETH | 0.00092358 | ||||
Repay | 20016243 | 153 days ago | IN | 0 ETH | 0.00088973 | ||||
Repay | 20016241 | 153 days ago | IN | 0 ETH | 0.00102227 | ||||
Repay | 20011727 | 154 days ago | IN | 0 ETH | 0.00399737 | ||||
Repay | 20000362 | 155 days ago | IN | 0 ETH | 0.00081285 | ||||
Repay | 20000346 | 155 days ago | IN | 0 ETH | 0.00068515 | ||||
Repay | 20000343 | 155 days ago | IN | 0 ETH | 0.00076516 | ||||
Repay | 19999990 | 155 days ago | IN | 0 ETH | 0.00083198 | ||||
Repay | 19998981 | 156 days ago | IN | 0 ETH | 0.00109969 | ||||
Repay | 19991929 | 157 days ago | IN | 0 ETH | 0.00156028 |
View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Contract Name:
BorrowerGateway
Compiler Version
v0.8.19+commit.7dd6d404
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Constants} from "../Constants.sol"; import {DataTypesPeerToPeer} from "./DataTypesPeerToPeer.sol"; import {Errors} from "../Errors.sol"; import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol"; import {IBaseCompartment} from "./interfaces/compartments/IBaseCompartment.sol"; import {IBorrowerGateway} from "./interfaces/IBorrowerGateway.sol"; import {ILenderVaultImpl} from "./interfaces/ILenderVaultImpl.sol"; import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol"; import {IQuoteHandler} from "./interfaces/IQuoteHandler.sol"; import {IVaultCallback} from "./interfaces/IVaultCallback.sol"; contract BorrowerGateway is ReentrancyGuard, IBorrowerGateway { using SafeERC20 for IERC20Metadata; // putting fee info in borrow gateway since borrower always pays this upfront address public immutable addressRegistry; // index 0: base protocol fee is paid even for swap (no tenor) // index 1: protocol fee slope scales protocol fee with tenor uint128[2] internal protocolFeeParams; constructor(address _addressRegistry) { if (_addressRegistry == address(0)) { revert Errors.InvalidAddress(); } addressRegistry = _addressRegistry; } function borrowWithOffChainQuote( address lenderVault, DataTypesPeerToPeer.BorrowTransferInstructions calldata borrowInstructions, DataTypesPeerToPeer.OffChainQuote calldata offChainQuote, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple, bytes32[] calldata proof ) external nonReentrant returns (DataTypesPeerToPeer.Loan memory) { _checkDeadlineAndRegisteredVault( borrowInstructions.deadline, lenderVault ); { address quoteHandler = IAddressRegistry(addressRegistry) .quoteHandler(); IQuoteHandler(quoteHandler).checkAndRegisterOffChainQuote( msg.sender, lenderVault, offChainQuote, quoteTuple, proof ); } ( DataTypesPeerToPeer.Loan memory loan, uint256 loanId, uint256 upfrontFee ) = _processBorrowTransaction( borrowInstructions, offChainQuote.generalQuoteInfo, quoteTuple, lenderVault ); emit Borrowed( lenderVault, loan.borrower, loan, upfrontFee, loanId, borrowInstructions.callbackAddr, borrowInstructions.callbackData ); return loan; } function borrowWithOnChainQuote( address lenderVault, DataTypesPeerToPeer.BorrowTransferInstructions calldata borrowInstructions, DataTypesPeerToPeer.OnChainQuote calldata onChainQuote, uint256 quoteTupleIdx ) external nonReentrant returns (DataTypesPeerToPeer.Loan memory) { // borrow gateway just forwards data to respective vault and orchestrates transfers // borrow gateway is oblivious towards and specific borrow details, and only fwds info // vaults needs to check details of given quote and whether it's valid // all lenderVaults need to approve BorrowGateway // 1. BorrowGateway "optimistically" pulls loanToken from lender vault: either transfers directly to (a) borrower or (b) callbacker for further processing // 2. BorrowGateway then pulls collToken from borrower to lender vault // 3. Finally, BorrowGateway updates lender vault storage state _checkDeadlineAndRegisteredVault( borrowInstructions.deadline, lenderVault ); { address quoteHandler = IAddressRegistry(addressRegistry) .quoteHandler(); IQuoteHandler(quoteHandler).checkAndRegisterOnChainQuote( msg.sender, lenderVault, quoteTupleIdx, onChainQuote ); } DataTypesPeerToPeer.QuoteTuple calldata quoteTuple = onChainQuote .quoteTuples[quoteTupleIdx]; ( DataTypesPeerToPeer.Loan memory loan, uint256 loanId, uint256 upfrontFee ) = _processBorrowTransaction( borrowInstructions, onChainQuote.generalQuoteInfo, quoteTuple, lenderVault ); emit Borrowed( lenderVault, loan.borrower, loan, upfrontFee, loanId, borrowInstructions.callbackAddr, borrowInstructions.callbackData ); return loan; } function repay( DataTypesPeerToPeer.LoanRepayInstructions calldata loanRepayInstructions, address vaultAddr ) external nonReentrant { _checkDeadlineAndRegisteredVault( loanRepayInstructions.deadline, vaultAddr ); if ( loanRepayInstructions.callbackAddr != address(0) && IAddressRegistry(addressRegistry).whitelistState( loanRepayInstructions.callbackAddr ) != DataTypesPeerToPeer.WhitelistState.CALLBACK ) { revert Errors.NonWhitelistedCallback(); } ILenderVaultImpl lenderVault = ILenderVaultImpl(vaultAddr); DataTypesPeerToPeer.Loan memory loan = lenderVault.loan( loanRepayInstructions.targetLoanId ); if (msg.sender != loan.borrower) { revert Errors.InvalidBorrower(); } if ( block.timestamp < loan.earliestRepay || block.timestamp >= loan.expiry ) { revert Errors.OutsideValidRepayWindow(); } // checks repayAmount <= remaining loan balance if ( loanRepayInstructions.targetRepayAmount == 0 || loanRepayInstructions.targetRepayAmount + loan.amountRepaidSoFar > loan.initRepayAmount ) { revert Errors.InvalidRepayAmount(); } bool noCompartment = loan.collTokenCompartmentAddr == address(0); // @dev: amountReclaimedSoFar cannot exceed initCollAmount for non-compartmentalized assets uint256 maxReclaimableCollAmount = noCompartment ? loan.initCollAmount - loan.amountReclaimedSoFar : IBaseCompartment(loan.collTokenCompartmentAddr) .getReclaimableBalance(loan.collToken); // @dev: amountRepaidSoFar cannot exceed initRepayAmount uint128 leftRepaymentAmount = loan.initRepayAmount - loan.amountRepaidSoFar; uint128 reclaimCollAmount = SafeCast.toUint128( (maxReclaimableCollAmount * uint256(loanRepayInstructions.targetRepayAmount)) / uint256(leftRepaymentAmount) ); if (reclaimCollAmount == 0) { revert Errors.ReclaimAmountIsZero(); } lenderVault.updateLoanInfo( loanRepayInstructions.targetRepayAmount, loanRepayInstructions.targetLoanId, reclaimCollAmount, noCompartment, loan.collToken ); _processRepayTransfers( vaultAddr, loanRepayInstructions, loan, leftRepaymentAmount, reclaimCollAmount, noCompartment ); emit Repaid( vaultAddr, loanRepayInstructions.targetLoanId, loanRepayInstructions.targetRepayAmount ); } /** * @notice Protocol fee is allowed to be zero, so no min fee checks, only max fee checks */ function setProtocolFeeParams(uint128[2] calldata _newFeeParams) external { if (msg.sender != IAddressRegistry(addressRegistry).owner()) { revert Errors.InvalidSender(); } if ( _newFeeParams[0] > Constants.MAX_SWAP_PROTOCOL_FEE || _newFeeParams[1] > Constants.MAX_FEE_PER_ANNUM || (_newFeeParams[0] == protocolFeeParams[0] && _newFeeParams[1] == protocolFeeParams[1]) ) { revert Errors.InvalidFee(); } protocolFeeParams = _newFeeParams; emit ProtocolFeeSet(_newFeeParams); } function getProtocolFeeParams() external view returns (uint128[2] memory) { return protocolFeeParams; } function _processBorrowTransaction( DataTypesPeerToPeer.BorrowTransferInstructions calldata borrowInstructions, DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple, address lenderVault ) internal returns (DataTypesPeerToPeer.Loan memory, uint256, uint256) { ( DataTypesPeerToPeer.Loan memory loan, uint256 loanId, DataTypesPeerToPeer.TransferInstructions memory transferInstructions ) = ILenderVaultImpl(lenderVault).processQuote( msg.sender, borrowInstructions, generalQuoteInfo, quoteTuple ); _processTransfers( lenderVault, borrowInstructions, loan, transferInstructions ); return (loan, loanId, transferInstructions.upfrontFee); } // solhint-disable code-complexity function _processTransfers( address lenderVault, DataTypesPeerToPeer.BorrowTransferInstructions calldata borrowInstructions, DataTypesPeerToPeer.Loan memory loan, DataTypesPeerToPeer.TransferInstructions memory transferInstructions ) internal { if ( borrowInstructions.callbackAddr != address(0) && IAddressRegistry(addressRegistry).whitelistState( borrowInstructions.callbackAddr ) != DataTypesPeerToPeer.WhitelistState.CALLBACK ) { revert Errors.NonWhitelistedCallback(); } ILenderVaultImpl(lenderVault).transferTo( loan.loanToken, borrowInstructions.callbackAddr == address(0) ? loan.borrower : borrowInstructions.callbackAddr, loan.initLoanAmount ); if (borrowInstructions.callbackAddr != address(0)) { IVaultCallback(borrowInstructions.callbackAddr).borrowCallback( loan, borrowInstructions.callbackData ); } uint128[2] memory currProtocolFeeParams = protocolFeeParams; uint128[2] memory applicableProtocolFeeParams = currProtocolFeeParams; address mysoTokenManager = IAddressRegistry(addressRegistry) .mysoTokenManager(); if (mysoTokenManager != address(0)) { applicableProtocolFeeParams = IMysoTokenManager(mysoTokenManager) .processP2PBorrow( applicableProtocolFeeParams, borrowInstructions, loan, lenderVault ); for (uint256 i; i < 2; ) { if (applicableProtocolFeeParams[i] > currProtocolFeeParams[i]) { revert Errors.InvalidFee(); } unchecked { ++i; } } } // Note: Collateral and fees flow and breakdown is as follows: // // collSendAmount ("collSendAmount") // | // |-- protocolFeeAmount ("protocolFeeAmount") // | // |-- gross pledge amount // | // |-- gross upfront fee // | | // | |-- net upfront fee ("upfrontFee") // | | // | |-- transfer fee 1 // | // |-- gross reclaimable collateral // | // |-- net reclaimable collateral ("initCollAmount") // | // |-- transfer fee 2 ("expectedCompartmentTransferFee") // // where expectedProtocolAndVaultTransferFee = protocolFeeAmount + transfer fee 1 uint256 protocolFeeAmount = _calculateProtocolFeeAmount( applicableProtocolFeeParams, borrowInstructions.collSendAmount, loan.initCollAmount == 0 ? 0 : loan.expiry - block.timestamp ); // check protocolFeeAmount <= expectedProtocolAndVaultTransferFee if ( protocolFeeAmount > borrowInstructions.expectedProtocolAndVaultTransferFee ) { revert Errors.InsufficientSendAmount(); } if (protocolFeeAmount != 0) { // note: if coll token has a transfer fee, then protocolFeeAmount received by the protocol will be less than // protocolFeeAmount; this is by design to not tax borrowers or lenders for transfer fees on protocol fees IERC20Metadata(loan.collToken).safeTransferFrom( loan.borrower, IAddressRegistry(addressRegistry).owner(), protocolFeeAmount ); } // determine any transfer fee for sending collateral to vault uint256 collTransferFeeForSendingToVault = borrowInstructions .expectedProtocolAndVaultTransferFee - protocolFeeAmount; // Note: initialize the coll amount that is sent to vault in case there's no compartment uint256 grossCollTransferAmountToVault = loan.initCollAmount + transferInstructions.upfrontFee + collTransferFeeForSendingToVault; // Note: initialize the vault's expected coll balance increase in case there's no compartment uint256 expVaultCollBalIncrease = loan.initCollAmount + transferInstructions.upfrontFee; if (transferInstructions.collReceiver != lenderVault) { // Note: if there's a compartment then adjust the coll amount that is sent to vault by deducting the amount // that goes to the compartment, i.e., the borrower's reclaimable coll amount and any associated transfer fees grossCollTransferAmountToVault -= loan.initCollAmount; // Note: similarly, adjust the vault's expected coll balance diff by deducting the reclaimable coll amount that // goes to the compartment expVaultCollBalIncrease -= loan.initCollAmount; uint256 collReceiverPreBal = IERC20Metadata(loan.collToken) .balanceOf(transferInstructions.collReceiver); IERC20Metadata(loan.collToken).safeTransferFrom( loan.borrower, transferInstructions.collReceiver, loan.initCollAmount + borrowInstructions.expectedCompartmentTransferFee ); // check that compartment balance increase matches the intended reclaimable collateral amount if ( IERC20Metadata(loan.collToken).balanceOf( transferInstructions.collReceiver ) != loan.initCollAmount + collReceiverPreBal ) { revert Errors.InvalidSendAmount(); } } if (grossCollTransferAmountToVault > 0) { // @dev: grossCollTransferAmountToVault can be zero in case no upfront fee and compartment is used if (expVaultCollBalIncrease == 0) { revert Errors.InconsistentExpVaultBalIncrease(); } uint256 vaultPreBal = IERC20Metadata(loan.collToken).balanceOf( lenderVault ); IERC20Metadata(loan.collToken).safeTransferFrom( loan.borrower, lenderVault, grossCollTransferAmountToVault ); if ( IERC20Metadata(loan.collToken).balanceOf(lenderVault) != vaultPreBal + expVaultCollBalIncrease ) { revert Errors.InvalidSendAmount(); } } } function _processRepayTransfers( address lenderVault, DataTypesPeerToPeer.LoanRepayInstructions memory loanRepayInstructions, DataTypesPeerToPeer.Loan memory loan, uint128 leftRepaymentAmount, uint128 reclaimCollAmount, bool noCompartment ) internal { noCompartment ? ILenderVaultImpl(lenderVault).transferTo( loan.collToken, loanRepayInstructions.callbackAddr == address(0) ? loan.borrower : loanRepayInstructions.callbackAddr, reclaimCollAmount ) : ILenderVaultImpl(lenderVault).transferCollFromCompartment( loanRepayInstructions.targetRepayAmount, leftRepaymentAmount, reclaimCollAmount, loan.borrower, loan.collToken, loanRepayInstructions.callbackAddr, loan.collTokenCompartmentAddr ); if (loanRepayInstructions.callbackAddr != address(0)) { IVaultCallback(loanRepayInstructions.callbackAddr).repayCallback( loan, loanRepayInstructions.callbackData ); } uint256 loanTokenReceived = IERC20Metadata(loan.loanToken).balanceOf( lenderVault ); IERC20Metadata(loan.loanToken).safeTransferFrom( loan.borrower, lenderVault, loanRepayInstructions.targetRepayAmount + loanRepayInstructions.expectedTransferFee ); loanTokenReceived = IERC20Metadata(loan.loanToken).balanceOf(lenderVault) - loanTokenReceived; if (loanTokenReceived != loanRepayInstructions.targetRepayAmount) { revert Errors.InvalidSendAmount(); } } function _checkDeadlineAndRegisteredVault( uint256 deadline, address lenderVault ) internal view { if (block.timestamp > deadline) { revert Errors.DeadlinePassed(); } if (!IAddressRegistry(addressRegistry).isRegisteredVault(lenderVault)) { revert Errors.UnregisteredVault(); } } function _calculateProtocolFeeAmount( uint128[2] memory _protocolFeeParams, uint256 collSendAmount, uint256 borrowDuration ) internal pure returns (uint256 protocolFeeAmount) { bool useMaxProtocolFee = _protocolFeeParams[0] + ((_protocolFeeParams[1] * borrowDuration) / Constants.YEAR_IN_SECONDS) > Constants.MAX_TOTAL_PROTOCOL_FEE; protocolFeeAmount = useMaxProtocolFee ? (collSendAmount * Constants.MAX_TOTAL_PROTOCOL_FEE) / Constants.BASE : ((_protocolFeeParams[0] * collSendAmount) / Constants.BASE) + ((collSendAmount * _protocolFeeParams[1] * borrowDuration) / (Constants.YEAR_IN_SECONDS * Constants.BASE)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol) pragma solidity ^0.8.0; import "./Ownable.sol"; /** * @dev Contract module which provides 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} and {acceptOwnership}. * * This module is used through inheritance. It will make available all functions * from parent (Ownable). */ abstract contract Ownable2Step is Ownable { address private _pendingOwner; event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { return _pendingOwner; } /** * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual override onlyOwner { _pendingOwner = newOwner; emit OwnershipTransferStarted(owner(), newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner. * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual override { delete _pendingOwner; super._transferOwnership(newOwner); } /** * @dev The new owner accepts the ownership transfer. */ function acceptOwnership() public virtual { address sender = _msgSender(); require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner"); _transferOwnership(sender); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (governance/utils/IVotes.sol) pragma solidity ^0.8.0; /** * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. * * _Available since v4.5._ */ interface IVotes { /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Returns the current amount of votes that `account` has. */ function getVotes(address account) external view returns (uint256); /** * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is * configured to use block numbers, this will return the value at the end of the corresponding block. */ function getPastVotes(address account, uint256 timepoint) external view returns (uint256); /** * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is * configured to use block numbers, this will return the value at the end of the corresponding block. * * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. * Votes that have not been delegated are still part of total supply, even though they would not participate in a * vote. */ function getPastTotalSupply(uint256 timepoint) external view returns (uint256); /** * @dev Returns the delegate that `account` has chosen. */ function delegates(address account) external view returns (address); /** * @dev Delegates votes from the sender to `delegatee`. */ function delegate(address delegatee) external; /** * @dev Delegates votes from signer to `delegatee`. */ function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes // of the `implementation` address with the bytecode before the address. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)) // Packs the remaining 17 bytes of `implementation` with the bytecode after the address. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)) instance := create(0, 0x09, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes // of the `implementation` address with the bytecode before the address. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)) // Packs the remaining 17 bytes of `implementation` with the bytecode after the address. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)) instance := create2(0, 0x09, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(add(ptr, 0x38), deployer) mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff) mstore(add(ptr, 0x14), implementation) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73) mstore(add(ptr, 0x58), salt) mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37)) predicted := keccak256(add(ptr, 0x43), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt ) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/Address.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) || (!Address.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; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
// 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; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (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. */ 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]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); } /** * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval * to be set to zero before setting it to a non-zero value, such as USDT. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } } /** * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. * Revert on invalid signature. */ function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: address zero is not a valid owner"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _ownerOf(tokenId); require(owner != address(0), "ERC721: invalid token ID"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { _requireMinted(tokenId); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not token owner or approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { _requireMinted(tokenId); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved"); _safeTransfer(from, to, tokenId, data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist */ function _ownerOf(uint256 tokenId) internal view virtual returns (address) { return _owners[tokenId]; } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _ownerOf(tokenId) != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { address owner = ERC721.ownerOf(tokenId); return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId, 1); // Check that tokenId was not minted by `_beforeTokenTransfer` hook require(!_exists(tokenId), "ERC721: token already minted"); unchecked { // Will not overflow unless all 2**256 token ids are minted to the same owner. // Given that tokens are minted one by one, it is impossible in practice that // this ever happens. Might change if we allow batch minting. // The ERC fails to describe this case. _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * This is an internal function that does not check if the sender is authorized to operate on the token. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId, 1); // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook owner = ERC721.ownerOf(tokenId); // Clear approvals delete _tokenApprovals[tokenId]; unchecked { // Cannot overflow, as that would require more tokens to be burned/transferred // out than the owner initially received through minting and transferring in. _balances[owner] -= 1; } delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId, 1); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId, 1); // Check that tokenId was not transferred by `_beforeTokenTransfer` hook require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); // Clear approvals from the previous owner delete _tokenApprovals[tokenId]; unchecked { // `_balances[from]` cannot overflow for the same reason as described in `_burn`: // `from`'s balance is the number of token held, which is at least one before the current // transfer. // `_balances[to]` could overflow in the conditions described in `_mint`. That would require // all 2**256 token ids to be minted, which in practice is impossible. _balances[from] -= 1; _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits an {ApprovalForAll} event. */ function _setApprovalForAll(address owner, address operator, bool approved) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Reverts if the `tokenId` has not been minted yet. */ function _requireMinted(uint256 tokenId) internal view virtual { require(_exists(tokenId), "ERC721: invalid token ID"); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { /// @solidity memory-safe-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`. * - When `from` is zero, the tokens will be minted for `to`. * - When `to` is zero, ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * - `batchSize` is non-zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {} /** * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`. * - When `from` is zero, the tokens were minted for `to`. * - When `to` is zero, ``from``'s tokens were burned. * - `from` and `to` are never both zero. * - `batchSize` is non-zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {} /** * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override. * * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such * that `ownerOf(tokenId)` is `a`. */ // solhint-disable-next-line func-name-mixedcase function __unsafe_increaseBalance(address account, uint256 amount) internal { _balances[account] += amount; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved"); _burn(tokenId); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721 * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must * understand this adds an external call which potentially creates a reentrancy vulnerability. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV // Deprecated in v4.8 } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) { // 32 is the length in bytes of hash, // enforced by the type signature above /// @solidity memory-safe-assembly assembly { mstore(0x00, "\x19Ethereum Signed Message:\n32") mstore(0x1c, hash) message := keccak256(0x00, 0x3c) } } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, "\x19\x01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) data := keccak256(ptr, 0x42) } } /** * @dev Returns an Ethereum Signed Data with intended validator, created from a * `validator` and `data` according to the version 0 of EIP-191. * * See {recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x00", validator, data)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Tree proofs. * * The tree and the proofs can be generated using our * https://github.com/OpenZeppelin/merkle-tree[JavaScript library]. * You will find a quickstart guide in the readme. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. * OpenZeppelin's JavaScript library generates merkle trees that are safe * against this attack out of the box. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Calldata version of {verify} * * _Available since v4.7._ */ function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProofCalldata(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Calldata version of {processProof} * * _Available since v4.7._ */ function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerify( bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProof(proof, proofFlags, leaves) == root; } /** * @dev Calldata version of {multiProofVerify} * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerifyCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProofCalldata(proof, proofFlags, leaves) == root; } /** * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false * respectively. * * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). * * _Available since v4.7._ */ function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { require(proofPos == proofLen, "MerkleProof: invalid multiproof"); unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Calldata version of {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function processMultiProofCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { require(proofPos == proofLen, "MerkleProof: invalid multiproof"); unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _efficientHash(a, b) : _efficientHash(b, a); } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1, "Math: mulDiv overflow"); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toUint248(uint256 value) internal pure returns (uint248) { require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits"); return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toUint240(uint256 value) internal pure returns (uint240) { require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits"); return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toUint232(uint256 value) internal pure returns (uint232) { require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits"); return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.2._ */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toUint216(uint256 value) internal pure returns (uint216) { require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits"); return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toUint208(uint256 value) internal pure returns (uint208) { require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits"); return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toUint200(uint256 value) internal pure returns (uint200) { require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits"); return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits"); return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toUint184(uint256 value) internal pure returns (uint184) { require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits"); return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toUint176(uint256 value) internal pure returns (uint176) { require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits"); return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toUint168(uint256 value) internal pure returns (uint168) { require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits"); return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits"); return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toUint152(uint256 value) internal pure returns (uint152) { require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits"); return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toUint144(uint256 value) internal pure returns (uint144) { require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits"); return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toUint136(uint256 value) internal pure returns (uint136) { require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits"); return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v2.5._ */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toUint120(uint256 value) internal pure returns (uint120) { require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits"); return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.2._ */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toUint88(uint256 value) internal pure returns (uint88) { require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits"); return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toUint80(uint256 value) internal pure returns (uint80) { require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits"); return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toUint72(uint256 value) internal pure returns (uint72) { require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits"); return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v2.5._ */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toUint56(uint256 value) internal pure returns (uint56) { require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits"); return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits"); return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toUint40(uint256 value) internal pure returns (uint40) { require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits"); return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v2.5._ */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toUint24(uint256 value) internal pure returns (uint24) { require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits"); return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v2.5._ */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v2.5._ */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. * * _Available since v3.0._ */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); require(downcasted == value, "SafeCast: value doesn't fit in 248 bits"); } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); require(downcasted == value, "SafeCast: value doesn't fit in 240 bits"); } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.7._ */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); require(downcasted == value, "SafeCast: value doesn't fit in 224 bits"); } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); require(downcasted == value, "SafeCast: value doesn't fit in 216 bits"); } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); require(downcasted == value, "SafeCast: value doesn't fit in 208 bits"); } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); require(downcasted == value, "SafeCast: value doesn't fit in 200 bits"); } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); require(downcasted == value, "SafeCast: value doesn't fit in 192 bits"); } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); require(downcasted == value, "SafeCast: value doesn't fit in 184 bits"); } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); require(downcasted == value, "SafeCast: value doesn't fit in 176 bits"); } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); require(downcasted == value, "SafeCast: value doesn't fit in 168 bits"); } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); require(downcasted == value, "SafeCast: value doesn't fit in 160 bits"); } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); require(downcasted == value, "SafeCast: value doesn't fit in 152 bits"); } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); require(downcasted == value, "SafeCast: value doesn't fit in 144 bits"); } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); require(downcasted == value, "SafeCast: value doesn't fit in 136 bits"); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); require(downcasted == value, "SafeCast: value doesn't fit in 128 bits"); } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); require(downcasted == value, "SafeCast: value doesn't fit in 120 bits"); } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); require(downcasted == value, "SafeCast: value doesn't fit in 112 bits"); } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.7._ */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); require(downcasted == value, "SafeCast: value doesn't fit in 88 bits"); } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); require(downcasted == value, "SafeCast: value doesn't fit in 80 bits"); } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); require(downcasted == value, "SafeCast: value doesn't fit in 72 bits"); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); require(downcasted == value, "SafeCast: value doesn't fit in 64 bits"); } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); require(downcasted == value, "SafeCast: value doesn't fit in 48 bits"); } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); require(downcasted == value, "SafeCast: value doesn't fit in 40 bits"); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); require(downcasted == value, "SafeCast: value doesn't fit in 32 bits"); } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); require(downcasted == value, "SafeCast: value doesn't fit in 16 bits"); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); require(downcasted == value, "SafeCast: value doesn't fit in 8 bits"); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. * * _Available since v3.0._ */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.0; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/Math.sol"; import "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant _SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toString(int256 value) internal pure returns (string memory) { return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value)))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } }
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.19; library Constants { uint256 internal constant YEAR_IN_SECONDS = 365 days; uint256 internal constant BASE = 1e18; uint256 internal constant MAX_FEE_PER_ANNUM = 0.05e18; // 5% max in base uint256 internal constant MAX_SWAP_PROTOCOL_FEE = 0.01e18; // 1% max in base uint256 internal constant MAX_TOTAL_PROTOCOL_FEE = 0.05e18; // 5% max in base uint256 internal constant MAX_P2POOL_PROTOCOL_FEE = 0.05e18; // 5% max in base uint256 internal constant MIN_TIME_BETWEEN_EARLIEST_REPAY_AND_EXPIRY = 1 days; uint256 internal constant MAX_PRICE_UPDATE_TIMESTAMP_DIVERGENCE = 1 days; uint256 internal constant SEQUENCER_GRACE_PERIOD = 1 hours; uint256 internal constant MIN_UNSUBSCRIBE_GRACE_PERIOD = 1 days; uint256 internal constant MAX_UNSUBSCRIBE_GRACE_PERIOD = 14 days; uint256 internal constant MIN_CONVERSION_GRACE_PERIOD = 1 days; uint256 internal constant MIN_REPAYMENT_GRACE_PERIOD = 1 days; uint256 internal constant LOAN_EXECUTION_GRACE_PERIOD = 1 days; uint256 internal constant MAX_CONVERSION_AND_REPAYMENT_GRACE_PERIOD = 30 days; uint256 internal constant MIN_TIME_UNTIL_FIRST_DUE_DATE = 1 days; uint256 internal constant MIN_TIME_BETWEEN_DUE_DATES = 7 days; uint256 internal constant MIN_WAIT_UNTIL_EARLIEST_UNSUBSCRIBE = 60 seconds; uint256 internal constant MAX_ARRANGER_FEE = 0.5e18; // 50% max in base uint256 internal constant LOAN_TERMS_UPDATE_COOL_OFF_PERIOD = 15 minutes; uint256 internal constant MAX_REPAYMENT_SCHEDULE_LENGTH = 20; uint256 internal constant SINGLE_WRAPPER_MIN_MINT = 1000; // in wei }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; library Errors { error UnregisteredVault(); error InvalidDelegatee(); error InvalidSender(); error InvalidFee(); error InsufficientSendAmount(); error NoOracle(); error InvalidOracleAnswer(); error InvalidOracleDecimals(); error InvalidOracleVersion(); error InvalidAddress(); error InvalidArrayLength(); error InvalidQuote(); error OutdatedQuote(); error InvalidOffChainSignature(); error InvalidOffChainMerkleProof(); error InvalidCollUnlock(); error InvalidAmount(); error UnknownOnChainQuote(); error NeitherTokenIsGOHM(); error NoLpTokens(); error ZeroReserve(); error IncorrectGaugeForLpToken(); error InvalidGaugeIndex(); error AlreadyStaked(); error InvalidWithdrawAmount(); error InvalidBorrower(); error OutsideValidRepayWindow(); error InvalidRepayAmount(); error ReclaimAmountIsZero(); error UnregisteredGateway(); error NonWhitelistedOracle(); error NonWhitelistedCompartment(); error NonWhitelistedCallback(); error NonWhitelistedToken(); error LtvHigherThanMax(); error InsufficientVaultFunds(); error InvalidInterestRateFactor(); error InconsistentUnlockTokenAddresses(); error InvalidEarliestRepay(); error InvalidNewMinNumOfSigners(); error AlreadySigner(); error InvalidArrayIndex(); error InvalidSignerRemoveInfo(); error InvalidSendAmount(); error TooSmallLoanAmount(); error DeadlinePassed(); error WithdrawEntered(); error DuplicateAddresses(); error OnChainQuoteAlreadyAdded(); error OffChainQuoteHasBeenInvalidated(); error Uninitialized(); error InvalidRepaymentScheduleLength(); error FirstDueDateTooCloseOrPassed(); error InvalidGracePeriod(); error UnregisteredLoanProposal(); error NotInSubscriptionPhase(); error NotInUnsubscriptionPhase(); error InsufficientBalance(); error InsufficientFreeSubscriptionSpace(); error BeforeEarliestUnsubscribe(); error InconsistentLastLoanTermsUpdateTime(); error InvalidActionForCurrentStatus(); error FellShortOfTotalSubscriptionTarget(); error InvalidRollBackRequest(); error UnsubscriptionAmountTooLarge(); error InvalidSubscriptionRange(); error InvalidMaxTotalSubscriptions(); error OutsideConversionTimeWindow(); error OutsideRepaymentTimeWindow(); error NoDefault(); error LoanIsFullyRepaid(); error RepaymentIdxTooLarge(); error AlreadyClaimed(); error AlreadyConverted(); error InvalidDueDates(); error LoanTokenDueIsZero(); error WaitForLoanTermsCoolOffPeriod(); error ZeroConversionAmount(); error InvalidNewOwnerProposal(); error CollateralMustBeCompartmentalized(); error InvalidCompartmentForToken(); error InvalidSignature(); error InvalidUpdate(); error CannotClaimOutdatedStatus(); error DelegateReducedBalance(); error FundingPoolAlreadyExists(); error InvalidLender(); error NonIncreasingTokenAddrs(); error NonIncreasingNonFungibleTokenIds(); error TransferToWrappedTokenFailed(); error TransferFromWrappedTokenFailed(); error StateAlreadySet(); error ReclaimableCollateralAmountZero(); error InvalidSwap(); error InvalidUpfrontFee(); error InvalidOracleTolerance(); error ReserveRatiosSkewedFromOraclePrice(); error SequencerDown(); error GracePeriodNotOver(); error LoanExpired(); error NoDsEth(); error TooShortTwapInterval(); error TooLongTwapInterval(); error TwapExceedsThreshold(); error Reentrancy(); error TokenNotStuck(); error InconsistentExpTransferFee(); error InconsistentExpVaultBalIncrease(); error DepositLockActive(); error DisallowedSubscriptionLockup(); error IncorrectLoanAmount(); error Disabled(); error CannotRemintUnlessZeroSupply(); error TokensStillMissingFromWrapper(); error OnlyMintFromSingleTokenWrapper(); error NonMintableTokenState(); error NoTokensTransferred(); error TokenAlreadyCountedInWrapper(); error TokenNotOwnedByWrapper(); error TokenDoesNotBelongInWrapper(address tokenAddr, uint256 tokenId); error InvalidMintAmount(); error QuoteViolatesPolicy(); error AlreadyPublished(); error PolicyAlreadySet(); error NoPolicyToDelete(); error InvalidTenorBounds(); error InvalidLtvBounds(); error InvalidLoanPerCollBounds(); error InvalidMinApr(); error NoPolicy(); error InvalidMinFee(); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; library Helpers { function splitSignature( bytes memory sig ) internal pure returns (bytes32 r, bytes32 vs) { require(sig.length == 64, "invalid signature length"); // solhint-disable no-inline-assembly assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes vs := mload(add(sig, 64)) } // implicitly return (r, vs) } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {DataTypesPeerToPeer} from "../peer-to-peer/DataTypesPeerToPeer.sol"; import {DataTypesPeerToPool} from "../peer-to-pool/DataTypesPeerToPool.sol"; interface IMysoTokenManager { function processP2PBorrow( uint128[2] memory currProtocolFeeParams, DataTypesPeerToPeer.BorrowTransferInstructions calldata borrowInstructions, DataTypesPeerToPeer.Loan calldata loan, address lenderVault ) external returns (uint128[2] memory applicableProtocolFeeParams); function processP2PCreateVault( uint256 numRegisteredVaults, address vaultCreator, address newLenderVaultAddr ) external; function processP2PCreateWrappedTokenForERC721s( address tokenCreator, DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped, bytes calldata mysoTokenManagerData ) external; function processP2PCreateWrappedTokenForERC20s( address tokenCreator, DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped, bytes calldata mysoTokenManagerData ) external; function processP2PoolDeposit( address fundingPool, address depositor, uint256 depositAmount, uint256 depositLockupDuration, uint256 transferFee ) external; function processP2PoolSubscribe( address fundingPool, address subscriber, address loanProposal, uint256 subscriptionAmount, uint256 subscriptionLockupDuration, uint256 totalSubscriptions, DataTypesPeerToPool.LoanTerms calldata loanTerms ) external; function processP2PoolLoanFinalization( address loanProposal, address fundingPool, address arranger, address borrower, uint256 grossLoanAmount, bytes calldata mysoTokenManagerData ) external; function processP2PoolCreateLoanProposal( address fundingPool, address proposalCreator, address collToken, uint256 arrangerFee, uint256 numLoanProposals ) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol"; import {DataTypesPeerToPeer} from "./DataTypesPeerToPeer.sol"; import {Errors} from "../Errors.sol"; import {Helpers} from "../Helpers.sol"; import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol"; import {IERC721Wrapper} from "./interfaces/wrappers/ERC721/IERC721Wrapper.sol"; import {IERC20Wrapper} from "./interfaces/wrappers/ERC20/IERC20Wrapper.sol"; import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol"; /** * @dev AddressRegistry is a contract that stores addresses of other contracts and controls whitelist state * IMPORTANT: This contract allows for de-whitelisting as well. This is an important security feature because if * a contract or token is found to present a vulnerability, it can be de-whitelisted to prevent further borrowing * with that token (repays and withdrawals would still be allowed). In the limit of a total de-whitelisting of all * tokens, all borrowing in the protocol would be paused. This feature can also be utilized if a fork with the same chainId is found. */ contract AddressRegistry is Initializable, Ownable2Step, IAddressRegistry { using ECDSA for bytes32; address public lenderVaultFactory; address public borrowerGateway; address public quoteHandler; address public mysoTokenManager; address public erc721Wrapper; address public erc20Wrapper; mapping(address => bool) public isRegisteredVault; mapping(bytes => bool) internal _signatureIsInvalidated; mapping(address => mapping(address => uint256)) internal _borrowerWhitelistedUntil; mapping(address => DataTypesPeerToPeer.WhitelistState) public whitelistState; // compartment => token => active mapping(address => mapping(address => bool)) internal _isTokenWhitelistedForCompartment; address[] internal _registeredVaults; constructor() { super._transferOwnership(msg.sender); } function initialize( address _lenderVaultFactory, address _borrowerGateway, address _quoteHandler ) external initializer { _checkOwner(); if ( _lenderVaultFactory == address(0) || _borrowerGateway == address(0) || _quoteHandler == address(0) ) { revert Errors.InvalidAddress(); } if ( _lenderVaultFactory == _borrowerGateway || _lenderVaultFactory == _quoteHandler || _borrowerGateway == _quoteHandler ) { revert Errors.DuplicateAddresses(); } lenderVaultFactory = _lenderVaultFactory; borrowerGateway = _borrowerGateway; quoteHandler = _quoteHandler; } function setWhitelistState( address[] calldata addrs, DataTypesPeerToPeer.WhitelistState state ) external { _checkIsInitialized(); _checkOwner(); uint256 addrsLen = addrs.length; if (addrsLen < 1) { revert Errors.InvalidArrayLength(); } ( address _erc721Wrapper, address _erc20Wrapper, address _mysoTokenManager ) = (erc721Wrapper, erc20Wrapper, mysoTokenManager); // note (1/2): ERC721WRAPPER, ERC20WRAPPER and MYSO_TOKEN_MANAGER state can only be "occupied" by // one addresses ("singleton state") if ( state == DataTypesPeerToPeer.WhitelistState.ERC721WRAPPER || state == DataTypesPeerToPeer.WhitelistState.ERC20WRAPPER || state == DataTypesPeerToPeer.WhitelistState.MYSO_TOKEN_MANAGER ) { if (addrsLen != 1) { revert Errors.InvalidArrayLength(); } if (addrs[0] == address(0)) { revert Errors.InvalidAddress(); } _updateSingletonAddr( addrs[0], state, _erc721Wrapper, _erc20Wrapper, _mysoTokenManager ); whitelistState[addrs[0]] = state; } else { // note (2/2): all other states can be "occupied" by multiple addresses for (uint256 i; i < addrsLen; ) { if (addrs[i] == address(0)) { revert Errors.InvalidAddress(); } if (whitelistState[addrs[i]] == state) { revert Errors.StateAlreadySet(); } // check if addr was singleton before and delete, if needed _checkAddrAndDeleteIfSingleton( addrs[i], _erc721Wrapper, _erc20Wrapper, _mysoTokenManager ); whitelistState[addrs[i]] = state; unchecked { ++i; } } } emit WhitelistStateUpdated(addrs, state); } function setAllowedTokensForCompartment( address compartmentImpl, address[] calldata tokens, bool allowTokensForCompartment ) external { _checkIsInitialized(); _checkOwner(); // check that tokens can only be whitelisted for valid compartment (whereas de-whitelisting is always possible) if ( allowTokensForCompartment && whitelistState[compartmentImpl] != DataTypesPeerToPeer.WhitelistState.COMPARTMENT ) { revert Errors.NonWhitelistedCompartment(); } uint256 tokensLen = tokens.length; if (tokensLen == 0) { revert Errors.InvalidArrayLength(); } for (uint256 i; i < tokensLen; ) { if (allowTokensForCompartment && !isWhitelistedERC20(tokens[i])) { revert Errors.NonWhitelistedToken(); } if ( _isTokenWhitelistedForCompartment[compartmentImpl][tokens[i]] == allowTokensForCompartment ) { revert Errors.InvalidUpdate(); } _isTokenWhitelistedForCompartment[compartmentImpl][ tokens[i] ] = allowTokensForCompartment; unchecked { ++i; } } emit AllowedTokensForCompartmentUpdated( compartmentImpl, tokens, allowTokensForCompartment ); } function addLenderVault(address addr) external returns (uint256) { _checkIsInitialized(); // catches case where address registry is uninitialized (lenderVaultFactory == address(0)) if (msg.sender != lenderVaultFactory) { revert Errors.InvalidSender(); } isRegisteredVault[addr] = true; _registeredVaults.push(addr); return _registeredVaults.length; } function claimBorrowerWhitelistStatus( address whitelistAuthority, uint256 whitelistedUntil, bytes calldata compactSig, bytes32 salt ) external { if (_signatureIsInvalidated[compactSig]) { revert Errors.InvalidSignature(); } bytes32 payloadHash = keccak256( abi.encode( address(this), msg.sender, whitelistedUntil, block.chainid, salt ) ); bytes32 messageHash = ECDSA.toEthSignedMessageHash(payloadHash); (bytes32 r, bytes32 vs) = Helpers.splitSignature(compactSig); address recoveredSigner = messageHash.recover(r, vs); if ( whitelistAuthority == address(0) || recoveredSigner != whitelistAuthority ) { revert Errors.InvalidSignature(); } mapping(address => uint256) storage whitelistedUntilPerBorrower = _borrowerWhitelistedUntil[ whitelistAuthority ]; if ( whitelistedUntil < block.timestamp || whitelistedUntil <= whitelistedUntilPerBorrower[msg.sender] ) { revert Errors.CannotClaimOutdatedStatus(); } whitelistedUntilPerBorrower[msg.sender] = whitelistedUntil; _signatureIsInvalidated[compactSig] = true; emit BorrowerWhitelistStatusClaimed( whitelistAuthority, msg.sender, whitelistedUntil ); } function createWrappedTokenForERC721s( DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped, string calldata name, string calldata symbol, bytes calldata mysoTokenManagerData ) external { address _erc721Wrapper = erc721Wrapper; if (_erc721Wrapper == address(0)) { revert Errors.InvalidAddress(); } if (mysoTokenManager != address(0)) { IMysoTokenManager(mysoTokenManager) .processP2PCreateWrappedTokenForERC721s( msg.sender, tokensToBeWrapped, mysoTokenManagerData ); } address newERC20Addr = IERC721Wrapper(_erc721Wrapper) .createWrappedToken(msg.sender, tokensToBeWrapped, name, symbol); whitelistState[newERC20Addr] = DataTypesPeerToPeer .WhitelistState .ERC20_TOKEN; emit CreatedWrappedTokenForERC721s( tokensToBeWrapped, name, symbol, newERC20Addr ); } function createWrappedTokenForERC20s( DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped, string calldata name, string calldata symbol, bytes calldata mysoTokenManagerData ) external { address _erc20Wrapper = erc20Wrapper; if (_erc20Wrapper == address(0)) { revert Errors.InvalidAddress(); } if (mysoTokenManager != address(0)) { IMysoTokenManager(mysoTokenManager) .processP2PCreateWrappedTokenForERC20s( msg.sender, tokensToBeWrapped, mysoTokenManagerData ); } address newERC20Addr = IERC20Wrapper(_erc20Wrapper).createWrappedToken( msg.sender, tokensToBeWrapped, name, symbol ); whitelistState[newERC20Addr] = DataTypesPeerToPeer .WhitelistState .ERC20_TOKEN; emit CreatedWrappedTokenForERC20s( tokensToBeWrapped, name, symbol, newERC20Addr ); } function updateBorrowerWhitelist( address[] calldata borrowers, uint256 whitelistedUntil ) external { uint256 borrowersLen = borrowers.length; if (borrowersLen == 0) { revert Errors.InvalidArrayLength(); } for (uint256 i; i < borrowersLen; ) { mapping(address => uint256) storage whitelistedUntilPerBorrower = _borrowerWhitelistedUntil[ msg.sender ]; if ( borrowers[i] == address(0) || whitelistedUntil == whitelistedUntilPerBorrower[borrowers[i]] ) { revert Errors.InvalidUpdate(); } whitelistedUntilPerBorrower[borrowers[i]] = whitelistedUntil; unchecked { ++i; } } emit BorrowerWhitelistUpdated(msg.sender, borrowers, whitelistedUntil); } function isWhitelistedBorrower( address whitelistAuthority, address borrower ) external view returns (bool) { return _borrowerWhitelistedUntil[whitelistAuthority][borrower] >= block.timestamp; } function isWhitelistedCompartment( address compartment, address token ) external view returns (bool) { return whitelistState[compartment] == DataTypesPeerToPeer.WhitelistState.COMPARTMENT && _isTokenWhitelistedForCompartment[compartment][token]; } function registeredVaults() external view returns (address[] memory) { return _registeredVaults; } function numRegisteredVaults() external view returns (uint256) { return _registeredVaults.length; } function transferOwnership( address _newOwnerProposal ) public override(Ownable2Step, IAddressRegistry) { _checkIsInitialized(); if ( _newOwnerProposal == address(this) || _newOwnerProposal == pendingOwner() || _newOwnerProposal == owner() ) { revert Errors.InvalidNewOwnerProposal(); } // @dev: access control check via super.transferOwnership() super.transferOwnership(_newOwnerProposal); } function owner() public view override(Ownable, IAddressRegistry) returns (address) { return super.owner(); } function pendingOwner() public view override(Ownable2Step, IAddressRegistry) returns (address) { return super.pendingOwner(); } function isWhitelistedERC20(address token) public view returns (bool) { DataTypesPeerToPeer.WhitelistState tokenWhitelistState = whitelistState[ token ]; return tokenWhitelistState == DataTypesPeerToPeer.WhitelistState.ERC20_TOKEN || tokenWhitelistState == DataTypesPeerToPeer .WhitelistState .ERC20_TOKEN_REQUIRING_COMPARTMENT; } function renounceOwnership() public pure override { revert Errors.Disabled(); } function _updateSingletonAddr( address newAddr, DataTypesPeerToPeer.WhitelistState state, address _erc721Wrapper, address _erc20Wrapper, address _mysoTokenManager ) internal { // check if address already has given state set or // other singleton addresses occupy target state if ( whitelistState[newAddr] == state || whitelistState[_erc721Wrapper] == state || whitelistState[_erc20Wrapper] == state || whitelistState[_mysoTokenManager] == state ) { revert Errors.StateAlreadySet(); } // check if addr was singleton before and delete, if needed _checkAddrAndDeleteIfSingleton( newAddr, _erc721Wrapper, _erc20Wrapper, _mysoTokenManager ); if (state == DataTypesPeerToPeer.WhitelistState.ERC721WRAPPER) { erc721Wrapper = newAddr; } else if (state == DataTypesPeerToPeer.WhitelistState.ERC20WRAPPER) { erc20Wrapper = newAddr; } else { mysoTokenManager = newAddr; } } function _checkAddrAndDeleteIfSingleton( address addr, address _erc721Wrapper, address _erc20Wrapper, address _mysoTokenManager ) internal { if (addr == _erc721Wrapper) { delete erc721Wrapper; } else if (addr == _erc20Wrapper) { delete erc20Wrapper; } else if (addr == _mysoTokenManager) { delete mysoTokenManager; } } function _checkIsInitialized() internal view { if (_getInitializedVersion() == 0) { revert Errors.Uninitialized(); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {IERC20Metadata, IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {BalancerDataTypes} from "../interfaces/callbacks/BalancerDataTypes.sol"; import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol"; import {VaultCallback} from "./VaultCallback.sol"; import {IBalancerAsset} from "../interfaces/callbacks/IBalancerAsset.sol"; import {IBalancerVault} from "../interfaces/callbacks/IBalancerVault.sol"; import {IVaultCallback} from "../interfaces/IVaultCallback.sol"; contract BalancerV2Looping is VaultCallback { using SafeERC20 for IERC20Metadata; address private constant BALANCER_V2_VAULT = 0xBA12222222228d8Ba445958a75a0704d566BF2C8; constructor(address _borrowerGateway) VaultCallback(_borrowerGateway) {} // solhint-disable no-empty-blocks function borrowCallback( DataTypesPeerToPeer.Loan calldata loan, bytes calldata data ) external { BalancerDataTypes.FundManagement memory fundManagement = BalancerDataTypes.FundManagement({ sender: address(this), // swap payer fromInternalBalance: false, // use payer's internal balance recipient: payable(loan.borrower), // swap receiver toInternalBalance: false // user receiver's internal balance }); (bytes32 poolId, uint256 minSwapReceive, uint256 deadline) = abi.decode( data, (bytes32, uint256, uint256) ); // swap whole loan token balance received from borrower gateway uint256 loanTokenBalance = IERC20(loan.loanToken).balanceOf( address(this) ); IERC20Metadata(loan.loanToken).safeIncreaseAllowance( BALANCER_V2_VAULT, loanTokenBalance ); BalancerDataTypes.SingleSwap memory singleSwap = BalancerDataTypes .SingleSwap({ poolId: poolId, kind: BalancerDataTypes.SwapKind.GIVEN_IN, assetIn: IBalancerAsset(loan.loanToken), assetOut: IBalancerAsset(loan.collToken), amount: loanTokenBalance, userData: "" }); IBalancerVault(BALANCER_V2_VAULT).swap( singleSwap, fundManagement, minSwapReceive, deadline ); IERC20Metadata(loan.loanToken).safeDecreaseAllowance( BALANCER_V2_VAULT, IERC20Metadata(loan.loanToken).allowance( address(this), BALANCER_V2_VAULT ) ); } function _repayCallback( DataTypesPeerToPeer.Loan calldata loan, bytes calldata data ) internal override { BalancerDataTypes.FundManagement memory fundManagement = BalancerDataTypes.FundManagement({ sender: address(this), // swap payer fromInternalBalance: false, // use payer's internal balance recipient: payable(loan.borrower), // swap receiver toInternalBalance: false // user receiver's internal balance }); (bytes32 poolId, uint256 minSwapReceive, uint256 deadline) = abi.decode( data, (bytes32, uint256, uint256) ); // swap whole coll token balance received from borrower gateway uint256 collBalance = IERC20(loan.collToken).balanceOf(address(this)); BalancerDataTypes.SingleSwap memory singleSwap = BalancerDataTypes .SingleSwap({ poolId: poolId, kind: BalancerDataTypes.SwapKind.GIVEN_IN, assetIn: IBalancerAsset(loan.collToken), assetOut: IBalancerAsset(loan.loanToken), amount: collBalance, userData: "" }); IERC20Metadata(loan.collToken).safeIncreaseAllowance( BALANCER_V2_VAULT, collBalance ); IBalancerVault(BALANCER_V2_VAULT).swap( singleSwap, fundManagement, minSwapReceive, deadline ); IERC20Metadata(loan.collToken).safeDecreaseAllowance( BALANCER_V2_VAULT, IERC20Metadata(loan.collToken).allowance( address(this), BALANCER_V2_VAULT ) ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {IERC20Metadata, IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol"; import {VaultCallback} from "./VaultCallback.sol"; import {ISwapRouter} from "../interfaces/callbacks/ISwapRouter.sol"; import {IVaultCallback} from "../interfaces/IVaultCallback.sol"; contract UniV3Looping is VaultCallback { using SafeERC20 for IERC20Metadata; address private constant UNI_V3_SWAP_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564; constructor(address _borrowerGateway) VaultCallback(_borrowerGateway) {} // solhint-disable no-empty-blocks function borrowCallback( DataTypesPeerToPeer.Loan calldata loan, bytes calldata data ) external { (uint256 minSwapReceive, uint256 deadline, uint24 poolFee) = abi.decode( data, (uint256, uint256, uint24) ); // swap whole loan token balance received from borrower gateway uint256 loanTokenBalance = IERC20(loan.loanToken).balanceOf( address(this) ); IERC20Metadata(loan.loanToken).safeIncreaseAllowance( UNI_V3_SWAP_ROUTER, loanTokenBalance ); ISwapRouter.ExactInputSingleParams memory params = ISwapRouter .ExactInputSingleParams({ tokenIn: loan.loanToken, tokenOut: loan.collToken, fee: poolFee, recipient: loan.borrower, deadline: deadline, amountIn: loanTokenBalance, amountOutMinimum: minSwapReceive, sqrtPriceLimitX96: 0 }); ISwapRouter(UNI_V3_SWAP_ROUTER).exactInputSingle(params); IERC20Metadata(loan.loanToken).safeDecreaseAllowance( UNI_V3_SWAP_ROUTER, IERC20Metadata(loan.loanToken).allowance( address(this), UNI_V3_SWAP_ROUTER ) ); } function _repayCallback( DataTypesPeerToPeer.Loan calldata loan, bytes calldata data ) internal override { (uint256 minSwapReceive, uint256 deadline, uint24 poolFee) = abi.decode( data, (uint256, uint256, uint24) ); // swap whole coll token balance received from borrower gateway uint256 collTokenBalance = IERC20(loan.collToken).balanceOf( address(this) ); IERC20Metadata(loan.collToken).safeIncreaseAllowance( UNI_V3_SWAP_ROUTER, collTokenBalance ); ISwapRouter.ExactInputSingleParams memory params = ISwapRouter .ExactInputSingleParams({ tokenIn: loan.collToken, tokenOut: loan.loanToken, fee: poolFee, recipient: loan.borrower, deadline: deadline, amountIn: collTokenBalance, amountOutMinimum: minSwapReceive, sqrtPriceLimitX96: 0 }); ISwapRouter(UNI_V3_SWAP_ROUTER).exactInputSingle(params); IERC20Metadata(loan.collToken).safeDecreaseAllowance( UNI_V3_SWAP_ROUTER, IERC20Metadata(loan.collToken).allowance( address(this), UNI_V3_SWAP_ROUTER ) ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol"; import {Errors} from "../../Errors.sol"; import {IVaultCallback} from "../interfaces/IVaultCallback.sol"; abstract contract VaultCallback is IVaultCallback { address public immutable borrowerGateway; constructor(address _borrowerGateway) { if (_borrowerGateway == address(0)) { revert Errors.InvalidAddress(); } borrowerGateway = _borrowerGateway; } function repayCallback( DataTypesPeerToPeer.Loan calldata loan, bytes calldata data ) external { if (msg.sender != borrowerGateway) { revert Errors.InvalidSender(); } _repayCallback(loan, data); } function _repayCallback( DataTypesPeerToPeer.Loan calldata loan, bytes calldata data ) internal virtual {} // solhint-disable no-empty-blocks }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IBaseCompartment} from "../interfaces/compartments/IBaseCompartment.sol"; import {ILenderVaultImpl} from "../interfaces/ILenderVaultImpl.sol"; import {Errors} from "../../Errors.sol"; abstract contract BaseCompartment is Initializable, IBaseCompartment { using SafeERC20 for IERC20; address public vaultAddr; uint256 public loanIdx; constructor() { _disableInitializers(); } function initialize( address _vaultAddr, uint256 _loanIdx ) external initializer { if (_vaultAddr == address(0)) { revert Errors.InvalidAddress(); } vaultAddr = _vaultAddr; loanIdx = _loanIdx; } // transfer coll on repays function _transferCollFromCompartment( uint128 reclaimCollAmount, address borrowerAddr, address collTokenAddr, address callbackAddr ) internal { _withdrawCheck(); if (msg.sender != vaultAddr) revert Errors.InvalidSender(); address collReceiver = callbackAddr == address(0) ? borrowerAddr : callbackAddr; IERC20(collTokenAddr).safeTransfer(collReceiver, reclaimCollAmount); } function _unlockCollToVault(address collTokenAddr) internal { _withdrawCheck(); if (msg.sender != vaultAddr) revert Errors.InvalidSender(); uint256 currentCollBalance = IERC20(collTokenAddr).balanceOf( address(this) ); IERC20(collTokenAddr).safeTransfer(msg.sender, currentCollBalance); } function _withdrawCheck() internal view { bool withdrawEntered = ILenderVaultImpl(vaultAddr).withdrawEntered(); if (withdrawEntered) { revert Errors.WithdrawEntered(); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {BaseCompartment} from "../BaseCompartment.sol"; contract AaveStakingCompartment is BaseCompartment { using SafeERC20 for IERC20; // transfer coll on repays function transferCollFromCompartment( uint256 /*repayAmount*/, uint256 /*repayAmountLeft*/, uint128 reclaimCollAmount, address borrowerAddr, address collTokenAddr, address callbackAddr ) external { _transferCollFromCompartment( reclaimCollAmount, borrowerAddr, collTokenAddr, callbackAddr ); } // unlockColl this would be called on defaults function unlockCollToVault(address collTokenAddr) external { _unlockCollToVault(collTokenAddr); } function getReclaimableBalance( address collToken ) external view override returns (uint256) { return IERC20(collToken).balanceOf(address(this)); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ICurveStakingHelper} from "../../interfaces/compartments/staking/ICurveStakingHelper.sol"; import {ILenderVaultImpl} from "../../interfaces/ILenderVaultImpl.sol"; import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol"; import {BaseCompartment} from "../BaseCompartment.sol"; import {Errors} from "../../../Errors.sol"; contract CurveLPStakingCompartment is BaseCompartment { using SafeERC20 for IERC20; address public liqGaugeAddr; address internal constant CRV_ADDR = 0xD533a949740bb3306d119CC777fa900bA034cd52; address internal constant GAUGE_CONTROLLER = 0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB; address internal constant CRV_MINTER_ADDR = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; mapping(address => bool) public approvedStaker; function stake(uint256 gaugeIndex) external { DataTypesPeerToPeer.Loan memory loan = ILenderVaultImpl(vaultAddr).loan( loanIdx ); if (msg.sender != loan.borrower && !approvedStaker[msg.sender]) { revert Errors.InvalidSender(); } if (block.timestamp >= loan.expiry) { revert Errors.LoanExpired(); } if (liqGaugeAddr != address(0)) { revert Errors.AlreadyStaked(); } uint256 amount = IERC20(loan.collToken).balanceOf(address(this)); address _liqGaugeAddr = ICurveStakingHelper(GAUGE_CONTROLLER).gauges( gaugeIndex ); if (_liqGaugeAddr == address(0)) { revert Errors.InvalidGaugeIndex(); } address lpTokenAddrForGauge = ICurveStakingHelper(_liqGaugeAddr) .lp_token(); if (lpTokenAddrForGauge != loan.collToken) { revert Errors.IncorrectGaugeForLpToken(); } liqGaugeAddr = _liqGaugeAddr; IERC20(loan.collToken).safeIncreaseAllowance(_liqGaugeAddr, amount); ICurveStakingHelper(_liqGaugeAddr).deposit(amount); IERC20(loan.collToken).safeDecreaseAllowance( _liqGaugeAddr, IERC20(loan.collToken).allowance(address(this), _liqGaugeAddr) ); emit Staked(gaugeIndex, _liqGaugeAddr, amount); } function toggleApprovedStaker(address _staker) external { DataTypesPeerToPeer.Loan memory loan = ILenderVaultImpl(vaultAddr).loan( loanIdx ); if (msg.sender != loan.borrower) { revert Errors.InvalidSender(); } bool currStakingState = approvedStaker[_staker]; approvedStaker[_staker] = !currStakingState; emit UpdatedApprovedStaker(_staker, !currStakingState); } // transfer coll on repays function transferCollFromCompartment( uint256 repayAmount, uint256 repayAmountLeft, uint128 /*reclaimCollAmount*/, address borrowerAddr, address collTokenAddr, address callbackAddr ) external { _collAccountingHelper( repayAmount, repayAmountLeft, 0, borrowerAddr, collTokenAddr, callbackAddr, false ); } // unlockColl this would be called on defaults function unlockCollToVault(address collTokenAddr) external { _collAccountingHelper( 1, 1, 0, address(0), collTokenAddr, address(0), true ); } function getReclaimableBalance( address collToken ) external view override returns (uint256 reclaimableCollBalance) { reclaimableCollBalance = IERC20(collToken).balanceOf(address(this)); address _liqGaugeAddr = liqGaugeAddr; if (_liqGaugeAddr != address(0)) { reclaimableCollBalance += IERC20(_liqGaugeAddr).balanceOf( address(this) ); } } function _getRewardTokensAndWithdrawFromGauge( address _liqGaugeAddr, uint256 repayAmount, uint256 repayAmountLeft ) internal returns (address[8] memory _rewardTokenAddr) { uint256 currentStakedBal = IERC20(_liqGaugeAddr).balanceOf( address(this) ); // withdraw proportion of gauge amount uint256 withdrawAmount = Math.mulDiv( repayAmount, currentStakedBal, repayAmountLeft ); ICurveStakingHelper(CRV_MINTER_ADDR).mint(_liqGaugeAddr); try ICurveStakingHelper(_liqGaugeAddr).reward_tokens(0) returns ( address rewardTokenAddrZeroIndex ) { // versions 2, 3, 4, or 5 _rewardTokenAddr[0] = rewardTokenAddrZeroIndex; address rewardTokenAddr; for (uint256 i; i < 7; ) { rewardTokenAddr = ICurveStakingHelper(_liqGaugeAddr) .reward_tokens(i + 1); if (rewardTokenAddr != address(0)) { _rewardTokenAddr[i + 1] = rewardTokenAddr; } else { break; } unchecked { ++i; } } try ICurveStakingHelper(_liqGaugeAddr).withdraw( withdrawAmount, true ) // solhint-disable no-empty-blocks { // version 3, 4, or 5 gauge } catch { // version 2 gauge if (_rewardTokenAddr[0] != address(0)) { ICurveStakingHelper(_liqGaugeAddr).claim_rewards(); } ICurveStakingHelper(_liqGaugeAddr).withdraw(withdrawAmount); } } catch { // version 1 gauge ICurveStakingHelper(_liqGaugeAddr).withdraw(withdrawAmount); } } function _collAccountingHelper( uint256 repayAmount, uint256 repayAmountLeft, uint128 /*reclaimableCollBalance*/, address borrowerAddr, address collTokenAddr, address callbackAddr, bool isUnlock ) internal returns (uint128 lpTokenAmount) { _withdrawCheck(); if (msg.sender != vaultAddr) revert Errors.InvalidSender(); address _liqGaugeAddr = liqGaugeAddr; // if gaugeAddr has been set, withdraw from gauge and get reward token addresses address[8] memory _rewardTokenAddr; if (_liqGaugeAddr != address(0)) { _rewardTokenAddr = _getRewardTokensAndWithdrawFromGauge( _liqGaugeAddr, repayAmount, repayAmountLeft ); } // now check lp token balance of compartment which will be portion unstaked (could have never been staked) uint256 currentCompartmentBal = IERC20(collTokenAddr).balanceOf( address(this) ); // transfer proportion of compartment lp token balance if never staked or an unlock, else all balance if staked lpTokenAmount = SafeCast.toUint128( isUnlock || _liqGaugeAddr != address(0) ? currentCompartmentBal : Math.mulDiv( repayAmount, currentCompartmentBal, repayAmountLeft ) ); // if unlock, send to vault (msg.sender), else if callback send directly there, else to borrower address lpTokenReceiver = isUnlock ? msg.sender : (callbackAddr == address(0) ? borrowerAddr : callbackAddr); IERC20(collTokenAddr).safeTransfer(lpTokenReceiver, lpTokenAmount); if (_liqGaugeAddr != address(0)) { _transferRewards( isUnlock, borrowerAddr, repayAmount, repayAmountLeft, collTokenAddr, _rewardTokenAddr ); } } function _transferRewards( bool isUnlock, address borrowerAddr, uint256 repayAmount, uint256 repayAmountLeft, address collTokenAddr, address[8] memory _rewardTokenAddr ) internal { // rest of rewards are always sent to borrower, not for callback // if unlock then sent to vaultAddr (msg.sender) address rewardReceiver = isUnlock ? msg.sender : borrowerAddr; // check crv token balance uint256 currentCrvBal = IERC20(CRV_ADDR).balanceOf(address(this)); // transfer proportion of crv token balance uint256 tokenAmount = isUnlock ? currentCrvBal : Math.mulDiv(repayAmount, currentCrvBal, repayAmountLeft); // only perform crv transfer if // 1) crv token amount > 0 and coll token is not CRV else skip // if unlock, still ok to skip since then all balance would have been // transferred to vault earlier in this _getRewardTokensAndWithdrawFromGauge function // note: this should never actually happen since crv // and this compartment should not be whitelisted, but just in case if (tokenAmount > 0 && CRV_ADDR != collTokenAddr) { IERC20(CRV_ADDR).safeTransfer(rewardReceiver, tokenAmount); } uint256 i; uint256 currentRewardTokenBal; while (i < 8 && _rewardTokenAddr[i] != address(0)) { // skip invalid reward tokens if (_checkIfValidRewardToken(collTokenAddr, i, _rewardTokenAddr)) { currentRewardTokenBal = IERC20(_rewardTokenAddr[i]).balanceOf( address(this) ); tokenAmount = isUnlock ? currentRewardTokenBal : Math.mulDiv( repayAmount, currentRewardTokenBal, repayAmountLeft ); if (tokenAmount > 0) { IERC20(_rewardTokenAddr[i]).safeTransfer( rewardReceiver, tokenAmount ); } } unchecked { ++i; } } } function _checkIfValidRewardToken( address collTokenAddr, uint256 index, address[8] memory rewardTokens ) internal pure returns (bool) { // invalid reward if it is equal to collateral or crv token if ( rewardTokens[index] == collTokenAddr || rewardTokens[index] == CRV_ADDR ) { return false; } // check if reward token is a duplicate in previous entries if (index > 0) { for (uint256 i; i < index; ) { if (rewardTokens[i] == rewardTokens[index]) { return false; } unchecked { ++i; } } } return true; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IGLPStakingHelper} from "../../interfaces/compartments/staking/IGLPStakingHelper.sol"; import {BaseCompartment} from "../BaseCompartment.sol"; contract GLPStakingCompartment is BaseCompartment { using SafeERC20 for IERC20; // arbitrum WETH address address private constant WETH = 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1; address private constant FEE_GLP = 0x4e971a87900b931fF39d1Aad67697F49835400b6; // transfer coll on repays function transferCollFromCompartment( uint256 repayAmount, uint256 repayAmountLeft, uint128 reclaimCollAmount, address borrowerAddr, address collTokenAddr, address callbackAddr ) external { _transferCollFromCompartment( reclaimCollAmount, borrowerAddr, collTokenAddr, callbackAddr ); _transferRewards( collTokenAddr, borrowerAddr, repayAmount, repayAmountLeft, false ); } // unlockColl this would be called on defaults function unlockCollToVault(address collTokenAddr) external { _unlockCollToVault(collTokenAddr); _transferRewards(collTokenAddr, vaultAddr, 0, 0, true); } function getReclaimableBalance( address collToken ) external view override returns (uint256) { return IERC20(collToken).balanceOf(address(this)); } function _transferRewards( address collTokenAddr, address recipient, uint256 repayAmount, uint256 repayAmountLeft, bool isUnlock ) internal { // if collTokenAddr is weth, then return so don't double transfer on partial repay // or waste gas on unlock when no rewards will be paid out // note: this should never actually happen since weth // and this compartment should not be whitelisted, but just in case if (collTokenAddr == WETH) { return; } // solhint-disable no-empty-blocks try IGLPStakingHelper(FEE_GLP).claim(address(this)) { // do nothing // solhint-disable no-empty-blocks } catch { // do nothing } // check weth token balance uint256 currentWethBal = IERC20(WETH).balanceOf(address(this)); // transfer proportion of weth token balance uint256 wethTokenAmount = isUnlock ? currentWethBal : Math.mulDiv(repayAmount, currentWethBal, repayAmountLeft); IERC20(WETH).safeTransfer(recipient, wethTokenAmount); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IVotes} from "@openzeppelin/contracts/governance/utils/IVotes.sol"; import {IAddressRegistry} from "../../interfaces/IAddressRegistry.sol"; import {ILenderVaultImpl} from "../../interfaces/ILenderVaultImpl.sol"; import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol"; import {BaseCompartment} from "../BaseCompartment.sol"; import {Errors} from "../../../Errors.sol"; contract VoteCompartment is BaseCompartment { using SafeERC20 for IERC20; mapping(address => bool) public approvedDelegator; function delegate(address _delegatee) external { DataTypesPeerToPeer.Loan memory loan = ILenderVaultImpl(vaultAddr).loan( loanIdx ); if (msg.sender != loan.borrower && !approvedDelegator[msg.sender]) { revert Errors.InvalidSender(); } if (block.timestamp >= loan.expiry) { revert Errors.LoanExpired(); } if (_delegatee == address(0)) { revert Errors.InvalidDelegatee(); } uint256 preDelegateCompartmentBal = IERC20(loan.collToken).balanceOf( address(this) ); IVotes(loan.collToken).delegate(_delegatee); if ( preDelegateCompartmentBal > IERC20(loan.collToken).balanceOf(address(this)) ) { revert Errors.DelegateReducedBalance(); } emit Delegated(msg.sender, _delegatee); } function toggleApprovedDelegator(address _delegate) external { DataTypesPeerToPeer.Loan memory loan = ILenderVaultImpl(vaultAddr).loan( loanIdx ); if (msg.sender != loan.borrower) { revert Errors.InvalidSender(); } bool currDelegateState = approvedDelegator[_delegate]; approvedDelegator[_delegate] = !currDelegateState; emit UpdatedApprovedDelegator(_delegate, !currDelegateState); } // transfer coll on repays function transferCollFromCompartment( uint256 /*repayAmount*/, uint256 /*repayAmountLeft*/, uint128 reclaimCollAmount, address borrowerAddr, address collTokenAddr, address callbackAddr ) external { _transferCollFromCompartment( reclaimCollAmount, borrowerAddr, collTokenAddr, callbackAddr ); } // unlockColl this would be called on defaults function unlockCollToVault(address collTokenAddr) external { _unlockCollToVault(collTokenAddr); } function getReclaimableBalance( address collToken ) external view override returns (uint256) { return IERC20(collToken).balanceOf(address(this)); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; library DataTypesPeerToPeer { struct Loan { // address of borrower address borrower; // address of coll token address collToken; // address of loan token address loanToken; // timestamp after which any portion of loan unpaid defaults uint40 expiry; // timestamp before which borrower cannot repay uint40 earliestRepay; // initial collateral amount of loan uint128 initCollAmount; // loan amount given uint128 initLoanAmount; // full repay amount at start of loan uint128 initRepayAmount; // amount repaid (loan token) up until current time // note: partial repayments are allowed uint128 amountRepaidSoFar; // amount reclaimed (coll token) up until current time // note: partial repayments are allowed uint128 amountReclaimedSoFar; // flag tracking if collateral has been unlocked by vault bool collUnlocked; // address of the compartment housing the collateral address collTokenCompartmentAddr; } struct QuoteTuple { // loan amount per one unit of collateral if no oracle // LTV in terms of the constant BASE (10 ** 18) if using oracle uint256 loanPerCollUnitOrLtv; // interest rate percentage in BASE (can be negative but greater than -BASE) // i.e. -100% < interestRatePct since repay amount of 0 is not allowed // also interestRatePctInBase is not annualized int256 interestRatePctInBase; // fee percentage,in BASE, which will be paid in upfront in collateral uint256 upfrontFeePctInBase; // length of the loan in seconds uint256 tenor; } struct GeneralQuoteInfo { // address of collateral token address collToken; // address of loan token address loanToken; // address of oracle (optional) address oracleAddr; // min loan amount (in loan token) prevent griefing attacks or // amounts lender feels isn't worth unlocking on default uint256 minLoan; // max loan amount (in loan token) if lender wants a cap uint256 maxLoan; // timestamp after which quote automatically invalidates uint256 validUntil; // time, in seconds, that loan cannot be exercised uint256 earliestRepayTenor; // address of compartment implementation (optional) address borrowerCompartmentImplementation; // will invalidate quote after one use // if false, will be a standing quote bool isSingleUse; // whitelist address (optional) address whitelistAddr; // flag indicating whether whitelistAddr refers to a single whitelisted // borrower or to a whitelist authority that can whitelist multiple addresses bool isWhitelistAddrSingleBorrower; } struct OnChainQuote { // general quote info GeneralQuoteInfo generalQuoteInfo; // array of quote parameters QuoteTuple[] quoteTuples; // provides more distinguishability of quotes to reduce // likelihood of collisions w.r.t. quote creations and invalidations bytes32 salt; } struct OffChainQuote { // general quote info GeneralQuoteInfo generalQuoteInfo; // root of the merkle tree, where the merkle tree encodes all QuoteTuples the lender accepts bytes32 quoteTuplesRoot; // provides more distinguishability of quotes to reduce // likelihood of collisions w.r.t. quote creations and invalidations bytes32 salt; // for invalidating multiple parallel quotes in one click uint256 nonce; // array of compact signatures from vault signers bytes[] compactSigs; } struct LoanRepayInstructions { // loan id being repaid uint256 targetLoanId; // repay amount after transfer fees in loan token uint128 targetRepayAmount; // expected transfer fees in loan token (=0 for tokens without transfer fee) // note: amount that borrower sends is targetRepayAmount + expectedTransferFee uint128 expectedTransferFee; // deadline to prevent stale transactions uint256 deadline; // e.g., for using collateral to payoff debt via DEX address callbackAddr; // any data needed by callback bytes callbackData; } struct BorrowTransferInstructions { // amount of collateral sent uint256 collSendAmount; // sum of (i) protocol fee and (ii) transfer fees (if any) associated with sending any collateral to vault uint256 expectedProtocolAndVaultTransferFee; // transfer fees associated with sending any collateral to compartment (if used) uint256 expectedCompartmentTransferFee; // deadline to prevent stale transactions uint256 deadline; // slippage protection if oracle price is too loose uint256 minLoanAmount; // e.g., for one-click leverage address callbackAddr; // any data needed by callback bytes callbackData; // any data needed by myso token manager bytes mysoTokenManagerData; } struct TransferInstructions { // collateral token receiver address collReceiver; // effective upfront fee in collateral tokens (vault or compartment) uint256 upfrontFee; } struct WrappedERC721TokenInfo { // address of the ERC721_TOKEN address tokenAddr; // array of ERC721_TOKEN ids uint256[] tokenIds; } struct WrappedERC20TokenInfo { // token addresse address tokenAddr; // token amounts uint256 tokenAmount; } struct OnChainQuoteInfo { // hash of on chain quote bytes32 quoteHash; // valid until timestamp uint256 validUntil; } enum WhitelistState { // not whitelisted NOT_WHITELISTED, // can be used as loan or collateral token ERC20_TOKEN, // can be be used as oracle ORACLE, // can be used as compartment COMPARTMENT, // can be used as callback contract CALLBACK, // can be used as loan or collateral token, but if collateral then must // be used in conjunction with a compartment (e.g., for stETH with possible // negative rebase that could otherwise affect other borrowers in the vault) ERC20_TOKEN_REQUIRING_COMPARTMENT, // can be used in conjunction with an ERC721 wrapper ERC721_TOKEN, // can be used as ERC721 wrapper contract ERC721WRAPPER, // can be used as ERC20 wrapper contract ERC20WRAPPER, // can be used as MYSO token manager contract MYSO_TOKEN_MANAGER, // can be used as quote policy manager contract QUOTE_POLICY_MANAGER } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {IBalancerAsset} from "./IBalancerAsset.sol"; library BalancerDataTypes { enum SwapKind { GIVEN_IN, GIVEN_OUT } struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } struct SingleSwap { bytes32 poolId; SwapKind kind; IBalancerAsset assetIn; IBalancerAsset assetOut; uint256 amount; bytes userData; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface IBalancerAsset { // solhint-disable-previous-line no-empty-blocks }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {BalancerDataTypes} from "./BalancerDataTypes.sol"; interface IBalancerVault { function swap( BalancerDataTypes.SingleSwap memory singleSwap, BalancerDataTypes.FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface ISwapRouter { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } function exactInputSingle( ExactInputSingleParams calldata params ) external payable returns (uint256 amountOut); function exactInput( ExactInputParams calldata params ) external payable returns (uint256 amountOut); function exactOutputSingle( ExactOutputSingleParams calldata params ) external payable returns (uint256 amountIn); function exactOutput( ExactOutputParams calldata params ) external payable returns (uint256 amountIn); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface IBaseCompartment { event Staked(uint256 gaugeIndex, address liqGaugeAddr, uint256 amount); event Delegated(address delegator, address delegatee); event UpdatedApprovedStaker(address staker, bool approvalState); event UpdatedApprovedDelegator(address delegator, bool approvalState); /** * @notice function to initialize collateral compartment * @dev factory creates clone and then initializes implementation contract * @param vaultAddr address of vault * @param loanId index of the loan */ function initialize(address vaultAddr, uint256 loanId) external; /** * @notice function to transfer some amount of collateral to borrower on repay * @dev this function can only be called by vault and tranfers proportional amount * of compartment collTokenBalance to borrower address. This needs use a proportion * and not the amount to account for possible changes due to rewards accruing * @param repayAmount amount of loan token to be repaid * @param repayAmountLeft amount of loan token still outstanding * @param reclaimCollAmount amount of collateral token to be reclaimed * @param borrowerAddr address of borrower receiving transfer * @param collTokenAddr address of collateral token being transferred * @param callbackAddr address to send collateral to instead of borrower if using callback */ function transferCollFromCompartment( uint256 repayAmount, uint256 repayAmountLeft, uint128 reclaimCollAmount, address borrowerAddr, address collTokenAddr, address callbackAddr ) external; /** * @notice function to unlock all collateral left in compartment * @dev this function can only be called by vault and returns all collateral to vault * @param collTokenAddr pass in collToken addr to avoid callback reads gas cost */ function unlockCollToVault(address collTokenAddr) external; /** * @notice function returns the potentially reclaimable collateral token balance * @param collTokenAddr address of collateral token for which reclaimable balance is being retrieved * @dev depending on compartment implementation this could be simple balanceOf or eg staked balance call */ function getReclaimableBalance( address collTokenAddr ) external view returns (uint256 reclaimableBalance); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; interface ICurveStakingHelper { /** * @notice Deposit `value` LP tokens, curve type take pools * @param value Number of tokens to deposit */ function deposit(uint256 value) external; /** * @notice Withdraw `value` LP tokens, curve type take pools * @dev This withdraw function is for gauges v1 and v2 * @param value Number of tokens to withdraw */ function withdraw(uint256 value) external; /** * @notice Withdraw `value` LP tokens, curve type take pools * @dev This withdraw function is for gauges v3, v4 and v5 * @param value Number of tokens to withdraw * @param withdrawRewards true if withdrawing rewards */ function withdraw(uint256 value, bool withdrawRewards) external; /** * @notice Claim all available reward tokens for msg.sender */ function claim_rewards() external; /** * @notice Mint allocated tokens for the caller based on a single gauge. * @param gaugeAddr address to get mintable amount from */ function mint(address gaugeAddr) external; /** * @notice returns lpToken address for gauge */ function lp_token() external view returns (address); /** * @notice returns reward token address for liquidity gauge by index * @param index index of particular token address in the reward token array */ function reward_tokens(uint256 index) external view returns (address); /** * @notice returns gauge address by index from gaugeController * @param index index in gauge controller array that returns liquidity gauge address */ function gauges(uint256 index) external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; interface IGLPStakingHelper { /** * @notice Claim fee reward tokens * @param _receiver address which is recipient of the claim */ function claim(address _receiver) external returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol"; interface IAddressRegistry { event WhitelistStateUpdated( address[] indexed whitelistAddrs, DataTypesPeerToPeer.WhitelistState indexed whitelistState ); event AllowedTokensForCompartmentUpdated( address indexed compartmentImpl, address[] tokens, bool isWhitelisted ); event BorrowerWhitelistStatusClaimed( address indexed whitelistAuthority, address indexed borrower, uint256 whitelistedUntil ); event BorrowerWhitelistUpdated( address indexed whitelistAuthority, address[] borrowers, uint256 whitelistedUntil ); event CreatedWrappedTokenForERC721s( DataTypesPeerToPeer.WrappedERC721TokenInfo[] wrappedTokensInfo, string name, string symbol, address newErc20Addr ); event CreatedWrappedTokenForERC20s( DataTypesPeerToPeer.WrappedERC20TokenInfo[] wrappedTokensInfo, string name, string symbol, address newERC20Addr ); /** * @notice initializes factory, gateway, and quote handler contracts * @param _lenderVaultFactory address of the factory for lender vaults * @param _borrowerGateway address of the gateway with which borrowers interact * @param _quoteHandler address of contract which handles quote logic */ function initialize( address _lenderVaultFactory, address _borrowerGateway, address _quoteHandler ) external; /** * @notice adds new lender vault to registry * @dev can only be called lender vault factory * @param addr address of new lender vault * @return numRegisteredVaults number of registered vaults */ function addLenderVault( address addr ) external returns (uint256 numRegisteredVaults); /** * @notice Allows user to claim whitelisted status * @param whitelistAuthority Address of whitelist authorithy * @param whitelistedUntil Timestamp until when user is whitelisted * @param compactSig Compact signature from whitelist authority * @param salt Salt to make signature unique */ function claimBorrowerWhitelistStatus( address whitelistAuthority, uint256 whitelistedUntil, bytes calldata compactSig, bytes32 salt ) external; /** * @notice Allows user to wrap (multiple) ERC721 into one ERC20 * @param tokensToBeWrapped Array of WrappedERC721TokenInfo * @param name Name of the new wrapper token * @param symbol Symbol of the new wrapper token * @param mysoTokenManagerData Data to be passed to MysoTokenManager */ function createWrappedTokenForERC721s( DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped, string calldata name, string calldata symbol, bytes calldata mysoTokenManagerData ) external; /** * @notice Allows user to wrap multiple ERC20 into one ERC20 * @param tokensToBeWrapped Array of WrappedERC20TokenInfo * @param name Name of the new wrapper token * @param symbol Symbol of the new wrapper token * @param mysoTokenManagerData Data to be passed to MysoTokenManager */ function createWrappedTokenForERC20s( DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped, string calldata name, string calldata symbol, bytes calldata mysoTokenManagerData ) external; /** * @notice Allows a whitelist authority to set the whitelistedUntil state for a given borrower * @dev Anyone can create their own whitelist, and lenders can decide if and which whitelist they want to use * @param borrowers Array of borrower addresses * @param whitelistedUntil Timestamp until which borrowers shall be whitelisted under given whitelist authority */ function updateBorrowerWhitelist( address[] calldata borrowers, uint256 whitelistedUntil ) external; /** * @notice Sets the whitelist state for a given address * @dev Can only be called by registry owner * @param addrs Addresses for which whitelist state shall be set * @param whitelistState The whitelist state to which addresses shall be set */ function setWhitelistState( address[] calldata addrs, DataTypesPeerToPeer.WhitelistState whitelistState ) external; /** * @notice Sets the allowed tokens for a given compartment implementation * @dev Can only be called by registry owner * @param compartmentImpl Compartment implementations for which allowed tokens shall be set * @param tokens List of tokens that shall be allowed for given compartment implementation * @param allowTokensForCompartment Boolean flag indicating whether tokens shall be allowed for compartment implementation */ function setAllowedTokensForCompartment( address compartmentImpl, address[] calldata tokens, bool allowTokensForCompartment ) external; /** * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current owner. * @param newOwner the proposed new owner address */ function transferOwnership(address newOwner) external; /** * @notice Returns boolean flag indicating whether the borrower has been whitelisted by whitelistAuthority * @param whitelistAuthority Addresses of the whitelist authority * @param borrower Addresses of the borrower * @return Boolean flag indicating whether the borrower has been whitelisted by whitelistAuthority */ function isWhitelistedBorrower( address whitelistAuthority, address borrower ) external view returns (bool); /** * @notice Returns boolean flag indicating whether token is whitelisted * @param token Addresses of the given token to check * @return Boolean flag indicating whether the token is whitelisted */ function isWhitelistedERC20(address token) external view returns (bool); /** * @notice Returns the address of the vault factory * @return Address of the vault factory contract */ function lenderVaultFactory() external view returns (address); /** * @notice Returns the address of the borrower gateway * @return Address of the borrower gateway contract */ function borrowerGateway() external view returns (address); /** * @notice Returns the address of the quote handler * @return Address of the quote handler contract */ function quoteHandler() external view returns (address); /** * @notice Returns the address of the MYSO token manager * @return Address of the MYSO token manager contract */ function mysoTokenManager() external view returns (address); /** * @notice Returns boolean flag indicating whether given address is a registered vault * @param addr Address to check if it is a registered vault * @return Boolean flag indicating whether given address is a registered vault */ function isRegisteredVault(address addr) external view returns (bool); /** * @notice Returns whitelist state for given address * @param addr Address to check whitelist state for * @return whitelistState Whitelist state for given address */ function whitelistState( address addr ) external view returns (DataTypesPeerToPeer.WhitelistState whitelistState); /** * @notice Returns an array of registered vault addresses * @return vaultAddrs The array of registered vault addresses */ function registeredVaults() external view returns (address[] memory vaultAddrs); /** * @notice Returns address of the owner * @return Address of the owner */ function owner() external view returns (address); /** * @notice Returns address of the pending owner * @return Address of the pending owner */ function pendingOwner() external view returns (address); /** * @notice Returns boolean flag indicating whether given compartment implementation and token combination is whitelisted * @param compartmentImpl Address of compartment implementation to check if it is allowed for token * @param token Address of token to check if compartment implementation is allowed * @return isWhitelisted Boolean flag indicating whether compartment implementation is whitelisted for given token */ function isWhitelistedCompartment( address compartmentImpl, address token ) external view returns (bool isWhitelisted); /** * @notice Returns current number of vaults registered * @return numVaults Current number of vaults registered */ function numRegisteredVaults() external view returns (uint256 numVaults); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol"; interface IBorrowerGateway { event Borrowed( address indexed vaultAddr, address indexed borrower, DataTypesPeerToPeer.Loan loan, uint256 upfrontFee, uint256 indexed loanId, address callbackAddr, bytes callbackData ); event Repaid( address indexed vaultAddr, uint256 indexed loanId, uint256 repayAmount ); event ProtocolFeeSet(uint128[2] newFeeParams); /** * @notice function which allows a borrower to use an offChain quote to borrow * @param lenderVault address of the vault whose owner(s) signed the offChain quote * @param borrowInstructions data needed for borrow (see DataTypesPeerToPeer comments) * @param offChainQuote quote data (see DataTypesPeerToPeer comments) * @param quoteTuple quote data (see DataTypesPeerToPeer comments) * @param proof array of bytes needed for merkle tree verification of quote * @return loan data */ function borrowWithOffChainQuote( address lenderVault, DataTypesPeerToPeer.BorrowTransferInstructions calldata borrowInstructions, DataTypesPeerToPeer.OffChainQuote calldata offChainQuote, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple, bytes32[] memory proof ) external returns (DataTypesPeerToPeer.Loan memory); /** * @notice function which allows a borrower to use an onChain quote to borrow * @param lenderVault address of the vault whose owner(s) enacted onChain quote * @param borrowInstructions data needed for borrow (see DataTypesPeerToPeer comments) * @param onChainQuote quote data (see DataTypesPeerToPeer comments) * @param quoteTupleIdx index of quote tuple array * @return loan data */ function borrowWithOnChainQuote( address lenderVault, DataTypesPeerToPeer.BorrowTransferInstructions calldata borrowInstructions, DataTypesPeerToPeer.OnChainQuote calldata onChainQuote, uint256 quoteTupleIdx ) external returns (DataTypesPeerToPeer.Loan memory); /** * @notice function which allows a borrower to repay a loan * @param loanRepayInstructions data needed for loan repay (see DataTypesPeerToPeer comments) * @param vaultAddr address of the vault in which loan was taken out */ function repay( DataTypesPeerToPeer.LoanRepayInstructions calldata loanRepayInstructions, address vaultAddr ) external; /** * @notice function which allows owner to set new protocol fee params * @dev protocolFee params are in units of BASE constant (10**18) and variable portion is annualized * @param _newFeeParams new base fee (constant) and fee slope (variable) in BASE */ function setProtocolFeeParams(uint128[2] calldata _newFeeParams) external; /** * @notice function returns address registry * @return address of registry */ function addressRegistry() external view returns (address); /** * @notice function returns protocol fee * @return protocolFeeParams protocol fee Params in Base */ function getProtocolFeeParams() external view returns (uint128[2] memory protocolFeeParams); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface ILenderVaultFactory { event NewVaultCreated( address indexed newLenderVaultAddr, address vaultOwner, uint256 numRegisteredVaults ); /** * @notice function creates new lender vaults * @param salt salt used for deterministic cloning * @return newLenderVaultAddr address of created vault */ function createVault( bytes32 salt ) external returns (address newLenderVaultAddr); /** * @notice function returns address registry * @return address of registry */ function addressRegistry() external view returns (address); /** * @notice function returns address of lender vault implementation contract * @return address of lender vault implementation */ function lenderVaultImpl() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol"; interface ILenderVaultImpl { event AddedSigners(address[] _signers); event MinNumberOfSignersSet(uint256 minNumSigners); event RemovedSigner( address signerRemoved, uint256 signerIdx, address signerMovedFromEnd ); event CollateralUnlocked( address indexed vaultOwner, address indexed collToken, uint256[] loanIds, uint256 amountUnlocked ); event QuoteProcessed( uint256 netPledgeAmount, DataTypesPeerToPeer.TransferInstructions transferInstructions ); event Withdrew(address indexed tokenAddr, uint256 withdrawAmount); event CircuitBreakerUpdated( address indexed newCircuitBreaker, address indexed oldCircuitBreaker ); event ReverseCircuitBreakerUpdated( address indexed newReverseCircuitBreaker, address indexed oldReverseCircuitBreaker ); event OnChainQuotingDelegateUpdated( address indexed newOnChainQuotingDelegate, address indexed oldOnChainQuotingDelegate ); /** * @notice function to initialize lender vault * @dev factory creates clone and then initializes the vault * @param vaultOwner address of vault owner * @param addressRegistry registry address */ function initialize(address vaultOwner, address addressRegistry) external; /** * @notice function to unlock defaulted collateral * @dev only loans with same collateral token can be unlocked in one call * function will revert if mismatch in coll token to a loan.collToken. * @param collToken address of the collateral token * @param _loanIds array of indices of the loans to unlock */ function unlockCollateral( address collToken, uint256[] calldata _loanIds ) external; /** * @notice function to update loan info on a reoay * @dev only borrower gateway can call this function * loanId is needed by vault to store updated loan info * @param repayAmount amount of loan repaid * @param loanId index of loan in loans array * @param collAmount amount of collateral to unlock * @param noCompartment boolean flag indicating whether loan has no compartment * @param collToken address of the collateral token */ function updateLoanInfo( uint128 repayAmount, uint256 loanId, uint128 collAmount, bool noCompartment, address collToken ) external; /** * @notice function to processQuote on a borrow * @dev only borrower gateway can call this function * @param borrower address of the borrower * @param borrowInstructions struct containing all info for borrow (see DataTypesPeerToPeer.sol notes) * @param generalQuoteInfo struct containing quote info (see Datatypes.sol notes) * @param quoteTuple struct containing specific quote tuple info (see DataTypesPeerToPeer.sol notes) * @return loan loan information after processing the quote * @return loanId index of loans in the loans array * @return transferInstructions struct containing transfer instruction info (see DataTypesPeerToPeer.sol notes) */ function processQuote( address borrower, DataTypesPeerToPeer.BorrowTransferInstructions calldata borrowInstructions, DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple ) external returns ( DataTypesPeerToPeer.Loan calldata loan, uint256 loanId, DataTypesPeerToPeer.TransferInstructions memory transferInstructions ); /** * @notice function to withdraw a token from a vault * @dev only vault owner can withdraw * @param token address of the token to withdraw * @param amount amount of token to withdraw */ function withdraw(address token, uint256 amount) external; /** * @notice function to transfer token from vault * @dev only borrow gateway can call this function * @param token address of the token to transfer * @param recipient address which receives the tokens * @param amount amount of token to transfer */ function transferTo( address token, address recipient, uint256 amount ) external; /** * @notice function to transfer token from a compartment * @dev only borrow gateway can call this function, if callbackAddr, then * the collateral will be transferred to the callback address * @param repayAmount amount of loan token to be repaid * @param repayAmountLeft amount of loan token still outstanding * @param reclaimCollAmount amount of collateral to be reclaimed * @param borrowerAddr address of the borrower * @param collTokenAddr address of the coll token to transfer to compartment * @param callbackAddr address of callback * @param collTokenCompartmentAddr address of the coll token compartment */ function transferCollFromCompartment( uint256 repayAmount, uint256 repayAmountLeft, uint128 reclaimCollAmount, address borrowerAddr, address collTokenAddr, address callbackAddr, address collTokenCompartmentAddr ) external; /** * @notice function to set minimum number of signers required for an offchain quote * @dev this function allows a multi-sig quorum to sign a quote offchain * @param _minNumOfSigners minimum number of signatures borrower needs to provide */ function setMinNumOfSigners(uint256 _minNumOfSigners) external; /** * @notice function to add a signer * @dev this function only can be called by vault owner * @param _signers array of signers to add */ function addSigners(address[] calldata _signers) external; /** * @notice function to remove a signer * @dev this function only can be called by vault owner * @param signer address of signer to be removed * @param signerIdx index of the signers array at which signer resides */ function removeSigner(address signer, uint256 signerIdx) external; /** * @notice function to set a circuit breaker * @dev the circuit breaker (and vault owner) can pause all loan offers; * note: circuit breaker and reverse circuit breaker can be the same account * @param circuitBreaker address of the circuit breaker */ function setCircuitBreaker(address circuitBreaker) external; /** * @notice function to set a reverse circuit breaker * @dev the reverse circuit breaker (and vault owner) can unpause all loan offers; * note: circuit breaker and reverse circuit breaker can be the same account * @param reverseCircuitBreaker address of the reverse circuit breaker */ function setReverseCircuitBreaker(address reverseCircuitBreaker) external; /** * @notice function to set a delegate for on chain quoting * @dev the quote handler (and vault owner) can add, delete and update on chain quotes * @param onChainQuotingDelegate address of the delegate */ function setOnChainQuotingDelegate(address onChainQuotingDelegate) external; /** * @notice function to pause all quotes from lendervault * @dev only vault owner and circuit breaker can pause quotes */ function pauseQuotes() external; /** * @notice function to unpause all quotes from lendervault * @dev only vault owner and reverse circuit breaker can unpause quotes again */ function unpauseQuotes() external; /** * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current owner. * @param newOwner the proposed new owner address */ function transferOwnership(address newOwner) external; /** * @notice function to retrieve loan from loans array in vault * @dev this function reverts on invalid index * @param index index of loan * @return loan loan stored at that index in vault */ function loan( uint256 index ) external view returns (DataTypesPeerToPeer.Loan memory loan); /** * @notice function to return owner address * @return owner address */ function owner() external view returns (address); /** * @notice Returns address of the pending owner * @return Address of the pending owner */ function pendingOwner() external view returns (address); /** * @notice function to return the total number of signers * @return number of signers */ function totalNumSigners() external view returns (uint256); /** * @notice function to return unlocked token balances * @param tokens array of token addresses * @return balances the vault balances of the token addresses * @return _lockedAmounts the vault locked amounts of the token addresses */ function getTokenBalancesAndLockedAmounts( address[] calldata tokens ) external view returns (uint256[] memory balances, uint256[] memory _lockedAmounts); /** * @notice function to return address of registry * @return registry address */ function addressRegistry() external view returns (address); /** * @notice function to return address of the circuit breaker * @return circuit breaker address */ function circuitBreaker() external view returns (address); /** * @notice function to return address of the reverse circuit breaker * @return reverse circuit breaker address */ function reverseCircuitBreaker() external view returns (address); /** * @notice function to return address of the delegate for on chain quoting * @return approved delegate address */ function onChainQuotingDelegate() external view returns (address); /** * @notice function returns signer at given index * @param index of the signers array * @return signer address */ function signers(uint256 index) external view returns (address); /** * @notice function returns minimum number of signers * @return minimum number of signers */ function minNumOfSigners() external view returns (uint256); /** * @notice function returns if address is a signer * @return true, if a signer, else false */ function isSigner(address signer) external view returns (bool); /** * @notice function returns if withdraw mutex is activated * @return true, if withdraw already called, else false */ function withdrawEntered() external view returns (bool); /** * @notice function returns current locked amounts of given token * @param token address of the token * @return amount of token locked */ function lockedAmounts(address token) external view returns (uint256); /** * @notice function returns total number of loans * @return total number of loans */ function totalNumLoans() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface IOracle { /** * @notice function checks oracle validity and calculates collTokenPriceInLoanToken * @param collToken address of coll token * @param loanToken address of loan token * @return collTokenPriceInLoanToken collateral price denominated in loan token */ function getPrice( address collToken, address loanToken ) external view returns (uint256 collTokenPriceInLoanToken); /** * @notice function checks oracle validity and retrieves prices in base currency unit * @param collToken address of coll token * @param loanToken address of loan token * @return collTokenPriceRaw and loanTokenPriceRaw denominated in base currency unit */ function getRawPrices( address collToken, address loanToken ) external view returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol"; interface IQuoteHandler { event OnChainQuoteAdded( address indexed lenderVault, DataTypesPeerToPeer.OnChainQuote onChainQuote, bytes32 indexed onChainQuoteHash ); event OnChainQuoteDeleted( address indexed lenderVault, bytes32 indexed onChainQuoteHash ); event OnChainQuoteInvalidated( address indexed lenderVault, bytes32 indexed onChainQuoteHash ); event OffChainQuoteNonceIncremented( address indexed lenderVault, uint256 newNonce ); event OffChainQuoteInvalidated( address indexed lenderVault, bytes32 indexed offChainQuoteHash ); event OnChainQuoteUsed( address indexed lenderVault, bytes32 indexed onChainQuoteHash, uint256 indexed toBeRegisteredLoanId, uint256 quoteTupleIdx ); event OffChainQuoteUsed( address indexed lenderVault, bytes32 indexed offChainQuoteHash, uint256 indexed toBeRegisteredLoanId, DataTypesPeerToPeer.QuoteTuple quoteTuple ); event QuotePolicyManagerUpdated( address indexed lenderVault, address indexed newPolicyManagerAddress ); event OnChainQuotePublished( DataTypesPeerToPeer.OnChainQuote onChainQuote, bytes32 indexed onChainQuoteHash, address indexed proposer ); event OnChainQuoteCopied( address indexed lenderVault, bytes32 indexed onChainQuoteHash ); /** * @notice function adds on chain quote * @dev function can only be called by vault owner or on chain quote delegate * @param lenderVault address of the vault adding quote * @param onChainQuote data for the onChain quote (See notes in DataTypesPeerToPeer.sol) */ function addOnChainQuote( address lenderVault, DataTypesPeerToPeer.OnChainQuote calldata onChainQuote ) external; /** * @notice function updates on chain quote * @dev function can only be called by vault owner or on chain quote delegate * @param lenderVault address of the vault updating quote * @param oldOnChainQuoteHash quote hash for the old onChain quote marked for deletion * @param newOnChainQuote data for the new onChain quote (See notes in DataTypesPeerToPeer.sol) */ function updateOnChainQuote( address lenderVault, bytes32 oldOnChainQuoteHash, DataTypesPeerToPeer.OnChainQuote calldata newOnChainQuote ) external; /** * @notice function deletes on chain quote * @dev function can only be called by vault owner or on chain quote delegate * @param lenderVault address of the vault deleting * @param onChainQuoteHash quote hash for the onChain quote marked for deletion */ function deleteOnChainQuote( address lenderVault, bytes32 onChainQuoteHash ) external; /** * @notice function to copy a published on chain quote * @dev function can only be called by vault owner or on chain quote delegate * @param lenderVault address of the vault approving * @param onChainQuoteHash quote hash of a published onChain quote */ function copyPublishedOnChainQuote( address lenderVault, bytes32 onChainQuoteHash ) external; /** * @notice function to publish an on chain quote * @dev function can be called by anyone and used by any vault * @param onChainQuote data for the onChain quote (See notes in DataTypesPeerToPeer.sol) */ function publishOnChainQuote( DataTypesPeerToPeer.OnChainQuote calldata onChainQuote ) external; /** * @notice function increments the nonce for a vault * @dev function can only be called by vault owner * incrementing the nonce can bulk invalidate any * off chain quotes with that nonce in one txn * @param lenderVault address of the vault */ function incrementOffChainQuoteNonce(address lenderVault) external; /** * @notice function invalidates off chain quote * @dev function can only be called by vault owner * this function invalidates one specific quote * @param lenderVault address of the vault * @param offChainQuoteHash hash of the off chain quote to be invalidated */ function invalidateOffChainQuote( address lenderVault, bytes32 offChainQuoteHash ) external; /** * @notice function performs checks on quote and, if valid, updates quotehandler's state * @dev function can only be called by borrowerGateway * @param borrower address of borrower * @param lenderVault address of the vault * @param quoteTupleIdx index of the quote tuple in the vault's quote array * @param onChainQuote data for the onChain quote (See notes in DataTypesPeerToPeer.sol) */ function checkAndRegisterOnChainQuote( address borrower, address lenderVault, uint256 quoteTupleIdx, DataTypesPeerToPeer.OnChainQuote memory onChainQuote ) external; /** * @notice function performs checks on quote and, if valid, updates quotehandler's state * @dev function can only be called by borrowerGateway * @param borrower address of borrower * @param lenderVault address of the vault * @param offChainQuote data for the offChain quote (See notes in DataTypesPeerToPeer.sol) * @param quoteTuple quote data (see notes in DataTypesPeerToPeer.sol) * @param proof array of bytes needed to verify merkle proof */ function checkAndRegisterOffChainQuote( address borrower, address lenderVault, DataTypesPeerToPeer.OffChainQuote calldata offChainQuote, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple, bytes32[] memory proof ) external; /** * @notice function to update the quote policy manager for a vault * @param lenderVault address for which quote policy manager is being updated * @param newPolicyManagerAddress address of new quote policy manager * @dev function can only be called by vault owner */ function updateQuotePolicyManagerForVault( address lenderVault, address newPolicyManagerAddress ) external; /** * @notice function to return address of registry * @return registry address */ function addressRegistry() external view returns (address); /** * @notice function to return the current nonce for offchain quotes * @param lender address for which nonce is being retrieved * @return current value of nonce */ function offChainQuoteNonce(address lender) external view returns (uint256); /** * @notice function returns if offchain quote hash is invalidated * @param lenderVault address of vault * @param hashToCheck hash of the offchain quote * @return true if invalidated, else false */ function offChainQuoteIsInvalidated( address lenderVault, bytes32 hashToCheck ) external view returns (bool); /** * @notice function returns if hash is for an on chain quote * @param lenderVault address of vault * @param hashToCheck hash of the on chain quote * @return true if hash belongs to a valid on-chain quote, else false */ function isOnChainQuote( address lenderVault, bytes32 hashToCheck ) external view returns (bool); /** * @notice function returns if hash belongs to a published on chain quote * @param hashToCheck hash of the on chain quote * @return true if hash belongs to a published on-chain quote, else false */ function isPublishedOnChainQuote( bytes32 hashToCheck ) external view returns (bool); /** * @notice function returns valid until timestamp of the published on-chain quote * @param hashToCheck hash of the on chain quote * @return valid until timestamp of the published on-chain quote */ function publishedOnChainQuoteValidUntil( bytes32 hashToCheck ) external view returns (uint256); /** * @notice function returns the address of the policy manager for a vault * @param lenderVault address of vault * @return address of quote policy manager for vault * @dev if policy manager address changes in registry, this function will still return the old address * unless and until the vault owner calls updateQuotePolicyManagerForVault */ function quotePolicyManagerForVault( address lenderVault ) external view returns (address); /** * @notice function returns element of on-chain history * @param lenderVault address of vault * @return element of on-chain quote history */ function getOnChainQuoteHistory( address lenderVault, uint256 idx ) external view returns (DataTypesPeerToPeer.OnChainQuoteInfo memory); /** * @notice function returns array of structs containing the on-chain quote hash and validUntil timestamp * @param lenderVault address of vault * @param startIdx starting index from on chain quote history array * @param endIdx ending index of on chain quote history array (non-inclusive) * @return array of quote hash and validUntil data for on-chain quote history of a vault */ function getOnChainQuoteHistorySlice( address lenderVault, uint256 startIdx, uint256 endIdx ) external view returns (DataTypesPeerToPeer.OnChainQuoteInfo[] memory); /** * @notice function returns the number of on-chain quotes that were added or updated * @param lenderVault address of vault * @return number of on-chain quotes that were added or updated */ function getOnChainQuoteHistoryLength( address lenderVault ) external view returns (uint256); }
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.19; import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol"; interface IVaultCallback { /** * @notice function which handles borrow side callback * @param loan loan data passed to the callback * @param data any extra info needed for the callback functionality */ function borrowCallback( DataTypesPeerToPeer.Loan calldata loan, bytes calldata data ) external; /** * @notice function which handles repay side callback * @param loan loan data passed to the callback * @param data any extra info needed for the callback functionality */ function repayCallback( DataTypesPeerToPeer.Loan calldata loan, bytes calldata data ) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; interface AggregatorV3Interface { function decimals() external view returns (uint8); 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 ); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; interface IDSETH { /** * @notice gets addresses of all components * @return array of token addresses */ function getComponents() external view returns (address[] memory); /** * @notice checks if token is a component * @param _token token address * @return true if token is a component */ function isComponent(address _token) external view returns (bool); /** * @notice gets the unit of token used in price calculation * @param _token token address * @return unit of token */ function getTotalComponentRealUnits( address _token ) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; interface IOlympus { /** * @notice index is used to convert from sOhm to gOhm */ function index() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; interface IUniV2 { /** * @notice returns reserves of uni v2 pool * @return token0 reserves * @return token1 reserves * @return timestamp */ function getReserves() external view returns (uint112, uint112, uint32); /** * @notice token0 address of pool */ function token0() external view returns (address); /** * @notice token1 address of pool */ function token1() external view returns (address); /** * @notice totalSupply of the lp token */ function totalSupply() external view returns (uint256); /** * @notice decimals of the lp token */ function decimals() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; interface ITwapGetter { /** * @dev returns the twap for the given uniswap v3 pool * @param inToken Address of the In Token * @param outToken Address of the Out Token * @param twapInterval Time interval for the twap * @param uniswapV3Pool Address of the Uniswap V3 Pool * @return twap The twap (in out token) for the given uniswap v3 pool */ function getTwap( address inToken, address outToken, uint32 twapInterval, address uniswapV3Pool ) external view returns (uint256 twap); /** * @dev returns the sqrt twap for the given uniswap v3 pool * @param uniswapV3Pool Address of the Uniswap V3 Pool * @param twapInterval Time interval for the twap * @return sqrtTwapPriceX96 The sqrt twap for the given uniswap v3 pool */ function getSqrtTwapX96( address uniswapV3Pool, uint32 twapInterval ) external view returns (uint160 sqrtTwapPriceX96); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {DataTypesBasicPolicies} from "../../policyManagers/DataTypesBasicPolicies.sol"; import {IQuotePolicyManager} from "./IQuotePolicyManager.sol"; interface IBasicQuotePolicyManager is IQuotePolicyManager { /** * @notice Retrieve the global quoting policy for a specific lender's vault * @param lenderVault The address of the lender's vault * @return The global quoting policy for the specified lender's vault */ function globalQuotingPolicy( address lenderVault ) external view returns (DataTypesBasicPolicies.GlobalPolicy memory); /** * @notice Retrieve the quoting policy for a specific lending pair involving collateral and loan tokens * @param lenderVault The address of the lender's vault * @param collToken The address of the collateral token * @param loanToken The address of the loan token * @return The quoting policy for the specified lender's vault, collateral, and loan tokens */ function pairQuotingPolicy( address lenderVault, address collToken, address loanToken ) external view returns (DataTypesBasicPolicies.PairPolicy memory); /** * @notice Check if there is a global quoting policy for a specific lender's vault * @param lenderVault The address of the lender's vault * @return True if there is a global quoting policy, false otherwise */ function hasGlobalQuotingPolicy( address lenderVault ) external view returns (bool); /** * @notice Check if there is a quoting policy for a specific lending pair involving collateral and loan tokens * @param lenderVault The address of the lender's vault * @param collToken The address of the collateral token * @param loanToken The address of the loan token * @return True if there is a quoting policy for the specified lender's vault, collateral, and loan tokens, false otherwise */ function hasPairQuotingPolicy( address lenderVault, address collToken, address loanToken ) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol"; interface IQuotePolicyManager { event PairPolicySet( address indexed lenderVault, address indexed collToken, address indexed loanToken, bytes singlePolicyData ); event GlobalPolicySet(address indexed lenderVault, bytes globalPolicyData); /** * @notice sets the global policy * @param lenderVault Address of the lender vault * @param globalPolicyData Global policy data to be set */ function setGlobalPolicy( address lenderVault, bytes calldata globalPolicyData ) external; /** * @notice sets the policy for a pair of tokens * @param lenderVault Address of the lender vault * @param collToken Address of the collateral token * @param loanToken Address of the loan token * @param pairPolicyData Pair policy data to be set */ function setPairPolicy( address lenderVault, address collToken, address loanToken, bytes calldata pairPolicyData ) external; /** * @notice Checks if a borrow is allowed * @param borrower Address of the borrower * @param lenderVault Address of the lender vault * @param generalQuoteInfo General quote info (see DataTypesPeerToPeer.sol) * @param quoteTuple Quote tuple (see DataTypesPeerToPeer.sol) * @return _isAllowed Flag to indicate if the borrow is allowed * @return minNumOfSignersOverwrite Overwrite of minimum number of signers (if zero ignored in quote handler) */ function isAllowed( address borrower, address lenderVault, DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple ) external view returns (bool _isAllowed, uint256 minNumOfSignersOverwrite); /** * @notice Gets the address registry * @return Address of the address registry */ function addressRegistry() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {DataTypesPeerToPeer} from "../../../../peer-to-peer/DataTypesPeerToPeer.sol"; interface IERC20Wrapper { event ERC20WrapperCreated( address indexed newErc20Addr, address indexed minter, uint256 numTokensCreated, DataTypesPeerToPeer.WrappedERC20TokenInfo[] wrappedTokensInfo ); /** * @notice Allows user to wrap multiple ERC20 into one ERC20 * @param minter Address of the minter * @param tokensToBeWrapped Array of WrappedERC20TokenInfo * @param name Name of the new wrapper token * @param symbol Symbol of the new wrapper token */ function createWrappedToken( address minter, DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped, string calldata name, string calldata symbol ) external returns (address); /** * @notice Returns address registry * @return address registry */ function addressRegistry() external view returns (address); /** * @notice Returns implementation contract address * @return implementation contract address */ function wrappedErc20Impl() external view returns (address); /** * @notice Returns array of tokens created * @return array of tokens created */ function allTokensCreated() external view returns (address[] memory); /** * @notice Returns the address of a token created by index * @param idx the index of the token * @return address of the token created */ function tokensCreated(uint256 idx) external view returns (address); /** * @notice Returns number of tokens created * @return number of tokens created */ function numTokensCreated() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {DataTypesPeerToPeer} from "../../../DataTypesPeerToPeer.sol"; interface IWrappedERC20Impl { event Redeemed(address indexed redeemer, address recipient, uint256 amount); /** * @notice Initializes the ERC20 wrapper * @param minter Address of the minter * @param wrappedTokens Array of WrappedERC20TokenInfo * @param totalInitialSupply Total initial supply of the wrapped token basket * @param name Name of the new wrapper token * @param symbol Symbol of the new wrapper token */ function initialize( address minter, DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata wrappedTokens, uint256 totalInitialSupply, string calldata name, string calldata symbol ) external; /** * @notice Function to redeem wrapped token for underlying tokens * @param account Account that is redeeming wrapped tokens * @param recipient Account that is receiving underlying tokens * @param amount Amount of wrapped tokens to be redeemed */ function redeem( address account, address recipient, uint256 amount ) external; /** * @notice Function to mint wrapped tokens for underlying token * @dev This function is only callable when the wrapped token has only one underlying token * @param recipient Account that is receiving the minted tokens * @param amount Amount of wrapped tokens to be minted * @param expectedTransferFee Expected transfer fee for the minted tokens (e.g. wrapping PAXG) */ function mint( address recipient, uint256 amount, uint256 expectedTransferFee ) external; /** * @notice Returns wrapped token addresses * @return wrappedTokens array of wrapped token addresses */ function getWrappedTokensInfo() external view returns (address[] calldata wrappedTokens); /** * @notice Returns whether wrapped token is IOU * @return boolean flag indicating whether wrapped token is IOU */ function isIOU() external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {DataTypesPeerToPeer} from "../../../DataTypesPeerToPeer.sol"; interface IERC721Wrapper { event ERC721WrapperCreated( address indexed newErc20Addr, address indexed minter, uint256 numTokensCreated, DataTypesPeerToPeer.WrappedERC721TokenInfo[] wrappedTokensInfo ); /** * @notice Allows user to wrap (multiple) ERC721 into one ERC20 * @param minter Address of the minter * @param tokensToBeWrapped Array of WrappedERC721TokenInfo * @param name Name of the new wrapper token * @param symbol Symbol of the new wrapper token */ function createWrappedToken( address minter, DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped, string calldata name, string calldata symbol ) external returns (address); /** * @notice Returns address registry * @return address registry */ function addressRegistry() external view returns (address); /** * @notice Returns implementation contract address * @return implementation contract address */ function wrappedErc721Impl() external view returns (address); /** * @notice Returns array of tokens created * @return array of tokens created */ function allTokensCreated() external view returns (address[] memory); /** * @notice Returns the address of a token created by index * @param idx the index of the token * @return address of the token created */ function tokensCreated(uint256 idx) external view returns (address); /** * @notice Returns number of tokens created * @return number of tokens created */ function numTokensCreated() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {DataTypesPeerToPeer} from "../../../DataTypesPeerToPeer.sol"; interface IWrappedERC721Impl { event Redeemed(address indexed redeemer, address recipient); event TransferFromWrappedTokenFailed( address indexed tokenAddr, uint256 indexed tokenId ); event TokenSweepAttempted(address indexed tokenAddr, uint256[] tokenIds); /** * @notice Initializes the ERC20 wrapper * @param minter Address of the minter * @param tokensToBeWrapped Array of token info (address and ids array) for the tokens to be wrapped * @param name Name of the new wrapper token * @param symbol Symbol of the new wrapper token */ function initialize( address minter, DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped, string calldata name, string calldata symbol ) external; /** * @notice Transfers any stuck wrapped tokens to the redeemer * @param tokenAddr Address of the token to be swept * @param tokenIds Array of token ids to be swept */ function sweepTokensLeftAfterRedeem( address tokenAddr, uint256[] calldata tokenIds ) external; /** * @notice Function to redeem wrapped token for underlying tokens * @param account Account that is redeeming wrapped tokens * @param recipient Account that is receiving underlying tokens */ function redeem(address account, address recipient) external; /** * @notice Function to remint wrapped token for underlying tokens * @param _wrappedTokensForRemint Array of token info (address and ids array) for the tokens to be reminted * @param recipient Account that is receiving the reminted ERC20 token */ function remint( DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata _wrappedTokensForRemint, address recipient ) external; /** * @notice Function to sync the wrapper state with the underlying tokens * @dev This function is callable by anyone and can sync back up accounting. * e.g. in case of transfer occurring outside remint function directly to wrapped token address * @param tokenAddr Address of the token to be synced * @param tokenId Id of the token to be synced */ function sync(address tokenAddr, uint256 tokenId) external; /** * @notice Returns wrapped token info * @return wrappedTokens array of struct containing information about wrapped tokens */ function getWrappedTokensInfo() external view returns ( DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata wrappedTokens ); /** * @notice Returns the total and current number of tokens in the wrapper * @return Array of total and current number of tokens in the wrapper, respectively */ function getTotalAndCurrentNumOfTokensInWrapper() external view returns (uint128[2] memory); /** * @notice Returns the address of the last redeemer * @return Address of the last redeemer */ function lastRedeemer() external view returns (address); /** * @notice Returns stuck token status * @param tokenAddr Address of the token to be checked * @param tokenId Id of the token to be checked * @return Returns true if the token is stuck, false otherwise */ function stuckTokens( address tokenAddr, uint256 tokenId ) external view returns (bool); /** * @notice Returns token currently counted in wrapper status * @param tokenAddr Address of the token to be checked * @param tokenId Id of the token to be checked * @return Returns true if the token is currently counted in the wrapper, false otherwise */ function isTokenCountedInWrapper( address tokenAddr, uint256 tokenId ) external view returns (bool); /** * @notice Returns whether token is an underlying member of the wrapper * @param tokenAddr Address of the token to be checked * @param tokenId Id of the token to be checked * @return Returns true if the token is an underlying member of the wrapper, false otherwise */ function isUnderlying( address tokenAddr, uint256 tokenId ) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {Errors} from "../Errors.sol"; import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol"; import {ILenderVaultFactory} from "./interfaces/ILenderVaultFactory.sol"; import {ILenderVaultImpl} from "./interfaces/ILenderVaultImpl.sol"; import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol"; contract LenderVaultFactory is ReentrancyGuard, ILenderVaultFactory { address public immutable addressRegistry; address public immutable lenderVaultImpl; constructor(address _addressRegistry, address _lenderVaultImpl) { if (_addressRegistry == address(0) || _lenderVaultImpl == address(0)) { revert Errors.InvalidAddress(); } addressRegistry = _addressRegistry; lenderVaultImpl = _lenderVaultImpl; } function createVault( bytes32 salt ) external nonReentrant returns (address newLenderVaultAddr) { newLenderVaultAddr = Clones.cloneDeterministic( lenderVaultImpl, keccak256(abi.encode(msg.sender, salt)) ); ILenderVaultImpl(newLenderVaultAddr).initialize( msg.sender, addressRegistry ); uint256 numRegisteredVaults = IAddressRegistry(addressRegistry) .addLenderVault(newLenderVaultAddr); address mysoTokenManager = IAddressRegistry(addressRegistry) .mysoTokenManager(); if (mysoTokenManager != address(0)) { IMysoTokenManager(mysoTokenManager).processP2PCreateVault( numRegisteredVaults, msg.sender, newLenderVaultAddr ); } emit NewVaultCreated( newLenderVaultAddr, msg.sender, numRegisteredVaults ); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {IERC20Metadata, IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {Constants} from "../Constants.sol"; import {DataTypesPeerToPeer} from "./DataTypesPeerToPeer.sol"; import {Errors} from "../Errors.sol"; import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol"; import {IBaseCompartment} from "./interfaces/compartments/IBaseCompartment.sol"; import {ILenderVaultImpl} from "./interfaces/ILenderVaultImpl.sol"; import {IOracle} from "./interfaces/IOracle.sol"; /** * @title LenderVaultImpl * @notice This contract implements the logic for the Lender Vault. * IMPORTANT: Security best practices dictate that the signers should always take care to * keep their private keys safe. Signing only trusted and human-readable public schema data is a good practice. Additionally, * the Myso team recommends that the signer should use a purpose-bound address for signing to reduce the chance * for a compromised private key to result in loss of funds. The Myso team also recommends that even vaults owned * by an EOA should have multiple signers to reduce chance of forged quotes. In the event that a signer is compromised, * the vault owner should immediately remove the compromised signer and if possible, add a new signer. */ contract LenderVaultImpl is Initializable, Ownable2Step, Pausable, ILenderVaultImpl { using SafeERC20 for IERC20Metadata; address public addressRegistry; address[] public signers; address public circuitBreaker; address public reverseCircuitBreaker; address public onChainQuotingDelegate; uint256 public minNumOfSigners; mapping(address => bool) public isSigner; bool public withdrawEntered; mapping(address => uint256) public lockedAmounts; DataTypesPeerToPeer.Loan[] internal _loans; constructor() { _disableInitializers(); } function initialize( address _vaultOwner, address _addressRegistry ) external initializer { addressRegistry = _addressRegistry; minNumOfSigners = 1; if (_vaultOwner == address(0) || _addressRegistry == address(0)) { revert Errors.InvalidAddress(); } super._transferOwnership(_vaultOwner); } function unlockCollateral( address collToken, uint256[] calldata _loanIds ) external { // only owner can call this function _checkOwner(); // if empty array is passed, revert uint256 loanIdsLen = _loanIds.length; if (loanIdsLen == 0) { revert Errors.InvalidArrayLength(); } uint256 totalUnlockableColl; for (uint256 i; i < loanIdsLen; ) { DataTypesPeerToPeer.Loan storage _loan = _loans[_loanIds[i]]; if (_loan.collToken != collToken) { revert Errors.InconsistentUnlockTokenAddresses(); } if (_loan.collUnlocked || block.timestamp < _loan.expiry) { revert Errors.InvalidCollUnlock(); } if (_loan.collTokenCompartmentAddr != address(0)) { IBaseCompartment(_loan.collTokenCompartmentAddr) .unlockCollToVault(collToken); } else { totalUnlockableColl += (_loan.initCollAmount - _loan.amountReclaimedSoFar); } _loan.collUnlocked = true; unchecked { ++i; } } lockedAmounts[collToken] -= totalUnlockableColl; emit CollateralUnlocked( owner(), collToken, _loanIds, totalUnlockableColl ); } function updateLoanInfo( uint128 repayAmount, uint256 loanId, uint128 reclaimCollAmount, bool noCompartment, address collToken ) external { _senderCheckGateway(); _loans[loanId].amountRepaidSoFar += repayAmount; _loans[loanId].amountReclaimedSoFar += reclaimCollAmount; // only update lockedAmounts when no compartment if (noCompartment) { lockedAmounts[collToken] -= reclaimCollAmount; } } function processQuote( address borrower, DataTypesPeerToPeer.BorrowTransferInstructions calldata borrowInstructions, DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple ) external whenNotPaused returns ( DataTypesPeerToPeer.Loan memory _loan, uint256 loanId, DataTypesPeerToPeer.TransferInstructions memory transferInstructions ) { _senderCheckGateway(); if ( borrowInstructions.collSendAmount < borrowInstructions.expectedProtocolAndVaultTransferFee + borrowInstructions.expectedCompartmentTransferFee ) { revert Errors.InsufficientSendAmount(); } // this check early in function removes need for other checks on sum of upfront plus transfer fees underflowing coll send amount if (quoteTuple.upfrontFeePctInBase > Constants.BASE) { revert Errors.InvalidUpfrontFee(); } // determine the effective net pledge amount on which loan amount and upfront fee calculation is based uint256 netPledgeAmount = borrowInstructions.collSendAmount - borrowInstructions.expectedProtocolAndVaultTransferFee - borrowInstructions.expectedCompartmentTransferFee; transferInstructions.upfrontFee = (netPledgeAmount * quoteTuple.upfrontFeePctInBase) / Constants.BASE; (uint256 loanAmount, uint256 repayAmount) = _getLoanAndRepayAmount( netPledgeAmount, generalQuoteInfo, quoteTuple, quoteTuple.upfrontFeePctInBase ); // checks to prevent griefing attacks (e.g. small unlocks that aren't worth it) if ( loanAmount < generalQuoteInfo.minLoan || loanAmount > generalQuoteInfo.maxLoan ) { revert Errors.InvalidSendAmount(); } if (loanAmount < borrowInstructions.minLoanAmount || loanAmount == 0) { revert Errors.TooSmallLoanAmount(); } transferInstructions.collReceiver = address(this); _loan.borrower = borrower; _loan.loanToken = generalQuoteInfo.loanToken; _loan.collToken = generalQuoteInfo.collToken; _loan.initLoanAmount = SafeCast.toUint128(loanAmount); _loan.initCollAmount = SafeCast.toUint128( netPledgeAmount - transferInstructions.upfrontFee ); if (quoteTuple.upfrontFeePctInBase < Constants.BASE) { // note: if upfrontFee<100% this corresponds to a loan; check that tenor and earliest repay are consistent if ( quoteTuple.tenor < SafeCast.toUint40( generalQuoteInfo.earliestRepayTenor + Constants.MIN_TIME_BETWEEN_EARLIEST_REPAY_AND_EXPIRY ) ) { revert Errors.InvalidEarliestRepay(); } _loan.expiry = SafeCast.toUint40( block.timestamp + quoteTuple.tenor ); _loan.earliestRepay = SafeCast.toUint40( block.timestamp + generalQuoteInfo.earliestRepayTenor ); if (_loan.initCollAmount == 0) { revert Errors.ReclaimableCollateralAmountZero(); } loanId = _loans.length; if ( generalQuoteInfo.borrowerCompartmentImplementation == address(0) ) { if (borrowInstructions.expectedCompartmentTransferFee > 0) { revert Errors.InconsistentExpTransferFee(); } lockedAmounts[_loan.collToken] += _loan.initCollAmount; } else { transferInstructions.collReceiver = _createCollCompartment( generalQuoteInfo.borrowerCompartmentImplementation, loanId ); _loan.collTokenCompartmentAddr = transferInstructions .collReceiver; } _loan.initRepayAmount = SafeCast.toUint128(repayAmount); _loans.push(_loan); } else { // note: only case left is upfrontFee = 100% and this corresponds to an outright swap; // check that tenor is zero and earliest repay is nonzero, and compartment is zero, with no compartment transfer fee if ( _loan.initCollAmount != 0 || quoteTuple.tenor + generalQuoteInfo.earliestRepayTenor != 0 || generalQuoteInfo.borrowerCompartmentImplementation != address(0) || borrowInstructions.expectedCompartmentTransferFee != 0 ) { revert Errors.InvalidSwap(); } } emit QuoteProcessed(netPledgeAmount, transferInstructions); } function withdraw(address token, uint256 amount) external { if (withdrawEntered) { revert Errors.WithdrawEntered(); } withdrawEntered = true; _checkOwner(); uint256 vaultBalance = IERC20Metadata(token).balanceOf(address(this)); if (amount == 0 || amount > vaultBalance - lockedAmounts[token]) { revert Errors.InvalidWithdrawAmount(); } IERC20Metadata(token).safeTransfer(owner(), amount); withdrawEntered = false; emit Withdrew(token, amount); } function transferTo( address token, address recipient, uint256 amount ) external { _senderCheckGateway(); if ( amount > IERC20Metadata(token).balanceOf(address(this)) - lockedAmounts[token] ) { revert Errors.InsufficientVaultFunds(); } IERC20Metadata(token).safeTransfer(recipient, amount); } function transferCollFromCompartment( uint256 repayAmount, uint256 repayAmountLeft, uint128 reclaimCollAmount, address borrowerAddr, address collTokenAddr, address callbackAddr, address collTokenCompartmentAddr ) external { _senderCheckGateway(); IBaseCompartment(collTokenCompartmentAddr).transferCollFromCompartment( repayAmount, repayAmountLeft, reclaimCollAmount, borrowerAddr, collTokenAddr, callbackAddr ); } function setMinNumOfSigners(uint256 _minNumOfSigners) external { _checkOwner(); if (_minNumOfSigners == 0 || _minNumOfSigners == minNumOfSigners) { revert Errors.InvalidNewMinNumOfSigners(); } minNumOfSigners = _minNumOfSigners; emit MinNumberOfSignersSet(_minNumOfSigners); } function addSigners(address[] calldata _signers) external { _checkOwner(); uint256 signersLen = _signers.length; if (signersLen == 0) { revert Errors.InvalidArrayLength(); } address vaultOwner = owner(); for (uint256 i; i < signersLen; ) { if (_signers[i] == address(0) || _signers[i] == vaultOwner) { revert Errors.InvalidAddress(); } if (isSigner[_signers[i]]) { revert Errors.AlreadySigner(); } isSigner[_signers[i]] = true; signers.push(_signers[i]); unchecked { ++i; } } emit AddedSigners(_signers); } function removeSigner(address signer, uint256 signerIdx) external { _checkOwner(); uint256 signersLen = signers.length; if (signerIdx >= signersLen) { revert Errors.InvalidArrayIndex(); } if (!isSigner[signer] || signer != signers[signerIdx]) { revert Errors.InvalidSignerRemoveInfo(); } address signerWithSwappedPosition; if (signerIdx != signersLen - 1) { signerWithSwappedPosition = signers[signersLen - 1]; signers[signerIdx] = signerWithSwappedPosition; } signers.pop(); isSigner[signer] = false; emit RemovedSigner(signer, signerIdx, signerWithSwappedPosition); } function setCircuitBreaker(address newCircuitBreaker) external { _checkOwner(); address oldCircuitBreaker = circuitBreaker; _checkCircuitBreaker(newCircuitBreaker, oldCircuitBreaker); circuitBreaker = newCircuitBreaker; emit CircuitBreakerUpdated(newCircuitBreaker, oldCircuitBreaker); } function setReverseCircuitBreaker( address newReverseCircuitBreaker ) external { _checkOwner(); address oldReverseCircuitBreaker = reverseCircuitBreaker; _checkCircuitBreaker( newReverseCircuitBreaker, oldReverseCircuitBreaker ); reverseCircuitBreaker = newReverseCircuitBreaker; emit ReverseCircuitBreakerUpdated( newReverseCircuitBreaker, oldReverseCircuitBreaker ); } function setOnChainQuotingDelegate( address newOnChainQuotingDelegate ) external { _checkOwner(); address oldOnChainQuotingDelegate = onChainQuotingDelegate; // delegate is allowed to be a signer, unlike owner, circuit breaker or reverse circuit breaker if ( newOnChainQuotingDelegate == oldOnChainQuotingDelegate || newOnChainQuotingDelegate == owner() ) { revert Errors.InvalidAddress(); } onChainQuotingDelegate = newOnChainQuotingDelegate; emit OnChainQuotingDelegateUpdated( newOnChainQuotingDelegate, oldOnChainQuotingDelegate ); } function pauseQuotes() external { if (msg.sender != circuitBreaker && msg.sender != owner()) { revert Errors.InvalidSender(); } _pause(); } function unpauseQuotes() external { if (msg.sender != reverseCircuitBreaker && msg.sender != owner()) { revert Errors.InvalidSender(); } _unpause(); } function loan( uint256 loanId ) external view returns (DataTypesPeerToPeer.Loan memory _loan) { uint256 loansLen = _loans.length; if (loanId >= loansLen) { revert Errors.InvalidArrayIndex(); } _loan = _loans[loanId]; } function totalNumLoans() external view returns (uint256) { return _loans.length; } function getTokenBalancesAndLockedAmounts( address[] calldata tokens ) external view returns (uint256[] memory balances, uint256[] memory _lockedAmounts) { uint256 tokensLen = tokens.length; if (tokensLen == 0) { revert Errors.InvalidArrayLength(); } balances = new uint256[](tokensLen); _lockedAmounts = new uint256[](tokensLen); for (uint256 i; i < tokensLen; ) { if (tokens[i] == address(0)) { revert Errors.InvalidAddress(); } balances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); _lockedAmounts[i] = lockedAmounts[tokens[i]]; unchecked { ++i; } } } function totalNumSigners() external view returns (uint256) { return signers.length; } function transferOwnership( address _newOwnerProposal ) public override(Ownable2Step, ILenderVaultImpl) { if ( _newOwnerProposal == address(this) || _newOwnerProposal == pendingOwner() || _newOwnerProposal == owner() || isSigner[_newOwnerProposal] ) { revert Errors.InvalidNewOwnerProposal(); } // @dev: access control check via super.transferOwnership() super.transferOwnership(_newOwnerProposal); } function owner() public view override(Ownable, ILenderVaultImpl) returns (address) { return super.owner(); } function pendingOwner() public view override(Ownable2Step, ILenderVaultImpl) returns (address) { return super.pendingOwner(); } function renounceOwnership() public pure override { revert Errors.Disabled(); } function _createCollCompartment( address borrowerCompartmentImplementation, uint256 loanId ) internal returns (address collCompartment) { collCompartment = Clones.clone(borrowerCompartmentImplementation); IBaseCompartment(collCompartment).initialize(address(this), loanId); } function _senderCheckGateway() internal view { if (msg.sender != IAddressRegistry(addressRegistry).borrowerGateway()) { revert Errors.UnregisteredGateway(); } } function _getLoanAndRepayAmount( uint256 netPledgeAmount, DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple, uint256 upfrontFeePctInBase ) internal view returns (uint256 loanAmount, uint256 repayAmount) { uint256 loanPerCollUnit; if (generalQuoteInfo.oracleAddr == address(0)) { loanPerCollUnit = quoteTuple.loanPerCollUnitOrLtv; } else { // arbitrage protection if LTV > 100% and no whitelist restriction if ( quoteTuple.loanPerCollUnitOrLtv > Constants.BASE && generalQuoteInfo.whitelistAddr == address(0) ) { revert Errors.LtvHigherThanMax(); } (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw) = IOracle( generalQuoteInfo.oracleAddr ).getRawPrices( generalQuoteInfo.collToken, generalQuoteInfo.loanToken ); loanPerCollUnit = Math.mulDiv( quoteTuple.loanPerCollUnitOrLtv, collTokenPriceRaw * 10 ** IERC20Metadata(generalQuoteInfo.loanToken) .decimals(), loanTokenPriceRaw ) / Constants.BASE; } uint256 unscaledLoanAmount = loanPerCollUnit * netPledgeAmount; uint256 collTokenDecimals = IERC20Metadata(generalQuoteInfo.collToken) .decimals(); // calculate loan amount loanAmount = unscaledLoanAmount / (10 ** collTokenDecimals); // calculate repay amount and interest rate factor only for loans if (upfrontFeePctInBase < Constants.BASE) { // calculate interest rate factor // @dev: custom typecasting rather than safecasting to catch when interest rate factor = 0 int256 _interestRateFactor = int256(Constants.BASE) + quoteTuple.interestRatePctInBase; if (_interestRateFactor <= 0) { revert Errors.InvalidInterestRateFactor(); } uint256 interestRateFactor = uint256(_interestRateFactor); // calculate repay amount repayAmount = Math.mulDiv( unscaledLoanAmount, interestRateFactor, Constants.BASE ) / (10 ** collTokenDecimals); } } function _checkCircuitBreaker( address newCircuitBreaker, address oldCircuitBreaker ) internal view { if ( newCircuitBreaker == oldCircuitBreaker || newCircuitBreaker == owner() || isSigner[newCircuitBreaker] ) { revert Errors.InvalidAddress(); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {AggregatorV3Interface} from "../../interfaces/oracles/chainlink/AggregatorV3Interface.sol"; import {ChainlinkBase} from "./ChainlinkBase.sol"; import {Constants} from "../../../Constants.sol"; import {Errors} from "../../../Errors.sol"; /** * @dev supports oracles which are compatible with v2v3 or v3 interfaces */ contract ChainlinkArbitrumSequencerUSD is ChainlinkBase { address internal constant SEQUENCER_FEED = 0xFdB631F5EE196F0ed6FAa767959853A9F217697D; // arbitrum sequencer feed uint256 internal constant ARB_USD_BASE_CURRENCY_UNIT = 1e8; // 8 decimals for USD based oracles constructor( address[] memory _tokenAddrs, address[] memory _oracleAddrs ) ChainlinkBase(_tokenAddrs, _oracleAddrs, ARB_USD_BASE_CURRENCY_UNIT) {} // solhint-disable no-empty-blocks function _checkAndReturnLatestRoundData( address oracleAddr ) internal view override returns (uint256 tokenPriceRaw) { (, int256 answer, uint256 startedAt, , ) = AggregatorV3Interface( SEQUENCER_FEED ).latestRoundData(); // check if sequencer is live if (answer != 0) { revert Errors.SequencerDown(); } // check if last restart was less than or equal grace period length if (startedAt + Constants.SEQUENCER_GRACE_PERIOD > block.timestamp) { revert Errors.GracePeriodNotOver(); } tokenPriceRaw = super._checkAndReturnLatestRoundData(oracleAddr); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {AggregatorV3Interface} from "../../interfaces/oracles/chainlink/AggregatorV3Interface.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {Constants} from "../../../Constants.sol"; import {Errors} from "../../../Errors.sol"; import {IOracle} from "../../interfaces/IOracle.sol"; /** * @dev supports oracles which are compatible with v2v3 or v3 interfaces */ abstract contract ChainlinkBase is IOracle { // solhint-disable var-name-mixedcase uint256 public immutable BASE_CURRENCY_UNIT; mapping(address => address) public oracleAddrs; constructor( address[] memory _tokenAddrs, address[] memory _oracleAddrs, uint256 baseCurrencyUnit ) { uint256 tokenAddrsLength = _tokenAddrs.length; if (tokenAddrsLength == 0 || tokenAddrsLength != _oracleAddrs.length) { revert Errors.InvalidArrayLength(); } uint8 oracleDecimals; uint256 version; for (uint256 i; i < tokenAddrsLength; ) { if (_tokenAddrs[i] == address(0) || _oracleAddrs[i] == address(0)) { revert Errors.InvalidAddress(); } oracleDecimals = AggregatorV3Interface(_oracleAddrs[i]).decimals(); if (10 ** oracleDecimals != baseCurrencyUnit) { revert Errors.InvalidOracleDecimals(); } version = AggregatorV3Interface(_oracleAddrs[i]).version(); if (version != 4) { revert Errors.InvalidOracleVersion(); } oracleAddrs[_tokenAddrs[i]] = _oracleAddrs[i]; unchecked { ++i; } } BASE_CURRENCY_UNIT = baseCurrencyUnit; } function getPrice( address collToken, address loanToken ) external view virtual returns (uint256 collTokenPriceInLoanToken) { (uint256 priceOfCollToken, uint256 priceOfLoanToken) = getRawPrices( collToken, loanToken ); uint256 loanTokenDecimals = IERC20Metadata(loanToken).decimals(); collTokenPriceInLoanToken = Math.mulDiv( priceOfCollToken, 10 ** loanTokenDecimals, priceOfLoanToken ); } function getRawPrices( address collToken, address loanToken ) public view virtual returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw) { (collTokenPriceRaw, loanTokenPriceRaw) = ( _getPriceOfToken(collToken), _getPriceOfToken(loanToken) ); } function _getPriceOfToken( address token ) internal view virtual returns (uint256 tokenPriceRaw) { address oracleAddr = oracleAddrs[token]; if (oracleAddr == address(0)) { revert Errors.NoOracle(); } tokenPriceRaw = _checkAndReturnLatestRoundData(oracleAddr); } function _checkAndReturnLatestRoundData( address oracleAddr ) internal view virtual returns (uint256 tokenPriceRaw) { ( uint80 roundId, int256 answer, , uint256 updatedAt, uint80 answeredInRound ) = AggregatorV3Interface(oracleAddr).latestRoundData(); if ( roundId == 0 || answeredInRound < roundId || answer < 1 || updatedAt > block.timestamp || updatedAt + Constants.MAX_PRICE_UPDATE_TIMESTAMP_DIVERGENCE < block.timestamp ) { revert Errors.InvalidOracleAnswer(); } tokenPriceRaw = uint256(answer); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {ChainlinkBase} from "./ChainlinkBase.sol"; import {Errors} from "../../../Errors.sol"; /** * @dev supports oracles which are compatible with v2v3 or v3 interfaces */ contract ChainlinkBasic is ChainlinkBase { // solhint-disable var-name-mixedcase address public immutable BASE_CURRENCY; constructor( address[] memory _tokenAddrs, address[] memory _oracleAddrs, address baseCurrency, uint256 baseCurrencyUnit ) ChainlinkBase(_tokenAddrs, _oracleAddrs, baseCurrencyUnit) { if (baseCurrency == address(0)) { revert Errors.InvalidAddress(); } BASE_CURRENCY = baseCurrency; } function _getPriceOfToken( address token ) internal view virtual override returns (uint256 tokenPriceRaw) { tokenPriceRaw = token == BASE_CURRENCY ? BASE_CURRENCY_UNIT : super._getPriceOfToken(token); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {ChainlinkBasic} from "./ChainlinkBasic.sol"; import {Errors} from "../../../Errors.sol"; /** * @dev supports oracles which are compatible with v2v3 or v3 interfaces */ contract ChainlinkBasicWithWbtc is ChainlinkBasic { address internal constant WBTC_BTC_ORACLE = 0xfdFD9C85aD200c506Cf9e21F1FD8dd01932FBB23; address internal constant BTC_USD_ORACLE = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; address internal constant WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; uint256 internal constant WBTC_BASE_CURRENCY_UNIT = 1e8; // 8 decimals for USD based oracles constructor( address[] memory _tokenAddrs, address[] memory _oracleAddrs ) ChainlinkBasic(_tokenAddrs, _oracleAddrs, WBTC, WBTC_BASE_CURRENCY_UNIT) {} // solhint-disable no-empty-blocks function _getPriceOfToken( address token ) internal view override returns (uint256 tokenPriceRaw) { if (token == BASE_CURRENCY) { uint256 answer1 = _checkAndReturnLatestRoundData(WBTC_BTC_ORACLE); uint256 answer2 = _checkAndReturnLatestRoundData(BTC_USD_ORACLE); tokenPriceRaw = (answer1 * answer2) / BASE_CURRENCY_UNIT; } else { tokenPriceRaw = super._getPriceOfToken(token); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {IOlympus} from "../../interfaces/oracles/IOlympus.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {ChainlinkBasic} from "./ChainlinkBasic.sol"; import {Errors} from "../../../Errors.sol"; /** * @dev supports olympus gOhm oracles which are compatible with v2v3 or v3 interfaces * should only be utilized with eth based oracles, not usd-based oracles */ contract OlympusOracle is ChainlinkBasic { address internal constant GOHM_ADDR = 0x0ab87046fBb341D058F17CBC4c1133F25a20a52f; uint256 internal constant SOHM_DECIMALS = 9; address internal constant ETH_OHM_ORACLE_ADDR = 0x9a72298ae3886221820B1c878d12D872087D3a23; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 internal constant GOHM_BASE_CURRENCY_UNIT = 1e18; // 18 decimals for ETH based oracles constructor( address[] memory _tokenAddrs, address[] memory _oracleAddrs ) ChainlinkBasic(_tokenAddrs, _oracleAddrs, WETH, GOHM_BASE_CURRENCY_UNIT) { oracleAddrs[GOHM_ADDR] = ETH_OHM_ORACLE_ADDR; } function getPrice( address collToken, address loanToken ) external view override returns (uint256 collTokenPriceInLoanToken) { if (collToken != GOHM_ADDR && loanToken != GOHM_ADDR) { revert Errors.NeitherTokenIsGOHM(); } (uint256 priceOfCollToken, uint256 priceOfLoanToken) = ( _getPriceOfToken(collToken), _getPriceOfToken(loanToken) ); uint256 loanTokenDecimals = IERC20Metadata(loanToken).decimals(); uint256 index = IOlympus(GOHM_ADDR).index(); collTokenPriceInLoanToken = collToken == GOHM_ADDR ? Math.mulDiv( priceOfCollToken, (10 ** loanTokenDecimals) * index, priceOfLoanToken * (10 ** SOHM_DECIMALS) ) : Math.mulDiv( priceOfCollToken, (10 ** loanTokenDecimals) * (10 ** SOHM_DECIMALS), priceOfLoanToken * index ); } function getRawPrices( address collToken, address loanToken ) public view override returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw) { if (collToken != GOHM_ADDR && loanToken != GOHM_ADDR) { revert Errors.NeitherTokenIsGOHM(); } uint256 index = IOlympus(GOHM_ADDR).index(); (collTokenPriceRaw, loanTokenPriceRaw) = ( _getPriceOfToken(collToken), _getPriceOfToken(loanToken) ); if (collToken == GOHM_ADDR) { collTokenPriceRaw = Math.mulDiv( collTokenPriceRaw, index, 10 ** SOHM_DECIMALS ); } else { loanTokenPriceRaw = Math.mulDiv( loanTokenPriceRaw, index, 10 ** SOHM_DECIMALS ); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {IUniV2} from "../../interfaces/oracles/IUniV2.sol"; import {ChainlinkBasic} from "./ChainlinkBasic.sol"; import {Errors} from "../../../Errors.sol"; /** * @dev supports oracles which have one token which is a 50/50 LP token * compatible with v2v3 or v3 interfaces * should only be utilized with eth based oracles, not usd-based oracles */ contract UniV2Chainlink is ChainlinkBasic { uint256 internal immutable _tolerance; // tolerance must be an integer less than 10000 and greater than 0 mapping(address => bool) public isLpToken; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 internal constant UNI_V2_BASE_CURRENCY_UNIT = 1e18; // 18 decimals for ETH based oracles constructor( address[] memory _tokenAddrs, address[] memory _oracleAddrs, address[] memory _lpAddrs, uint256 _toleranceAmount ) ChainlinkBasic( _tokenAddrs, _oracleAddrs, WETH, UNI_V2_BASE_CURRENCY_UNIT ) { uint256 lpAddrsLen = _lpAddrs.length; if (lpAddrsLen == 0) { revert Errors.InvalidArrayLength(); } if (_toleranceAmount >= 10000 || _toleranceAmount == 0) { revert Errors.InvalidOracleTolerance(); } _tolerance = _toleranceAmount; for (uint256 i; i < lpAddrsLen; ) { if (_lpAddrs[i] == address(0)) { revert Errors.InvalidAddress(); } isLpToken[_lpAddrs[i]] = true; unchecked { ++i; } } } function getPrice( address collToken, address loanToken ) external view override returns (uint256 collTokenPriceInLoanToken) { (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw) = getRawPrices( collToken, loanToken ); uint256 loanTokenDecimals = IERC20Metadata(loanToken).decimals(); collTokenPriceInLoanToken = Math.mulDiv( collTokenPriceRaw, 10 ** loanTokenDecimals, loanTokenPriceRaw ); } function getRawPrices( address collToken, address loanToken ) public view override returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw) { bool isCollTokenLpToken = isLpToken[collToken]; bool isLoanTokenLpToken = isLpToken[loanToken]; if (!isCollTokenLpToken && !isLoanTokenLpToken) { revert Errors.NoLpTokens(); } collTokenPriceRaw = isCollTokenLpToken ? getLpTokenPrice(collToken) : _getPriceOfToken(collToken); loanTokenPriceRaw = isLoanTokenLpToken ? getLpTokenPrice(loanToken) : _getPriceOfToken(loanToken); } /** * @notice Returns the price of 1 "whole" LP token (in 1 base currency unit, e.g., 10**18) in ETH * @dev Since the uniswap reserves could be skewed in any direction by flash loans, * we need to calculate the "fair" reserve of each token in the pool using invariant K * and then calculate the price of each token in ETH using the oracle prices for each token * @param lpToken Address of LP token * @return lpTokenPriceInEth of LP token in ETH */ function getLpTokenPrice( address lpToken ) public view returns (uint256 lpTokenPriceInEth) { // assign uint112 reserves to uint256 to also handle large k invariants (uint256 reserve0, uint256 reserve1, ) = IUniV2(lpToken).getReserves(); if (reserve0 * reserve1 == 0) { revert Errors.ZeroReserve(); } (address token0, address token1) = ( IUniV2(lpToken).token0(), IUniV2(lpToken).token1() ); uint256 totalLpSupply = IUniV2(lpToken).totalSupply(); uint256 priceToken0 = _getPriceOfToken(token0); uint256 priceToken1 = _getPriceOfToken(token1); uint256 token0Decimals = IERC20Metadata(token0).decimals(); uint256 token1Decimals = IERC20Metadata(token1).decimals(); _reserveAndPriceCheck( reserve0, reserve1, priceToken0, priceToken1, token0Decimals, token1Decimals ); // calculate fair LP token price based on "fair reserves" as described in // https://blog.alphaventuredao.io/fair-lp-token-pricing/ // formula: p = 2 * sqrt(r0 * r1) * sqrt(p0) * sqrt(p1) / s // note: price is for 1 "whole" LP token unit, hence need to scale up by LP token decimals; // need to divide by sqrt reserve decimals to cancel out units of invariant k // IMPORTANT: while formula is robust against typical flashloan skews, lenders should use this // oracle with caution and take into account skew scenarios when setting their LTVs lpTokenPriceInEth = Math.mulDiv( 2 * Math.sqrt(reserve0 * reserve1), Math.sqrt(priceToken0 * priceToken1) * UNI_V2_BASE_CURRENCY_UNIT, totalLpSupply * Math.sqrt(10 ** token0Decimals * 10 ** token1Decimals) ); } /** * @notice function checks that price from reserves is within tolerance of price from oracle * @dev This function is needed because a one-sided donation and sync can skew the fair reserve * calculation above. This function checks that the price from reserves is within a tolerance * @param reserve0 Reserve of token0 * @param reserve1 Reserve of token1 * @param priceToken0 Price of token0 from oracle * @param priceToken1 Price of token1 from oracle * @param token0Decimals Decimals of token0 * @param token1Decimals Decimals of token1 */ function _reserveAndPriceCheck( uint256 reserve0, uint256 reserve1, uint256 priceToken0, uint256 priceToken1, uint256 token0Decimals, uint256 token1Decimals ) internal view { uint256 priceFromReserves = (reserve0 * 10 ** token1Decimals) / reserve1; uint256 priceFromOracle = (priceToken1 * 10 ** token0Decimals) / priceToken0; if ( priceFromReserves > ((10000 + _tolerance) * priceFromOracle) / 10000 || priceFromReserves < ((10000 - _tolerance) * priceFromOracle) / 10000 ) { revert Errors.ReserveRatiosSkewedFromOraclePrice(); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {OracleLibrary} from "../uniswap/OracleLibrary.sol"; import {ChainlinkBase} from "../chainlink/ChainlinkBase.sol"; import {Errors} from "../../../Errors.sol"; import {TwapGetter} from "../uniswap/TwapGetter.sol"; import {IDSETH} from "../../interfaces/oracles/IDSETH.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; /** * @dev custom oracle for ds-eth */ contract DsEthOracle is ChainlinkBase, TwapGetter { // must be paired with WETH and only allow components within ds eth to use TWAP mapping(address => address) public uniV3PairAddrs; uint256 internal immutable _tolerance; // tolerance must be an integer less than 10000 and greater than 0 address internal constant DS_ETH = 0x341c05c0E9b33C0E38d64de76516b2Ce970bB3BE; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 internal constant INDEX_COOP_BASE_CURRENCY_UNIT = 1e18; // 18 decimals for ETH based oracles uint32 internal immutable _twapInterval; // in seconds (e.g. 1 hour = 3600 seconds) constructor( address[] memory _tokenAddrs, address[] memory _oracleAddrs, address[] memory _uniswapV3PairAddrs, uint32 twapInterval, uint256 tolerance ) ChainlinkBase(_tokenAddrs, _oracleAddrs, INDEX_COOP_BASE_CURRENCY_UNIT) { if (tolerance >= 10000 || tolerance == 0) { revert Errors.InvalidOracleTolerance(); } _tolerance = tolerance; // min 30 minute twap interval if (twapInterval < 30 minutes) { revert Errors.TooShortTwapInterval(); } _twapInterval = twapInterval; // in future could be possible that all constituents are chainlink compatible // so _uniswapV3PairAddrs.length == 0 is allowed, hence no length == 0 check address token1; for (uint256 i; i < _uniswapV3PairAddrs.length; ) { if (_uniswapV3PairAddrs[i] == address(0)) { revert Errors.InvalidAddress(); } // try could also pass if you passed in uni v2 pair address // though should later fail when trying to price in future // care must be taken not to pass in uni v2 pair address try IUniswapV3Pool(_uniswapV3PairAddrs[i]).token0() returns ( address token0 ) { token1 = IUniswapV3Pool(_uniswapV3PairAddrs[i]).token1(); // must have one token weth and other token component in ds eth if ( !(token0 == WETH && IDSETH(DS_ETH).isComponent(token1)) && !(token1 == WETH && IDSETH(DS_ETH).isComponent(token0)) ) { revert Errors.InvalidAddress(); } // store non weth token address as key with uni v3 pair address as value uniV3PairAddrs[ token0 == WETH ? token1 : token0 ] = _uniswapV3PairAddrs[i]; } catch { revert Errors.InvalidAddress(); } unchecked { ++i; } } } function getPrice( address collToken, address loanToken ) external view override returns (uint256 collTokenPriceInLoanToken) { // must have at least one token is DS_ETH to use this oracle (uint256 priceOfCollToken, uint256 priceOfLoanToken) = getRawPrices( collToken, loanToken ); uint256 loanTokenDecimals = (loanToken == WETH || loanToken == DS_ETH) ? 18 : IERC20Metadata(loanToken).decimals(); collTokenPriceInLoanToken = (priceOfCollToken * 10 ** loanTokenDecimals) / priceOfLoanToken; } function getRawPrices( address collToken, address loanToken ) public view override returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw) { // must have at least one token is DS_ETH to use this oracle if (collToken != DS_ETH && loanToken != DS_ETH) { revert Errors.NoDsEth(); } (collTokenPriceRaw, loanTokenPriceRaw) = ( _getPriceOfToken(collToken), _getPriceOfToken(loanToken) ); } function _getPriceOfToken( address token ) internal view virtual override returns (uint256 tokenPriceRaw) { // note: if token is not WETH or DS_ETH, then will revert if not a chainlink oracle // this is by design, even if that address has a TWAP, it will not be used // except only when calculating ds eth price to minimize risk // i.e. if stakewise eth has uni v3 address but no chainlink address, and lender // tries to use stakewise eth as loan and ds eth as collateral, then revert // @dev: no use of nested ternary operator for npx hardhat compatibility reasons if (token == WETH) { tokenPriceRaw = BASE_CURRENCY_UNIT; } else { tokenPriceRaw = token == DS_ETH ? _getDsEthPrice() : super._getPriceOfToken(token); } } function _getDsEthPrice() internal view returns (uint256 dsEthPriceRaw) { address[] memory components = IDSETH(DS_ETH).getComponents(); address currComponent; uint256 currComponentPrice; uint256 totalPriceUniCumSum; for (uint256 i; i < components.length; ) { currComponent = components[i]; if ( oracleAddrs[currComponent] == address(0) && uniV3PairAddrs[currComponent] == address(0) ) { // if component has no oracle and no uni v3 pair, then revert revert Errors.NoOracle(); } // always try to use chainlink oracle if available even if also had uni v3 pair passed in by mistake too currComponentPrice = oracleAddrs[currComponent] == address(0) ? _getTwapPrice(uniV3PairAddrs[currComponent]) : _getPriceOfToken(currComponent); totalPriceUniCumSum += (currComponentPrice * IDSETH(DS_ETH).getTotalComponentRealUnits(currComponent)); unchecked { ++i; } } dsEthPriceRaw = totalPriceUniCumSum / INDEX_COOP_BASE_CURRENCY_UNIT; } function _getTwapPrice( address uniV3PairAddr ) internal view returns (uint256 twapPriceRaw) { (address token0, address token1) = ( IUniswapV3Pool(uniV3PairAddr).token0(), IUniswapV3Pool(uniV3PairAddr).token1() ); (address inToken, address outToken) = ( token0 == WETH ? token1 : token0, token1 == WETH ? token1 : token0 ); twapPriceRaw = getTwap(inToken, outToken, _twapInterval, uniV3PairAddr); (, int24 tick, , , , , ) = IUniswapV3Pool(uniV3PairAddr).slot0(); uint256 spotPrice = OracleLibrary.getQuoteAtTick( tick, SafeCast.toUint128(10 ** IERC20Metadata(inToken).decimals()), inToken, outToken ); // if twap price exceeds threshold from spot proxy price, then revert if ( twapPriceRaw > ((10000 + _tolerance) * spotPrice) / 10000 || twapPriceRaw < ((10000 - _tolerance) * spotPrice) / 10000 ) { revert Errors.TwapExceedsThreshold(); } } }
// SPDX-License-Identifier: MIT /* solhint-disable */ pragma solidity ^0.8.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then 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(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (0 - denominator) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } 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 // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use 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. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // 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 precoditions 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 * inv; return result; } } }
// SPDX-License-Identifier: MIT /* solhint-disable */ pragma solidity ^0.8.0; import {FullMath} from "./FullMath.sol"; // cannot import from @uniswap due to incompatible versions import {TickMath} from "./TickMath.sol"; // cannot import from @uniswap due to incompatible versions /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv( sqrtRatioX96, sqrtRatioX96, 1 << 64 ); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } }
// SPDX-License-Identifier: GPL-2.0-or-later /* solhint-disable */ pragma solidity ^0.8.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { error T(); error R(); /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick( int24 tick ) internal pure returns (uint160 sqrtPriceX96) { unchecked { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); if (absTick > uint256(int256(MAX_TICK))) revert T(); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160( (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1) ); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {FixedPoint96} from "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; import {IUniswapV3Factory} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol"; import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {FullMath} from "./FullMath.sol"; // cannot import from @uniswap due to incompatible versions import {TickMath} from "./TickMath.sol"; // cannot import from @uniswap due to incompatible versions import {Errors} from "../../../Errors.sol"; import {ITwapGetter} from "../../interfaces/oracles/uniswap/ITwapGetter.sol"; abstract contract TwapGetter is ITwapGetter { // inToken: `1 unit of inToken` // outToken: resulting units of outToken (in "base unit" of outTokens, e.g. if 427518869723400 and outToken is eth, then this corresponds to 427518869723400/10^18) function getTwap( address inToken, address outToken, uint32 twapInterval, address uniswapV3Pool ) public view returns (uint256 twap) { (address token0, address token1) = inToken < outToken ? (inToken, outToken) : (outToken, inToken); // note: this returns the sqrt price uint160 sqrtPriceX96 = getSqrtTwapX96(uniswapV3Pool, twapInterval); // note: this returns the price in base 2**96 and denominated in token1 // i.e., `1 unit of token0` corresponds to `sqrtPriceX96 units (divided by 2**96) of token1` uint256 priceX96 = FullMath.mulDiv( sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96 ); twap = inToken == token0 ? FullMath.mulDiv( priceX96, 10 ** IERC20Metadata(token0).decimals(), FixedPoint96.Q96 ) : FullMath.mulDiv( FixedPoint96.Q96, 10 ** IERC20Metadata(token1).decimals(), priceX96 ); } function getSqrtTwapX96( address uniswapV3Pool, uint32 twapInterval ) public view returns (uint160 sqrtPriceX96) { if (twapInterval == 0) { (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0(); } else { uint32[] memory secondsAgo = new uint32[](2); // @dev: revert if twapInterval doesn't fit into smaller int32 if (twapInterval > uint32(type(int32).max)) { revert Errors.TooLongTwapInterval(); } secondsAgo[0] = twapInterval; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapV3Pool) .observe(secondsAgo); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; int24 averageTick = SafeCast.toInt24( tickCumulativesDelta / int32(twapInterval) ); sqrtPriceX96 = TickMath.getSqrtRatioAtTick(averageTick); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol"; import {DataTypesBasicPolicies} from "./DataTypesBasicPolicies.sol"; import {Constants} from "../../Constants.sol"; import {Errors} from "../../Errors.sol"; import {IAddressRegistry} from "../interfaces/IAddressRegistry.sol"; import {ILenderVaultImpl} from "../interfaces/ILenderVaultImpl.sol"; import {IQuotePolicyManager} from "../interfaces/policyManagers/IQuotePolicyManager.sol"; contract BasicQuotePolicyManager is IQuotePolicyManager { mapping(address => DataTypesBasicPolicies.GlobalPolicy) internal _globalQuotingPolicies; mapping(address => mapping(address => mapping(address => DataTypesBasicPolicies.PairPolicy))) internal _pairQuotingPolicies; mapping(address => bool) internal _hasGlobalQuotingPolicy; mapping(address => mapping(address => mapping(address => bool))) internal _hasPairQuotingPolicy; address public immutable addressRegistry; constructor(address _addressRegistry) { addressRegistry = _addressRegistry; } // @dev: When no global policy is set (default case), all pairs are automatically blocked except // for those where a pair policy is explicitly set. In the case where a global policy is set, // all pairs are assumed to be allowed (no blocking). function setGlobalPolicy( address lenderVault, bytes calldata globalPolicyData ) external { // @dev: global policy applies across all pairs; // note: pair policies (if defined) take precedence over global policy _checkIsVaultAndSenderIsOwner(lenderVault); if (globalPolicyData.length > 0) { DataTypesBasicPolicies.GlobalPolicy memory globalPolicy = abi .decode( globalPolicyData, (DataTypesBasicPolicies.GlobalPolicy) ); DataTypesBasicPolicies.GlobalPolicy memory currGlobalPolicy = _globalQuotingPolicies[lenderVault]; if ( globalPolicy.requiresOracle == currGlobalPolicy.requiresOracle && _equalQuoteBounds( globalPolicy.quoteBounds, currGlobalPolicy.quoteBounds ) ) { revert Errors.PolicyAlreadySet(); } _checkNewQuoteBounds(globalPolicy.quoteBounds); if (!_hasGlobalQuotingPolicy[lenderVault]) { _hasGlobalQuotingPolicy[lenderVault] = true; } _globalQuotingPolicies[lenderVault] = globalPolicy; } else { if (!_hasGlobalQuotingPolicy[lenderVault]) { revert Errors.NoPolicyToDelete(); } delete _hasGlobalQuotingPolicy[lenderVault]; delete _globalQuotingPolicies[lenderVault]; } emit GlobalPolicySet(lenderVault, globalPolicyData); } // @dev: If no global policy is set, then setting a pair policy allows one to explicitly unblock a specific pair; // in the other case where a global policy is set, setting a pair policy allows overwriting global policy // parameters as well as overwriting minimum signer threshold requirements. function setPairPolicy( address lenderVault, address collToken, address loanToken, bytes calldata pairPolicyData ) external { // @dev: pair policies (if defined) take precedence over global policy _checkIsVaultAndSenderIsOwner(lenderVault); if (collToken == address(0) || loanToken == address(0)) { revert Errors.InvalidAddress(); } mapping(address => bool) storage _hasSingleQuotingPolicy = _hasPairQuotingPolicy[ lenderVault ][collToken]; if (pairPolicyData.length > 0) { DataTypesBasicPolicies.PairPolicy memory singlePolicy = abi.decode( pairPolicyData, (DataTypesBasicPolicies.PairPolicy) ); DataTypesBasicPolicies.PairPolicy memory currSinglePolicy = _pairQuotingPolicies[lenderVault][ collToken ][loanToken]; if ( singlePolicy.requiresOracle == currSinglePolicy.requiresOracle && singlePolicy.minNumOfSignersOverwrite == currSinglePolicy.minNumOfSignersOverwrite && singlePolicy.minLoanPerCollUnit == currSinglePolicy.minLoanPerCollUnit && singlePolicy.maxLoanPerCollUnit == currSinglePolicy.maxLoanPerCollUnit && _equalQuoteBounds( singlePolicy.quoteBounds, currSinglePolicy.quoteBounds ) ) { revert Errors.PolicyAlreadySet(); } _checkNewQuoteBounds(singlePolicy.quoteBounds); if ( singlePolicy.minLoanPerCollUnit == 0 || singlePolicy.minLoanPerCollUnit > singlePolicy.maxLoanPerCollUnit ) { revert Errors.InvalidLoanPerCollBounds(); } if (!_hasSingleQuotingPolicy[loanToken]) { _hasSingleQuotingPolicy[loanToken] = true; } _pairQuotingPolicies[lenderVault][collToken][ loanToken ] = singlePolicy; } else { if (!_hasSingleQuotingPolicy[loanToken]) { revert Errors.NoPolicyToDelete(); } delete _hasSingleQuotingPolicy[loanToken]; delete _pairQuotingPolicies[lenderVault][collToken][loanToken]; } emit PairPolicySet(lenderVault, collToken, loanToken, pairPolicyData); } function isAllowed( address /*borrower*/, address lenderVault, DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple ) external view returns (bool _isAllowed, uint256 minNumOfSignersOverwrite) { DataTypesBasicPolicies.GlobalPolicy memory globalPolicy = _globalQuotingPolicies[lenderVault]; bool hasPairPolicy = _hasPairQuotingPolicy[lenderVault][ generalQuoteInfo.collToken ][generalQuoteInfo.loanToken]; if (!_hasGlobalQuotingPolicy[lenderVault] && !hasPairPolicy) { return (false, 0); } // @dev: pair policy (if defined) takes precedence over global policy bool hasOracle = generalQuoteInfo.oracleAddr != address(0); bool checkLoanPerColl; bool requiresOracle; uint256[2] memory minMaxLoanPerCollUnit; DataTypesBasicPolicies.QuoteBounds memory quoteBounds; if (hasPairPolicy) { DataTypesBasicPolicies.PairPolicy memory singlePolicy = _pairQuotingPolicies[lenderVault][ generalQuoteInfo.collToken ][generalQuoteInfo.loanToken]; quoteBounds = singlePolicy.quoteBounds; minMaxLoanPerCollUnit[0] = singlePolicy.minLoanPerCollUnit; minMaxLoanPerCollUnit[1] = singlePolicy.maxLoanPerCollUnit; requiresOracle = singlePolicy.requiresOracle; minNumOfSignersOverwrite = singlePolicy.minNumOfSignersOverwrite; checkLoanPerColl = !hasOracle; } else { quoteBounds = globalPolicy.quoteBounds; requiresOracle = globalPolicy.requiresOracle; } if (requiresOracle && !hasOracle) { return (false, 0); } return ( _isAllowedWithBounds( quoteBounds, minMaxLoanPerCollUnit, quoteTuple, generalQuoteInfo.earliestRepayTenor, hasOracle, checkLoanPerColl ), minNumOfSignersOverwrite ); } function globalQuotingPolicy( address lenderVault ) external view returns (DataTypesBasicPolicies.GlobalPolicy memory) { if (!_hasGlobalQuotingPolicy[lenderVault]) { revert Errors.NoPolicy(); } return _globalQuotingPolicies[lenderVault]; } function pairQuotingPolicy( address lenderVault, address collToken, address loanToken ) external view returns (DataTypesBasicPolicies.PairPolicy memory) { if (!_hasPairQuotingPolicy[lenderVault][collToken][loanToken]) { revert Errors.NoPolicy(); } return _pairQuotingPolicies[lenderVault][collToken][loanToken]; } function hasGlobalQuotingPolicy( address lenderVault ) external view returns (bool) { return _hasGlobalQuotingPolicy[lenderVault]; } function hasPairQuotingPolicy( address lenderVault, address collToken, address loanToken ) external view returns (bool) { return _hasPairQuotingPolicy[lenderVault][collToken][loanToken]; } function _checkIsVaultAndSenderIsOwner(address lenderVault) internal view { if (!IAddressRegistry(addressRegistry).isRegisteredVault(lenderVault)) { revert Errors.UnregisteredVault(); } if (ILenderVaultImpl(lenderVault).owner() != msg.sender) { revert Errors.InvalidSender(); } } function _equalQuoteBounds( DataTypesBasicPolicies.QuoteBounds memory quoteBounds1, DataTypesBasicPolicies.QuoteBounds memory quoteBounds2 ) internal pure returns (bool isEqual) { if ( quoteBounds1.minTenor == quoteBounds2.minTenor && quoteBounds1.maxTenor == quoteBounds2.maxTenor && quoteBounds1.minFee == quoteBounds2.minFee && quoteBounds1.minApr == quoteBounds2.minApr && quoteBounds1.minLtv == quoteBounds2.minLtv && quoteBounds1.maxLtv == quoteBounds2.maxLtv ) { isEqual = true; } } function _checkNewQuoteBounds( DataTypesBasicPolicies.QuoteBounds memory quoteBounds ) internal pure { // @dev: allow minTenor == 0 to enable swaps if (quoteBounds.minTenor > quoteBounds.maxTenor) { revert Errors.InvalidTenorBounds(); } if ( quoteBounds.minLtv == 0 || quoteBounds.minLtv > quoteBounds.maxLtv ) { revert Errors.InvalidLtvBounds(); } if (quoteBounds.minApr + int(Constants.BASE) <= 0) { revert Errors.InvalidMinApr(); } // @dev: if minFee = BASE, then only swaps will be allowed if (quoteBounds.minFee > Constants.BASE) { revert Errors.InvalidMinFee(); } } function _isAllowedWithBounds( DataTypesBasicPolicies.QuoteBounds memory quoteBounds, uint256[2] memory minMaxLoanPerCollUnit, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple, uint256 earliestRepayTenor, bool checkLtv, bool checkLoanPerColl ) internal pure returns (bool) { if ( quoteTuple.tenor < quoteBounds.minTenor || quoteTuple.tenor > quoteBounds.maxTenor ) { return false; } if (checkLtv) { // @dev: check either against LTV bounds if ( quoteTuple.loanPerCollUnitOrLtv < quoteBounds.minLtv || quoteTuple.loanPerCollUnitOrLtv > quoteBounds.maxLtv ) { return false; } } else if ( // @dev: only check against absolute loan-per-coll bounds on pair policy and if no oracle checkLoanPerColl && (quoteTuple.loanPerCollUnitOrLtv < minMaxLoanPerCollUnit[0] || quoteTuple.loanPerCollUnitOrLtv > minMaxLoanPerCollUnit[1]) ) { return false; } // @dev: if tenor is zero then tx is swap and no need to check apr if (quoteTuple.tenor > 0) { int256 apr = (quoteTuple.interestRatePctInBase * SafeCast.toInt256(Constants.YEAR_IN_SECONDS)) / SafeCast.toInt256(quoteTuple.tenor); if (apr < quoteBounds.minApr) { return false; } // @dev: disallow if negative apr and earliest repay is below bound if ( apr < 0 && earliestRepayTenor < quoteBounds.minEarliestRepayTenor ) { return false; } // @dev: only check upfront fee for loans (can skip for swaps where tenor=0) if (quoteTuple.upfrontFeePctInBase < quoteBounds.minFee) { return false; } } return true; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; library DataTypesBasicPolicies { struct QuoteBounds { // Allowed minimum tenor for the quote (in seconds) uint32 minTenor; // Allowed maximum tenor for the quote (in seconds) uint32 maxTenor; // Allowed minimum fee for the quote (in BASE) uint80 minFee; // Allowed minimum APR for the quote (in BASE) int80 minApr; // Allowed minimum earliest repay tenor uint32 minEarliestRepayTenor; // Allowed minimum LTV for the quote uint128 minLtv; // Allowed maximum LTV for the quote uint128 maxLtv; } struct GlobalPolicy { // Applicable general bounds QuoteBounds quoteBounds; // Flag indicating if an oracle is required for the pair bool requiresOracle; } struct PairPolicy { // Applicable general bounds QuoteBounds quoteBounds; // Allowed minimum loan per collateral unit or LTV for the quote uint128 minLoanPerCollUnit; // Allowed maximum loan per collateral unit or LTV for the quote uint128 maxLoanPerCollUnit; // Flag indicating if an oracle is required for the pair bool requiresOracle; // Minimum number of signers required for the pair (if zero ignored, otherwise overwrites vault min signers) // @dev: can overwrite signer threshold to be lower or higher than vault min signers uint8 minNumOfSignersOverwrite; } }
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.19; import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import {Constants} from "../Constants.sol"; import {DataTypesPeerToPeer} from "./DataTypesPeerToPeer.sol"; import {Errors} from "../Errors.sol"; import {Helpers} from "../Helpers.sol"; import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol"; import {ILenderVaultImpl} from "./interfaces/ILenderVaultImpl.sol"; import {IQuoteHandler} from "./interfaces/IQuoteHandler.sol"; import {IQuotePolicyManager} from "./interfaces/policyManagers/IQuotePolicyManager.sol"; contract QuoteHandler is IQuoteHandler { using ECDSA for bytes32; address public immutable addressRegistry; mapping(address => uint256) public offChainQuoteNonce; mapping(address => mapping(bytes32 => bool)) public offChainQuoteIsInvalidated; mapping(address => mapping(bytes32 => bool)) public isOnChainQuote; mapping(bytes32 => bool) public isPublishedOnChainQuote; mapping(bytes32 => uint256) public publishedOnChainQuoteValidUntil; mapping(address => address) public quotePolicyManagerForVault; mapping(address => DataTypesPeerToPeer.OnChainQuoteInfo[]) internal _onChainQuoteHistory; constructor(address _addressRegistry) { if (_addressRegistry == address(0)) { revert Errors.InvalidAddress(); } addressRegistry = _addressRegistry; } function addOnChainQuote( address lenderVault, DataTypesPeerToPeer.OnChainQuote calldata onChainQuote ) external { _checkIsVaultAndSenderIsApproved(lenderVault, false); if (!_isValidOnChainQuote(onChainQuote)) { revert Errors.InvalidQuote(); } mapping(bytes32 => bool) storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault]; bytes32 onChainQuoteHash = _hashOnChainQuote(onChainQuote); if (isOnChainQuoteFromVault[onChainQuoteHash]) { revert Errors.OnChainQuoteAlreadyAdded(); } // @dev: on-chain quote history is append only _onChainQuoteHistory[lenderVault].push( DataTypesPeerToPeer.OnChainQuoteInfo({ quoteHash: onChainQuoteHash, validUntil: onChainQuote.generalQuoteInfo.validUntil }) ); isOnChainQuoteFromVault[onChainQuoteHash] = true; emit OnChainQuoteAdded(lenderVault, onChainQuote, onChainQuoteHash); } function updateOnChainQuote( address lenderVault, bytes32 oldOnChainQuoteHash, DataTypesPeerToPeer.OnChainQuote calldata newOnChainQuote ) external { _checkIsVaultAndSenderIsApproved(lenderVault, false); if (!_isValidOnChainQuote(newOnChainQuote)) { revert Errors.InvalidQuote(); } mapping(bytes32 => bool) storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault]; bytes32 newOnChainQuoteHash = _hashOnChainQuote(newOnChainQuote); // this check will catch the case where the old quote is the same as the new quote if (isOnChainQuoteFromVault[newOnChainQuoteHash]) { revert Errors.OnChainQuoteAlreadyAdded(); } if (!isOnChainQuoteFromVault[oldOnChainQuoteHash]) { revert Errors.UnknownOnChainQuote(); } // @dev: on-chain quote history is append only _onChainQuoteHistory[lenderVault].push( DataTypesPeerToPeer.OnChainQuoteInfo({ quoteHash: newOnChainQuoteHash, validUntil: newOnChainQuote.generalQuoteInfo.validUntil }) ); isOnChainQuoteFromVault[oldOnChainQuoteHash] = false; emit OnChainQuoteDeleted(lenderVault, oldOnChainQuoteHash); isOnChainQuoteFromVault[newOnChainQuoteHash] = true; emit OnChainQuoteAdded( lenderVault, newOnChainQuote, newOnChainQuoteHash ); } function deleteOnChainQuote( address lenderVault, bytes32 onChainQuoteHash ) external { _checkIsVaultAndSenderIsApproved(lenderVault, false); mapping(bytes32 => bool) storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault]; if (!isOnChainQuoteFromVault[onChainQuoteHash]) { revert Errors.UnknownOnChainQuote(); } isOnChainQuoteFromVault[onChainQuoteHash] = false; emit OnChainQuoteDeleted(lenderVault, onChainQuoteHash); } function copyPublishedOnChainQuote( address lenderVault, bytes32 onChainQuoteHash ) external { _checkIsVaultAndSenderIsApproved(lenderVault, false); mapping(bytes32 => bool) storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault]; uint256 validUntil = publishedOnChainQuoteValidUntil[onChainQuoteHash]; if ( !isPublishedOnChainQuote[onChainQuoteHash] || isOnChainQuoteFromVault[onChainQuoteHash] || validUntil < block.timestamp ) { revert Errors.InvalidQuote(); } // @dev: on-chain quote history is append only _onChainQuoteHistory[lenderVault].push( DataTypesPeerToPeer.OnChainQuoteInfo({ quoteHash: onChainQuoteHash, validUntil: validUntil }) ); isOnChainQuoteFromVault[onChainQuoteHash] = true; emit OnChainQuoteCopied(lenderVault, onChainQuoteHash); } function publishOnChainQuote( DataTypesPeerToPeer.OnChainQuote calldata onChainQuote ) external { if (!_isValidOnChainQuote(onChainQuote)) { revert Errors.InvalidQuote(); } bytes32 onChainQuoteHash = _hashOnChainQuote(onChainQuote); if (isPublishedOnChainQuote[onChainQuoteHash]) { revert Errors.AlreadyPublished(); } isPublishedOnChainQuote[onChainQuoteHash] = true; publishedOnChainQuoteValidUntil[onChainQuoteHash] = onChainQuote .generalQuoteInfo .validUntil; emit OnChainQuotePublished(onChainQuote, onChainQuoteHash, msg.sender); } function incrementOffChainQuoteNonce(address lenderVault) external { _checkIsVaultAndSenderIsApproved(lenderVault, true); uint256 newNonce = offChainQuoteNonce[lenderVault] + 1; offChainQuoteNonce[lenderVault] = newNonce; emit OffChainQuoteNonceIncremented(lenderVault, newNonce); } function invalidateOffChainQuote( address lenderVault, bytes32 offChainQuoteHash ) external { _checkIsVaultAndSenderIsApproved(lenderVault, true); offChainQuoteIsInvalidated[lenderVault][offChainQuoteHash] = true; emit OffChainQuoteInvalidated(lenderVault, offChainQuoteHash); } function checkAndRegisterOnChainQuote( address borrower, address lenderVault, uint256 quoteTupleIdx, DataTypesPeerToPeer.OnChainQuote calldata onChainQuote ) external { if (quoteTupleIdx >= onChainQuote.quoteTuples.length) { revert Errors.InvalidArrayIndex(); } // @dev: ignore returned minNumOfSignersOverwrite for on-chain quotes _checkSenderAndPolicyAndQuoteInfo( borrower, lenderVault, onChainQuote.generalQuoteInfo, onChainQuote.quoteTuples[quoteTupleIdx] ); mapping(bytes32 => bool) storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault]; bytes32 onChainQuoteHash = _hashOnChainQuote(onChainQuote); if (!isOnChainQuoteFromVault[onChainQuoteHash]) { revert Errors.UnknownOnChainQuote(); } if (onChainQuote.generalQuoteInfo.isSingleUse) { isOnChainQuoteFromVault[onChainQuoteHash] = false; emit OnChainQuoteInvalidated(lenderVault, onChainQuoteHash); } uint256 nextLoanIdx = ILenderVaultImpl(lenderVault).totalNumLoans(); emit OnChainQuoteUsed( lenderVault, onChainQuoteHash, nextLoanIdx, quoteTupleIdx ); } function checkAndRegisterOffChainQuote( address borrower, address lenderVault, DataTypesPeerToPeer.OffChainQuote calldata offChainQuote, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple, bytes32[] calldata proof ) external { uint256 minNumOfSignersOverwrite = _checkSenderAndPolicyAndQuoteInfo( borrower, lenderVault, offChainQuote.generalQuoteInfo, quoteTuple ); if (offChainQuote.nonce < offChainQuoteNonce[lenderVault]) { revert Errors.InvalidQuote(); } mapping(bytes32 => bool) storage offChainQuoteFromVaultIsInvalidated = offChainQuoteIsInvalidated[ lenderVault ]; bytes32 offChainQuoteHash = _hashOffChainQuote( offChainQuote, lenderVault ); if (offChainQuoteFromVaultIsInvalidated[offChainQuoteHash]) { revert Errors.OffChainQuoteHasBeenInvalidated(); } if ( !_areValidSignatures( lenderVault, offChainQuoteHash, minNumOfSignersOverwrite, offChainQuote.compactSigs ) ) { revert Errors.InvalidOffChainSignature(); } bytes32 leaf = keccak256( bytes.concat( keccak256( abi.encode( quoteTuple.loanPerCollUnitOrLtv, quoteTuple.interestRatePctInBase, quoteTuple.upfrontFeePctInBase, quoteTuple.tenor ) ) ) ); if (!MerkleProof.verify(proof, offChainQuote.quoteTuplesRoot, leaf)) { revert Errors.InvalidOffChainMerkleProof(); } if (offChainQuote.generalQuoteInfo.isSingleUse) { offChainQuoteFromVaultIsInvalidated[offChainQuoteHash] = true; emit OffChainQuoteInvalidated(lenderVault, offChainQuoteHash); } uint256 toBeRegisteredLoanId = ILenderVaultImpl(lenderVault) .totalNumLoans(); emit OffChainQuoteUsed( lenderVault, offChainQuoteHash, toBeRegisteredLoanId, quoteTuple ); } function updateQuotePolicyManagerForVault( address lenderVault, address newPolicyManagerAddress ) external { _checkIsVaultAndSenderIsApproved(lenderVault, true); if (newPolicyManagerAddress == address(0)) { delete quotePolicyManagerForVault[lenderVault]; } else { if ( IAddressRegistry(addressRegistry).whitelistState( newPolicyManagerAddress ) != DataTypesPeerToPeer.WhitelistState.QUOTE_POLICY_MANAGER || newPolicyManagerAddress == quotePolicyManagerForVault[lenderVault] ) { revert Errors.InvalidAddress(); } // note: this will overwrite any existing policy manager to a new valid quote policy manager quotePolicyManagerForVault[lenderVault] = newPolicyManagerAddress; } emit QuotePolicyManagerUpdated(lenderVault, newPolicyManagerAddress); } function getOnChainQuoteHistory( address lenderVault, uint256 idx ) external view returns (DataTypesPeerToPeer.OnChainQuoteInfo memory) { if (idx < _onChainQuoteHistory[lenderVault].length) { return _onChainQuoteHistory[lenderVault][idx]; } else { revert Errors.InvalidArrayIndex(); } } function getOnChainQuoteHistorySlice( address lenderVault, uint256 startIdx, uint256 endIdx ) external view returns (DataTypesPeerToPeer.OnChainQuoteInfo[] memory) { uint256 onChainQuoteHistoryLen = _onChainQuoteHistory[lenderVault] .length; if (startIdx > endIdx || startIdx >= onChainQuoteHistoryLen) { revert Errors.InvalidArrayIndex(); } endIdx = endIdx < onChainQuoteHistoryLen ? endIdx : onChainQuoteHistoryLen; if (startIdx == 0 && endIdx == onChainQuoteHistoryLen) { return _onChainQuoteHistory[lenderVault]; } DataTypesPeerToPeer.OnChainQuoteInfo[] memory onChainQuoteHistoryRequested = new DataTypesPeerToPeer.OnChainQuoteInfo[]( endIdx - startIdx ); for (uint256 i = startIdx; i < endIdx; ) { onChainQuoteHistoryRequested[i - startIdx] = _onChainQuoteHistory[ lenderVault ][i]; unchecked { ++i; } } return onChainQuoteHistoryRequested; } function getOnChainQuoteHistoryLength( address lenderVault ) external view returns (uint256) { return _onChainQuoteHistory[lenderVault].length; } /** * @dev The passed signatures must be sorted such that recovered addresses are increasing. */ function _areValidSignatures( address lenderVault, bytes32 offChainQuoteHash, uint256 minNumOfSignersOverwrite, bytes[] calldata compactSigs ) internal view returns (bool) { uint256 compactSigsLength = compactSigs.length; // @dev: if defined in policy, allow overwriting of min number of signers (except zero) uint256 minNumOfSigners = minNumOfSignersOverwrite == 0 ? ILenderVaultImpl(lenderVault).minNumOfSigners() : minNumOfSignersOverwrite; if (compactSigsLength < minNumOfSigners) { return false; } bytes32 messageHash = ECDSA.toEthSignedMessageHash(offChainQuoteHash); address recoveredSigner; address prevSigner; for (uint256 i; i < compactSigsLength; ) { (bytes32 r, bytes32 vs) = Helpers.splitSignature(compactSigs[i]); recoveredSigner = messageHash.recover(r, vs); if (!ILenderVaultImpl(lenderVault).isSigner(recoveredSigner)) { return false; } if (recoveredSigner <= prevSigner) { return false; } prevSigner = recoveredSigner; unchecked { ++i; } } return true; } function _hashOffChainQuote( DataTypesPeerToPeer.OffChainQuote memory offChainQuote, address lenderVault ) internal view returns (bytes32 quoteHash) { quoteHash = keccak256( abi.encode( offChainQuote.generalQuoteInfo, offChainQuote.quoteTuplesRoot, offChainQuote.salt, offChainQuote.nonce, lenderVault, block.chainid ) ); } function _checkSenderAndPolicyAndQuoteInfo( address borrower, address lenderVault, DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple ) internal view returns (uint256 minNumOfSignersOverwrite) { if (msg.sender != IAddressRegistry(addressRegistry).borrowerGateway()) { revert Errors.InvalidSender(); } address quotePolicyManager = quotePolicyManagerForVault[lenderVault]; if (quotePolicyManager != address(0)) { bool isAllowed; (isAllowed, minNumOfSignersOverwrite) = IQuotePolicyManager( quotePolicyManager ).isAllowed(borrower, lenderVault, generalQuoteInfo, quoteTuple); if (!isAllowed) { revert Errors.QuoteViolatesPolicy(); } } _checkWhitelist( generalQuoteInfo.collToken, generalQuoteInfo.loanToken, generalQuoteInfo.borrowerCompartmentImplementation, generalQuoteInfo.oracleAddr, _isSwap(generalQuoteInfo, quoteTuple) ); if (generalQuoteInfo.validUntil < block.timestamp) { revert Errors.OutdatedQuote(); } if ( generalQuoteInfo.collToken == generalQuoteInfo.loanToken || generalQuoteInfo.maxLoan == 0 || generalQuoteInfo.minLoan == 0 || generalQuoteInfo.minLoan > generalQuoteInfo.maxLoan ) { revert Errors.InvalidQuote(); } if ( generalQuoteInfo.whitelistAddr != address(0) && ((generalQuoteInfo.isWhitelistAddrSingleBorrower && generalQuoteInfo.whitelistAddr != borrower) || (!generalQuoteInfo.isWhitelistAddrSingleBorrower && !IAddressRegistry(addressRegistry).isWhitelistedBorrower( generalQuoteInfo.whitelistAddr, borrower ))) ) { revert Errors.InvalidBorrower(); } } function _isValidOnChainQuote( DataTypesPeerToPeer.OnChainQuote calldata onChainQuote ) internal view returns (bool) { if ( onChainQuote.generalQuoteInfo.collToken == onChainQuote.generalQuoteInfo.loanToken ) { return false; } if (onChainQuote.generalQuoteInfo.validUntil < block.timestamp) { return false; } if ( onChainQuote.generalQuoteInfo.maxLoan == 0 || onChainQuote.generalQuoteInfo.minLoan == 0 || onChainQuote.generalQuoteInfo.minLoan > onChainQuote.generalQuoteInfo.maxLoan ) { return false; } uint256 quoteTuplesLen = onChainQuote.quoteTuples.length; if (quoteTuplesLen == 0) { return false; } bool isSwap; for (uint256 k; k < quoteTuplesLen; ) { (bool isValid, bool isSwapCurr) = _isValidOnChainQuoteTuple( onChainQuote.generalQuoteInfo, onChainQuote.quoteTuples[k] ); if (!isValid) { return false; } if (isSwapCurr && quoteTuplesLen > 1) { return false; } isSwap = isSwapCurr; unchecked { ++k; } } _checkWhitelist( onChainQuote.generalQuoteInfo.collToken, onChainQuote.generalQuoteInfo.loanToken, onChainQuote.generalQuoteInfo.borrowerCompartmentImplementation, onChainQuote.generalQuoteInfo.oracleAddr, isSwap ); return true; } function _checkWhitelist( address collToken, address loanToken, address compartmentImpl, address oracleAddr, bool isSwap ) internal view { if ( !IAddressRegistry(addressRegistry).isWhitelistedERC20(loanToken) || !IAddressRegistry(addressRegistry).isWhitelistedERC20(collToken) ) { revert Errors.NonWhitelistedToken(); } if (isSwap) { if (compartmentImpl != address(0)) { revert Errors.InvalidSwap(); } return; } if (compartmentImpl == address(0)) { DataTypesPeerToPeer.WhitelistState collTokenWhitelistState = IAddressRegistry( addressRegistry ).whitelistState(collToken); if ( collTokenWhitelistState == DataTypesPeerToPeer .WhitelistState .ERC20_TOKEN_REQUIRING_COMPARTMENT ) { revert Errors.CollateralMustBeCompartmentalized(); } } else { if ( !IAddressRegistry(addressRegistry).isWhitelistedCompartment( compartmentImpl, collToken ) ) { revert Errors.InvalidCompartmentForToken(); } } if ( oracleAddr != address(0) && IAddressRegistry(addressRegistry).whitelistState(oracleAddr) != DataTypesPeerToPeer.WhitelistState.ORACLE ) { revert Errors.NonWhitelistedOracle(); } } function _checkIsVaultAndSenderIsApproved( address lenderVault, bool onlyOwner ) internal view { if (!IAddressRegistry(addressRegistry).isRegisteredVault(lenderVault)) { revert Errors.UnregisteredVault(); } if ( ILenderVaultImpl(lenderVault).owner() != msg.sender && (onlyOwner || ILenderVaultImpl(lenderVault).onChainQuotingDelegate() != msg.sender) ) { revert Errors.InvalidSender(); } } function _hashOnChainQuote( DataTypesPeerToPeer.OnChainQuote memory onChainQuote ) internal pure returns (bytes32 quoteHash) { quoteHash = keccak256(abi.encode(onChainQuote)); } function _isValidOnChainQuoteTuple( DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple ) internal pure returns (bool, bool) { bool isSwap = _isSwap(generalQuoteInfo, quoteTuple); if (quoteTuple.upfrontFeePctInBase < Constants.BASE) { // note: if upfrontFee<100% this corresponds to a loan; check that tenor and earliest repay are consistent if ( quoteTuple.tenor < generalQuoteInfo.earliestRepayTenor + Constants.MIN_TIME_BETWEEN_EARLIEST_REPAY_AND_EXPIRY ) { return (false, isSwap); } } else if (quoteTuple.upfrontFeePctInBase == Constants.BASE) { // note: if upfrontFee=100% this corresponds to an outright swap; check other fields are consistent if (!isSwap) { return (false, isSwap); } } else { // note: if upfrontFee>100% this is invalid return (false, isSwap); } if (quoteTuple.loanPerCollUnitOrLtv == 0) { return (false, isSwap); } // If the oracle address is set and there is not specified whitelistAddr // then LTV must be set to a value <= 100% (overcollateralized). // note: Loans with whitelisted borrowers CAN be undercollateralized with oracles (LTV > 100%). // oracle address is set // ---> whitelistAddr is not set // ---> ---> LTV must be overcollateralized // ---> whitelistAddr is set // ---> ---> LTV can be any // oracle address is not set // ---> loanPerCollUnit can be any with or without whitelistAddr if ( generalQuoteInfo.oracleAddr != address(0) && quoteTuple.loanPerCollUnitOrLtv > Constants.BASE && generalQuoteInfo.whitelistAddr == address(0) ) { return (false, isSwap); } if (quoteTuple.interestRatePctInBase + int(Constants.BASE) <= 0) { return (false, isSwap); } return (true, isSwap); } function _isSwap( DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo, DataTypesPeerToPeer.QuoteTuple calldata quoteTuple ) internal pure returns (bool) { return quoteTuple.upfrontFeePctInBase == Constants.BASE && quoteTuple.tenor + generalQuoteInfo.earliestRepayTenor == 0 && quoteTuple.interestRatePctInBase == 0 && generalQuoteInfo.borrowerCompartmentImplementation == address(0); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IAddressRegistry} from "../../interfaces/IAddressRegistry.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {DataTypesPeerToPeer} from "../../../peer-to-peer/DataTypesPeerToPeer.sol"; import {Errors} from "../../../Errors.sol"; import {IERC20Wrapper} from "../../interfaces/wrappers/ERC20/IERC20Wrapper.sol"; import {IWrappedERC20Impl} from "../../interfaces/wrappers/ERC20/IWrappedERC20Impl.sol"; /** * @dev ERC20Wrapper is a contract that wraps tokens from possibly multiple ERC20 contracts * IMPORTANT: This contract allows for wrapping tokens that are whitelisted with the address registry. */ contract ERC20Wrapper is ReentrancyGuard, IERC20Wrapper { using SafeERC20 for IERC20; address public immutable addressRegistry; address public immutable wrappedErc20Impl; address[] public tokensCreated; constructor(address _addressRegistry, address _wrappedErc20Impl) { if (_addressRegistry == address(0) || _wrappedErc20Impl == address(0)) { revert Errors.InvalidAddress(); } addressRegistry = _addressRegistry; wrappedErc20Impl = _wrappedErc20Impl; } // token addresses must be unique and passed in increasing order. // token amounts must be non-zero. // minter must approve this contract to transfer all tokens to be wrapped. function createWrappedToken( address minter, DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped, string calldata name, string calldata symbol ) external nonReentrant returns (address newErc20Addr) { if (msg.sender != addressRegistry) { revert Errors.InvalidSender(); } if (minter == address(0) || minter == address(this)) { revert Errors.InvalidAddress(); } // @dev: allow multiple wrappers with same underlyings to exist // note: in case a griefer wanted to lock-up a wrapper token one could easily create another one newErc20Addr = Clones.clone(wrappedErc20Impl); tokensCreated.push(newErc20Addr); // @dev: external call happens before state update due to minTokenAmount determination ( uint256 numTokensToBeWrapped, uint256 minTokenAmount ) = _transferTokens(minter, tokensToBeWrapped, newErc20Addr); // @dev: case where numTokensToBeWrapped == 0 represents an IOU token IWrappedERC20Impl(newErc20Addr).initialize( minter, tokensToBeWrapped, numTokensToBeWrapped == 0 ? 10 ** 18 : minTokenAmount, name, symbol ); emit ERC20WrapperCreated( newErc20Addr, minter, tokensCreated.length, tokensToBeWrapped ); } function allTokensCreated() external view returns (address[] memory) { return tokensCreated; } function numTokensCreated() external view returns (uint256) { return tokensCreated.length; } function _transferTokens( address minter, DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped, address newErc20Addr ) internal returns (uint256 numTokensToBeWrapped, uint256 minTokenAmount) { minTokenAmount = type(uint256).max; address prevTokenAddress; address currAddress; numTokensToBeWrapped = tokensToBeWrapped.length; for (uint256 i; i < numTokensToBeWrapped; ) { if ( !IAddressRegistry(addressRegistry).isWhitelistedERC20( tokensToBeWrapped[i].tokenAddr ) ) { revert Errors.NonWhitelistedToken(); } currAddress = tokensToBeWrapped[i].tokenAddr; if (currAddress <= prevTokenAddress) { revert Errors.NonIncreasingTokenAddrs(); } if (tokensToBeWrapped[i].tokenAmount == 0) { revert Errors.InvalidSendAmount(); } minTokenAmount = minTokenAmount > tokensToBeWrapped[i].tokenAmount ? tokensToBeWrapped[i].tokenAmount : minTokenAmount; IERC20(tokensToBeWrapped[i].tokenAddr).safeTransferFrom( minter, newErc20Addr, tokensToBeWrapped[i].tokenAmount ); prevTokenAddress = currAddress; unchecked { ++i; } } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {Constants} from "../../../Constants.sol"; import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol"; import {Errors} from "../../../Errors.sol"; import {IAddressRegistry} from "../../interfaces/IAddressRegistry.sol"; import {IWrappedERC20Impl} from "../../interfaces/wrappers/ERC20/IWrappedERC20Impl.sol"; contract WrappedERC20Impl is ERC20, Initializable, ReentrancyGuard, IWrappedERC20Impl { using SafeERC20 for IERC20Metadata; string internal _tokenName; string internal _tokenSymbol; uint8 internal _tokenDecimals; address[] internal _wrappedTokens; constructor() ERC20("Wrapped ERC20 Impl", "Wrapped ERC20 Impl") { _disableInitializers(); } function initialize( address minter, DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata wrappedTokens, uint256 totalInitialSupply, string calldata _name, string calldata _symbol ) external initializer { uint256 wrappedTokensLen = wrappedTokens.length; if (wrappedTokensLen == 1) { // check for minimum mint amount if (totalInitialSupply <= Constants.SINGLE_WRAPPER_MIN_MINT) { revert Errors.InvalidMintAmount(); } _tokenDecimals = IERC20Metadata(wrappedTokens[0].tokenAddr) .decimals(); _wrappedTokens.push(wrappedTokens[0].tokenAddr); // @dev: mint small dust amount to this address, which will be locked in contract // @note: given this initial mint amount the wrapper cannot easily be locked up for future mints _mint(address(this), Constants.SINGLE_WRAPPER_MIN_MINT); _mint( minter, totalInitialSupply - Constants.SINGLE_WRAPPER_MIN_MINT ); } else { _tokenDecimals = 18; for (uint256 i; i < wrappedTokensLen; ) { _wrappedTokens.push(wrappedTokens[i].tokenAddr); unchecked { ++i; } } _mint( minter, totalInitialSupply < 10 ** 18 ? totalInitialSupply : 10 ** 18 ); } _tokenName = _name; _tokenSymbol = _symbol; } function redeem( address account, address recipient, uint256 amount ) external nonReentrant { if (amount == 0) { revert Errors.InvalidAmount(); } if (recipient == address(0)) { revert Errors.InvalidAddress(); } uint256 currTotalSupply = totalSupply(); if (msg.sender != account) { _spendAllowance(account, msg.sender, amount); } _burn(account, amount); // @dev: if isIOU then _wrappedTokens.length == 0 and this loop is skipped automatically uint256 wrappedTokensLen = _wrappedTokens.length; for (uint256 i; i < wrappedTokensLen; ) { address tokenAddr = _wrappedTokens[i]; // @note: The underlying token transfers are all-or-nothing. In other words, if one token transfer fails, // the entire redemption process will fail as well. Users should only use wrappers if they deem this risk // to be acceptable or non-existent (for example, in cases where the underlying tokens can never have any // transfer restrictions). uint256 redemptionAmount = Math.mulDiv( IERC20Metadata(tokenAddr).balanceOf(address(this)), amount, currTotalSupply ); IERC20Metadata(tokenAddr).safeTransfer(recipient, redemptionAmount); unchecked { ++i; } } emit Redeemed(account, recipient, amount); } function mint( address recipient, uint256 amount, uint256 expectedTransferFee ) external nonReentrant { if (_wrappedTokens.length != 1) { // @dev: only on single token wrappers do we allow minting // @note: IOU has no underlying tokens, so they are also disabled from minting revert Errors.OnlyMintFromSingleTokenWrapper(); } if (amount == 0) { revert Errors.InvalidAmount(); } if (recipient == address(0)) { revert Errors.InvalidAddress(); } uint256 currTotalSupply = totalSupply(); address tokenAddr = _wrappedTokens[0]; uint256 tokenPreBal = IERC20Metadata(tokenAddr).balanceOf( address(this) ); if (tokenPreBal == 0) { // @dev: this would be an unintended state, for instance a negative rebase down to 0 balance with still outstanding supply // in which case to not allow possibly diluted or unfair proportions for new minters, will revert // @note: the state token balance > 0, but total supply == 0 is allowed (e.g. donations to address before mint) revert Errors.NonMintableTokenState(); } uint256 mintAmount = Math.mulDiv(amount, currTotalSupply, tokenPreBal); // @dev: revert in case mint amount is truncated to zero. This may also happen in case the mint transaction is front-run // with donations. Note that griefing with donations will be costly due to redemption fee. if (mintAmount == 0) { revert Errors.InvalidMintAmount(); } _mint(recipient, mintAmount); IERC20Metadata(tokenAddr).safeTransferFrom( msg.sender, address(this), amount + expectedTransferFee ); uint256 tokenPostBal = IERC20Metadata(tokenAddr).balanceOf( address(this) ); if (tokenPostBal != tokenPreBal + amount) { revert Errors.InvalidSendAmount(); } } function isIOU() external view returns (bool) { return _wrappedTokens.length == 0; } function getWrappedTokensInfo() external view returns (address[] memory) { return _wrappedTokens; } function name() public view virtual override returns (string memory) { return _tokenName; } function symbol() public view virtual override returns (string memory) { return _tokenSymbol; } function decimals() public view virtual override returns (uint8) { return _tokenDecimals; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IAddressRegistry} from "../../interfaces/IAddressRegistry.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol"; import {Errors} from "../../../Errors.sol"; import {IERC721Wrapper} from "../../interfaces/wrappers/ERC721/IERC721Wrapper.sol"; import {IWrappedERC721Impl} from "../../interfaces/wrappers/ERC721/IWrappedERC721Impl.sol"; /** * @dev ERC721Wrapper is a contract that wraps tokens from possibly multiple contracts and ids * IMPORTANT: This contract allows for whitelisting registered token addresses IF an address registry is provided. * This is to prevent the creation of wrapped tokens for non-registered tokens if that is a functionality that * is desired. If not, then the address registry can be set to the zero address. */ contract ERC721Wrapper is ReentrancyGuard, IERC721Wrapper { address public immutable addressRegistry; address public immutable wrappedErc721Impl; address[] public tokensCreated; constructor(address _addressRegistry, address _wrappedErc721Impl) { if ( _addressRegistry == address(0) || _wrappedErc721Impl == address(0) ) { revert Errors.InvalidAddress(); } addressRegistry = _addressRegistry; wrappedErc721Impl = _wrappedErc721Impl; } // token ids must be unique and passed in increasing order for each token address. // minter must approve this contract to transfer all tokens to be wrapped. function createWrappedToken( address minter, DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped, string calldata name, string calldata symbol ) external nonReentrant returns (address newErc20Addr) { if (msg.sender != addressRegistry) { revert Errors.InvalidSender(); } if (minter == address(0) || minter == address(this)) { revert Errors.InvalidAddress(); } uint256 numTokensToBeWrapped = tokensToBeWrapped.length; if (numTokensToBeWrapped == 0) { revert Errors.InvalidArrayLength(); } // note: this will revert if the wrapped token already exists // this is to prevent the creation of duplicate wrapped tokens // will need to use the remint on the already existing token address // also unique ordering of token addresses and ids enforces uniqueness of wrapped token address // e.g. you can't mint a wrapped token for token address A with token ids 1, 2, 3 and then // mint a wrapped token for token address A with token ids 3, 2, 1 newErc20Addr = Clones.cloneDeterministic( wrappedErc721Impl, keccak256(abi.encode(tokensToBeWrapped)) ); tokensCreated.push(newErc20Addr); IWrappedERC721Impl(newErc20Addr).initialize( minter, tokensToBeWrapped, name, symbol ); _transferTokens( minter, numTokensToBeWrapped, tokensToBeWrapped, newErc20Addr ); emit ERC721WrapperCreated( newErc20Addr, minter, tokensCreated.length, tokensToBeWrapped ); } function allTokensCreated() external view returns (address[] memory) { return tokensCreated; } function numTokensCreated() external view returns (uint256) { return tokensCreated.length; } function _transferTokens( address minter, uint256 numTokensToBeWrapped, DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped, address newErc20Addr ) internal { address prevNftAddress; address currNftAddress; uint256 checkedId; for (uint256 i; i < numTokensToBeWrapped; ) { uint256 numTokenIds = tokensToBeWrapped[i].tokenIds.length; if (numTokenIds == 0) { revert Errors.InvalidArrayLength(); } if ( IAddressRegistry(addressRegistry).whitelistState( tokensToBeWrapped[i].tokenAddr ) != DataTypesPeerToPeer.WhitelistState.ERC721_TOKEN ) { revert Errors.NonWhitelistedToken(); } currNftAddress = tokensToBeWrapped[i].tokenAddr; if (currNftAddress <= prevNftAddress) { revert Errors.NonIncreasingTokenAddrs(); } for (uint256 j; j < numTokenIds; ) { if (tokensToBeWrapped[i].tokenIds[j] <= checkedId && j != 0) { revert Errors.NonIncreasingNonFungibleTokenIds(); } checkedId = tokensToBeWrapped[i].tokenIds[j]; try IERC721(tokensToBeWrapped[i].tokenAddr).transferFrom( minter, newErc20Addr, checkedId ) { unchecked { ++j; } } catch { revert Errors.TransferToWrappedTokenFailed(); } } prevNftAddress = currNftAddress; unchecked { ++i; } } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol"; import {Errors} from "../../../Errors.sol"; import {IWrappedERC721Impl} from "../../interfaces/wrappers/ERC721/IWrappedERC721Impl.sol"; contract WrappedERC721Impl is ERC20, Initializable, ReentrancyGuard, IWrappedERC721Impl { string internal _tokenName; string internal _tokenSymbol; DataTypesPeerToPeer.WrappedERC721TokenInfo[] internal _wrappedTokens; address public lastRedeemer; mapping(address => mapping(uint256 => bool)) public stuckTokens; mapping(address => mapping(uint256 => bool)) public isTokenCountedInWrapper; mapping(address => mapping(uint256 => bool)) public isUnderlying; uint128[2] internal totalAndCurrentNumOfTokensInWrapper; constructor() ERC20("Wrapped ERC721 Impl", "Wrapped ERC721 Impl") { _disableInitializers(); } function initialize( address minter, DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata wrappedTokens, string calldata _name, string calldata _symbol ) external initializer { uint128 numTokens; for (uint256 i; i < wrappedTokens.length; ) { _wrappedTokens.push(wrappedTokens[i]); for (uint256 j; j < wrappedTokens[i].tokenIds.length; ) { mapping(uint256 => bool) storage isTokenAddr = isUnderlying[ wrappedTokens[i].tokenAddr ]; mapping(uint256 => bool) storage isTokenIdInWrapper = isTokenCountedInWrapper[ wrappedTokens[i].tokenAddr ]; isTokenAddr[wrappedTokens[i].tokenIds[j]] = true; isTokenIdInWrapper[wrappedTokens[i].tokenIds[j]] = true; unchecked { ++numTokens; ++j; } } unchecked { ++i; } } _tokenName = _name; _tokenSymbol = _symbol; // @dev: packed storage layout to track total number of tokens and current number of tokens in wrapper // this is to prevent having to loop through all the tokens to get the total supply on remints with stuck tokens totalAndCurrentNumOfTokensInWrapper = [numTokens, numTokens]; _mint(minter, 1); } function redeem(address account, address recipient) external nonReentrant { if (recipient == address(0)) { revert Errors.InvalidAddress(); } if (msg.sender != account) { _spendAllowance(account, msg.sender, 1); } _burn(account, 1); lastRedeemer = account; address tokenAddr; uint256 tokenId; uint128 tokensRemoved; for (uint256 i; i < _wrappedTokens.length; ) { tokenAddr = _wrappedTokens[i].tokenAddr; for (uint256 j; j < _wrappedTokens[i].tokenIds.length; ) { tokenId = _wrappedTokens[i].tokenIds[j]; try IERC721(tokenAddr).safeTransferFrom( address(this), recipient, tokenId ) { ++tokensRemoved; isTokenCountedInWrapper[tokenAddr][tokenId] = false; } catch { stuckTokens[tokenAddr][tokenId] = true; emit TransferFromWrappedTokenFailed(tokenAddr, tokenId); } unchecked { ++j; } } unchecked { ++i; } } if (tokensRemoved == 0) { revert Errors.NoTokensTransferred(); } unchecked { totalAndCurrentNumOfTokensInWrapper[1] -= tokensRemoved; } emit Redeemed(account, recipient); } function sweepTokensLeftAfterRedeem( address tokenAddr, uint256[] calldata tokenIds ) external nonReentrant { if (msg.sender != lastRedeemer) { revert Errors.InvalidSender(); } if (tokenIds.length == 0) { revert Errors.InvalidArrayLength(); } mapping(uint256 => bool) storage stuckTokenAddr = stuckTokens[ tokenAddr ]; mapping(uint256 => bool) storage isTokenIdInWrapper = isTokenCountedInWrapper[tokenAddr]; uint128 tokensRemoved; for (uint256 i; i < tokenIds.length; ) { if (!stuckTokenAddr[tokenIds[i]]) { revert Errors.TokenNotStuck(); } try IERC721(tokenAddr).safeTransferFrom( address(this), msg.sender, tokenIds[i] ) { delete stuckTokenAddr[tokenIds[i]]; delete isTokenIdInWrapper[tokenIds[i]]; ++tokensRemoved; } catch { emit TransferFromWrappedTokenFailed(tokenAddr, tokenIds[i]); } unchecked { ++i; } } if (tokensRemoved == 0) { revert Errors.NoTokensTransferred(); } unchecked { totalAndCurrentNumOfTokensInWrapper[1] -= tokensRemoved; } emit TokenSweepAttempted(tokenAddr, tokenIds); } function remint( DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata _wrappedTokensForRemint, address recipient ) external nonReentrant { if (recipient == address(0)) { revert Errors.InvalidAddress(); } if (totalSupply() != 0) { // @note: totalSupply can be zero yet there are still tokens in the wrapper due to being stuck revert Errors.CannotRemintUnlessZeroSupply(); } // whoever remints must be able to transfer all the tokens to be reminted (all non-stuck tokens) back // to this contract. If even one transfer fails, then the remint fails. uint128 tokensNeeded = totalAndCurrentNumOfTokensInWrapper[0] - totalAndCurrentNumOfTokensInWrapper[1]; totalAndCurrentNumOfTokensInWrapper[ 1 ] = totalAndCurrentNumOfTokensInWrapper[0]; if (tokensNeeded == 0 && msg.sender != lastRedeemer) { // @note: tokensNeeded = 0 is case where the wrapper through sync function has all tokens accounted for // in this special case, since no transfer is made, we allow only the lastRedeemer to remint to // avoid race conditions for anyone being able to remint. In cases where the wrapper has tokens // being transferred, then sender with that permission to transfer those tokens (owner or approved) can remint revert Errors.InvalidSender(); } if (_wrappedTokensForRemint.length == 0 && tokensNeeded != 0) { revert Errors.InvalidArrayLength(); } _mint(recipient, 1); uint128 tokensAdded = _wrappedTokensForRemint.length == 0 ? 0 : _transferTokens(_wrappedTokensForRemint); if (tokensAdded != tokensNeeded) { revert Errors.TokensStillMissingFromWrapper(); } } function sync(address tokenAddr, uint256 tokenId) external nonReentrant { mapping(uint256 => bool) storage isTokenIdInWrapper = isTokenCountedInWrapper[tokenAddr]; if (isTokenIdInWrapper[tokenId]) { revert Errors.TokenAlreadyCountedInWrapper(); } if (!isUnderlying[tokenAddr][tokenId]) { revert Errors.TokenDoesNotBelongInWrapper(tokenAddr, tokenId); } isTokenIdInWrapper[tokenId] = true; unchecked { ++totalAndCurrentNumOfTokensInWrapper[1]; } if (IERC721(tokenAddr).ownerOf(tokenId) != address(this)) { revert Errors.TokenNotOwnedByWrapper(); } } function getWrappedTokensInfo() external view returns (DataTypesPeerToPeer.WrappedERC721TokenInfo[] memory) { return _wrappedTokens; } function getTotalAndCurrentNumOfTokensInWrapper() external view returns (uint128[2] memory) { return totalAndCurrentNumOfTokensInWrapper; } function name() public view virtual override returns (string memory) { return _tokenName; } function symbol() public view virtual override returns (string memory) { return _tokenSymbol; } function decimals() public view virtual override returns (uint8) { return 0; } // @dev: no need for ordering check here function _transferTokens( DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped ) internal returns (uint128 numTokensAdded) { uint256 checkedId; address currNftAddress; for (uint256 i; i < tokensToBeWrapped.length; ) { if (tokensToBeWrapped[i].tokenIds.length == 0) { revert Errors.InvalidArrayLength(); } currNftAddress = tokensToBeWrapped[i].tokenAddr; for (uint256 j; j < tokensToBeWrapped[i].tokenIds.length; ) { checkedId = tokensToBeWrapped[i].tokenIds[j]; if (!isUnderlying[currNftAddress][checkedId]) { revert Errors.TokenDoesNotBelongInWrapper( currNftAddress, checkedId ); } try IERC721(currNftAddress).transferFrom( msg.sender, address(this), checkedId ) { isTokenCountedInWrapper[currNftAddress][checkedId] = true; unchecked { ++numTokensAdded; ++j; } } catch { revert Errors.TransferToWrappedTokenFailed(); } } unchecked { ++i; } } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; library DataTypesPeerToPool { struct Repayment { // The loan token amount due for given period; initially, expressed in relative terms (100%=BASE), once // finalized in absolute terms (in loanToken) uint128 loanTokenDue; // The coll token amount that can be converted for given period; initially, expressed in relative terms w.r.t. // loanTokenDue (e.g., convert every 1 loanToken for 8 collToken), once finalized in absolute terms (in collToken) uint128 collTokenDueIfConverted; // Timestamp when repayment is due uint40 dueTimestamp; } struct LoanTerms { // Min subscription amount (in loan token) that the borrower deems acceptable uint128 minTotalSubscriptions; // Max subscription amount (in loan token) that the borrower deems acceptable uint128 maxTotalSubscriptions; // The number of collateral tokens the borrower pledges per loan token borrowed as collateral for default case uint128 collPerLoanToken; // Borrower who can finalize given loan proposal address borrower; // Array of scheduled repayments Repayment[] repaymentSchedule; } struct StaticLoanProposalData { // Factory address from which the loan proposal is created address factory; // Funding pool address that is associated with given loan proposal and from which loan liquidity can be // sourced address fundingPool; // Address of collateral token to be used for given loan proposal address collToken; // Address of arranger who can manage the loan proposal contract address arranger; // Address of whitelist authority who can manage the lender whitelist (optional) address whitelistAuthority; // Unsubscribe grace period (in seconds), i.e., after acceptance by borrower lenders can unsubscribe and // remove liquidity for this duration before being locked-in uint256 unsubscribeGracePeriod; // Conversion grace period (in seconds), i.e., lenders can exercise their conversion right between // [dueTimeStamp, dueTimeStamp+conversionGracePeriod] uint256 conversionGracePeriod; // Repayment grace period (in seconds), i.e., borrowers can repay between // [dueTimeStamp+conversionGracePeriod, dueTimeStamp+conversionGracePeriod+repaymentGracePeriod] uint256 repaymentGracePeriod; } struct DynamicLoanProposalData { // Arranger fee charged on final loan amount, initially in relative terms (100%=BASE), and after finalization // in absolute terms (in loan token) uint256 arrangerFee; // The gross loan amount; initially this is zero and gets set once loan proposal gets accepted and finalized; // note that the borrower receives the gross loan amount minus any arranger and protocol fees uint256 grossLoanAmount; // Final collateral amount reserved for defaults; initially this is zero and gets set once loan proposal got // accepted and finalized uint256 finalCollAmountReservedForDefault; // Final collateral amount reserved for conversions; initially this is zero and gets set once loan proposal got // accepted and finalized uint256 finalCollAmountReservedForConversions; // Timestamp when the loan terms get accepted by borrower and after which they cannot be changed anymore uint256 loanTermsLockedTime; // Current repayment index, mapping to currently relevant repayment schedule element; note the // currentRepaymentIdx (initially 0) only ever gets incremented on repay uint256 currentRepaymentIdx; // Status of current loan proposal DataTypesPeerToPool.LoanStatus status; // Protocol fee, initially in relative terms (100%=BASE), and after finalization in absolute terms (in loan token); // note that the relative protocol fee is locked in at the time when the loan proposal is created uint256 protocolFee; } enum LoanStatus { WITHOUT_LOAN_TERMS, IN_NEGOTIATION, LOAN_TERMS_LOCKED, READY_TO_EXECUTE, ROLLBACK, LOAN_DEPLOYED, DEFAULTED } }
{ "optimizer": { "enabled": true, "runs": 1000 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "abi" ] } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"address","name":"_addressRegistry","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"DeadlinePassed","type":"error"},{"inputs":[],"name":"InconsistentExpVaultBalIncrease","type":"error"},{"inputs":[],"name":"InsufficientSendAmount","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidBorrower","type":"error"},{"inputs":[],"name":"InvalidFee","type":"error"},{"inputs":[],"name":"InvalidRepayAmount","type":"error"},{"inputs":[],"name":"InvalidSendAmount","type":"error"},{"inputs":[],"name":"InvalidSender","type":"error"},{"inputs":[],"name":"NonWhitelistedCallback","type":"error"},{"inputs":[],"name":"OutsideValidRepayWindow","type":"error"},{"inputs":[],"name":"ReclaimAmountIsZero","type":"error"},{"inputs":[],"name":"UnregisteredVault","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"vaultAddr","type":"address"},{"indexed":true,"internalType":"address","name":"borrower","type":"address"},{"components":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"address","name":"collToken","type":"address"},{"internalType":"address","name":"loanToken","type":"address"},{"internalType":"uint40","name":"expiry","type":"uint40"},{"internalType":"uint40","name":"earliestRepay","type":"uint40"},{"internalType":"uint128","name":"initCollAmount","type":"uint128"},{"internalType":"uint128","name":"initLoanAmount","type":"uint128"},{"internalType":"uint128","name":"initRepayAmount","type":"uint128"},{"internalType":"uint128","name":"amountRepaidSoFar","type":"uint128"},{"internalType":"uint128","name":"amountReclaimedSoFar","type":"uint128"},{"internalType":"bool","name":"collUnlocked","type":"bool"},{"internalType":"address","name":"collTokenCompartmentAddr","type":"address"}],"indexed":false,"internalType":"struct DataTypesPeerToPeer.Loan","name":"loan","type":"tuple"},{"indexed":false,"internalType":"uint256","name":"upfrontFee","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"loanId","type":"uint256"},{"indexed":false,"internalType":"address","name":"callbackAddr","type":"address"},{"indexed":false,"internalType":"bytes","name":"callbackData","type":"bytes"}],"name":"Borrowed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint128[2]","name":"newFeeParams","type":"uint128[2]"}],"name":"ProtocolFeeSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"vaultAddr","type":"address"},{"indexed":true,"internalType":"uint256","name":"loanId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"Repaid","type":"event"},{"inputs":[],"name":"addressRegistry","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"lenderVault","type":"address"},{"components":[{"internalType":"uint256","name":"collSendAmount","type":"uint256"},{"internalType":"uint256","name":"expectedProtocolAndVaultTransferFee","type":"uint256"},{"internalType":"uint256","name":"expectedCompartmentTransferFee","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"minLoanAmount","type":"uint256"},{"internalType":"address","name":"callbackAddr","type":"address"},{"internalType":"bytes","name":"callbackData","type":"bytes"},{"internalType":"bytes","name":"mysoTokenManagerData","type":"bytes"}],"internalType":"struct DataTypesPeerToPeer.BorrowTransferInstructions","name":"borrowInstructions","type":"tuple"},{"components":[{"components":[{"internalType":"address","name":"collToken","type":"address"},{"internalType":"address","name":"loanToken","type":"address"},{"internalType":"address","name":"oracleAddr","type":"address"},{"internalType":"uint256","name":"minLoan","type":"uint256"},{"internalType":"uint256","name":"maxLoan","type":"uint256"},{"internalType":"uint256","name":"validUntil","type":"uint256"},{"internalType":"uint256","name":"earliestRepayTenor","type":"uint256"},{"internalType":"address","name":"borrowerCompartmentImplementation","type":"address"},{"internalType":"bool","name":"isSingleUse","type":"bool"},{"internalType":"address","name":"whitelistAddr","type":"address"},{"internalType":"bool","name":"isWhitelistAddrSingleBorrower","type":"bool"}],"internalType":"struct DataTypesPeerToPeer.GeneralQuoteInfo","name":"generalQuoteInfo","type":"tuple"},{"internalType":"bytes32","name":"quoteTuplesRoot","type":"bytes32"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"bytes[]","name":"compactSigs","type":"bytes[]"}],"internalType":"struct DataTypesPeerToPeer.OffChainQuote","name":"offChainQuote","type":"tuple"},{"components":[{"internalType":"uint256","name":"loanPerCollUnitOrLtv","type":"uint256"},{"internalType":"int256","name":"interestRatePctInBase","type":"int256"},{"internalType":"uint256","name":"upfrontFeePctInBase","type":"uint256"},{"internalType":"uint256","name":"tenor","type":"uint256"}],"internalType":"struct DataTypesPeerToPeer.QuoteTuple","name":"quoteTuple","type":"tuple"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"name":"borrowWithOffChainQuote","outputs":[{"components":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"address","name":"collToken","type":"address"},{"internalType":"address","name":"loanToken","type":"address"},{"internalType":"uint40","name":"expiry","type":"uint40"},{"internalType":"uint40","name":"earliestRepay","type":"uint40"},{"internalType":"uint128","name":"initCollAmount","type":"uint128"},{"internalType":"uint128","name":"initLoanAmount","type":"uint128"},{"internalType":"uint128","name":"initRepayAmount","type":"uint128"},{"internalType":"uint128","name":"amountRepaidSoFar","type":"uint128"},{"internalType":"uint128","name":"amountReclaimedSoFar","type":"uint128"},{"internalType":"bool","name":"collUnlocked","type":"bool"},{"internalType":"address","name":"collTokenCompartmentAddr","type":"address"}],"internalType":"struct DataTypesPeerToPeer.Loan","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"lenderVault","type":"address"},{"components":[{"internalType":"uint256","name":"collSendAmount","type":"uint256"},{"internalType":"uint256","name":"expectedProtocolAndVaultTransferFee","type":"uint256"},{"internalType":"uint256","name":"expectedCompartmentTransferFee","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"minLoanAmount","type":"uint256"},{"internalType":"address","name":"callbackAddr","type":"address"},{"internalType":"bytes","name":"callbackData","type":"bytes"},{"internalType":"bytes","name":"mysoTokenManagerData","type":"bytes"}],"internalType":"struct DataTypesPeerToPeer.BorrowTransferInstructions","name":"borrowInstructions","type":"tuple"},{"components":[{"components":[{"internalType":"address","name":"collToken","type":"address"},{"internalType":"address","name":"loanToken","type":"address"},{"internalType":"address","name":"oracleAddr","type":"address"},{"internalType":"uint256","name":"minLoan","type":"uint256"},{"internalType":"uint256","name":"maxLoan","type":"uint256"},{"internalType":"uint256","name":"validUntil","type":"uint256"},{"internalType":"uint256","name":"earliestRepayTenor","type":"uint256"},{"internalType":"address","name":"borrowerCompartmentImplementation","type":"address"},{"internalType":"bool","name":"isSingleUse","type":"bool"},{"internalType":"address","name":"whitelistAddr","type":"address"},{"internalType":"bool","name":"isWhitelistAddrSingleBorrower","type":"bool"}],"internalType":"struct DataTypesPeerToPeer.GeneralQuoteInfo","name":"generalQuoteInfo","type":"tuple"},{"components":[{"internalType":"uint256","name":"loanPerCollUnitOrLtv","type":"uint256"},{"internalType":"int256","name":"interestRatePctInBase","type":"int256"},{"internalType":"uint256","name":"upfrontFeePctInBase","type":"uint256"},{"internalType":"uint256","name":"tenor","type":"uint256"}],"internalType":"struct DataTypesPeerToPeer.QuoteTuple[]","name":"quoteTuples","type":"tuple[]"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct DataTypesPeerToPeer.OnChainQuote","name":"onChainQuote","type":"tuple"},{"internalType":"uint256","name":"quoteTupleIdx","type":"uint256"}],"name":"borrowWithOnChainQuote","outputs":[{"components":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"address","name":"collToken","type":"address"},{"internalType":"address","name":"loanToken","type":"address"},{"internalType":"uint40","name":"expiry","type":"uint40"},{"internalType":"uint40","name":"earliestRepay","type":"uint40"},{"internalType":"uint128","name":"initCollAmount","type":"uint128"},{"internalType":"uint128","name":"initLoanAmount","type":"uint128"},{"internalType":"uint128","name":"initRepayAmount","type":"uint128"},{"internalType":"uint128","name":"amountRepaidSoFar","type":"uint128"},{"internalType":"uint128","name":"amountReclaimedSoFar","type":"uint128"},{"internalType":"bool","name":"collUnlocked","type":"bool"},{"internalType":"address","name":"collTokenCompartmentAddr","type":"address"}],"internalType":"struct DataTypesPeerToPeer.Loan","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getProtocolFeeParams","outputs":[{"internalType":"uint128[2]","name":"","type":"uint128[2]"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"targetLoanId","type":"uint256"},{"internalType":"uint128","name":"targetRepayAmount","type":"uint128"},{"internalType":"uint128","name":"expectedTransferFee","type":"uint128"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"address","name":"callbackAddr","type":"address"},{"internalType":"bytes","name":"callbackData","type":"bytes"}],"internalType":"struct DataTypesPeerToPeer.LoanRepayInstructions","name":"loanRepayInstructions","type":"tuple"},{"internalType":"address","name":"vaultAddr","type":"address"}],"name":"repay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128[2]","name":"_newFeeParams","type":"uint128[2]"}],"name":"setProtocolFeeParams","outputs":[],"stateMutability":"nonpayable","type":"function"}]
Contract Creation Code
60a06040523480156200001157600080fd5b506040516200329938038062003299833981016040819052620000349162000073565b60016000556001600160a01b038116620000615760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0316608052620000a5565b6000602082840312156200008657600080fd5b81516001600160a01b03811681146200009e57600080fd5b9392505050565b6080516131a1620000f86000396000818160e0015281816101aa01528181610357015281816105b5015281816107d001528181610e25015281816113d601528181611671015261189901526131a16000f3fe608060405234801561001057600080fd5b50600436106100725760003560e01c8063e48479fc11610050578063e48479fc146100c8578063f3ad65f4146100db578063fffcdfc21461011a57600080fd5b80632729ad721461007757806329cc71d7146100a057806352a04c1c146100b5575b600080fd5b61008a6100853660046121bd565b61012f565b604051610097919061239a565b60405180910390f35b6100b36100ae3660046123af565b610355565b005b61008a6100c33660046123d1565b61053a565b6100b36100d6366004612455565b61078a565b6101027f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610097565b610122610cea565b60405161009791906124d8565b6040805161018081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081018290526101408101829052610160810191909152610198610d55565b6101a6866060013588610db3565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639cccf2ad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610206573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061022a91906124f1565b6040517fe1b6da680000000000000000000000000000000000000000000000000000000081529091506001600160a01b0382169063e1b6da689061027c9033908c908b908b908b908b90600401612720565b600060405180830381600087803b15801561029657600080fd5b505af11580156102aa573d6000803e3d6000fd5b505050505060008060006102c38989600001898d610ec6565b9250925092508183600001516001600160a01b03168b6001600160a01b03167f59cbd4236c6b452e4e797de7793e6ea99bba862e5509291b51bae6764ed639eb86858e60a00160208101906103189190612822565b8f8060c00190610328919061283f565b604051610339959493929190612886565b60405180910390a45050600160005590505b9695505050505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156103b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103d791906124f1565b6001600160a01b0316336001600160a01b031614610421576040517fddb5de5e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b662386f26fc1000061043660208301836128f7565b6001600160801b03161180610469575066b1a2bc2ec5000061045e60408301602084016128f7565b6001600160801b0316115b806104d457506001546001600160801b031661048860208301836128f7565b6001600160801b03161480156104d4575060015470010000000000000000000000000000000090046001600160801b03166104c960408301602084016128f7565b6001600160801b0316145b156104f2576040516358d620b360e01b815260040160405180910390fd5b6104ff6001826002612053565b507f7e8b49a52419ca08bd7d5948a445eab6e864ef64520b480d616081c9ef4ff81a8160405161052f9190612914565b60405180910390a150565b6040805161018081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810182905261014081018290526101608101919091526105a3610d55565b6105b1846060013586610db3565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639cccf2ad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610611573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061063591906124f1565b6040517fd6d39d3e0000000000000000000000000000000000000000000000000000000081529091506001600160a01b0382169063d6d39d3e906106839033908a9088908a90600401612958565b600060405180830381600087803b15801561069d57600080fd5b505af11580156106b1573d6000803e3d6000fd5b505050505036838061016001906106c89190612a46565b848181106106d8576106d86128cc565b905060800201905060008060006106f48888600001868c610ec6565b9250925092508183600001516001600160a01b03168a6001600160a01b03167f59cbd4236c6b452e4e797de7793e6ea99bba862e5509291b51bae6764ed639eb86858d60a00160208101906107499190612822565b8e8060c00190610759919061283f565b60405161076a959493929190612886565b60405180910390a45090925050506107826001600055565b949350505050565b610792610d55565b6107a0826060013582610db3565b60006107b260a0840160808501612822565b6001600160a01b031614158015610881575060046001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016633577d16e61080560a0860160808701612822565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602401602060405180830381865afa158015610849573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061086d9190612aa6565b600a81111561087e5761087e612a90565b14155b1561089f5760405163345b213d60e01b815260040160405180910390fd5b6040517f365a53060000000000000000000000000000000000000000000000000000000081528235600482015281906000906001600160a01b0383169063365a53069060240161018060405180830381865afa158015610903573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109279190612c42565b80519091506001600160a01b0316331461096d576040517f6f5f81d700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b806080015164ffffffffff164210806109915750806060015164ffffffffff164210155b156109c8576040517f612ef71d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6109d860408501602086016128f7565b6001600160801b03161580610a2457508060e001516001600160801b0316816101000151856020016020810190610a0f91906128f7565b610a199190612c75565b6001600160801b0316115b15610a5b576040517f3d56fe3400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6101608101516001600160a01b031615600081610b055761016083015160208401516040517f5ac8c9c10000000000000000000000000000000000000000000000000000000081526001600160a01b039182166004820152911690635ac8c9c190602401602060405180830381865afa158015610adc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b009190612c9c565b610b24565b8261012001518360a00151610b1a9190612cb5565b6001600160801b03165b905060008361010001518460e00151610b3d9190612cb5565b90506000610b806001600160801b038316610b5e60408b0160208c016128f7565b610b71906001600160801b031686612cd5565b610b7b9190612cec565b610fcb565b9050806001600160801b0316600003610bc5576040517f90225cf500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b038616633e9738df610be460408b0160208c016128f7565b602088015160405160e084901b6001600160e01b03191681526001600160801b0392831660048201528c356024820152918516604483015287151560648301526001600160a01b0316608482015260a401600060405180830381600087803b158015610c4f57600080fd5b505af1158015610c63573d6000803e3d6000fd5b50505050610c7e8789610c7590612d9b565b8785858961104e565b87356001600160a01b0388167f1b8cd61ed43bec7c6bdad3a18ffee613f99c853d16c50678d248d879e1b43438610cbb60408c0160208d016128f7565b6040516001600160801b03909116815260200160405180910390a3505050505050610ce66001600055565b5050565b610cf26120fd565b604080518082019182905290600190600290826000855b82829054906101000a90046001600160801b03166001600160801b031681526020019060100190602082600f01049283019260010382029150808411610d095790505050505050905090565b600260005403610dac5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064015b60405180910390fd5b6002600055565b81421115610ded576040517f70f65caa00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f7b769d870000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301527f00000000000000000000000000000000000000000000000000000000000000001690637b769d8790602401602060405180830381865afa158015610e6c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e909190612e52565b610ce6576040517f8635e03400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040805161018081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810182905261014081018290526101608101919091526000806000806000866001600160a01b031663ba9dc192338c8c8c6040518563ffffffff1660e01b8152600401610f619493929190612f00565b6101e0604051808303816000875af1158015610f81573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fa59190612f61565b925092509250610fb7878b85846113a6565b602001519199909850909650945050505050565b60006001600160801b0382111561104a5760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203160448201527f32382062697473000000000000000000000000000000000000000000000000006064820152608401610da3565b5090565b8061111a5760208581015185519186015160808801516101608801516040517fed22e8bd0000000000000000000000000000000000000000000000000000000081526001600160801b039485166004820152848916602482015293871660448501526001600160a01b0394851660648501529184166084840152831660a4830152821660c48201529087169063ed22e8bd9060e401600060405180830381600087803b1580156110fd57600080fd5b505af1158015611111573d6000803e3d6000fd5b505050506111c9565b856001600160a01b031663a5f2a152856020015160006001600160a01b031688608001516001600160a01b031614611156578760800151611159565b86515b6040516001600160e01b031960e085901b1681526001600160a01b039283166004820152911660248201526001600160801b0385166044820152606401600060405180830381600087803b1580156111b057600080fd5b505af11580156111c4573d6000803e3d6000fd5b505050505b60808501516001600160a01b0316156112455784608001516001600160a01b031663c363b39c858760a001516040518363ffffffff1660e01b815260040161121292919061301e565b600060405180830381600087803b15801561122c57600080fd5b505af1158015611240573d6000803e3d6000fd5b505050505b60408085015190516370a0823160e01b81526001600160a01b03888116600483015260009216906370a0823190602401602060405180830381865afa158015611292573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112b69190612c9c565b90506112f4856000015188886040015189602001516112d59190612c75565b60408901516001600160a01b03169291906001600160801b0316611cb8565b60408086015190516370a0823160e01b81526001600160a01b038981166004830152839216906370a0823190602401602060405180830381865afa158015611340573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113649190612c9c565b61136e9190613040565b905085602001516001600160801b0316811461139d57604051630f93115d60e21b815260040160405180910390fd5b50505050505050565b60006113b860c0850160a08601612822565b6001600160a01b031614158015611487575060046001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016633577d16e61140b60c0870160a08801612822565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602401602060405180830381865afa15801561144f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114739190612aa6565b600a81111561148457611484612a90565b14155b156114a55760405163345b213d60e01b815260040160405180910390fd5b60408201516001600160a01b0385169063a5f2a1529060006114cd60c0880160a08901612822565b6001600160a01b0316146114f0576114eb60c0870160a08801612822565b6114f3565b84515b60c08601516040516001600160e01b031960e086901b1681526001600160a01b0393841660048201529290911660248301526001600160801b03166044820152606401600060405180830381600087803b15801561155057600080fd5b505af1158015611564573d6000803e3d6000fd5b506000925061157c91505060c0850160a08601612822565b6001600160a01b0316146116075761159a60c0840160a08501612822565b6001600160a01b031663b0f21355836115b660c087018761283f565b6040518463ffffffff1660e01b81526004016115d493929190613053565b600060405180830381600087803b1580156115ee57600080fd5b505af1158015611602573d6000803e3d6000fd5b505050505b60408051808201918290526000916001906002908285855b82829054906101000a90046001600160801b03166001600160801b031681526020019060100190602082600f0104928301926001038202915080841161161f57905050505050509050600081905060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166308e39fe56040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116f191906124f1565b90506001600160a01b03811615611806576040517fccbecfdc0000000000000000000000000000000000000000000000000000000081526001600160a01b0382169063ccbecfdc9061174d9085908a908a908d90600401613076565b60408051808303816000875af115801561176b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061178f91906130c0565b915060005b6002811015611804578381600281106117af576117af6128cc565b60200201516001600160801b03168382600281106117cf576117cf6128cc565b60200201516001600160801b031611156117fc576040516358d620b360e01b815260040160405180910390fd5b600101611794565b505b60006118498388600001358860a001516001600160801b03166000146118425742896060015164ffffffffff1661183d9190613040565b611d46565b6000611d46565b90508660200135811115611889576040517ff3e44e0c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b801561192f5761192f86600001517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118f5573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061191991906124f1565b60208901516001600160a01b0316919084611cb8565b600061193f8260208a0135613040565b905060008187602001518960a001516001600160801b03166119619190613129565b61196b9190613129565b9050600087602001518960a001516001600160801b031661198c9190613129565b90508a6001600160a01b031688600001516001600160a01b031614611b415760a08901516119c3906001600160801b031683613040565b91508860a001516001600160801b0316816119de9190613040565b60208a015189516040516370a0823160e01b81526001600160a01b0391821660048201529293506000929116906370a0823190602401602060405180830381865afa158015611a31573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a559190612c9c565b9050611a978a600001518a600001518d604001358d60a001516001600160801b0316611a819190613129565b60208e01516001600160a01b0316929190611cb8565b808a60a001516001600160801b0316611ab09190613129565b60208b01518a516040516370a0823160e01b81526001600160a01b0391821660048201529116906370a0823190602401602060405180830381865afa158015611afd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b219190612c9c565b14611b3f57604051630f93115d60e21b815260040160405180910390fd5b505b8115611cab5780600003611b81576040517f3690c13e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60208901516040516370a0823160e01b81526001600160a01b038d8116600483015260009216906370a0823190602401602060405180830381865afa158015611bce573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bf29190612c9c565b8a5160208c0151919250611c11916001600160a01b0316908e86611cb8565b611c1b8282613129565b60208b01516040516370a0823160e01b81526001600160a01b038f81166004830152909116906370a0823190602401602060405180830381865afa158015611c67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c8b9190612c9c565b14611ca957604051630f93115d60e21b815260040160405180910390fd5b505b5050505050505050505050565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f23b872dd00000000000000000000000000000000000000000000000000000000179052611d40908590611e43565b50505050565b60008066b1a2bc2ec500006301e133808487600160200201516001600160801b0316611d729190612cd5565b611d7c9190612cec565b8651611d9191906001600160801b0316613129565b11905080611e1657611daf670de0b6b3a76400006301e13380612cd5565b60208601518490611dc9906001600160801b031687612cd5565b611dd39190612cd5565b611ddd9190612cec565b8551670de0b6b3a764000090611dfd9087906001600160801b0316612cd5565b611e079190612cec565b611e119190613129565b611e3a565b670de0b6b3a7640000611e3066b1a2bc2ec5000086612cd5565b611e3a9190612cec565b95945050505050565b6000611e98826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611f309092919063ffffffff16565b9050805160001480611eb9575080806020019051810190611eb99190612e52565b611f2b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f742073756363656564000000000000000000000000000000000000000000006064820152608401610da3565b505050565b6060610782848460008585600080866001600160a01b03168587604051611f57919061313c565b60006040518083038185875af1925050503d8060008114611f94576040519150601f19603f3d011682016040523d82523d6000602084013e611f99565b606091505b5091509150611faa87838387611fb5565b979650505050505050565b6060831561202457825160000361201d576001600160a01b0385163b61201d5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610da3565b5081610782565b61078283838151156120395781518083602001fd5b8060405162461bcd60e51b8152600401610da39190613158565b6001830191839082156120f15791602002820160005b838211156120bc5783356001600160801b031683826101000a8154816001600160801b0302191690836001600160801b031602179055509260200192601001602081600f01049283019260010302612069565b80156120ef5782816101000a8154906001600160801b030219169055601001602081600f010492830192600103026120bc565b505b5061104a92915061211b565b60405180604001604052806002906020820280368337509192915050565b5b8082111561104a576000815560010161211c565b6001600160a01b038116811461214557600080fd5b50565b803561215381612130565b919050565b6000610100828403121561216b57600080fd5b50919050565b60008083601f84011261218357600080fd5b50813567ffffffffffffffff81111561219b57600080fd5b6020830191508360208260051b85010111156121b657600080fd5b9250929050565b6000806000806000808688036101008112156121d857600080fd5b87356121e381612130565b9650602088013567ffffffffffffffff8082111561220057600080fd5b61220c8b838c01612158565b975060408a013591508082111561222257600080fd5b908901906101e0828c03121561223757600080fd5b8196506080605f198401121561224c57600080fd5b60608a01955060e08a013592508083111561226657600080fd5b505061227489828a01612171565b979a9699509497509295939492505050565b80516001600160a01b0316825260208101516122ad60208401826001600160a01b03169052565b5060408101516122c860408401826001600160a01b03169052565b5060608101516122e1606084018264ffffffffff169052565b5060808101516122fa608084018264ffffffffff169052565b5060a081015161231560a08401826001600160801b03169052565b5060c081015161233060c08401826001600160801b03169052565b5060e081015161234b60e08401826001600160801b03169052565b50610100818101516001600160801b0390811691840191909152610120808301519091169083015261014080820151151590830152610160808201516001600160a01b03811682850152611d40565b61018081016123a98284612286565b92915050565b6000604082840312156123c157600080fd5b8260408301111561216b57600080fd5b600080600080608085870312156123e757600080fd5b84356123f281612130565b9350602085013567ffffffffffffffff8082111561240f57600080fd5b61241b88838901612158565b9450604087013591508082111561243157600080fd5b5085016101a0818803121561244557600080fd5b9396929550929360600135925050565b6000806040838503121561246857600080fd5b823567ffffffffffffffff81111561247f57600080fd5b830160c0818603121561249157600080fd5b915060208301356124a181612130565b809150509250929050565b8060005b6002811015611d405781516001600160801b03168452602093840193909101906001016124b0565b604081016123a982846124ac565b805161215381612130565b60006020828403121561250357600080fd5b815161250e81612130565b9392505050565b801515811461214557600080fd5b803561215381612515565b6125488261253b83612148565b6001600160a01b03169052565b61255460208201612148565b6001600160a01b0316602083015261256e60408201612148565b6001600160a01b038116604084015250606081013560608301526080810135608083015260a081013560a083015260c081013560c08301526125b260e08201612148565b6001600160a01b031660e08301526101006125ce828201612523565b1515908301526101206125e2828201612148565b6001600160a01b0316908301526101406125fd828201612523565b80151584830152611d40565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6000808335601e1984360301811261264957600080fd5b830160208101925035905067ffffffffffffffff81111561266957600080fd5b8036038213156121b657600080fd5b81835260006020808501808196508560051b810191508460005b878110156126c85782840389526126a98288612632565b6126b4868284612609565b9a87019a9550505090840190600101612692565b5091979650505050505050565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83111561270757600080fd5b8260051b80836020870137939093016020019392505050565b60006101006001600160a01b03808a16845280891660208501525080604084015261274d8184018861252e565b506101608601356102608301526101808601356102808301526101a08601356102a08301526101c0860135601e1987360301811261278a57600080fd5b860160208101903567ffffffffffffffff8111156127a757600080fd5b8060051b36038213156127b957600080fd5b6101e06102c08501526127d16102e085018284612678565b9150506128026060840187803582526020810135602083015260408101356040830152606081013560608301525050565b82810360e08401526128158185876126d5565b9998505050505050505050565b60006020828403121561283457600080fd5b813561250e81612130565b6000808335601e1984360301811261285657600080fd5b83018035915067ffffffffffffffff82111561287157600080fd5b6020019150368190038213156121b657600080fd5b60006101e06128958389612286565b866101808401526001600160a01b0386166101a0840152806101c08401526128c08184018587612609565b98975050505050505050565b634e487b7160e01b600052603260045260246000fd5b6001600160801b038116811461214557600080fd5b60006020828403121561290957600080fd5b813561250e816128e2565b60408101818360005b600281101561294f578135612931816128e2565b6001600160801b03168352602092830192919091019060010161291d565b50505092915050565b600060806001600160a01b038088168452808716602085015250846040840152806060840152610220830161298f8285018661252e565b610160850135601e198636030181126129a757600080fd5b850160208101903567ffffffffffffffff8111156129c457600080fd5b8060071b36038213156129d657600080fd5b6101a06101e0870152918290529060009061024086015b81831015612a295783358152602080850135908201526040808501359082015260608085013590820152928401926001929092019184016129ed565b610180880135610200880152809550505050505095945050505050565b6000808335601e19843603018112612a5d57600080fd5b83018035915067ffffffffffffffff821115612a7857600080fd5b6020019150600781901b36038213156121b657600080fd5b634e487b7160e01b600052602160045260246000fd5b600060208284031215612ab857600080fd5b8151600b811061250e57600080fd5b634e487b7160e01b600052604160045260246000fd5b604051610180810167ffffffffffffffff81118282101715612b0157612b01612ac7565b60405290565b6040805190810167ffffffffffffffff81118282101715612b0157612b01612ac7565b805164ffffffffff8116811461215357600080fd5b8051612153816128e2565b805161215381612515565b60006101808284031215612b6857600080fd5b612b70612add565b9050612b7b826124e6565b8152612b89602083016124e6565b6020820152612b9a604083016124e6565b6040820152612bab60608301612b2a565b6060820152612bbc60808301612b2a565b6080820152612bcd60a08301612b3f565b60a0820152612bde60c08301612b3f565b60c0820152612bef60e08301612b3f565b60e0820152610100612c02818401612b3f565b90820152610120612c14838201612b3f565b90820152610140612c26838201612b4a565b90820152610160612c388382016124e6565b9082015292915050565b60006101808284031215612c5557600080fd5b61250e8383612b55565b634e487b7160e01b600052601160045260246000fd5b6001600160801b03818116838216019080821115612c9557612c95612c5f565b5092915050565b600060208284031215612cae57600080fd5b5051919050565b6001600160801b03828116828216039080821115612c9557612c95612c5f565b80820281158282048414176123a9576123a9612c5f565b600082612d0957634e487b7160e01b600052601260045260246000fd5b500490565b600082601f830112612d1f57600080fd5b813567ffffffffffffffff80821115612d3a57612d3a612ac7565b604051601f8301601f19908116603f01168101908282118183101715612d6257612d62612ac7565b81604052838152866020858801011115612d7b57600080fd5b836020870160208301376000602085830101528094505050505092915050565b600060c08236031215612dad57600080fd5b60405160c0810167ffffffffffffffff8282108183111715612dd157612dd1612ac7565b816040528435835260208501359150612de9826128e2565b81602084015260408501359150612dff826128e2565b8160408401526060850135606084015260808501359150612e1f82612130565b81608084015260a0850135915080821115612e3957600080fd5b50612e4636828601612d0e565b60a08301525092915050565b600060208284031215612e6457600080fd5b815161250e81612515565b6000610100823584526020830135602085015260408301356040850152606083013560608501526080830135608085015260a0830135612eae81612130565b6001600160a01b031660a0850152612ec960c0840184612632565b8260c0870152612edc8387018284612609565b92505050612eed60e0840184612632565b85830360e087015261034b838284612609565b60006102206001600160a01b0387168352806020840152612f2381840187612e6f565b915050612f33604083018561252e565b82356101a083015260208301356101c083015260408301356101e08301526060830135610200830152611e3a565b60008060008385036101e0811215612f7857600080fd5b612f828686612b55565b93506101808501519250604061019f1982011215612f9f57600080fd5b50612fa8612b07565b6101a0850151612fb781612130565b81526101c094909401516020850152509093909250565b60005b83811015612fe9578181015183820152602001612fd1565b50506000910152565b6000815180845261300a816020860160208601612fce565b601f01601f19169290920160200192915050565b60006101a061302d8386612286565b80610180840152611e3a81840185612ff2565b818103818111156123a9576123a9612c5f565b60006101a06130628387612286565b8061018084015261034b8184018587612609565b600061020061308583886124ac565b80604084015261309781840187612e6f565b9150506130a76060830185612286565b6001600160a01b0383166101e083015295945050505050565b6000604082840312156130d257600080fd5b82601f8301126130e157600080fd5b6130e9612b07565b8060408401858111156130fb57600080fd5b845b8181101561311e578051613110816128e2565b8452602093840193016130fd565b509095945050505050565b808201808211156123a9576123a9612c5f565b6000825161314e818460208701612fce565b9190910192915050565b60208152600061250e6020830184612ff256fea2646970667358221220065f3b26b9da5bb6526526216724e231103729c04e4744372c5b808cb655cda264736f6c63430008130033000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106100725760003560e01c8063e48479fc11610050578063e48479fc146100c8578063f3ad65f4146100db578063fffcdfc21461011a57600080fd5b80632729ad721461007757806329cc71d7146100a057806352a04c1c146100b5575b600080fd5b61008a6100853660046121bd565b61012f565b604051610097919061239a565b60405180910390f35b6100b36100ae3660046123af565b610355565b005b61008a6100c33660046123d1565b61053a565b6100b36100d6366004612455565b61078a565b6101027f000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c81565b6040516001600160a01b039091168152602001610097565b610122610cea565b60405161009791906124d8565b6040805161018081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081018290526101408101829052610160810191909152610198610d55565b6101a6866060013588610db3565b60007f000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c6001600160a01b0316639cccf2ad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610206573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061022a91906124f1565b6040517fe1b6da680000000000000000000000000000000000000000000000000000000081529091506001600160a01b0382169063e1b6da689061027c9033908c908b908b908b908b90600401612720565b600060405180830381600087803b15801561029657600080fd5b505af11580156102aa573d6000803e3d6000fd5b505050505060008060006102c38989600001898d610ec6565b9250925092508183600001516001600160a01b03168b6001600160a01b03167f59cbd4236c6b452e4e797de7793e6ea99bba862e5509291b51bae6764ed639eb86858e60a00160208101906103189190612822565b8f8060c00190610328919061283f565b604051610339959493929190612886565b60405180910390a45050600160005590505b9695505050505050565b7f000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c6001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156103b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103d791906124f1565b6001600160a01b0316336001600160a01b031614610421576040517fddb5de5e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b662386f26fc1000061043660208301836128f7565b6001600160801b03161180610469575066b1a2bc2ec5000061045e60408301602084016128f7565b6001600160801b0316115b806104d457506001546001600160801b031661048860208301836128f7565b6001600160801b03161480156104d4575060015470010000000000000000000000000000000090046001600160801b03166104c960408301602084016128f7565b6001600160801b0316145b156104f2576040516358d620b360e01b815260040160405180910390fd5b6104ff6001826002612053565b507f7e8b49a52419ca08bd7d5948a445eab6e864ef64520b480d616081c9ef4ff81a8160405161052f9190612914565b60405180910390a150565b6040805161018081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810182905261014081018290526101608101919091526105a3610d55565b6105b1846060013586610db3565b60007f000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c6001600160a01b0316639cccf2ad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610611573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061063591906124f1565b6040517fd6d39d3e0000000000000000000000000000000000000000000000000000000081529091506001600160a01b0382169063d6d39d3e906106839033908a9088908a90600401612958565b600060405180830381600087803b15801561069d57600080fd5b505af11580156106b1573d6000803e3d6000fd5b505050505036838061016001906106c89190612a46565b848181106106d8576106d86128cc565b905060800201905060008060006106f48888600001868c610ec6565b9250925092508183600001516001600160a01b03168a6001600160a01b03167f59cbd4236c6b452e4e797de7793e6ea99bba862e5509291b51bae6764ed639eb86858d60a00160208101906107499190612822565b8e8060c00190610759919061283f565b60405161076a959493929190612886565b60405180910390a45090925050506107826001600055565b949350505050565b610792610d55565b6107a0826060013582610db3565b60006107b260a0840160808501612822565b6001600160a01b031614158015610881575060046001600160a01b037f000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c16633577d16e61080560a0860160808701612822565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602401602060405180830381865afa158015610849573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061086d9190612aa6565b600a81111561087e5761087e612a90565b14155b1561089f5760405163345b213d60e01b815260040160405180910390fd5b6040517f365a53060000000000000000000000000000000000000000000000000000000081528235600482015281906000906001600160a01b0383169063365a53069060240161018060405180830381865afa158015610903573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109279190612c42565b80519091506001600160a01b0316331461096d576040517f6f5f81d700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b806080015164ffffffffff164210806109915750806060015164ffffffffff164210155b156109c8576040517f612ef71d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6109d860408501602086016128f7565b6001600160801b03161580610a2457508060e001516001600160801b0316816101000151856020016020810190610a0f91906128f7565b610a199190612c75565b6001600160801b0316115b15610a5b576040517f3d56fe3400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6101608101516001600160a01b031615600081610b055761016083015160208401516040517f5ac8c9c10000000000000000000000000000000000000000000000000000000081526001600160a01b039182166004820152911690635ac8c9c190602401602060405180830381865afa158015610adc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b009190612c9c565b610b24565b8261012001518360a00151610b1a9190612cb5565b6001600160801b03165b905060008361010001518460e00151610b3d9190612cb5565b90506000610b806001600160801b038316610b5e60408b0160208c016128f7565b610b71906001600160801b031686612cd5565b610b7b9190612cec565b610fcb565b9050806001600160801b0316600003610bc5576040517f90225cf500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b038616633e9738df610be460408b0160208c016128f7565b602088015160405160e084901b6001600160e01b03191681526001600160801b0392831660048201528c356024820152918516604483015287151560648301526001600160a01b0316608482015260a401600060405180830381600087803b158015610c4f57600080fd5b505af1158015610c63573d6000803e3d6000fd5b50505050610c7e8789610c7590612d9b565b8785858961104e565b87356001600160a01b0388167f1b8cd61ed43bec7c6bdad3a18ffee613f99c853d16c50678d248d879e1b43438610cbb60408c0160208d016128f7565b6040516001600160801b03909116815260200160405180910390a3505050505050610ce66001600055565b5050565b610cf26120fd565b604080518082019182905290600190600290826000855b82829054906101000a90046001600160801b03166001600160801b031681526020019060100190602082600f01049283019260010382029150808411610d095790505050505050905090565b600260005403610dac5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064015b60405180910390fd5b6002600055565b81421115610ded576040517f70f65caa00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f7b769d870000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301527f000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c1690637b769d8790602401602060405180830381865afa158015610e6c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e909190612e52565b610ce6576040517f8635e03400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040805161018081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810182905261014081018290526101608101919091526000806000806000866001600160a01b031663ba9dc192338c8c8c6040518563ffffffff1660e01b8152600401610f619493929190612f00565b6101e0604051808303816000875af1158015610f81573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fa59190612f61565b925092509250610fb7878b85846113a6565b602001519199909850909650945050505050565b60006001600160801b0382111561104a5760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203160448201527f32382062697473000000000000000000000000000000000000000000000000006064820152608401610da3565b5090565b8061111a5760208581015185519186015160808801516101608801516040517fed22e8bd0000000000000000000000000000000000000000000000000000000081526001600160801b039485166004820152848916602482015293871660448501526001600160a01b0394851660648501529184166084840152831660a4830152821660c48201529087169063ed22e8bd9060e401600060405180830381600087803b1580156110fd57600080fd5b505af1158015611111573d6000803e3d6000fd5b505050506111c9565b856001600160a01b031663a5f2a152856020015160006001600160a01b031688608001516001600160a01b031614611156578760800151611159565b86515b6040516001600160e01b031960e085901b1681526001600160a01b039283166004820152911660248201526001600160801b0385166044820152606401600060405180830381600087803b1580156111b057600080fd5b505af11580156111c4573d6000803e3d6000fd5b505050505b60808501516001600160a01b0316156112455784608001516001600160a01b031663c363b39c858760a001516040518363ffffffff1660e01b815260040161121292919061301e565b600060405180830381600087803b15801561122c57600080fd5b505af1158015611240573d6000803e3d6000fd5b505050505b60408085015190516370a0823160e01b81526001600160a01b03888116600483015260009216906370a0823190602401602060405180830381865afa158015611292573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112b69190612c9c565b90506112f4856000015188886040015189602001516112d59190612c75565b60408901516001600160a01b03169291906001600160801b0316611cb8565b60408086015190516370a0823160e01b81526001600160a01b038981166004830152839216906370a0823190602401602060405180830381865afa158015611340573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113649190612c9c565b61136e9190613040565b905085602001516001600160801b0316811461139d57604051630f93115d60e21b815260040160405180910390fd5b50505050505050565b60006113b860c0850160a08601612822565b6001600160a01b031614158015611487575060046001600160a01b037f000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c16633577d16e61140b60c0870160a08801612822565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602401602060405180830381865afa15801561144f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114739190612aa6565b600a81111561148457611484612a90565b14155b156114a55760405163345b213d60e01b815260040160405180910390fd5b60408201516001600160a01b0385169063a5f2a1529060006114cd60c0880160a08901612822565b6001600160a01b0316146114f0576114eb60c0870160a08801612822565b6114f3565b84515b60c08601516040516001600160e01b031960e086901b1681526001600160a01b0393841660048201529290911660248301526001600160801b03166044820152606401600060405180830381600087803b15801561155057600080fd5b505af1158015611564573d6000803e3d6000fd5b506000925061157c91505060c0850160a08601612822565b6001600160a01b0316146116075761159a60c0840160a08501612822565b6001600160a01b031663b0f21355836115b660c087018761283f565b6040518463ffffffff1660e01b81526004016115d493929190613053565b600060405180830381600087803b1580156115ee57600080fd5b505af1158015611602573d6000803e3d6000fd5b505050505b60408051808201918290526000916001906002908285855b82829054906101000a90046001600160801b03166001600160801b031681526020019060100190602082600f0104928301926001038202915080841161161f57905050505050509050600081905060007f000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c6001600160a01b03166308e39fe56040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116f191906124f1565b90506001600160a01b03811615611806576040517fccbecfdc0000000000000000000000000000000000000000000000000000000081526001600160a01b0382169063ccbecfdc9061174d9085908a908a908d90600401613076565b60408051808303816000875af115801561176b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061178f91906130c0565b915060005b6002811015611804578381600281106117af576117af6128cc565b60200201516001600160801b03168382600281106117cf576117cf6128cc565b60200201516001600160801b031611156117fc576040516358d620b360e01b815260040160405180910390fd5b600101611794565b505b60006118498388600001358860a001516001600160801b03166000146118425742896060015164ffffffffff1661183d9190613040565b611d46565b6000611d46565b90508660200135811115611889576040517ff3e44e0c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b801561192f5761192f86600001517f000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c6001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118f5573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061191991906124f1565b60208901516001600160a01b0316919084611cb8565b600061193f8260208a0135613040565b905060008187602001518960a001516001600160801b03166119619190613129565b61196b9190613129565b9050600087602001518960a001516001600160801b031661198c9190613129565b90508a6001600160a01b031688600001516001600160a01b031614611b415760a08901516119c3906001600160801b031683613040565b91508860a001516001600160801b0316816119de9190613040565b60208a015189516040516370a0823160e01b81526001600160a01b0391821660048201529293506000929116906370a0823190602401602060405180830381865afa158015611a31573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a559190612c9c565b9050611a978a600001518a600001518d604001358d60a001516001600160801b0316611a819190613129565b60208e01516001600160a01b0316929190611cb8565b808a60a001516001600160801b0316611ab09190613129565b60208b01518a516040516370a0823160e01b81526001600160a01b0391821660048201529116906370a0823190602401602060405180830381865afa158015611afd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b219190612c9c565b14611b3f57604051630f93115d60e21b815260040160405180910390fd5b505b8115611cab5780600003611b81576040517f3690c13e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60208901516040516370a0823160e01b81526001600160a01b038d8116600483015260009216906370a0823190602401602060405180830381865afa158015611bce573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bf29190612c9c565b8a5160208c0151919250611c11916001600160a01b0316908e86611cb8565b611c1b8282613129565b60208b01516040516370a0823160e01b81526001600160a01b038f81166004830152909116906370a0823190602401602060405180830381865afa158015611c67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c8b9190612c9c565b14611ca957604051630f93115d60e21b815260040160405180910390fd5b505b5050505050505050505050565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f23b872dd00000000000000000000000000000000000000000000000000000000179052611d40908590611e43565b50505050565b60008066b1a2bc2ec500006301e133808487600160200201516001600160801b0316611d729190612cd5565b611d7c9190612cec565b8651611d9191906001600160801b0316613129565b11905080611e1657611daf670de0b6b3a76400006301e13380612cd5565b60208601518490611dc9906001600160801b031687612cd5565b611dd39190612cd5565b611ddd9190612cec565b8551670de0b6b3a764000090611dfd9087906001600160801b0316612cd5565b611e079190612cec565b611e119190613129565b611e3a565b670de0b6b3a7640000611e3066b1a2bc2ec5000086612cd5565b611e3a9190612cec565b95945050505050565b6000611e98826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611f309092919063ffffffff16565b9050805160001480611eb9575080806020019051810190611eb99190612e52565b611f2b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f742073756363656564000000000000000000000000000000000000000000006064820152608401610da3565b505050565b6060610782848460008585600080866001600160a01b03168587604051611f57919061313c565b60006040518083038185875af1925050503d8060008114611f94576040519150601f19603f3d011682016040523d82523d6000602084013e611f99565b606091505b5091509150611faa87838387611fb5565b979650505050505050565b6060831561202457825160000361201d576001600160a01b0385163b61201d5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610da3565b5081610782565b61078283838151156120395781518083602001fd5b8060405162461bcd60e51b8152600401610da39190613158565b6001830191839082156120f15791602002820160005b838211156120bc5783356001600160801b031683826101000a8154816001600160801b0302191690836001600160801b031602179055509260200192601001602081600f01049283019260010302612069565b80156120ef5782816101000a8154906001600160801b030219169055601001602081600f010492830192600103026120bc565b505b5061104a92915061211b565b60405180604001604052806002906020820280368337509192915050565b5b8082111561104a576000815560010161211c565b6001600160a01b038116811461214557600080fd5b50565b803561215381612130565b919050565b6000610100828403121561216b57600080fd5b50919050565b60008083601f84011261218357600080fd5b50813567ffffffffffffffff81111561219b57600080fd5b6020830191508360208260051b85010111156121b657600080fd5b9250929050565b6000806000806000808688036101008112156121d857600080fd5b87356121e381612130565b9650602088013567ffffffffffffffff8082111561220057600080fd5b61220c8b838c01612158565b975060408a013591508082111561222257600080fd5b908901906101e0828c03121561223757600080fd5b8196506080605f198401121561224c57600080fd5b60608a01955060e08a013592508083111561226657600080fd5b505061227489828a01612171565b979a9699509497509295939492505050565b80516001600160a01b0316825260208101516122ad60208401826001600160a01b03169052565b5060408101516122c860408401826001600160a01b03169052565b5060608101516122e1606084018264ffffffffff169052565b5060808101516122fa608084018264ffffffffff169052565b5060a081015161231560a08401826001600160801b03169052565b5060c081015161233060c08401826001600160801b03169052565b5060e081015161234b60e08401826001600160801b03169052565b50610100818101516001600160801b0390811691840191909152610120808301519091169083015261014080820151151590830152610160808201516001600160a01b03811682850152611d40565b61018081016123a98284612286565b92915050565b6000604082840312156123c157600080fd5b8260408301111561216b57600080fd5b600080600080608085870312156123e757600080fd5b84356123f281612130565b9350602085013567ffffffffffffffff8082111561240f57600080fd5b61241b88838901612158565b9450604087013591508082111561243157600080fd5b5085016101a0818803121561244557600080fd5b9396929550929360600135925050565b6000806040838503121561246857600080fd5b823567ffffffffffffffff81111561247f57600080fd5b830160c0818603121561249157600080fd5b915060208301356124a181612130565b809150509250929050565b8060005b6002811015611d405781516001600160801b03168452602093840193909101906001016124b0565b604081016123a982846124ac565b805161215381612130565b60006020828403121561250357600080fd5b815161250e81612130565b9392505050565b801515811461214557600080fd5b803561215381612515565b6125488261253b83612148565b6001600160a01b03169052565b61255460208201612148565b6001600160a01b0316602083015261256e60408201612148565b6001600160a01b038116604084015250606081013560608301526080810135608083015260a081013560a083015260c081013560c08301526125b260e08201612148565b6001600160a01b031660e08301526101006125ce828201612523565b1515908301526101206125e2828201612148565b6001600160a01b0316908301526101406125fd828201612523565b80151584830152611d40565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6000808335601e1984360301811261264957600080fd5b830160208101925035905067ffffffffffffffff81111561266957600080fd5b8036038213156121b657600080fd5b81835260006020808501808196508560051b810191508460005b878110156126c85782840389526126a98288612632565b6126b4868284612609565b9a87019a9550505090840190600101612692565b5091979650505050505050565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83111561270757600080fd5b8260051b80836020870137939093016020019392505050565b60006101006001600160a01b03808a16845280891660208501525080604084015261274d8184018861252e565b506101608601356102608301526101808601356102808301526101a08601356102a08301526101c0860135601e1987360301811261278a57600080fd5b860160208101903567ffffffffffffffff8111156127a757600080fd5b8060051b36038213156127b957600080fd5b6101e06102c08501526127d16102e085018284612678565b9150506128026060840187803582526020810135602083015260408101356040830152606081013560608301525050565b82810360e08401526128158185876126d5565b9998505050505050505050565b60006020828403121561283457600080fd5b813561250e81612130565b6000808335601e1984360301811261285657600080fd5b83018035915067ffffffffffffffff82111561287157600080fd5b6020019150368190038213156121b657600080fd5b60006101e06128958389612286565b866101808401526001600160a01b0386166101a0840152806101c08401526128c08184018587612609565b98975050505050505050565b634e487b7160e01b600052603260045260246000fd5b6001600160801b038116811461214557600080fd5b60006020828403121561290957600080fd5b813561250e816128e2565b60408101818360005b600281101561294f578135612931816128e2565b6001600160801b03168352602092830192919091019060010161291d565b50505092915050565b600060806001600160a01b038088168452808716602085015250846040840152806060840152610220830161298f8285018661252e565b610160850135601e198636030181126129a757600080fd5b850160208101903567ffffffffffffffff8111156129c457600080fd5b8060071b36038213156129d657600080fd5b6101a06101e0870152918290529060009061024086015b81831015612a295783358152602080850135908201526040808501359082015260608085013590820152928401926001929092019184016129ed565b610180880135610200880152809550505050505095945050505050565b6000808335601e19843603018112612a5d57600080fd5b83018035915067ffffffffffffffff821115612a7857600080fd5b6020019150600781901b36038213156121b657600080fd5b634e487b7160e01b600052602160045260246000fd5b600060208284031215612ab857600080fd5b8151600b811061250e57600080fd5b634e487b7160e01b600052604160045260246000fd5b604051610180810167ffffffffffffffff81118282101715612b0157612b01612ac7565b60405290565b6040805190810167ffffffffffffffff81118282101715612b0157612b01612ac7565b805164ffffffffff8116811461215357600080fd5b8051612153816128e2565b805161215381612515565b60006101808284031215612b6857600080fd5b612b70612add565b9050612b7b826124e6565b8152612b89602083016124e6565b6020820152612b9a604083016124e6565b6040820152612bab60608301612b2a565b6060820152612bbc60808301612b2a565b6080820152612bcd60a08301612b3f565b60a0820152612bde60c08301612b3f565b60c0820152612bef60e08301612b3f565b60e0820152610100612c02818401612b3f565b90820152610120612c14838201612b3f565b90820152610140612c26838201612b4a565b90820152610160612c388382016124e6565b9082015292915050565b60006101808284031215612c5557600080fd5b61250e8383612b55565b634e487b7160e01b600052601160045260246000fd5b6001600160801b03818116838216019080821115612c9557612c95612c5f565b5092915050565b600060208284031215612cae57600080fd5b5051919050565b6001600160801b03828116828216039080821115612c9557612c95612c5f565b80820281158282048414176123a9576123a9612c5f565b600082612d0957634e487b7160e01b600052601260045260246000fd5b500490565b600082601f830112612d1f57600080fd5b813567ffffffffffffffff80821115612d3a57612d3a612ac7565b604051601f8301601f19908116603f01168101908282118183101715612d6257612d62612ac7565b81604052838152866020858801011115612d7b57600080fd5b836020870160208301376000602085830101528094505050505092915050565b600060c08236031215612dad57600080fd5b60405160c0810167ffffffffffffffff8282108183111715612dd157612dd1612ac7565b816040528435835260208501359150612de9826128e2565b81602084015260408501359150612dff826128e2565b8160408401526060850135606084015260808501359150612e1f82612130565b81608084015260a0850135915080821115612e3957600080fd5b50612e4636828601612d0e565b60a08301525092915050565b600060208284031215612e6457600080fd5b815161250e81612515565b6000610100823584526020830135602085015260408301356040850152606083013560608501526080830135608085015260a0830135612eae81612130565b6001600160a01b031660a0850152612ec960c0840184612632565b8260c0870152612edc8387018284612609565b92505050612eed60e0840184612632565b85830360e087015261034b838284612609565b60006102206001600160a01b0387168352806020840152612f2381840187612e6f565b915050612f33604083018561252e565b82356101a083015260208301356101c083015260408301356101e08301526060830135610200830152611e3a565b60008060008385036101e0811215612f7857600080fd5b612f828686612b55565b93506101808501519250604061019f1982011215612f9f57600080fd5b50612fa8612b07565b6101a0850151612fb781612130565b81526101c094909401516020850152509093909250565b60005b83811015612fe9578181015183820152602001612fd1565b50506000910152565b6000815180845261300a816020860160208601612fce565b601f01601f19169290920160200192915050565b60006101a061302d8386612286565b80610180840152611e3a81840185612ff2565b818103818111156123a9576123a9612c5f565b60006101a06130628387612286565b8061018084015261034b8184018587612609565b600061020061308583886124ac565b80604084015261309781840187612e6f565b9150506130a76060830185612286565b6001600160a01b0383166101e083015295945050505050565b6000604082840312156130d257600080fd5b82601f8301126130e157600080fd5b6130e9612b07565b8060408401858111156130fb57600080fd5b845b8181101561311e578051613110816128e2565b8452602093840193016130fd565b509095945050505050565b808201808211156123a9576123a9612c5f565b6000825161314e818460208701612fce565b9190910192915050565b60208152600061250e6020830184612ff256fea2646970667358221220065f3b26b9da5bb6526526216724e231103729c04e4744372c5b808cb655cda264736f6c63430008130033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c
-----Decoded View---------------
Arg [0] : _addressRegistry (address): 0xd8b132A0abA610D0AaA18716A2b26e14141f112C
-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000d8b132a0aba610d0aaa18716a2b26e14141f112c
Deployed Bytecode Sourcemap
1046:19038:44:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1671:1477;;;;;;:::i;:::-;;:::i;:::-;;;;;;;:::i;:::-;;;;;;;;8417:624;;;;;;:::i;:::-;;:::i;:::-;;3156:2152;;;;;;:::i;:::-;;:::i;5316:2981::-;;;;;;:::i;:::-;;:::i;1241:40::-;;;;;;;;-1:-1:-1;;;;;6152:55:100;;;6134:74;;6122:2;6107:18;1241:40:44;5988:226:100;9049:117:44;;;:::i;:::-;;;;;;;:::i;1671:1477::-;-1:-1:-1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2261:21:6;:19;:21::i;:::-;2077:111:44::1;2124:18;:27;;;2166:11;2077:32;:111::i;:::-;2214:20;2254:15;-1:-1:-1::0;;;;;2237:64:44::1;;:66;;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;2318:216;::::0;;;;2214:89;;-1:-1:-1;;;;;;2318:57:44;::::1;::::0;::::1;::::0;:216:::1;::::0;2394:10:::1;::::0;2423:11;;2453:13;;2485:10;;2514:5;;;;2318:216:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;2199:347;2573:36;2624:14:::0;2653:18:::1;2685:185;2729:18;2766:13;:30;;2815:10;2844:11;2685:25;:185::i;:::-;2558:312;;;;;;3009:6;2937:4;:13;;;-1:-1:-1::0;;;;;2888:230:44::1;2911:11;-1:-1:-1::0;;;;;2888:230:44::1;;2965:4;2984:10;3030:18;:31;;;;;;;;;;:::i;:::-;3076:18;:31;;;;;;;;:::i;:::-;2888:230;;;;;;;;;;:::i;:::-;;;;;;;;-1:-1:-1::0;;1716:1:6;2809:7;:22;3136:4:44;-1:-1:-1;2303:20:6;1671:1477:44;;;;;;;;:::o;8417:624::-;8537:15;-1:-1:-1;;;;;8520:39:44;;:41;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1;;;;;8506:55:44;:10;-1:-1:-1;;;;;8506:55:44;;8502:117;;8585:22;;;;;;;;;;;;;;8502:117;321:7:39;8647:16:44;;;;:13;:16;:::i;:::-;-1:-1:-1;;;;;8647:50:44;;:113;;;-1:-1:-1;239:7:39;8714:16:44;;;;;;;;:::i;:::-;-1:-1:-1;;;;;8714:46:44;;8647:113;:233;;;-1:-1:-1;8798:17:44;:20;-1:-1:-1;;;;;8798:20:44;8778:16;;;;:13;:16;:::i;:::-;-1:-1:-1;;;;;8778:40:44;;:101;;;;-1:-1:-1;8859:17:44;:20;;;;-1:-1:-1;;;;;8859:20:44;8839:16;;;;;;;;:::i;:::-;-1:-1:-1;;;;;8839:40:44;;8778:101;8629:316;;;8914:19;;-1:-1:-1;;;8914:19:44;;;;;;;;;;;8629:316;8955:33;:17;8975:13;8955:33;;:::i;:::-;;9004:29;9019:13;9004:29;;;;;;:::i;:::-;;;;;;;;8417:624;:::o;3156:2152::-;-1:-1:-1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2261:21:6;:19;:21::i;:::-;4144:111:44::1;4191:18;:27;;;4233:11;4144:32;:111::i;:::-;4281:20;4321:15;-1:-1:-1::0;;;;;4304:64:44::1;;:66;;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;4385:193;::::0;;;;4281:89;;-1:-1:-1;;;;;;4385:56:44;::::1;::::0;::::1;::::0;:193:::1;::::0;4460:10:::1;::::0;4489:11;;4519:13;;4551:12;;4385:193:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;4266:324;4600:50;4653:12;:38;;;;;;;;:::i;:::-;4692:13;4653:53;;;;;;;:::i;:::-;;;;;;4600:106;;4734:36;4785:14:::0;4814:18:::1;4846:184;4890:18;4927:12;:29;;4975:10;5004:11;4846:25;:184::i;:::-;4719:311;;;;;;5169:6;5097:4;:13;;;-1:-1:-1::0;;;;;5048:230:44::1;5071:11;-1:-1:-1::0;;;;;5048:230:44::1;;5125:4;5144:10;5190:18;:31;;;;;;;;;;:::i;:::-;5236:18;:31;;;;;;;;:::i;:::-;5048:230;;;;;;;;;;:::i;:::-;;;;;;;;-1:-1:-1::0;5296:4:44;;-1:-1:-1;;;2303:20:6;1716:1;2809:7;:22;2629:209;2303:20;3156:2152:44;;;;;;:::o;5316:2981::-;2261:21:6;:19;:21::i;:::-;5495:112:44::1;5542:21;:30;;;5587:9;5495:32;:112::i;:::-;5682:1;5636:34;::::0;;;::::1;::::0;::::1;;:::i;:::-;-1:-1:-1::0;;;;;5636:48:44::1;;;:241;;;;-1:-1:-1::0;5834:43:44::1;-1:-1:-1::0;;;;;5718:15:44::1;5701:48;;5768:34;::::0;;;::::1;::::0;::::1;;:::i;:::-;5701:116;::::0;-1:-1:-1;;;;;;5701:116:44::1;::::0;;;;;;-1:-1:-1;;;;;6152:55:100;;;5701:116:44::1;::::0;::::1;6134:74:100::0;6107:18;;5701:116:44::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:176;;;;;;;;:::i;:::-;;;5636:241;5618:336;;;5911:31;;-1:-1:-1::0;;;5911:31:44::1;;;;;;;;;;;5618:336;6072:76;::::0;;;;6103:34;::::1;6072:76;::::0;::::1;17920:25:100::0;6012:9:44;;5964:28:::1;::::0;-1:-1:-1;;;;;6072:16:44;::::1;::::0;::::1;::::0;17893:18:100;;6072:76:44::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;6177:13:::0;;;;-1:-1:-1;;;;;;6163:27:44::1;:10;:27;6159:91;;6214:24;;;;;;;;;;;;;;6159:91;6296:4;:18;;;6278:36;;:15;:36;:83;;;;6350:4;:11;;;6331:30;;:15;:30;;6278:83;6260:179;;;6395:32;;;;;;;;;;;;;;6260:179;6524:39;::::0;;;::::1;::::0;::::1;;:::i;:::-;-1:-1:-1::0;;;;;6524:44:44::1;::::0;;:161:::1;;;6665:4;:20;;;-1:-1:-1::0;;;;;6585:100:44::1;6627:4;:22;;;6585:21;:39;;;;;;;;;;:::i;:::-;:64;;;;:::i;:::-;-1:-1:-1::0;;;;;6585:100:44::1;;6524:161;6506:252;;;6719:27;;;;;;;;;;;;;;6506:252;6789:29;::::0;::::1;::::0;-1:-1:-1;;;;;6789:43:44::1;::::0;6768:18:::1;6789:43:::0;6979:195:::1;;7088:29;::::0;::::1;::::0;7159:14:::1;::::0;::::1;::::0;7071:103:::1;::::0;;;;-1:-1:-1;;;;;6152:55:100;;;7071:103:44::1;::::0;::::1;6134:74:100::0;7071:87:44;::::1;::::0;::::1;::::0;6107:18:100;;7071:103:44::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;6979:195;;;7030:4;:25;;;7008:4;:19;;;:47;;;;:::i;:::-;-1:-1:-1::0;;;;;6979:195:44::1;;6944:230;;7253:27;7319:4;:22;;;7283:4;:20;;;:58;;;;:::i;:::-;7253:88:::0;-1:-1:-1;7352:25:44::1;7380:186;-1:-1:-1::0;;;;;7527:28:44;::::1;7466:39;::::0;;;::::1;::::0;::::1;;:::i;:::-;7414:92;::::0;-1:-1:-1;;;;;7458:48:44::1;7414:24:::0;:92:::1;:::i;:::-;7413:142;;;;:::i;:::-;7380:18;:186::i;:::-;7352:214;;7581:17;-1:-1:-1::0;;;;;7581:22:44::1;7602:1;7581:22:::0;7577:90:::1;;7627:28;;;;;;;;;;;;;;7577:90;-1:-1:-1::0;;;;;7679:26:44;::::1;;7720:39;::::0;;;::::1;::::0;::::1;;:::i;:::-;7883:14;::::0;::::1;::::0;7679:229:::1;::::0;::::1;::::0;;;-1:-1:-1;;;;;;7679:229:44;;;-1:-1:-1;;;;;22164:15:100;;;7679:229:44::1;::::0;::::1;22146:34:100::0;7774::44;::::1;22196:18:100::0;;;22189:34;22259:15;;;22239:18;;;22232:43;22318:14;;22311:22;22291:18;;;22284:50;-1:-1:-1;;;;;22371:55:100;22350:19;;;22343:84;22065:19;;7679:229:44::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;7921:206;7958:9;7982:21;7921:206;;;:::i;:::-;8018:4;8037:19;8071:17;8103:13;7921:22;:206::i;:::-;8190:34:::0;::::1;-1:-1:-1::0;;;;;8145:144:44;::::1;;8239:39;::::0;;;::::1;::::0;::::1;;:::i;:::-;8145:144;::::0;-1:-1:-1;;;;;24497:47:100;;;24479:66;;24467:2;24452:18;8145:144:44::1;;;;;;;5484:2813;;;;;;2303:20:6::0;1716:1;2809:7;:22;2629:209;2303:20;5316:2981:44;;:::o;9049:117::-;9104:17;;:::i;:::-;9134:24;;;;;;;;;;;9141:17;;9134:24;;9141:17;-1:-1:-1;9134:24:44;;;;;;;;;;;-1:-1:-1;;;;;9134:24:44;-1:-1:-1;;;;;9134:24:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;9049:117;:::o;2336:287:6:-;1759:1;2468:7;;:19;2460:63;;;;-1:-1:-1;;;2460:63:6;;24758:2:100;2460:63:6;;;24740:21:100;24797:2;24777:18;;;24770:30;24836:33;24816:18;;;24809:61;24887:18;;2460:63:6;;;;;;;;;1759:1;2598:7;:18;2336:287::o;18911:368:44:-;19064:8;19046:15;:26;19042:89;;;19096:23;;;;;;;;;;;;;;19042:89;19146:64;;;;;-1:-1:-1;;;;;6152:55:100;;;19146:64:44;;;6134:74:100;19163:15:44;19146:51;;;;6107:18:100;;19146:64:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;19141:131;;19234:26;;;;;;;;;;;;;;9174:975;-1:-1:-1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;9529:7:44;9538;9573:36;9624:14;9653:68;9752:11;-1:-1:-1;;;;;9735:42:44;;9796:10;9825:18;9862:16;9897:10;9735:187;;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;9558:364;;;;;;9935:141;9967:11;9993:18;10026:4;10045:20;9935:17;:141::i;:::-;10109:31;;;10095:4;;10101:6;;-1:-1:-1;10109:31:44;;-1:-1:-1;9174:975:44;-1:-1:-1;;;;;9174:975:44:o;9088:192:25:-;9145:7;-1:-1:-1;;;;;9172:26:25;;;9164:78;;;;-1:-1:-1;;;9164:78:25;;27932:2:100;9164:78:25;;;27914:21:100;27971:2;27951:18;;;27944:30;28010:34;27990:18;;;27983:62;28081:9;28061:18;;;28054:37;28108:19;;9164:78:25;27730:403:100;9164:78:25;-1:-1:-1;9267:5:25;9088:192::o;17004:1899:44:-;17324:13;:701;;17731:39;;;;;17863:13;;17895:14;;;;17928:34;;;;17981:29;;;;17655:370;;;;;-1:-1:-1;;;;;28524:15:100;;;17655:370:44;;;28506:34:100;28576:15;;;28556:18;;;28549:43;28628:15;;;28608:18;;;28601:43;-1:-1:-1;;;;;28741:15:100;;;28721:18;;;28714:43;28794:15;;;28773:19;;;28766:44;28847:15;;28826:19;;;28819:44;28900:15;;28879:19;;;28872:44;17655:57:44;;;;;;28425:19:100;;17655:370:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;17324:701;;;17370:11;-1:-1:-1;;;;;17353:40:44;;17412:4;:14;;;17491:1;-1:-1:-1;;;;;17445:48:44;:21;:34;;;-1:-1:-1;;;;;17445:48:44;;:143;;17554:21;:34;;;17445:143;;;17517:13;;17445:143;17353:286;;-1:-1:-1;;;;;;17353:286:44;;;;;;;-1:-1:-1;;;;;29208:15:100;;;17353:286:44;;;29190:34:100;29260:15;;29240:18;;;29233:43;-1:-1:-1;;;;;29312:47:100;;29292:18;;;29285:75;29102:18;;17353:286:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;17324:701;18040:34;;;;-1:-1:-1;;;;;18040:48:44;;18036:236;;18120:21;:34;;;-1:-1:-1;;;;;18105:64:44;;18188:4;18211:21;:34;;;18105:155;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;18036:236;18325:14;;;;;18310:77;;-1:-1:-1;;;18310:77:44;;-1:-1:-1;;;;;6152:55:100;;;18310:77:44;;;6134:74:100;18282:25:44;;18310:40;;;;6107:18:100;;18310:77:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;18282:105;;18400:227;18462:4;:13;;;18490:11;18575:21;:41;;;18516:21;:39;;;:100;;;;:::i;:::-;18415:14;;;;-1:-1:-1;;;;;18400:47:44;;:227;;-1:-1:-1;;;;;18400:227:44;:47;:227::i;:::-;18688:14;;;;;18673:53;;-1:-1:-1;;;18673:53:44;;-1:-1:-1;;;;;6152:55:100;;;18673:53:44;;;6134:74:100;18742:17:44;;18673:40;;;;6107:18:100;;18673:53:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:86;;;;:::i;:::-;18640:119;;18795:21;:39;;;-1:-1:-1;;;;;18774:60:44;:17;:60;18770:126;;18858:26;;-1:-1:-1;;;18858:26:44;;;;;;;;;;;18770:126;17313:1590;17004:1899;;;;;;:::o;10197:6799::-;10566:1;10523:31;;;;;;;;:::i;:::-;-1:-1:-1;;;;;10523:45:44;;;:235;;;;-1:-1:-1;10715:43:44;-1:-1:-1;;;;;10602:15:44;10585:48;;10652:31;;;;;;;;:::i;:::-;10585:113;;-1:-1:-1;;;;;;10585:113:44;;;;;;;-1:-1:-1;;;;;6152:55:100;;;10585:113:44;;;6134:74:100;6107:18;;10585:113:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:173;;;;;;;;:::i;:::-;;;10523:235;10505:330;;;10792:31;;-1:-1:-1;;;10792:31:44;;;;;;;;;;;10505:330;10900:14;;;;-1:-1:-1;;;;;10845:40:44;;;;;10972:1;10929:31;;;;;;;;:::i;:::-;-1:-1:-1;;;;;10929:45:44;;:129;;11027:31;;;;;;;;:::i;:::-;10929:129;;;10994:13;;10929:129;11073:19;;;;10845:258;;-1:-1:-1;;;;;;10845:258:44;;;;;;;-1:-1:-1;;;;;29208:15:100;;;10845:258:44;;;29190:34:100;29260:15;;;;29240:18;;;29233:43;-1:-1:-1;;;;;29312:47:100;29292:18;;;29285:75;29102:18;;10845:258:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;11161:1:44;;-1:-1:-1;11118:31:44;;-1:-1:-1;;11118:31:44;;;;;;;:::i;:::-;-1:-1:-1;;;;;11118:45:44;;11114:228;;11195:31;;;;;;;;:::i;:::-;-1:-1:-1;;;;;11180:62:44;;11261:4;11284:31;;;;:18;:31;:::i;:::-;11180:150;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;11114:228;11354:59;;;;;;;;;;-1:-1:-1;;11396:17:44;;11354:59;;11396:17;-1:-1:-1;11354:59:44;;;;;;;;;;;-1:-1:-1;;;;;11354:59:44;-1:-1:-1;;;;;11354:59:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;11424:45;11472:21;11424:69;;11506:24;11550:15;-1:-1:-1;;;;;11533:64:44;;:66;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;11506:93;-1:-1:-1;;;;;;11614:30:44;;;11610:613;;11691:241;;;;;-1:-1:-1;;;;;11691:70:44;;;;;:241;;11784:27;;11834:18;;11875:4;;11902:11;;11691:241;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;11661:271;;11952:9;11947:265;11967:1;11963;:5;11947:265;;;12028:21;12050:1;12028:24;;;;;;;:::i;:::-;;;;;-1:-1:-1;;;;;11995:57:44;:27;12023:1;11995:30;;;;;;;:::i;:::-;;;;;-1:-1:-1;;;;;11995:57:44;;11991:132;;;12084:19;;-1:-1:-1;;;12084:19:44;;;;;;;;;;;11991:132;12174:3;;11947:265;;;;11610:613;13039:25;13067:203;13109:27;13151:18;:33;;;13199:4;:19;;;-1:-1:-1;;;;;13199:24:44;13222:1;13199:24;:60;;13244:15;13230:4;:11;;;:29;;;;;;:::i;:::-;13067:27;:203::i;13199:60::-;13226:1;13067:27;:203::i;:::-;13039:231;;13409:18;:54;;;13376:17;:87;13358:182;;;13497:31;;;;;;;;;;;;;;13358:182;13556:22;;13552:487;;13837:190;13903:4;:13;;;13952:15;-1:-1:-1;;;;;13935:39:44;;:41;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;13852:14;;;;-1:-1:-1;;;;;13837:47:44;;:190;13995:17;13837:47;:190::i;:::-;14120:40;14163:88;14234:17;14163:68;;;;:88;:::i;:::-;14120:131;;14360:38;14483:32;14436:20;:31;;;14401:4;:19;;;-1:-1:-1;;;;;14401:66:44;;;;;:::i;:::-;:114;;;;:::i;:::-;14360:155;;14629:31;14698:20;:31;;;14663:4;:19;;;-1:-1:-1;;;;;14663:66:44;;;;;:::i;:::-;14629:100;;14781:11;-1:-1:-1;;;;;14744:48:44;:20;:33;;;-1:-1:-1;;;;;14744:48:44;;14740:1402;;15088:19;;;;15054:53;;-1:-1:-1;;;;;15054:53:44;;;:::i;:::-;;;15314:4;:19;;;-1:-1:-1;;;;;15287:46:44;;;;;;:::i;:::-;15394:14;;;;15438:33;;15379:93;;-1:-1:-1;;;15379:93:44;;-1:-1:-1;;;;;6152:55:100;;;15379:93:44;;;6134:74:100;15287:46:44;;-1:-1:-1;15350:26:44;;15379:58;;;;;6107:18:100;;15379:93:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;15350:122;;15487:257;15553:4;:13;;;15585:20;:33;;;15680:18;:49;;;15637:4;:19;;;-1:-1:-1;;;;;15637:92:44;;;;;:::i;:::-;15502:14;;;;-1:-1:-1;;;;;15487:47:44;;:257;;:47;:257::i;:::-;16029:18;16007:4;:19;;;-1:-1:-1;;;;;16007:40:44;;;;;:::i;:::-;15903:14;;;;15951:33;;15888:115;;-1:-1:-1;;;15888:115:44;;-1:-1:-1;;;;;6152:55:100;;;15888:115:44;;;6134:74:100;15888:40:44;;;;;6107:18:100;;15888:115:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:159;15866:265;;16089:26;;-1:-1:-1;;;16089:26:44;;;;;;;;;;;15866:265;14794:1348;14740:1402;16158:34;;16154:835;;16325:23;16352:1;16325:28;16321:116;;16381:40;;;;;;;;;;;;;;16321:116;16488:14;;;;16473:85;;-1:-1:-1;;;16473:85:44;;-1:-1:-1;;;;;6152:55:100;;;16473:85:44;;;6134:74:100;16451:19:44;;16473:40;;;;6107:18:100;;16473:85:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;16639:13;;16588:14;;;;16451:107;;-1:-1:-1;16573:173:44;;-1:-1:-1;;;;;16573:47:44;;16671:11;16701:30;16573:47;:173::i;:::-;16857:37;16871:23;16857:11;:37;:::i;:::-;16798:14;;;;16783:53;;-1:-1:-1;;;16783:53:44;;-1:-1:-1;;;;;6152:55:100;;;16783:53:44;;;6134:74:100;16783:40:44;;;;;;6107:18:100;;16783:53:44;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:111;16761:217;;16936:26;;-1:-1:-1;;;16936:26:44;;;;;;;;;;;16761:217;16194:795;16154:835;10494:6502;;;;;;;10197:6799;;;;:::o;1355:203:11:-;1482:68;;;-1:-1:-1;;;;;32652:15:100;;;1482:68:11;;;32634:34:100;32704:15;;32684:18;;;32677:43;32736:18;;;;32729:34;;;1482:68:11;;;;;;;;;;32546:18:100;;;;1482:68:11;;;;;;;;;;1505:27;1482:68;;;1455:96;;1475:5;;1455:19;:96::i;:::-;1355:203;;;;:::o;19287:794:44:-;19467:25;;404:7:39;134:8;19593:14:44;19569:18;19588:1;19569:21;;;;-1:-1:-1;;;;;19569:38:44;;;;;:::i;:::-;19568:85;;;;:::i;:::-;19530:21;;:124;;;-1:-1:-1;;;;;19530:124:44;;:::i;:::-;:172;19505:197;;19733:17;:340;;20029:42;182:4:39;134:8;20029:42:44;:::i;:::-;19965:21;;;;19989:14;;19948:38;;-1:-1:-1;;;;;19948:38:44;:14;:38;:::i;:::-;:55;;;;:::i;:::-;19947:125;;;;:::i;:::-;19869:21;;182:4:39;;19869:38:44;;19893:14;;-1:-1:-1;;;;;19869:38:44;;:::i;:::-;19868:57;;;;:::i;:::-;19867:206;;;;:::i;:::-;19733:340;;;182:4:39;19767:49:44;404:7:39;19767:14:44;:49;:::i;:::-;19766:85;;;;:::i;:::-;19713:360;19287:794;-1:-1:-1;;;;;19287:794:44:o;5196:642:11:-;5615:23;5641:69;5669:4;5641:69;;;;;;;;;;;;;;;;;5649:5;-1:-1:-1;;;;;5641:27:11;;;:69;;;;;:::i;:::-;5615:95;;5728:10;:17;5749:1;5728:22;:56;;;;5765:10;5754:30;;;;;;;;;;;;:::i;:::-;5720:111;;;;-1:-1:-1;;;5720:111:11;;32976:2:100;5720:111:11;;;32958:21:100;33015:2;32995:18;;;32988:30;33054:34;33034:18;;;33027:62;33125:12;33105:18;;;33098:40;33155:19;;5720:111:11;32774:406:100;5720:111:11;5266:572;5196:642;;:::o;4108:223:17:-;4241:12;4272:52;4294:6;4302:4;4308:1;4311:12;4241;5446;5460:23;5487:6;-1:-1:-1;;;;;5487:11:17;5506:5;5513:4;5487:31;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;5445:73;;;;5535:69;5562:6;5570:7;5579:10;5591:12;5535:26;:69::i;:::-;5528:76;5165:446;-1:-1:-1;;;;;;;5165:446:17:o;7671:628::-;7851:12;7879:7;7875:418;;;7906:10;:17;7927:1;7906:22;7902:286;;-1:-1:-1;;;;;1702:19:17;;;8113:60;;;;-1:-1:-1;;;8113:60:17;;34086:2:100;8113:60:17;;;34068:21:100;34125:2;34105:18;;;34098:30;34164:31;34144:18;;;34137:59;34213:18;;8113:60:17;33884:353:100;8113:60:17;-1:-1:-1;8208:10:17;8201:17;;7875:418;8249:33;8257:10;8269:12;8980:17;;:21;8976:379;;9208:10;9202:17;9264:15;9251:10;9247:2;9243:19;9236:44;8976:379;9331:12;9324:20;;-1:-1:-1;;;9324:20:17;;;;;;;;:::i;-1:-1:-1:-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;:::o;:::-;;;;;;;;;;;;;;;14:154:100;-1:-1:-1;;;;;93:5:100;89:54;82:5;79:65;69:93;;158:1;155;148:12;69:93;14:154;:::o;173:134::-;241:20;;270:31;241:20;270:31;:::i;:::-;173:134;;;:::o;312:175::-;391:5;436:3;427:6;422:3;418:16;414:26;411:46;;;453:1;450;443:12;411:46;-1:-1:-1;475:6:100;312:175;-1:-1:-1;312:175:100:o;492:367::-;555:8;565:6;619:3;612:4;604:6;600:17;596:27;586:55;;637:1;634;627:12;586:55;-1:-1:-1;660:20:100;;703:18;692:30;;689:50;;;735:1;732;725:12;689:50;772:4;764:6;760:17;748:29;;832:3;825:4;815:6;812:1;808:14;800:6;796:27;792:38;789:47;786:67;;;849:1;846;839:12;786:67;492:367;;;;;:::o;864:1301::-;1098:6;1106;1114;1122;1130;1138;1182:9;1173:7;1169:23;1212:3;1208:2;1204:12;1201:32;;;1229:1;1226;1219:12;1201:32;1268:9;1255:23;1287:31;1312:5;1287:31;:::i;:::-;1337:5;-1:-1:-1;1393:2:100;1378:18;;1365:32;1416:18;1446:14;;;1443:34;;;1473:1;1470;1463:12;1443:34;1496:86;1574:7;1565:6;1554:9;1550:22;1496:86;:::i;:::-;1486:96;;1635:2;1624:9;1620:18;1607:32;1591:48;;1664:2;1654:8;1651:16;1648:36;;;1680:1;1677;1670:12;1648:36;1703:24;;;;1761:3;1743:16;;;1739:26;1736:46;;;1778:1;1775;1768:12;1736:46;1801:2;1791:12;;1837:3;1831:2;1827:7;1823:2;1819:16;1815:26;1812:46;;;1854:1;1851;1844:12;1812:46;1892:2;1881:9;1877:18;1867:28;;1948:3;1937:9;1933:19;1920:33;1904:49;;1978:2;1968:8;1965:16;1962:36;;;1994:1;1991;1984:12;1962:36;;;2033:72;2097:7;2086:8;2075:9;2071:24;2033:72;:::i;:::-;864:1301;;;;-1:-1:-1;864:1301:100;;-1:-1:-1;864:1301:100;;2124:8;;864:1301;-1:-1:-1;;;864:1301:100:o;2623:1421::-;2700:12;;-1:-1:-1;;;;;2236:54:100;2224:67;;2764:4;2757:5;2753:16;2747:23;2779:48;2821:4;2816:3;2812:14;2798:12;-1:-1:-1;;;;;2236:54:100;2224:67;;2170:127;2779:48;;2875:4;2868:5;2864:16;2858:23;2890:50;2934:4;2929:3;2925:14;2909;-1:-1:-1;;;;;2236:54:100;2224:67;;2170:127;2890:50;;2988:4;2981:5;2977:16;2971:23;3003:49;3046:4;3041:3;3037:14;3021;2378:12;2367:24;2355:37;;2302:96;3003:49;;3100:4;3093:5;3089:16;3083:23;3115:49;3158:4;3153:3;3149:14;3133;2378:12;2367:24;2355:37;;2302:96;3115:49;;3212:4;3205:5;3201:16;3195:23;3227:50;3271:4;3266:3;3262:14;3246;-1:-1:-1;;;;;2469:46:100;2457:59;;2403:119;3227:50;;3325:4;3318:5;3314:16;3308:23;3340:50;3384:4;3379:3;3375:14;3359;-1:-1:-1;;;;;2469:46:100;2457:59;;2403:119;3340:50;;3438:4;3431:5;3427:16;3421:23;3453:50;3497:4;3492:3;3488:14;3472;-1:-1:-1;;;;;2469:46:100;2457:59;;2403:119;3453:50;-1:-1:-1;3522:6:100;3565:14;;;3559:21;-1:-1:-1;;;;;2469:46:100;;;3624:12;;;2457:59;;;;3656:6;3699:14;;;3693:21;2469:46;;;3758:12;;;2457:59;3790:6;3833:14;;;3827:21;2597:13;2590:21;3889:12;;;2578:34;3921:6;3965:14;;;3959:21;-1:-1:-1;;;;;2236:54:100;;4025:12;;;2224:67;3989:49;2170:127;4049:240;4229:3;4214:19;;4242:41;4218:9;4265:6;4242:41;:::i;:::-;4049:240;;;;:::o;4294:251::-;4378:6;4431:2;4419:9;4410:7;4406:23;4402:32;4399:52;;;4447:1;4444;4437:12;4399:52;4486:7;4481:2;4470:9;4466:18;4463:31;4460:51;;;4507:1;4504;4497:12;4550:891;4716:6;4724;4732;4740;4793:3;4781:9;4772:7;4768:23;4764:33;4761:53;;;4810:1;4807;4800:12;4761:53;4849:9;4836:23;4868:31;4893:5;4868:31;:::i;:::-;4918:5;-1:-1:-1;4974:2:100;4959:18;;4946:32;4997:18;5027:14;;;5024:34;;;5054:1;5051;5044:12;5024:34;5077:86;5155:7;5146:6;5135:9;5131:22;5077:86;:::i;:::-;5067:96;;5216:2;5205:9;5201:18;5188:32;5172:48;;5245:2;5235:8;5232:16;5229:36;;;5261:1;5258;5251:12;5229:36;-1:-1:-1;5284:24:100;;5342:3;5324:16;;;5320:26;5317:46;;;5359:1;5356;5349:12;5317:46;4550:891;;;;-1:-1:-1;5382:2:100;;5431;5416:18;5403:32;;-1:-1:-1;;4550:891:100:o;5446:537::-;5556:6;5564;5617:2;5605:9;5596:7;5592:23;5588:32;5585:52;;;5633:1;5630;5623:12;5585:52;5673:9;5660:23;5706:18;5698:6;5695:30;5692:50;;;5738:1;5735;5728:12;5692:50;5761:22;;5817:3;5799:16;;;5795:26;5792:46;;;5834:1;5831;5824:12;5792:46;5857:2;-1:-1:-1;5909:2:100;5894:18;;5881:32;5922:31;5881:32;5922:31;:::i;:::-;5972:5;5962:15;;;5446:537;;;;;:::o;6219:367::-;6312:5;6335:1;6345:235;6359:4;6356:1;6353:11;6345:235;;;6422:13;;-1:-1:-1;;;;;6418:54:100;6406:67;;6496:4;6520:12;;;;6555:15;;;;6379:1;6372:9;6345:235;;6591:241;6771:2;6756:18;;6783:43;6760:9;6808:6;6783:43;:::i;6837:138::-;6916:13;;6938:31;6916:13;6938:31;:::i;6980:251::-;7050:6;7103:2;7091:9;7082:7;7078:23;7074:32;7071:52;;;7119:1;7116;7109:12;7071:52;7151:9;7145:16;7170:31;7195:5;7170:31;:::i;:::-;7220:5;6980:251;-1:-1:-1;;;6980:251:100:o;7236:118::-;7322:5;7315:13;7308:21;7301:5;7298:32;7288:60;;7344:1;7341;7334:12;7359:128;7424:20;;7453:28;7424:20;7453:28;:::i;7492:1190::-;7571:50;7617:3;7590:25;7609:5;7590:25;:::i;:::-;-1:-1:-1;;;;;2236:54:100;2224:67;;2170:127;7571:50;7650:36;7680:4;7673:5;7669:16;7650:36;:::i;:::-;-1:-1:-1;;;;;2236:54:100;7737:4;7728:14;;2224:67;7774:36;7804:4;7793:16;;7774:36;:::i;:::-;-1:-1:-1;;;;;2236:54:100;;7863:4;7854:14;;2224:67;7819:50;7925:4;7918:5;7914:16;7901:30;7894:4;7889:3;7885:14;7878:54;7988:4;7981:5;7977:16;7964:30;7957:4;7952:3;7948:14;7941:54;8051:4;8044:5;8040:16;8027:30;8020:4;8015:3;8011:14;8004:54;8114:4;8107:5;8103:16;8090:30;8083:4;8078:3;8074:14;8067:54;8152:36;8182:4;8175:5;8171:16;8152:36;:::i;:::-;-1:-1:-1;;;;;2236:54:100;8241:4;8232:14;;2224:67;8266:6;8303:31;8319:14;;;8303:31;:::i;:::-;2597:13;2590:21;8375:12;;;2578:34;8407:6;8444:34;8463:14;;;8444:34;:::i;:::-;-1:-1:-1;;;;;2236:54:100;8522:12;;;2224:67;8554:6;8591:31;8607:14;;;8591:31;:::i;:::-;2597:13;;2590:21;8663:12;;;2578:34;8631:45;2527:91;8687:266;8775:6;8770:3;8763:19;8827:6;8820:5;8813:4;8808:3;8804:14;8791:43;-1:-1:-1;8879:1:100;8854:16;;;8872:4;8850:27;;;8843:38;;;;8935:2;8914:15;;;-1:-1:-1;;8910:29:100;8901:39;;;8897:50;;8687:266::o;8958:500::-;9016:5;9023:6;9083:3;9070:17;9169:2;9165:7;9154:8;9138:14;9134:29;9130:43;9110:18;9106:68;9096:96;;9188:1;9185;9178:12;9096:96;9216:33;;9320:4;9307:18;;;-1:-1:-1;9268:21:100;;-1:-1:-1;9348:18:100;9337:30;;9334:50;;;9380:1;9377;9370:12;9334:50;9427:6;9411:14;9407:27;9400:5;9396:39;9393:59;;;9448:1;9445;9438:12;9463:714;9570:6;9565:3;9558:19;9540:3;9596:4;9637:2;9632:3;9628:12;9662:11;9689;9682:18;;9739:6;9736:1;9732:14;9725:5;9721:26;9709:38;;9770:5;9793:1;9803:348;9817:6;9814:1;9811:13;9803:348;;;9888:5;9882:4;9878:16;9873:3;9866:29;9944:45;9982:6;9975:5;9944:45;:::i;:::-;10010:61;10066:4;10051:13;10036;10010:61;:::i;:::-;10129:12;;;;10002:69;-1:-1:-1;;;10094:15:100;;;;9839:1;9832:9;9803:348;;;-1:-1:-1;10167:4:100;;9463:714;-1:-1:-1;;;;;;;9463:714:100:o;10487:358::-;10587:6;10582:3;10575:19;10557:3;10617:66;10609:6;10606:78;10603:98;;;10697:1;10694;10687:12;10603:98;10733:6;10730:1;10726:14;10785:8;10778:5;10771:4;10766:3;10762:14;10749:45;10814:18;;;;10834:4;10810:29;;10487:358;-1:-1:-1;;;10487:358:100:o;10850:1709::-;11240:4;11269:3;-1:-1:-1;;;;;11372:2:100;11364:6;11360:15;11349:9;11342:34;11424:2;11416:6;11412:15;11407:2;11396:9;11392:18;11385:43;;11464:2;11459;11448:9;11444:18;11437:30;11476:71;11543:2;11532:9;11528:18;11520:6;11476:71;:::i;:::-;;11609:6;11601;11597:19;11584:33;11578:3;11567:9;11563:19;11556:62;11680:6;11672;11668:19;11655:33;11649:3;11638:9;11634:19;11627:62;11751:6;11743;11739:19;11726:33;11720:3;11709:9;11705:19;11698:62;11820:6;11812;11808:19;11795:33;11908:2;11904:7;11895:6;11879:14;11875:27;11871:41;11851:18;11847:66;11837:94;;11927:1;11924;11917:12;11837:94;11953:31;;12061:2;12050:14;;;12007:19;12087:18;12076:30;;12073:50;;;12119:1;12116;12109:12;12073:50;12175:6;12172:1;12168:14;12152;12148:35;12139:7;12135:49;12132:69;;;12197:1;12194;12187:12;12132:69;12238:6;12232:3;12221:9;12217:19;12210:35;12265:82;12342:3;12331:9;12327:19;12319:6;12310:7;12265:82;:::i;:::-;12254:93;;;12356:65;12417:2;12406:9;12402:18;12394:6;10280:5;10267:19;10262:3;10255:32;10343:4;10336:5;10332:16;10319:30;10312:4;10307:3;10303:14;10296:54;10406:4;10399:5;10395:16;10382:30;10375:4;10370:3;10366:14;10359:54;10469:4;10462:5;10458:16;10445:30;10438:4;10433:3;10429:14;10422:54;;;10182:300;12356:65;12467:9;12462:3;12458:19;12452:3;12441:9;12437:19;12430:48;12495:58;12549:3;12541:6;12533;12495:58;:::i;:::-;12487:66;10850:1709;-1:-1:-1;;;;;;;;;10850:1709:100:o;12564:247::-;12623:6;12676:2;12664:9;12655:7;12651:23;12647:32;12644:52;;;12692:1;12689;12682:12;12644:52;12731:9;12718:23;12750:31;12775:5;12750:31;:::i;12816:521::-;12893:4;12899:6;12959:11;12946:25;13053:2;13049:7;13038:8;13022:14;13018:29;13014:43;12994:18;12990:68;12980:96;;13072:1;13069;13062:12;12980:96;13099:33;;13151:20;;;-1:-1:-1;13194:18:100;13183:30;;13180:50;;;13226:1;13223;13216:12;13180:50;13259:4;13247:17;;-1:-1:-1;13290:14:100;13286:27;;;13276:38;;13273:58;;;13327:1;13324;13317:12;13342:593;13592:4;13621:3;13633:41;13664:9;13656:6;13633:41;:::i;:::-;13711:6;13705:3;13694:9;13690:19;13683:35;-1:-1:-1;;;;;13759:6:100;13755:55;13749:3;13738:9;13734:19;13727:84;13848:2;13842:3;13831:9;13827:19;13820:31;13868:61;13925:2;13914:9;13910:18;13902:6;13894;13868:61;:::i;:::-;13860:69;13342:593;-1:-1:-1;;;;;;;;13342:593:100:o;13940:184::-;-1:-1:-1;;;13989:1:100;13982:88;14089:4;14086:1;14079:15;14113:4;14110:1;14103:15;14129:146;-1:-1:-1;;;;;14208:5:100;14204:46;14197:5;14194:57;14184:85;;14265:1;14262;14255:12;14280:247;14339:6;14392:2;14380:9;14371:7;14367:23;14363:32;14360:52;;;14408:1;14405;14398:12;14360:52;14447:9;14434:23;14466:31;14491:5;14466:31;:::i;14532:619::-;14714:2;14699:18;;14703:9;14794:6;14672:4;14828:317;14842:4;14839:1;14836:11;14828:317;;;14915:6;14902:20;14935:31;14960:5;14935:31;:::i;:::-;-1:-1:-1;;;;;14991:46:100;14979:59;;15061:4;15085:12;;;;15120:15;;;;;14862:1;14855:9;14828:317;;;14832:3;;;14532:619;;;;:::o;15156:1557::-;15396:4;15425:3;-1:-1:-1;;;;;15528:2:100;15520:6;15516:15;15505:9;15498:34;15580:2;15572:6;15568:15;15563:2;15552:9;15548:18;15541:43;;15620:6;15615:2;15604:9;15600:18;15593:34;15663:2;15658;15647:9;15643:18;15636:30;15704:3;15693:9;15689:19;15717:71;15784:2;15773:9;15769:18;15761:6;15717:71;:::i;:::-;15848:6;15840;15836:19;15823:33;15936:2;15932:7;15923:6;15907:14;15903:27;15899:41;15879:18;15875:66;15865:94;;15955:1;15952;15945:12;15865:94;15981:31;;16089:2;16078:14;;;16035:19;16115:18;16104:30;;16101:50;;;16147:1;16144;16137:12;16101:50;16203:6;16200:1;16196:14;16180;16176:35;16167:7;16163:49;16160:69;;;16225:1;16222;16215:12;16160:69;16266:6;16260:3;16245:19;;16238:35;16308:22;;;;16388:7;16413:1;;16361:3;16346:19;;16423:193;16437:6;16434:1;16431:13;16423:193;;;10267:19;;10255:32;;10343:4;10332:16;;;10319:30;10303:14;;;10296:54;10406:4;10395:16;;;10382:30;10366:14;;;10359:54;10469:4;10458:16;;;10445:30;10429:14;;;10422:54;16591:15;;;;16459:1;16452:9;;;;;16556:12;;16423:193;;;16678:6;16670;16666:19;16653:33;16647:3;16636:9;16632:19;16625:62;16704:3;16696:11;;;;;;;15156:1557;;;;;;;:::o;16718:576::-;16842:4;16848:6;16908:11;16895:25;17002:2;16998:7;16987:8;16971:14;16967:29;16963:43;16943:18;16939:68;16929:96;;17021:1;17018;17011:12;16929:96;17048:33;;17100:20;;;-1:-1:-1;17143:18:100;17132:30;;17129:50;;;17175:1;17172;17165:12;17129:50;17208:4;17196:17;;-1:-1:-1;17259:1:100;17255:14;;;17239;17235:35;17225:46;;17222:66;;;17284:1;17281;17274:12;17299:184;-1:-1:-1;;;17348:1:100;17341:88;17448:4;17445:1;17438:15;17472:4;17469:1;17462:15;17488:281;17578:6;17631:2;17619:9;17610:7;17606:23;17602:32;17599:52;;;17647:1;17644;17637:12;17599:52;17679:9;17673:16;17718:2;17711:5;17708:13;17698:41;;17735:1;17732;17725:12;17956:184;-1:-1:-1;;;18005:1:100;17998:88;18105:4;18102:1;18095:15;18129:4;18126:1;18119:15;18145:250;18212:2;18206:9;18254:6;18242:19;;18291:18;18276:34;;18312:22;;;18273:62;18270:88;;;18338:18;;:::i;:::-;18374:2;18367:22;18145:250;:::o;18400:257::-;18472:4;18466:11;;;18504:17;;18551:18;18536:34;;18572:22;;;18533:62;18530:88;;;18598:18;;:::i;18662:169::-;18740:13;;18793:12;18782:24;;18772:35;;18762:63;;18821:1;18818;18811:12;18836:138;18915:13;;18937:31;18915:13;18937:31;:::i;18979:132::-;19055:13;;19077:28;19055:13;19077:28;:::i;19116:1232::-;19178:5;19226:6;19214:9;19209:3;19205:19;19201:32;19198:52;;;19246:1;19243;19236:12;19198:52;19268:17;;:::i;:::-;19259:26;;19308:40;19338:9;19308:40;:::i;:::-;19301:5;19294:55;19381:49;19426:2;19415:9;19411:18;19381:49;:::i;:::-;19376:2;19369:5;19365:14;19358:73;19463:49;19508:2;19497:9;19493:18;19463:49;:::i;:::-;19458:2;19451:5;19447:14;19440:73;19545:48;19589:2;19578:9;19574:18;19545:48;:::i;:::-;19540:2;19533:5;19529:14;19522:72;19627:49;19671:3;19660:9;19656:19;19627:49;:::i;:::-;19621:3;19614:5;19610:15;19603:74;19710:50;19755:3;19744:9;19740:19;19710:50;:::i;:::-;19704:3;19697:5;19693:15;19686:75;19794:50;19839:3;19828:9;19824:19;19794:50;:::i;:::-;19788:3;19781:5;19777:15;19770:75;19878:50;19923:3;19912:9;19908:19;19878:50;:::i;:::-;19872:3;19865:5;19861:15;19854:75;19948:3;19983:49;20028:2;20017:9;20013:18;19983:49;:::i;:::-;19967:14;;;19960:73;20052:3;20087:49;20117:18;;;20087:49;:::i;:::-;20071:14;;;20064:73;20156:3;20191:46;20218:18;;;20191:46;:::i;:::-;20175:14;;;20168:70;20257:3;20292:49;20322:18;;;20292:49;:::i;:::-;20276:14;;;20269:73;20280:5;19116:1232;-1:-1:-1;;19116:1232:100:o;20353:245::-;20446:6;20499:3;20487:9;20478:7;20474:23;20470:33;20467:53;;;20516:1;20513;20506:12;20467:53;20539;20584:7;20573:9;20539:53;:::i;20603:184::-;-1:-1:-1;;;20652:1:100;20645:88;20752:4;20749:1;20742:15;20776:4;20773:1;20766:15;20792:197;-1:-1:-1;;;;;20914:10:100;;;20926;;;20910:27;;20949:11;;;20946:37;;;20963:18;;:::i;:::-;20946:37;20792:197;;;;:::o;20994:184::-;21064:6;21117:2;21105:9;21096:7;21092:23;21088:32;21085:52;;;21133:1;21130;21123:12;21085:52;-1:-1:-1;21156:16:100;;20994:184;-1:-1:-1;20994:184:100:o;21183:200::-;-1:-1:-1;;;;;21319:10:100;;;21307;;;21303:27;;21342:12;;;21339:38;;;21357:18;;:::i;21388:168::-;21461:9;;;21492;;21509:15;;;21503:22;;21489:37;21479:71;;21530:18;;:::i;21561:274::-;21601:1;21627;21617:189;;-1:-1:-1;;;21659:1:100;21652:88;21763:4;21760:1;21753:15;21791:4;21788:1;21781:15;21617:189;-1:-1:-1;21820:9:100;;21561:274::o;22438:718::-;22480:5;22533:3;22526:4;22518:6;22514:17;22510:27;22500:55;;22551:1;22548;22541:12;22500:55;22587:6;22574:20;22613:18;22650:2;22646;22643:10;22640:36;;;22656:18;;:::i;:::-;22731:2;22725:9;22699:2;22785:13;;-1:-1:-1;;22781:22:100;;;22805:2;22777:31;22773:40;22761:53;;;22829:18;;;22849:22;;;22826:46;22823:72;;;22875:18;;:::i;:::-;22915:10;22911:2;22904:22;22950:2;22942:6;22935:18;22996:3;22989:4;22984:2;22976:6;22972:15;22968:26;22965:35;22962:55;;;23013:1;23010;23003:12;22962:55;23077:2;23070:4;23062:6;23058:17;23051:4;23043:6;23039:17;23026:54;23124:1;23117:4;23112:2;23104:6;23100:15;23096:26;23089:37;23144:6;23135:15;;;;;;22438:718;;;;:::o;23161:1167::-;23293:9;23352:4;23344:5;23328:14;23324:26;23320:37;23317:57;;;23370:1;23367;23360:12;23317:57;23403:2;23397:9;23445:4;23437:6;23433:17;23469:18;23537:6;23525:10;23522:22;23517:2;23505:10;23502:18;23499:46;23496:72;;;23548:18;;:::i;:::-;23588:10;23584:2;23577:22;23636:5;23623:19;23615:6;23608:35;23691:2;23684:5;23680:14;23667:28;23652:43;;23704:33;23729:7;23704:33;:::i;:::-;23770:7;23765:2;23757:6;23753:15;23746:32;23826:2;23819:5;23815:14;23802:28;23787:43;;23839:33;23864:7;23839:33;:::i;:::-;23905:7;23900:2;23892:6;23888:15;23881:32;23970:2;23963:5;23959:14;23946:28;23941:2;23933:6;23929:15;23922:53;24023:3;24016:5;24012:15;23999:29;23984:44;;24037:33;24062:7;24037:33;:::i;:::-;24104:7;24098:3;24090:6;24086:16;24079:33;24159:3;24152:5;24148:15;24135:29;24121:43;;24187:2;24179:6;24176:14;24173:34;;;24203:1;24200;24193:12;24173:34;;24241:52;24278:14;24269:6;24262:5;24258:18;24241:52;:::i;:::-;24235:3;24223:16;;24216:78;-1:-1:-1;24227:6:100;23161:1167;-1:-1:-1;;23161:1167:100:o;24916:245::-;24983:6;25036:2;25024:9;25015:7;25011:23;25007:32;25004:52;;;25052:1;25049;25042:12;25004:52;25084:9;25078:16;25103:28;25125:5;25103:28;:::i;25166:1045::-;25244:3;25272:6;25312:5;25299:19;25294:3;25287:32;25375:4;25368:5;25364:16;25351:30;25344:4;25339:3;25335:14;25328:54;25438:4;25431:5;25427:16;25414:30;25407:4;25402:3;25398:14;25391:54;25501:4;25494:5;25490:16;25477:30;25470:4;25465:3;25461:14;25454:54;25564:4;25557:5;25553:16;25540:30;25533:4;25528:3;25524:14;25517:54;25619:4;25612:5;25608:16;25595:30;25634:33;25659:7;25634:33;:::i;:::-;-1:-1:-1;;;;;25699:56:100;25692:4;25683:14;;25676:80;25799:55;25848:4;25837:16;;25841:5;25799:55;:::i;:::-;25886:2;25879:4;25874:3;25870:14;25863:26;25910:67;25973:2;25968:3;25964:12;25950;25936;25910:67;:::i;:::-;25898:79;;;;26024:55;26073:4;26066:5;26062:16;26055:5;26024:55;:::i;:::-;26121:3;26115:4;26111:14;26104:4;26099:3;26095:14;26088:38;26142:63;26200:4;26184:14;26168;26142:63;:::i;26216:813::-;26616:4;26645:3;-1:-1:-1;;;;;26679:6:100;26675:55;26664:9;26657:74;26767:2;26762;26751:9;26747:18;26740:30;26787:81;26864:2;26853:9;26849:18;26841:6;26787:81;:::i;:::-;26779:89;;;26877:71;26944:2;26933:9;26929:18;26921:6;26877:71;:::i;:::-;10267:19;;27018:3;27003:19;;10255:32;10343:4;10332:16;;10319:30;10303:14;;;10296:54;10406:4;10395:16;;10382:30;10366:14;;;10359:54;10469:4;10458:16;;10445:30;10429:14;;;10422:54;26957:66;10182:300;27034:691;27184:6;27192;27200;27244:9;27235:7;27231:23;27274:3;27270:2;27266:12;27263:32;;;27291:1;27288;27281:12;27263:32;27314:53;27359:7;27348:9;27314:53;:::i;:::-;27304:63;;27407:3;27396:9;27392:19;27386:26;27376:36;;27447:4;27440:3;27436:8;27432:2;27428:17;27424:28;27421:48;;;27465:1;27462;27455:12;27421:48;;27491:22;;:::i;:::-;27558:3;27547:9;27543:19;27537:26;27572:33;27597:7;27572:33;:::i;:::-;27614:22;;27689:3;27674:19;;;;27668:26;27663:2;27652:14;;27645:50;-1:-1:-1;27034:691:100;;;;-1:-1:-1;27034:691:100:o;29371:250::-;29456:1;29466:113;29480:6;29477:1;29474:13;29466:113;;;29556:11;;;29550:18;29537:11;;;29530:39;29502:2;29495:10;29466:113;;;-1:-1:-1;;29613:1:100;29595:16;;29588:27;29371:250::o;29626:270::-;29667:3;29705:5;29699:12;29732:6;29727:3;29720:19;29748:76;29817:6;29810:4;29805:3;29801:14;29794:4;29787:5;29783:16;29748:76;:::i;:::-;29878:2;29857:15;-1:-1:-1;;29853:29:100;29844:39;;;;29885:4;29840:50;;29626:270;-1:-1:-1;;29626:270:100:o;29901:373::-;30085:4;30114:3;30126:41;30157:9;30149:6;30126:41;:::i;:::-;30204:2;30198:3;30187:9;30183:19;30176:31;30224:44;30264:2;30253:9;30249:18;30241:6;30224:44;:::i;30279:128::-;30346:9;;;30367:11;;;30364:37;;;30381:18;;:::i;30412:400::-;30606:4;30635:3;30647:41;30678:9;30670:6;30647:41;:::i;:::-;30725:2;30719:3;30708:9;30704:19;30697:31;30745:61;30802:2;30791:9;30787:18;30779:6;30771;30745:61;:::i;30817:739::-;31177:4;31206:3;31218:43;31251:9;31243:6;31218:43;:::i;:::-;31297:2;31292;31281:9;31277:18;31270:30;31317:81;31394:2;31383:9;31379:18;31371:6;31317:81;:::i;:::-;31309:89;;;31407:50;31453:2;31442:9;31438:18;31430:6;31407:50;:::i;:::-;-1:-1:-1;;;;;31498:6:100;31494:55;31488:3;31477:9;31473:19;31466:84;30817:739;;;;;;;:::o;31561:675::-;31654:6;31707:2;31695:9;31686:7;31682:23;31678:32;31675:52;;;31723:1;31720;31713:12;31675:52;31772:7;31765:4;31754:9;31750:20;31746:34;31736:62;;31794:1;31791;31784:12;31736:62;31818:22;;:::i;:::-;31862:3;31903:2;31892:9;31888:18;31929:7;31921:6;31918:19;31915:39;;;31950:1;31947;31940:12;31915:39;31974:9;31992:214;32008:6;32003:3;32000:15;31992:214;;;32083:3;32077:10;32100:31;32125:5;32100:31;:::i;:::-;32144:18;;32191:4;32182:14;;;;32025;31992:214;;;-1:-1:-1;32225:5:100;;31561:675;-1:-1:-1;;;;;31561:675:100:o;32241:125::-;32306:9;;;32327:10;;;32324:36;;;32340:18;;:::i;33592:287::-;33721:3;33759:6;33753:13;33775:66;33834:6;33829:3;33822:4;33814:6;33810:17;33775:66;:::i;:::-;33857:16;;;;;33592:287;-1:-1:-1;;33592:287:100:o;34242:219::-;34391:2;34380:9;34373:21;34354:4;34411:44;34451:2;34440:9;34436:18;34428:6;34411:44;:::i
Swarm Source
ipfs://065f3b26b9da5bb6526526216724e231103729c04e4744372c5b808cb655cda2
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.