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/80001/0xA9D8Cc83f67346efc626dee60117B73D15Ac8d29/sources/project_/contracts/interfaces/IFeeManagerFacet.sol
|
Control this facet by fee manager address use external storage mapper byte key = keccak256(abi.encodePacked("FEE_AMOUNT",_tokenAddr,_chainId)) value: uint = _fee and key = keccak256(abi.encodePacked("IS_FEE_SET",_tokenAddr,_chainId)) value: bool = true when set fee for token
|
interface IFeeManagerFacet {
function setFeeNormalReceiverAddr(address _tokenAddr,address _feeAddr) external;
function setFeePercentReceiverAddr(address _tokenAddr,address _feeAddr) external;
function getFeeNormalReceiverAddr(address _tokenAddr) external returns (address);
function getFeePercentReceiverAddr(address _tokenAddr) external returns (address);
function calCulateFeePercent(address _tokenAddr,uint256 _amount,uint256 _destChainId) view external returns (uint256);
function setBridgeFeeNormalByChain(address _tokenAddr,uint256 _chainId,uint256 _fee) external;
function getBridgeFeeNormalByChain(address _tokenAddr,uint256 _chainId) external returns(uint256);
function setBridgeFeePercentByChain(address _tokenAddr,uint256 _chainId,uint256 _feePercent) external;
function getBridgeFeePercentByChain(address _tokenAddr,uint256 _chainId) external returns(uint256);
}
| 5,631,487
|
./full_match/4/0x942f977dBAFCEcB89f9b22bc0F1c91364441675f/sources/browser/Chainz.sol
|
Gets the last update at a given geohash. _geohash String - the geohash/
|
function getLastUpdateByGeohash(string calldata _geohash) external payable
oneFinney()
returns(uint64)
{
return lastUpdateByGeohash[_geohash];
}
| 674,859
|
// File: @openzeppelin/contracts/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/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: @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() {
_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);
}
}
// 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;
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);
}
}
}
}
// 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/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: @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/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/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/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/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}. 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 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.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,
uint256 tokenId
) internal virtual {}
}
// 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: EnchantedGolemsRockSociety.sol
pragma solidity ^0.8.0;
contract EnchantedGolemsRockSociety is ERC721Enumerable, Ownable {
using Address for address;
using Strings for uint256;
string public baseURI = "";
string public ipfsBaseURI = "";
mapping (uint256 => string) public tokenIdToIpfsHash;
IERC1155 public WhitelistContract;
uint256 public constant MAX_SUPPLY = 10000;
uint256 public constant MAX_PER_TX = 15;
bool public ipfsLocked = false;
bool public manualMintDisabled = false;
bool public publicSaleStarted = false;
bool public presaleEnded = false;
uint256 public mintedByOwner = 0;
uint256 public constant RESERVED_FOR_OWNER = 160;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory _uri, address _whitelist)
ERC721("Enchanted Golems Rock Society", "EGRS")
{
baseURI = _uri;
WhitelistContract = IERC1155(_whitelist);
}
/**
* ------------ METADATA ------------
*/
/**
* @dev Gets base metadata URI
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/**
* @dev Gets ipfs metadata URI
*/
function _ipfsBaseURI() internal view returns (string memory) {
return ipfsBaseURI;
}
/**
* @dev Sets base metadata URI, callable by owner
*/
function setBaseUri(string memory _uri) external onlyOwner {
baseURI = _uri;
}
/**
* @dev Sets ipfs metadata URI, callable by owner
*/
function setIpfsBaseUri(string memory _uri) external onlyOwner {
require(ipfsLocked == false);
ipfsBaseURI = _uri;
}
/**
* @dev Lock ipfs metadata URI and hashes, callable by owner
*/
function lockIpfsMetadata() external onlyOwner {
require(ipfsLocked == false);
ipfsLocked = true;
}
/**
* @dev Set manual ipfs hash for token, callable by owner
*/
function setIpfsHash(uint256 tokenId, string memory hash) external onlyOwner {
require(ipfsLocked == false);
tokenIdToIpfsHash[tokenId] = hash;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory base = _baseURI();
string memory ipfsBase = _ipfsBaseURI();
string memory ipfsHash = tokenIdToIpfsHash[tokenId];
if (bytes(ipfsBase).length == 0) {
return string(abi.encodePacked(base, tokenId.toString()));
} else {
if (bytes(ipfsHash).length == 0) {
return string(abi.encodePacked(ipfsBase, tokenId.toString()));
} else {
return string(abi.encodePacked(ipfsBase, ipfsHash));
}
}
}
/**
* ------------ SALE AND PRESALE ------------
*/
/**
* @dev Starts public sale, callable by owner
*/
function startPublicSale() external onlyOwner {
publicSaleStarted = true;
}
/**
* @dev Ends the presale, callable by owner
*/
function endPresale() external onlyOwner {
presaleEnded = true;
}
/**
* @dev Sets the whitelist contract applicable during presale, callable by owner
*/
function setWhitelistContract(address _contract) external onlyOwner {
WhitelistContract = IERC1155(_contract);
}
/**
* ------------ MINTING ------------
*/
/**
* @dev Mints `count` tokens to `to` address, internal
*/
function mintInternal(address to, uint256 count) internal {
for (uint256 i = 0; i < count; i++) {
_mint(to, totalSupply());
}
}
/**
* @dev Disables manual minting by owner, callable by owner
*/
function disableManualMint() public onlyOwner {
manualMintDisabled = true;
}
/**
* @dev Manual minting by owner, callable by owner
*/
function mintOwner(address[] calldata owners, uint256[] calldata counts) public onlyOwner {
require(!manualMintDisabled, "Not allowed");
require(owners.length == counts.length, "Bad length");
for (uint256 i = 0; i < counts.length; i++) {
require(totalSupply() + counts[i] <= MAX_SUPPLY, "Supply exceeded");
mintInternal(owners[i], counts[i]);
mintedByOwner += counts[i];
}
}
/**
* @dev Gets the price tier from token count
*/
function getPrice(uint256 count) public pure returns (uint256) {
if (count <= 3) {
return 0.0678 ether;
} else if (count <= 8) {
return 0.0654 ether;
} else {
return 0.0612 ether;
}
}
/**
* @dev Public minting
*/
function mint(uint256 count) public payable{
require(publicSaleStarted, "Sale not started");
require(count <= MAX_PER_TX, "Too many tokens");
require(msg.value == count * getPrice(count), "Ether value incorrect");
require((totalSupply() + (RESERVED_FOR_OWNER - mintedByOwner) + count) <= MAX_SUPPLY, "Supply exceeded");
if (!presaleEnded) {
require(WhitelistContract.balanceOf(msg.sender, 0) > 0, "You need to be whitelisted to mint during presale");
}
mintInternal(msg.sender, count);
}
/**
* @dev Withdraw ether from this contract, callable by owner
*/
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
}
|
Lock ipfs metadata URI and hashes, callable by owner/
|
function lockIpfsMetadata() external onlyOwner {
require(ipfsLocked == false);
ipfsLocked = true;
}
| 12,120,792
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract NFTMarket is ReentrancyGuard, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _itemIds;
Counters.Counter private _itemsSold;
Counters.Counter private _itemsOnSale;
Counters.Counter private _OrgIds;
uint256 private listingPrice = 0.005 ether;
// define DonationItem struct
struct MarketItem {
uint itemId;
address nftContract;
uint256 tokenId;
address payable owner;
uint256 price;
bool bid;
bool sold;
address payable donateTo;
address payable highestBider;
uint256 bidingStart;
uint256 bidingEnd;
}
// define Organization struct
struct Organization{
uint256 id;
address orgAddress;
string name;
}
// map item token id to Donation Item
mapping(uint256 => MarketItem) private idToMarketItem;
mapping(uint256 => Organization) private idToOrgainzations;
mapping(address => bool) private orgExist;
//event when New Dontation Item is created
event MarketItemCreated (
uint indexed itemId,
address indexed nftContract,
uint256 indexed tokenId,
address owner,
uint256 price,
bool sold
);
//event when new Organizaion is created
event newOrgCreated(
uint256 id,
address _orgAddress,
string _orgName
);
//event when exist organization is deleted
event orgDeleted(
uint256 id,
address _orgAddress,
string _orgName
);
// add an Organization
function addOrganization(address _orgAddress, string memory _orgName) public onlyOwner returns(uint256){
//check if org alreay exist
require(orgExist[_orgAddress] == false,"Organization is already exist");
//get orgId of current
uint256 newTokenId = _OrgIds.current();
//set if to Organization
idToOrgainzations[newTokenId] = Organization(newTokenId, _orgAddress, _orgName);
//emit newOrgCreated event
emit newOrgCreated(newTokenId, _orgAddress, _orgName);
//increase orgId
_OrgIds.increment();
//org exist now
orgExist[_orgAddress] = true;
//return for front-end
return newTokenId;
}
//delete an Organization
function deleteOrgainzation(uint256 _tokenId) public onlyOwner{
//require(idToOrgainzations[_tokenId],"This orgization does not exist");
emit newOrgCreated(_tokenId, idToOrgainzations[_tokenId].orgAddress, idToOrgainzations[_tokenId].name);
delete idToOrgainzations[_tokenId];
}
//get Organization address by id
function getOrgAddressById(uint256 _tokenId) public view returns(address){
return idToOrgainzations[_tokenId].orgAddress;
}
//fetch all organization
function fetchOrganization() public view returns(Organization[] memory){
uint totalNumOfOrg = _OrgIds.current();
uint currentIndex = 0;
Organization[] memory orgs = new Organization[](totalNumOfOrg);
for(uint i=0; i<totalNumOfOrg; i++){
uint currentId = idToOrgainzations[i].id;
Organization storage currentOrg = idToOrgainzations [currentId];
orgs[currentIndex] = currentOrg;
currentIndex += 1;
}
return orgs;
}
////////////////////////////////////////////////////////////////////////////////////////////////
/* Returns the listing price of the contract */
function getListingPrice() public view returns (uint256) {
return listingPrice;
}
// Setting New Listing Price around 1500 won
function setListingPrice(uint _newListingPrice) public onlyOwner {
listingPrice = _newListingPrice;
}
// Creating a new Donation Item
function createMarketItem(
address nftContract,
uint256 tokenId,
uint256 price,
address _donateToWho,
bool _bid,
uint256 _biddingTime
) public payable nonReentrant {
require(price > 0, "Price must be higher than 0 wei");
require(msg.value == listingPrice,"Price must be equal to list price");
uint256 itemId = _itemIds.current();
idToMarketItem[itemId] = MarketItem(
itemId,
nftContract,
tokenId,
payable(msg.sender),
price,
_bid,
false,
payable(_donateToWho),
payable(address(0)),
block.timestamp,
block.timestamp + _biddingTime
);
// if(_bid == true){
// placeBid(itemId);
// }
IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId);
_itemIds.increment();
payable(owner()).transfer(msg.value);
emit MarketItemCreated(
itemId,
nftContract,
tokenId,
msg.sender,
price,
false
);
}
//Sell Item
function createMarketSale(
address nftContract,
uint256 _itemId
) public payable nonReentrant {
//get item Price
uint price = idToMarketItem[_itemId].price;
//get item Id
uint tokenId = idToMarketItem[_itemId].tokenId;
//check Item price is equal to mag.value
require(msg.value == price,"does not equal to price");
//calculate ethers to owner
uint priceToOwner = (msg.value)/10 * 1;
//calculate ethers to Org
uint priceToOrg = ((msg.value)/10) * 9;
//send ethers to owner and donated Org
idToMarketItem[_itemId].owner.transfer(priceToOwner);
idToMarketItem[_itemId].donateTo.transfer(priceToOrg);
//change the ownership of token to buyer
IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);
idToMarketItem[_itemId].owner = payable(msg.sender);
idToMarketItem[_itemId].sold = true;
_itemsSold.increment();
//payable(owner).transfer(listingPrice);
}
////////////////////////////////////////////////////////////////////////////////////////////////
function placeBid(uint256 _itemId) public payable {
require(idToMarketItem[_itemId].bid == true, "not on bid");
require(idToMarketItem[_itemId].price < msg.value, "Bidding price can not be less than or equal to highest price");
require(block.timestamp <= idToMarketItem[_itemId].bidingEnd, "bidding was over");
require(msg.sender != idToMarketItem[_itemId].owner);
idToMarketItem[_itemId].highestBider == msg.sender;
idToMarketItem[_itemId].price == msg.value;
}
////////////////////////////////////////////////////////////////////////////////////////////////
//fetch marketItem for frontEnd
function fetchMarketItems() public view returns (MarketItem[] memory){
uint itemCount = _itemIds.current();
uint unsoldItemCount = _itemsOnSale.current() - _itemsSold.current();
uint currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
for(uint i=0;i<itemCount;i++){
if(idToMarketItem[i].sold == false){
uint currentId = idToMarketItem[i].itemId;
MarketItem storage currentItem = idToMarketItem [currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
//fetch NFTs that msg.sender owns
function fetchMyNFTs() public view returns (MarketItem[] memory){
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for(uint i = 0; i<totalItemCount; i++){
if(idToMarketItem[i].owner == msg.sender){
itemCount += 1;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for(uint i = 0; i<totalItemCount; i++){
if(idToMarketItem[i].owner == msg.sender){
uint currentId = idToMarketItem[i].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
function fetchBidItems() public view returns(MarketItem[] memory) {
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for(uint i = 0; i<totalItemCount; i++){
if(idToMarketItem[i].bid == true){
itemCount += 1;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for(uint i = 0; i<totalItemCount; i++){
if(idToMarketItem[i].bid == true){
uint currentId = idToMarketItem[i].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
}
|
Returns the listing price of the contract /
|
function getListingPrice() public view returns (uint256) {
return listingPrice;
}
| 13,035,370
|
./full_match/4/0x1f25d75544C351D3379F64F3c1B3E03dBdF54A63/sources/nftcontract/ERC1155Tradable.sol
|
Overrides ERC1155MintBurn to change the batch birth events to creator transfers, and to set _supply Number of mints to execute Origin of tokens will be the _from parameter Executing all minting Update storage balance
|
function _batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) internal virtual whenNotPaused {
require(
_ids.length == _amounts.length,
"ERC1155Tradable#batchMint: INVALID_ARRAYS_LENGTH"
);
uint256 nMint = _ids.length;
address origin = _origin(_ids[0]);
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), _to, _ids, _amounts, _data);
for (uint256 i = 0; i < nMint; i++) {
uint256 id = _ids[i];
uint256 amount = _amounts[i];
_beforeMint(id, amount);
require(
_origin(id) == origin,
"ERC1155Tradable#batchMint: MULTIPLE_ORIGINS_NOT_ALLOWED"
);
balances[id][_to] += amount;
_supply[id] += amount;
}
operator,
origin,
_to,
_ids,
_amounts,
_data
);
}
| 760,402
|
pragma solidity 0.4.24;
contract IMigrationContract {
function migrate(address _addr, uint256 _tokens, uint256 _totaltokens) public returns (bool success);
}
/* taking ideas from FirstBlood token */
contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
function safeDiv(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x / y;
return z;
}
}
/**
* @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 ethFundDeposit;
event OwnershipTransferred(address indexed ethFundDeposit, address indexed _newFundDeposit);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
ethFundDeposit = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == ethFundDeposit);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a _newFundDeposit.
* @param _newFundDeposit The address to transfer ownership to.
*/
function transferOwnership(address _newFundDeposit) public onlyOwner {
require(_newFundDeposit != address(0));
emit OwnershipTransferred(ethFundDeposit, _newFundDeposit);
ethFundDeposit = _newFundDeposit;
}
}
/**
* @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() 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();
}
}
/**
* @title Controllable
* @dev Base contract which allows children to control the address
*/
contract controllable is Ownable {
event AddToBlacklist(address _addr);
event DeleteFromBlacklist(address _addr);
// controllable variable
mapping (address => bool) internal blacklist; // black list
/**
* @dev called by the owner to AddToBlacklist
*/
function addtoblacklist(address _addr) public onlyOwner {
blacklist[_addr] = true;
emit AddToBlacklist(_addr);
}
/**
* @dev called by the owner to unpDeleteFromBlacklistause
*/
function deletefromblacklist(address _addr) public onlyOwner {
blacklist[_addr] = false;
emit DeleteFromBlacklist(_addr);
}
/**
* @dev called by the owner to check the blacklist address
*/
function isBlacklist(address _addr) public view returns(bool) {
return blacklist[_addr];
}
}
/**
* @title Lockable
* @dev Base contract which allows children to control the token release mechanism
*/
contract Lockable is Ownable, SafeMath {
// parameters
mapping (address => uint256) balances;
mapping (address => uint256) totalbalances;
uint256 public totalreleaseblances;
mapping (address => mapping (uint256 => uint256)) userbalances; // address , order ,balances amount
mapping (address => mapping (uint256 => uint256)) userRelease; // address , order ,release amount
mapping (address => mapping (uint256 => uint256)) isRelease; // already release period
mapping (address => mapping (uint256 => uint256)) userChargeTime; // address , order ,charge time
mapping (address => uint256) userChargeCount; // user total charge times
mapping (address => mapping (uint256 => uint256)) lastCliff; // address , order ,last cliff time
// userbalances each time segmentation
mapping (address => mapping (uint256 => mapping (uint256 => uint256))) userbalancesSegmentation; // address , order ,balances amount
uint256 internal duration = 30*15 days;
uint256 internal cliff = 90 days;
// event
event userlockmechanism(address _addr,uint256 _amount,uint256 _timestamp);
event userrelease(address _addr, uint256 _times, uint256 _amount);
modifier onlySelfOrOwner(address _addr) {
require(msg.sender == _addr || msg.sender == ethFundDeposit);
_;
}
function LockMechanism (
address _addr,
uint256 _value
)
internal
{
require(_addr != address(0));
require(_value != 0);
// count
userChargeCount[_addr] = safeAdd(userChargeCount[_addr],1);
uint256 _times = userChargeCount[_addr];
// time
userChargeTime[_addr][_times] = ShowTime();
// balances
userbalances[_addr][_times] = _value;
initsegmentation(_addr,userChargeCount[_addr],_value);
totalbalances[_addr] = safeAdd(totalbalances[_addr],_value);
isRelease[_addr][_times] = 0;
emit userlockmechanism(_addr,_value,ShowTime());
}
// init segmentation
function initsegmentation(address _addr,uint256 _times,uint256 _value) internal {
for (uint8 i = 1 ; i <= 5 ; i++ ) {
userbalancesSegmentation[_addr][_times][i] = safeDiv(_value,5);
}
}
// calculate period
function CalcPeriod(address _addr, uint256 _times) public view returns (uint256) {
uint256 userstart = userChargeTime[_addr][_times];
if (ShowTime() >= safeAdd(userstart,duration)) {
return 5;
}
uint256 timedifference = safeSubtract(ShowTime(),userstart);
uint256 period = 0;
for (uint8 i = 1 ; i <= 5 ; i++ ) {
if (timedifference >= cliff) {
timedifference = safeSubtract(timedifference,cliff);
period += 1;
}
}
return period;
}
// ReleasableAmount() looking for the current releasable amount
function ReleasableAmount(address _addr, uint256 _times) public view returns (uint256) {
require(_addr != address(0));
uint256 period = CalcPeriod(_addr,_times);
if (safeSubtract(period,isRelease[_addr][_times]) > 0){
uint256 amount = 0;
for (uint256 i = safeAdd(isRelease[_addr][_times],1) ; i <= period ; i++ ) {
amount = safeAdd(amount,userbalancesSegmentation[_addr][_times][i]);
}
return amount;
} else {
return 0;
}
}
// release() release the current releasable amount
function release(address _addr, uint256 _times) external onlySelfOrOwner(_addr) {
uint256 amount = ReleasableAmount(_addr,_times);
require(amount > 0);
userRelease[_addr][_times] = safeAdd(userRelease[_addr][_times],amount);
balances[_addr] = safeAdd(balances[_addr],amount);
lastCliff[_addr][_times] = ShowTime();
isRelease[_addr][_times] = CalcPeriod(_addr,_times);
totalreleaseblances = safeAdd(totalreleaseblances,amount);
emit userrelease(_addr, _times, amount);
}
// ShowTime
function ShowTime() internal view returns (uint256) {
return block.timestamp;
}
// totalBalance()
function totalBalanceOf(address _addr) public view returns (uint256) {
return totalbalances[_addr];
}
// ShowRelease() looking for the already release amount of the address at some time
function ShowRelease(address _addr, uint256 _times) public view returns (uint256) {
return userRelease[_addr][_times];
}
// ShowUnrelease() looking for the not yet release amount of the address at some time
function ShowUnrelease(address _addr, uint256 _times) public view returns (uint256) {
return safeSubtract(userbalances[_addr][_times],ShowRelease(_addr,_times));
}
// ShowChargeTime() looking for the charge time
function ShowChargeTime(address _addr, uint256 _times) public view returns (uint256) {
return userChargeTime[_addr][_times];
}
// ShowChargeCount() looking for the user total charge times
function ShowChargeCount(address _addr) public view returns (uint256) {
return userChargeCount[_addr];
}
// ShowNextCliff() looking for the nex cliff time
function ShowNextCliff(address _addr, uint256 _times) public view returns (uint256) {
return safeAdd(lastCliff[_addr][_times],cliff);
}
// ShowSegmentation() looking for the user balances Segmentation
function ShowSegmentation(address _addr, uint256 _times,uint256 _period) public view returns (uint256) {
return userbalancesSegmentation[_addr][_times][_period];
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) public view 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) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/* ERC 20 token */
contract StandardToken is controllable, Pausable, Token, Lockable {
function transfer(address _to, uint256 _value) public whenNotPaused() returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to] && !isBlacklist(msg.sender)) {
// sender
balances[msg.sender] = safeSubtract(balances[msg.sender],_value);
totalbalances[msg.sender] = safeSubtract(totalbalances[msg.sender],_value);
// _to
balances[_to] = safeAdd(balances[_to],_value);
totalbalances[_to] = safeAdd(totalbalances[_to],_value);
emit Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused() returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to] && !isBlacklist(msg.sender)) {
// _to
balances[_to] = safeAdd(balances[_to],_value);
totalbalances[_to] = safeAdd(totalbalances[_to],_value);
// _from
balances[_from] = safeSubtract(balances[_from],_value);
totalbalances[_from] = safeSubtract(totalbalances[_from],_value);
// allowed
allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value);
emit Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract BugXToken is StandardToken {
/**
* base parameters
*/
// metadata
string public constant name = "BUGX2.0";
string public constant symbol = "BUGX";
uint256 public constant decimals = 18;
string public version = "2.0";
// contracts
address public newContractAddr; // the new contract for BUGX token updates;
// crowdsale parameters
bool public isFunding; // switched to true in operational state
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // current supply tokens for sell
uint256 public tokenRaised = 0; // the number of total sold token
uint256 public tokenIssued = 0; // the number of total issued token
uint256 public tokenMigrated = 0; // the number of total Migrated token
uint256 internal tokenExchangeRate = 9000; // 9000 BUGX tokens per 1 ETH
uint256 internal tokenExchangeRateTwo = 9900; // 9000 * 1.1 BUGX tokens per 1 ETH
uint256 internal tokenExchangeRateThree = 11250; // 9000 * 1.25 BUGX tokens per 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // issue token to buyer;
event TakebackToken(address indexed _from, uint256 _value); // record token take back info;
event RaiseToken(address indexed _to, uint256 _value); // record token raise info;
event IssueToken(address indexed _to, uint256 _value);
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _addr, uint256 _tokens, uint256 _totaltokens);
// format decimals.
function formatDecimals(uint256 _value) internal pure returns (uint256 ) {
return _value * 10 ** decimals;
}
/**
* constructor function
*/
// constructor
constructor(
address _ethFundDeposit,
uint256 _currentSupply
)
public
{
require(_ethFundDeposit != address(0x0));
ethFundDeposit = _ethFundDeposit;
isFunding = false; //controls pre through crowdsale state
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(1500000000); //1,500,000,000 total supply
require(currentSupply <= totalSupply);
balances[ethFundDeposit] = currentSupply;
totalbalances[ethFundDeposit] = currentSupply;
}
/**
* Modify currentSupply functions
*/
/// @dev increase the token's supply
function increaseSupply (uint256 _tokens) onlyOwner external {
uint256 _value = formatDecimals(_tokens);
require (_value + currentSupply <= totalSupply);
currentSupply = safeAdd(currentSupply, _value);
tokenadd(ethFundDeposit,_value);
emit IncreaseSupply(_value);
}
/// @dev decrease the token's supply
function decreaseSupply (uint256 _tokens) onlyOwner external {
uint256 _value = formatDecimals(_tokens);
uint256 tokenCirculation = safeAdd(tokenRaised,tokenIssued);
require (safeAdd(_value,tokenCirculation) <= currentSupply);
currentSupply = safeSubtract(currentSupply, _value);
tokensub(ethFundDeposit,_value);
emit DecreaseSupply(_value);
}
/**
* Funding functions
*/
modifier whenFunding() {
require (isFunding);
require (block.number >= fundingStartBlock);
require (block.number <= fundingStopBlock);
_;
}
/// @dev turn on the funding state
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) onlyOwner external {
require (!isFunding);
require (_fundingStartBlock < _fundingStopBlock);
require (block.number < _fundingStartBlock);
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// @dev turn off the funding state
function stopFunding() onlyOwner external {
require (isFunding);
isFunding = false;
}
/**
* migrate functions
*/
/// @dev set a new contract for recieve the tokens (for update contract)
function setMigrateContract(address _newContractAddr) onlyOwner external {
require (_newContractAddr != newContractAddr);
newContractAddr = _newContractAddr;
}
/// sends the tokens to new contract by owner
function migrate(address _addr) onlySelfOrOwner(_addr) external {
require(!isFunding);
require(newContractAddr != address(0x0));
uint256 tokens_value = balances[_addr];
uint256 totaltokens_value = totalbalances[_addr];
require (tokens_value != 0 || totaltokens_value != 0);
balances[_addr] = 0;
totalbalances[_addr] = 0;
IMigrationContract newContract = IMigrationContract(newContractAddr);
require (newContract.migrate(_addr, tokens_value, totaltokens_value));
tokenMigrated = safeAdd(tokenMigrated, totaltokens_value);
emit Migrate(_addr, tokens_value, totaltokens_value);
}
/**
* tokenRaised and tokenIssued control functions
* base functions
*/
/// token raised
function tokenRaise (address _addr,uint256 _value) internal {
uint256 tokenCirculation = safeAdd(tokenRaised,tokenIssued);
require (safeAdd(_value,tokenCirculation) <= currentSupply);
tokenRaised = safeAdd(tokenRaised, _value);
emit RaiseToken(_addr, _value);
}
/// issue token 1 : token issued
function tokenIssue (address _addr,uint256 _value) internal {
uint256 tokenCirculation = safeAdd(tokenRaised,tokenIssued);
require (safeAdd(_value,tokenCirculation) <= currentSupply);
tokenIssued = safeAdd(tokenIssued, _value);
emit IssueToken(_addr, _value);
}
/// issue token 2 : issue token take back
function tokenTakeback (address _addr,uint256 _value) internal {
require (tokenIssued >= _value);
tokenIssued = safeSubtract(tokenIssued, _value);
emit TakebackToken(_addr, _value);
}
/// issue token take from ethFundDeposit to user
function tokenadd (address _addr,uint256 _value) internal {
require(_value != 0);
require (_addr != address(0x0));
balances[_addr] = safeAdd(balances[_addr], _value);
totalbalances[_addr] = safeAdd(totalbalances[_addr], _value);
}
/// issue token take from user to ethFundDeposit
function tokensub (address _addr,uint256 _value) internal {
require(_value != 0);
require (_addr != address(0x0));
balances[_addr] = safeSubtract(balances[_addr], _value);
totalbalances[_addr] = safeSubtract(totalbalances[_addr], _value);
}
/**
* tokenRaised and tokenIssued control functions
* main functions
*/
/// Issues tokens to buyers.
function allocateToken(address _addr, uint256 _tokens) onlyOwner external {
uint256 _value = formatDecimals(_tokens);
tokenadd(_addr,_value);
tokensub(ethFundDeposit,_value);
tokenIssue(_addr,_value);
emit Transfer(ethFundDeposit, _addr, _value);
}
/// Issues tokens deduction.
function deductionToken (address _addr, uint256 _tokens) onlyOwner external {
uint256 _value = formatDecimals(_tokens);
tokensub(_addr,_value);
tokenadd(ethFundDeposit,_value);
tokenTakeback(_addr,_value);
emit Transfer(_addr, ethFundDeposit, _value);
}
/// add the segmentation
function addSegmentation(address _addr, uint256 _times,uint256 _period,uint256 _tokens) onlyOwner external returns (bool) {
uint256 amount = userbalancesSegmentation[_addr][_times][_period];
if (amount != 0 && _tokens != 0){
uint256 _value = formatDecimals(_tokens);
userbalancesSegmentation[_addr][_times][_period] = safeAdd(amount,_value);
userbalances[_addr][_times] = safeAdd(userbalances[_addr][_times], _value);
totalbalances[_addr] = safeAdd(totalbalances[_addr], _value);
tokensub(ethFundDeposit,_value);
tokenIssue(_addr,_value);
return true;
} else {
return false;
}
}
/// sub the segmentation
function subSegmentation(address _addr, uint256 _times,uint256 _period,uint256 _tokens) onlyOwner external returns (bool) {
uint256 amount = userbalancesSegmentation[_addr][_times][_period];
if (amount != 0 && _tokens != 0){
uint256 _value = formatDecimals(_tokens);
userbalancesSegmentation[_addr][_times][_period] = safeSubtract(amount,_value);
userbalances[_addr][_times] = safeSubtract(userbalances[_addr][_times], _value);
totalbalances[_addr] = safeSubtract(totalbalances[_addr], _value);
tokenadd(ethFundDeposit,_value);
tokenTakeback(_addr,_value);
return true;
} else {
return false;
}
}
/**
* tokenExchangeRate functions
*/
/// @dev set the token's tokenExchangeRate,
function setTokenExchangeRate(uint256 _RateOne,uint256 _RateTwo,uint256 _RateThree) onlyOwner external {
require (_RateOne != 0 && _RateTwo != 0 && _RateThree != 0);
require (_RateOne != tokenExchangeRate && _RateTwo != tokenExchangeRateTwo && _RateThree != tokenExchangeRateThree);
tokenExchangeRate = _RateOne;
tokenExchangeRateTwo = _RateTwo;
tokenExchangeRateThree = _RateThree;
}
/// calculate the tokenExchangeRate
function computeTokenAmount(uint256 _eth) internal view returns (uint256 tokens) {
if(_eth > 0 && _eth < 100 ether){
tokens = safeMult(_eth, tokenExchangeRate);
}
if (_eth >= 100 ether && _eth < 500 ether){
tokens = safeMult(_eth, tokenExchangeRateTwo);
}
if (_eth >= 500 ether ){
tokens = safeMult(_eth, tokenExchangeRateThree);
}
}
/**
* Append : the LockMechanism functions by owner
*/
function LockMechanismByOwner (
address _addr,
uint256 _tokens
)
external onlyOwner whenFunding
{
require (_tokens != 0);
uint256 _value = formatDecimals(_tokens);
tokenRaise(_addr,_value);
tokensub(ethFundDeposit,_value);
LockMechanism(_addr,_value);
emit Transfer(ethFundDeposit,_addr,_value);
}
/**
* ETH control functions
*/
/// @dev sends ETH to BUGX team
function transferETH() onlyOwner external {
require (address(this).balance != 0);
ethFundDeposit.transfer(address(this).balance);
}
function () public payable whenFunding { // fallback function
require (msg.value != 0);
uint256 _value = computeTokenAmount(msg.value);
tokenRaise(msg.sender,_value);
tokensub(ethFundDeposit,_value);
LockMechanism(msg.sender,_value);
emit Transfer(ethFundDeposit,msg.sender,_value);
}
}
|
ShowUnrelease() looking for the not yet release amount of the address at some time
|
function ShowUnrelease(address _addr, uint256 _times) public view returns (uint256) {
return safeSubtract(userbalances[_addr][_times],ShowRelease(_addr,_times));
}
| 5,466,064
|
./full_match/4/0x0Dd102AC8Ce99aF70E1FDd1985EaD99a441A65D7/sources/Web.sol
|
Will update the base URL of token's URI _newBaseMetadataURI New base URL of token's URI/ TODO: auth
|
function setBaseMetadataURI(string memory _newBaseMetadataURI) public {
setBaseMetadataURI(_newBaseMetadataURI);
}
| 746,615
|
pragma solidity >= 0.5.0 < 0.7.0;
// pragma experimental ABIEncoderV2; // To support struct as return value
// WifiAllocation.sol: Performs bandwidth allocation according to the proportional rule
// Based on the previous version, and added support for requesting both (1) bandwidth and (2) burst data volume
contract WifiAllocation {
// Only owner can perform the allocation
address payable public owner;
uint public totalBandwidth;
uint public totalDesiredBandwidth;
uint public totalDesiredNonDynamic;
uint public totalDesiredDynamic;
uint public totalDesiredBurst;
// The owner can set a minimum unit price of the bandwidth.
// Unit: wei
// The price has to be an integer, so it is scaled for higher precision; same for bandwidth
uint constant bandwidthPriceScalingFactor = 100;
uint constant bandwidthScalingFactor = 100;
uint constant burstPriceScalingFactor = 100;
uint public minBandwidthPrice;
uint public bandwidthPrice;
uint public oldPrice;
uint public minBurstPriceFactor;
// If user does not specify desired burst, a default value is returned (e.g., 1MB)
uint public burstPrice;
// uint public weight; // Changed to local variables to reduce gas cost
// uint public weightedPrice;
// The bids to be collected by the contract owner
uint public pendingCollection;
uint public totalCollected;
uint public latestTransaction;
// Keep record of all users
uint public numUsers;
uint[] public allocatedBandwidth;
uint[] public currentBalances;
bool[] public isActive;
// Whether the user accepts dynamic bandwidth allocation
// i.e., the allocated bandwidth may fluctuate, while the bid remains the same
bool[] public isDynamic;
// The corresponding prices that users are charged according to
uint[] public actualPrices;
uint[] public burstVol;
struct User {
address userAddress;
uint desiredBandwidth;
uint receivedBandwidth;
uint lastPaymentTime;
uint thresholdBid;
uint burst;
}
mapping(uint => User) users;
mapping(address => uint) occupiedID;
mapping(address => uint) pendingWithdrawl;
event UponAllocation(
uint _numUsers,
uint[] _allocatedBandwidth,
uint[] _currentBalances,
uint[] _actualPrices,
bool[] _isActive,
uint[] _burstVol
);
modifier onlyOwner {
require(
msg.sender == owner,
"Only the owner can call this function"
);
_;
}
modifier onlyNotOwner {
require(
msg.sender != owner,
"The owner cannot call this function"
);
_;
}
modifier requirePayment {
require(
msg.value > 0,
"You must pay some value !"
);
_;
}
constructor(uint _totalBandwidth, uint _minBandwidthPrice, uint _minBurstPriceFactor) public {
// Initialises with the total bandwidth specified
owner = msg.sender;
totalBandwidth = _totalBandwidth;
minBandwidthPrice = _minBandwidthPrice;
minBurstPriceFactor = _minBurstPriceFactor;
bandwidthPrice = minBandwidthPrice * bandwidthPriceScalingFactor;
// By default totalDesiredBurst is set to 1
burstPrice = minBurstPriceFactor * 1 * 1;
}
// Called by a user when joining or exitting the wifi connection
function uponConnection(uint bandwidth, uint thresholdBid, uint burst) public payable onlyNotOwner {
latestTransaction = now;
if(bandwidth > 0) {
// The user wants to join the connection
// Check if user already exists
if(occupiedID[msg.sender] > 0) {
uint userID = occupiedID[msg.sender];
// Array index starts from 0, userID starts from 1
if(isActive[userID - 1]) {
/// @notice Case1: The user is still actively connected: renewal of connection
connectionRenewal(userID, bandwidth, thresholdBid, burst);
} else {
/// @notice Case2: The user has been disconnected: reentry of connection
connectionReentry(userID, bandwidth, thresholdBid, burst);
}
} else {
/// @notice Case3: The user has never connected before: initialisation of connection
occupiedID[msg.sender] = connectionInitialisation(bandwidth, thresholdBid, burst);
}
} else {
/// @notice Case4: The user wants to quit the connection (by indicating a bandwidth of 0)
require(occupiedID[msg.sender] > 0, "You are not an existing user!");
connectionTermination(occupiedID[msg.sender]);
withdrawBalance();
}
}
// Called by an ACTIVE user when he only selects to top up balance
function addBalance() public payable onlyNotOwner {
require(occupiedID[msg.sender] > 0, "You are not an existing user!");
currentBalances[occupiedID[msg.sender] - 1] += msg.value;
}
// // Called by the owner to check results for testing purposes
// function getAllocationResults() public onlyOwner {
// // returns (uint[] memory, uint[] memory, uint, bool[] memory, bool[] memory, uint[] memory) {
// // updateBalance();
// emit UponAllocation(numUsers, allocatedBandwidth, currentBalances, actualPrices, isActive);
// // return (currentBalances, actualPrices, totalCollected, isActive, isDynamic, allocatedBandwidth);
// }
// // Called by users to check the real-time supply and price
// function getPriceAndSupply() public view returns (uint, uint, uint, uint) {
// // Param1: current unit price of bandwidth (scaled by bandwidthPriceScalingFactor)
// // Param2: total demand (totalDesiredBandwidth)
// // Param3: total demand of dynamic users (totalDesiredDynamic)
// // Param4: total demand of non-dynamic users (totalDesiredNonDynamic)
// return (bandwidthPrice, totalDesiredBandwidth, totalDesiredDynamic, totalDesiredNonDynamic);
// }
// Get user profile
// function getUserProfile(uint userID) public view returns (User memory) {
// return users[userID];
// }
// Get userID
function getUserID(address _user) public view returns (uint) {
return occupiedID[_user];
}
function getUserAllocation(uint _userID) public view returns (uint) {
return allocatedBandwidth[_userID]/bandwidthScalingFactor;
}
function getUserBalance(uint _userID) public view returns (uint) {
return currentBalances[_userID];
}
// Perform bandwidth allocation depending on the demand and supply
function performAllocation() public {
if(totalDesiredBandwidth <= totalBandwidth) {
demandNotExceedSupply();
} else {
demandExceedSupply();
}
}
// Deduct balance according to usage
// If the balance is not enough, the user is deactived from connection
function updateBalance() public {
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
uint currentTime = now;
uint currentFee = bandwidthPrice * users[i + 1].receivedBandwidth * (currentTime - users[i + 1].lastPaymentTime) / (bandwidthPriceScalingFactor * bandwidthScalingFactor);
// Since there is no capacity limit on burst volume, users are only charged at a constant price specified by owner
// The cost of burst is VOLUME * UNIT PRICE * TIME DURATION
currentFee += burstPrice * users[i + 1].burst * (currentTime - users[i + 1].lastPaymentTime) / burstPriceScalingFactor;
users[i + 1].lastPaymentTime = currentTime;
if(currentBalances[i] >= currentFee) {
currentBalances[i] -= currentFee;
pendingCollection += currentFee;
} else {
// Deactivate the user from connection
currentFee = currentBalances[i];
currentBalances[i] = 0;
pendingCollection += currentFee;
users[i + 1].receivedBandwidth = 0;
totalDesiredBandwidth -= users[i + 1].desiredBandwidth;
if(isDynamic[i]) {
totalDesiredDynamic -= users[i + 1].desiredBandwidth;
} else {
totalDesiredNonDynamic -= users[i + 1].desiredBandwidth;
}
users[i + 1].desiredBandwidth = 0;
allocatedBandwidth[i] = 0;
actualPrices[i] = 0;
isActive[i] = false;
isDynamic[i] = false;
users[i + 1].burst = 0;
burstVol[i] = 0;
// Calculate the allocation again since the demand has changed
// performAllocation();
}
}
}
collectBids();
emit UponAllocation(numUsers, allocatedBandwidth, currentBalances, actualPrices, isActive, burstVol);
}
// Top-up back to user according to the bandwidth wasted
// e.g. userID 1, bandwidth 1MB, duration 2 second: (1, 100, 200, false)
function topBack(uint userID, uint bandwidth, uint duration, bool useOldPrice) public onlyOwner {
uint timingFactor = 100;
if(isActive[userID]) {
uint price = useOldPrice ? oldPrice : bandwidthPrice;
uint topBackFee = price * bandwidth * duration / (bandwidthPriceScalingFactor * bandwidthScalingFactor * timingFactor);
currentBalances[userID] += topBackFee;
if (pendingCollection >= topBackFee) {
pendingCollection -= topBackFee;
} else {
pendingCollection = 0;
}
}
}
// When the user has never connected before
function connectionInitialisation(uint bandwidth, uint thresholdBid, uint burst) internal requirePayment returns (uint userID) {
// Create profile for the new user
userID = ++numUsers;
// {userAddress, desiredBandwidth, receivedBandwidth, lastPaymentTime, thresholdBid, burst}
users[userID] = User(msg.sender, bandwidth, 0, now, thresholdBid, burst);
isActive.push(true);
totalDesiredBandwidth += bandwidth;
// In this case, the thresholdBid is compared with desiredBandwidth * bandwidthPrice to determine whether the user is dynamic
if(bandwidthPrice * bandwidth / bandwidthPriceScalingFactor > thresholdBid) {
isDynamic.push(true);
totalDesiredDynamic += bandwidth;
} else {
isDynamic.push(false);
totalDesiredNonDynamic += bandwidth;
}
totalDesiredBurst += burst;
allocatedBandwidth.push(0);
currentBalances.push(msg.value);
actualPrices.push(bandwidthPrice);
burstVol.push(burst);
updatePrice(bandwidth * bandwidthScalingFactor, true);
performAllocation();
updateBalance();
}
// When the user is still connected
// The user can either top up his balance or modify his desired bandwidth
function connectionRenewal(uint userID, uint bandwidth, uint thresholdBid, uint burst) internal {
totalDesiredBandwidth = totalDesiredBandwidth + bandwidth - users[userID].desiredBandwidth;
// Since the user is still active, there is no need to update isDynamic (later in performAllocation())
if(isDynamic[userID - 1]) {
totalDesiredDynamic = totalDesiredDynamic + bandwidth - users[userID].desiredBandwidth;
} else {
totalDesiredNonDynamic = totalDesiredNonDynamic + bandwidth - users[userID].desiredBandwidth;
}
totalDesiredBurst = totalDesiredBurst + burst - users[userID].burst;
// Update user profile
currentBalances[userID - 1] += msg.value;
users[userID].desiredBandwidth = bandwidth;
users[userID].thresholdBid = thresholdBid;
users[userID].burst = burst;
burstVol[userID - 1] = burst;
// No need to update lastPaymentTime here
// Check whether the demand is increasing or decreasing, depending on the *actually received bandwidth(WHICH IS SCALED)*
// e.g., User i desires 40 units bandwidth at price 1.2, but receives 32 units at price 1.5
// Now he only wants 20 units instead, so the total bid is reduced by 1.5 * (32 - 20)
// ***NOTE***: receivedBandwidth is scaled by bandwidthScalingFactor
// bool isPositive = (bandwidth * bandwidthScalingFactor >= users[userID].receivedBandwidth);
// updatePrice(isPositive ? (bandwidth * bandwidthScalingFactor - users[userID].receivedBandwidth) : (users[userID].receivedBandwidth - bandwidth * bandwidthScalingFactor), isPositive);
// --------------------------------------
// // ***REMOVED***: depending on the *desired bandwidth* instead, otherwise a user who only wants to top up his balance but retaining his desired bandwidth may
// // unintentionally increase the price
bool isPositive = (bandwidth >= users[userID].desiredBandwidth);
updatePrice(isPositive ? (bandwidth - users[userID].desiredBandwidth) * bandwidthScalingFactor : (users[userID].desiredBandwidth - bandwidth) * bandwidthScalingFactor, isPositive);
performAllocation();
updateBalance();
}
// When the user has connected before but was deactivated from connection
// The owner still keeps the user profile for a certain period
function connectionReentry(uint userID, uint bandwidth, uint thresholdBid, uint burst) internal requirePayment {
// Update user profile
isActive[userID - 1] = true;
totalDesiredBandwidth += bandwidth;
// In this case, the thresholdBid is compared with desiredBandwidth * bandwidthPrice to determine whether the user is dynamic
if(bandwidthPrice * bandwidth / bandwidthPriceScalingFactor > thresholdBid) {
isDynamic[userID - 1] = true;
totalDesiredDynamic += bandwidth;
} else {
isDynamic[userID - 1] = false;
totalDesiredNonDynamic += bandwidth;
}
totalDesiredBurst += burst;
currentBalances[userID - 1] += msg.value;
users[userID].desiredBandwidth = bandwidth;
users[userID].lastPaymentTime = now;
users[userID].thresholdBid = thresholdBid;
users[userID].burst = burst;
burstVol[userID - 1] = burst;
updatePrice(bandwidth * bandwidthScalingFactor, true);
performAllocation();
updateBalance();
}
// When the user wants to quit the connection
// The owner still keeps the user profile for a certain period
function connectionTermination(uint userID) internal {
uint deltaBandwidth = users[userID].receivedBandwidth;
// uint deltaBandwidth = users[userID].desiredBandwidth * bandwidthScalingFactor;
pendingWithdrawl[users[userID].userAddress] += (currentBalances[userID - 1] + msg.value);
isActive[userID - 1] = false;
totalDesiredBandwidth -= users[userID].desiredBandwidth;
if(isDynamic[userID - 1]) {
totalDesiredDynamic -= users[userID].desiredBandwidth;
} else {
totalDesiredNonDynamic -= users[userID].desiredBandwidth;
}
totalDesiredBurst -= users[userID].burst;
isDynamic[userID - 1] = false;
currentBalances[userID - 1] = 0;
users[userID].receivedBandwidth = 0;
users[userID].desiredBandwidth = 0;
users[userID].thresholdBid = 0;
users[userID].burst = 0;
burstVol[userID - 1] = 0;
allocatedBandwidth[userID - 1] = 0;
actualPrices[userID - 1] = 0;
// Similar to connectionRenewal(), the deltaBandwidth depends on the *actually received bandwidth*
updatePrice(deltaBandwidth, false);
performAllocation();
updateBalance();
}
// When the total desired bandwidth does not exceed the available bandwidth:
// Everyone simply gets as much as desired
function demandNotExceedSupply() internal {
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
actualPrices[i] = bandwidthPrice;
allocatedBandwidth[i] = users[i + 1].desiredBandwidth * bandwidthScalingFactor;
users[i + 1].receivedBandwidth = users[i + 1].desiredBandwidth * bandwidthScalingFactor;
}
}
}
// When the total desired bandwidth exceeds the available bandwidth:
// The resource allocation mechanism is triggered
function demandExceedSupply() internal {
// uint weight;
uint weightedPrice;
updateIsDynamic();
if(totalDesiredNonDynamic >= totalBandwidth) {
// Ignore isDynamic[] and actualPrices[], and all users are charged bandwidthPrice
// Proportionally allocate the bandwidth according to desired bandwidth
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
actualPrices[i] = bandwidthPrice;
allocatedBandwidth[i] = users[i + 1].desiredBandwidth * totalBandwidth * bandwidthScalingFactor / totalDesiredBandwidth;
users[i + 1].receivedBandwidth = allocatedBandwidth[i];
}
}
} else {
// Non-dynamic users receive desired bandwidth, while dynamic users proportionally share the remaining
// weight = totalDesiredDynamic * bandwidthPriceScalingFactor / (totalBandwidth - totalDesiredNonDynamic);
// weightedPrice = weight * bandwidthPrice / bandwidthPriceScalingFactor;
weightedPrice = totalDesiredDynamic * bandwidthPrice / (totalBandwidth - totalDesiredNonDynamic);
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
if(isDynamic[i]) {
actualPrices[i] = bandwidthPrice;
allocatedBandwidth[i] = users[i + 1].desiredBandwidth * (totalBandwidth - totalDesiredNonDynamic) * bandwidthScalingFactor / totalDesiredDynamic;
users[i + 1].receivedBandwidth = allocatedBandwidth[i];
} else {
// actualPrices[i] = weight * bandwidthPrice / bandwidthPriceScalingFactor;
actualPrices[i] = weightedPrice;
allocatedBandwidth[i] = users[i + 1].desiredBandwidth * bandwidthScalingFactor;
users[i + 1].receivedBandwidth = users[i + 1].desiredBandwidth * bandwidthScalingFactor;
}
}
}
}
}
// Update the real-time unit price according to user demand
// NOTICE: deltaBandwidth is a scaled value
function updatePrice(uint deltaBandwidth, bool isPositive) internal {
// uint prevPrice = bandwidthPrice;
oldPrice = bandwidthPrice;
if(totalDesiredBandwidth <= totalBandwidth) {
bandwidthPrice = minBandwidthPrice * bandwidthPriceScalingFactor;
} else {
if(isPositive) {
// New price = Total bid / Total bandwidth = Current price * (Total allocated bandwidth + New demand) / Total bandwidth
// (1) Total allocated bandwidth < Total bandwidth, i.e., totalDesiredBandwidth - deltaBandwidth < totalBandwidth
// (2) Total allocated bandwidth = Total bandwidth, i.e., totalDesiredBandwidth - deltaBandwidth >= totalBandwidth
if(totalDesiredBandwidth * bandwidthScalingFactor - deltaBandwidth < totalBandwidth * bandwidthScalingFactor) {
bandwidthPrice = bandwidthPrice * totalDesiredBandwidth / totalBandwidth;
} else {
bandwidthPrice = bandwidthPrice * (totalBandwidth * bandwidthScalingFactor + deltaBandwidth) / (totalBandwidth * bandwidthScalingFactor);
// bandwidthPrice = bandwidthPrice * totalDesiredBandwidth * bandwidthScalingFactor / (totalDesiredBandwidth * bandwidthScalingFactor - deltaBandwidth);
}
} else {
// The condition has guaranteed that: Total allocated bandwidth = Total bandwidth
// New price = Total bid / Total bandwidth = Current Price * (Total bandwidth - Reduced demand) / Total bandwidth
bandwidthPrice = bandwidthPrice * (totalBandwidth * bandwidthScalingFactor - deltaBandwidth) / (totalBandwidth * bandwidthScalingFactor);
// bandwidthPrice = bandwidthPrice * totalDesiredBandwidth * bandwidthScalingFactor / (totalDesiredBandwidth * bandwidthScalingFactor + deltaBandwidth);
}
}
burstPrice = minBurstPriceFactor * totalDesiredBurst * totalDesiredBurst;
}
// Update whether the user is dynamic according to current demand and price
function updateIsDynamic() internal {
// uint weight;
uint weightedPrice;
if(totalDesiredNonDynamic >= totalBandwidth) {
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
// In this case, the thresholdBid is compared with desiredBandwidth * bandwidthPrice to determine whether the user is dynamic
if(!isDynamic[i] && bandwidthPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor > users[i + 1].thresholdBid) {
isDynamic[i] = true;
totalDesiredNonDynamic -= users[i + 1].desiredBandwidth;
totalDesiredDynamic += users[i + 1].desiredBandwidth;
} else if (isDynamic[i] && bandwidthPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor <= users[i + 1].thresholdBid) {
isDynamic[i] = false;
totalDesiredDynamic -= users[i + 1].desiredBandwidth;
totalDesiredNonDynamic += users[i + 1].desiredBandwidth;
}
}
}
}
// Not using *else* here, since a second-round update may be needed after the first *if*
// weight > 1, so some non-dynamic users after the first round may be tagged as dynamic in this round
// weight is decreasing, so probably multiple rounds of update are needed
// ***UPDATE***: Limit the number of cycles to avoid gas over limit
uint numCycle;
while(true) {
numCycle++;
bool hasChanged;
if(totalDesiredNonDynamic < totalBandwidth) {
// weight = totalDesiredDynamic * bandwidthPriceScalingFactor / (totalBandwidth - totalDesiredNonDynamic);
// weightedPrice = weight * bandwidthPrice / bandwidthPriceScalingFactor;
weightedPrice = totalDesiredDynamic * bandwidthPrice / (totalBandwidth - totalDesiredNonDynamic);
// If the bid per unit time exceeds the thresholdBid, the user becomes dynamic
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
// In this case, the thresholdBid is compared with desiredBandwidth * weightedPrice to determine whether the user is dynamic
if(!isDynamic[i] && weightedPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor > users[i + 1].thresholdBid) {
isDynamic[i] = true;
totalDesiredNonDynamic -= users[i + 1].desiredBandwidth;
totalDesiredDynamic += users[i + 1].desiredBandwidth;
hasChanged = true;
} else if(isDynamic[i] && weightedPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor <= users[i + 1].thresholdBid) {
isDynamic[i] = false;
totalDesiredDynamic -= users[i + 1].desiredBandwidth;
totalDesiredNonDynamic += users[i + 1].desiredBandwidth;
hasChanged = true;
}
}
}
}
// Check numCycle to avoid infinite loop, e.g., when a user keeps changing between the dynamic and non-dynamic users
if(!hasChanged || numCycle == 10 || totalDesiredNonDynamic == 0) {
break;
}
}
}
// Allow the user to withdraw remaining balance upon connection termination
function withdrawBalance() internal {
uint amount = pendingWithdrawl[msg.sender];
pendingWithdrawl[msg.sender] = 0;
msg.sender.transfer(amount);
}
// Allow the owner to collect bids submitted by users
function collectBids() internal {
uint amount = pendingCollection;
pendingCollection = 0;
totalCollected += amount;
owner.transfer(amount);
}
// Clearing all existing user profiles and reset the parameters
function resetAll() internal onlyOwner {
for(uint i = 0; i < numUsers; i++) {
delete(pendingWithdrawl[users[i + 1].userAddress]);
delete(occupiedID[users[i + 1].userAddress]);
delete(users[i + 1]);
}
delete currentBalances;
delete allocatedBandwidth;
delete actualPrices;
delete isDynamic;
delete isActive;
delete numUsers;
delete totalCollected;
delete pendingCollection;
bandwidthPrice = minBandwidthPrice * bandwidthPriceScalingFactor;
delete totalDesiredBurst;
delete totalDesiredDynamic;
delete totalDesiredNonDynamic;
delete totalDesiredBandwidth;
delete burstVol;
}
}
|
Called by an ACTIVE user when he only selects to top up balance
|
function addBalance() public payable onlyNotOwner {
require(occupiedID[msg.sender] > 0, "You are not an existing user!");
currentBalances[occupiedID[msg.sender] - 1] += msg.value;
}
| 6,478,402
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "../tokens/QuantizedERC20.sol";
import "hardhat/console.sol";
contract QuantizedERC20Factory {
address private operator;
mapping(address => address) private _getQuantized;
mapping(address => address) private _getQuantizedSource;
address[] private _allQuantized;
/**
* @dev emitted when a new quantized token has been added to the system
*/
event QuantizedCreated(address indexed token, address indexed qtoken, uint256 newLen);
/**
* @dev Contract initializer.
*/
constructor() {
//
}
/**
* @dev Set the address allowed to mint and burn
*/
function setOperator(address _operator) external {
require(operator == address(0), "IMMUTABLE");
operator = _operator;
}
/**
* @dev is this a quantized token
*/
function getQuantizedSource(address _addr) public view returns (address quantizedSource) {
quantizedSource = _getQuantizedSource[_addr];
}
/**
* @dev get the quantized token for this
*/
function getQuantized(address _addr) public view returns (address quantizedToken) {
quantizedToken = _getQuantized[_addr];
}
/**
* @dev get the quantized token for this
*/
function allQuantized(uint256 idx) public view returns (address quantizedToken) {
quantizedToken = _allQuantized[idx];
}
/**
* @dev number of quantized addresses
*/
function allQuantizedLength() public view returns (uint256) {
return _allQuantized.length;
}
/**
* @dev deploy a new erc20 token using create2
*/
function createQuantized(
address owner,
address multiToken,
uint256 tokenHash
) public returns (address quantizedToken) {
require(msg.sender == operator, "UNAUTHORIZED"); // only the operator may create new ERC20 tokens
require(_getQuantizedSource[address(tokenHash)] == address(0), "TOKEN_EXISTS"); // single check is sufficient
require(_getQuantized[address(tokenHash)] == address(0), "TOKEN_EXISTS"); // single check is sufficient
// create the quantized erc20 token using create2, which lets us determine the
// quantized erc20 address of a token without interacting with the contract itself
bytes32 salt = keccak256(abi.encodePacked(owner, multiToken, tokenHash));
bytes memory bytecode = type(QuantizedERC20).creationCode;
assembly {
quantizedToken := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
// initialize the erc20 contract with the relevant addresses which it proxies
QuantizedERC20(quantizedToken).initialize(owner, multiToken, address(tokenHash));
console.log("createQuantized", tokenHash, quantizedToken);
// insert the erc20 contract address into lists - one that maps source to quantized,
_getQuantized[address(tokenHash)] = quantizedToken;
_getQuantizedSource[quantizedToken] = address(tokenHash);
_allQuantized.push(quantizedToken);
emit QuantizedCreated(address(tokenHash), quantizedToken, _allQuantized.length);
}
}
|
get the quantized token for this/
|
function allQuantized(uint256 idx) public view returns (address quantizedToken) {
quantizedToken = _allQuantized[idx];
}
| 12,548,273
|
./partial_match/1/0x41C1F38A4BbFA4f14Ef235ed8901b3a0e51a2933/sources/NABC.sol
|
Remove pair if added incorrectly or pair is now not valid/
|
function removePair(address pair) external onlyOwner {
pairs[pair] = false;
}
| 2,617,116
|
//Address: 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad
//Contract name: ValusCrowdsale
//Balance: 0 Ether
//Verification Date: 10/13/2017
//Transacion Count: 19
// CODE STARTS HERE
pragma solidity ^0.4.17;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract IValusToken {
function mintTokens(address _to, uint256 _amount);
function totalSupply() constant returns (uint256 totalSupply);
}
contract IERC20Token {
function totalSupply() constant returns (uint256 totalSupply);
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
}
|
Owner can claim reserved tokens on the end of crowsale /
|
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
| 6,431,246
|
pragma solidity ^0.6.6;
import "./ERC20.sol";
import "./Address.sol";
import "./BokkyPooBahsDateTimeLibrary.sol";
import "./Strings.sol";
/**
* @title ACOToken
* @dev The implementation of the ACO token.
* The token is ERC20 compliance.
*/
contract ACOToken is ERC20 {
using Address for address;
/**
* @dev Struct to store the accounts that generated tokens with a collateral deposit.
*/
struct TokenCollateralized {
/**
* @dev Current amount of tokens.
*/
uint256 amount;
/**
* @dev Index on the collateral owners array.
*/
uint256 index;
}
/**
* @dev Emitted when collateral is deposited on the contract.
* @param account Address of the collateral owner.
* @param amount Amount of collateral deposited.
*/
event CollateralDeposit(address indexed account, uint256 amount);
/**
* @dev Emitted when collateral is withdrawn from the contract.
* @param account Address of the collateral destination.
* @param amount Amount of collateral withdrawn.
* @param fee The fee amount charged on the withdrawal.
*/
event CollateralWithdraw(address indexed account, uint256 amount, uint256 fee);
/**
* @dev Emitted when the collateral is used on an assignment.
* @param from Address of the account of the collateral owner.
* @param to Address of the account that exercises tokens to get the collateral.
* @param paidAmount Amount paid to the collateral owner.
* @param tokenAmount Amount of tokens used to exercise.
*/
event Assigned(address indexed from, address indexed to, uint256 paidAmount, uint256 tokenAmount);
/**
* @dev The ERC20 token address for the underlying asset (0x0 for Ethereum).
*/
address public underlying;
/**
* @dev The ERC20 token address for the strike asset (0x0 for Ethereum).
*/
address public strikeAsset;
/**
* @dev Address of the fee destination charged on the exercise.
*/
address payable public feeDestination;
/**
* @dev True if the type is CALL, false for PUT.
*/
bool public isCall;
/**
* @dev The strike price for the token with the strike asset precision.
*/
uint256 public strikePrice;
/**
* @dev The UNIX time for the token expiration.
*/
uint256 public expiryTime;
/**
* @dev The total amount of collateral on the contract.
*/
uint256 public totalCollateral;
/**
* @dev The fee value. It is a percentage value (100000 is 100%).
*/
uint256 public acoFee;
/**
* @dev Symbol of the underlying asset.
*/
string public underlyingSymbol;
/**
* @dev Symbol of the strike asset.
*/
string public strikeAssetSymbol;
/**
* @dev Decimals for the underlying asset.
*/
uint8 public underlyingDecimals;
/**
* @dev Decimals for the strike asset.
*/
uint8 public strikeAssetDecimals;
/**
* @dev Underlying precision. (10 ^ underlyingDecimals)
*/
uint256 internal underlyingPrecision;
/**
* @dev Accounts that generated tokens with a collateral deposit.
*/
mapping(address => TokenCollateralized) internal tokenData;
/**
* @dev Array with all accounts with collateral deposited.
*/
address[] internal _collateralOwners;
/**
* @dev Internal data to control the reentrancy.
*/
bool internal _notEntered;
/**
* @dev Modifier to check if the token is not expired.
* It is executed only while the token is not expired.
*/
modifier notExpired() {
require(_notExpired(), "ACOToken::Expired");
_;
}
/**
* @dev Modifier to prevents a contract from calling itself during the function execution.
*/
modifier nonReentrant() {
require(_notEntered, "ACOToken::Reentry");
_notEntered = false;
_;
_notEntered = true;
}
/**
* @dev Function to initialize the contract.
* It should be called when creating the token.
* It must be called only once. The `assert` is to guarantee that behavior.
* @param _underlying Address of the underlying asset (0x0 for Ethereum).
* @param _strikeAsset Address of the strike asset (0x0 for Ethereum).
* @param _isCall True if the type is CALL, false for PUT.
* @param _strikePrice The strike price with the strike asset precision.
* @param _expiryTime The UNIX time for the token expiration.
* @param _acoFee Value of the ACO fee. It is a percentage value (100000 is 100%).
* @param _feeDestination Address of the fee destination charged on the exercise.
*/
function init(
address _underlying,
address _strikeAsset,
bool _isCall,
uint256 _strikePrice,
uint256 _expiryTime,
uint256 _acoFee,
address payable _feeDestination
) public {
require(underlying == address(0) && strikeAsset == address(0) && strikePrice == 0, "ACOToken::init: Already initialized");
require(_expiryTime > now, "ACOToken::init: Invalid expiry");
require(_strikePrice > 0, "ACOToken::init: Invalid strike price");
require(_underlying != _strikeAsset, "ACOToken::init: Same assets");
require(_acoFee <= 500, "ACOToken::init: Invalid ACO fee"); // Maximum is 0.5%
require(_isEther(_underlying) || _underlying.isContract(), "ACOToken::init: Invalid underlying");
require(_isEther(_strikeAsset) || _strikeAsset.isContract(), "ACOToken::init: Invalid strike asset");
underlying = _underlying;
strikeAsset = _strikeAsset;
isCall = _isCall;
strikePrice = _strikePrice;
expiryTime = _expiryTime;
acoFee = _acoFee;
feeDestination = _feeDestination;
underlyingDecimals = _getAssetDecimals(_underlying);
strikeAssetDecimals = _getAssetDecimals(_strikeAsset);
underlyingSymbol = _getAssetSymbol(_underlying);
strikeAssetSymbol = _getAssetSymbol(_strikeAsset);
underlyingPrecision = 10 ** uint256(underlyingDecimals);
_notEntered = true;
}
/**
* @dev Function to guarantee that the contract will not receive ether directly.
*/
receive() external payable {
revert();
}
/**
* @dev Function to get the token name.
*/
function name() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token symbol, that it is equal to the name.
*/
function symbol() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token decimals, that it is equal to the underlying asset decimals.
*/
function decimals() public view override returns(uint8) {
return underlyingDecimals;
}
/**
* @dev Function to get the current amount of collateral for an account.
* @param account Address of the account.
* @return The current amount of collateral.
*/
function currentCollateral(address account) public view returns(uint256) {
return getCollateralAmount(currentCollateralizedTokens(account));
}
/**
* @dev Function to get the current amount of unassignable collateral for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the unassignable collateral is equal to the account's collateral balance.
* @param account Address of the account.
* @return The respective amount of unassignable collateral.
*/
function unassignableCollateral(address account) public view returns(uint256) {
return getCollateralAmount(unassignableTokens(account));
}
/**
* @dev Function to get the current amount of assignable collateral for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the assignable collateral is zero.
* @param account Address of the account.
* @return The respective amount of assignable collateral.
*/
function assignableCollateral(address account) public view returns(uint256) {
return getCollateralAmount(assignableTokens(account));
}
/**
* @dev Function to get the current amount of collateralized tokens for an account.
* @param account Address of the account.
* @return The current amount of collateralized tokens.
*/
function currentCollateralizedTokens(address account) public view returns(uint256) {
return tokenData[account].amount;
}
/**
* @dev Function to get the current amount of unassignable tokens for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the unassignable tokens is equal to the account's collateralized tokens.
* @param account Address of the account.
* @return The respective amount of unassignable tokens.
*/
function unassignableTokens(address account) public view returns(uint256) {
if (balanceOf(account) > tokenData[account].amount) {
return tokenData[account].amount;
} else {
return balanceOf(account);
}
}
/**
* @dev Function to get the current amount of assignable tokens for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the assignable tokens is zero.
* @param account Address of the account.
* @return The respective amount of assignable tokens.
*/
function assignableTokens(address account) public view returns(uint256) {
return _getAssignableAmount(account);
}
/**
* @dev Function to get the equivalent collateral amount for a token amount.
* @param tokenAmount Amount of tokens.
* @return The respective amount of collateral.
*/
function getCollateralAmount(uint256 tokenAmount) public view returns(uint256) {
if (isCall) {
return tokenAmount;
} else if (tokenAmount > 0) {
return _getTokenStrikePriceRelation(tokenAmount);
} else {
return 0;
}
}
/**
* @dev Function to get the equivalent token amount for a collateral amount.
* @param collateralAmount Amount of collateral.
* @return The respective amount of tokens.
*/
function getTokenAmount(uint256 collateralAmount) public view returns(uint256) {
if (isCall) {
return collateralAmount;
} else if (collateralAmount > 0) {
return collateralAmount.mul(underlyingPrecision).div(strikePrice);
} else {
return 0;
}
}
/**
* @dev Function to get the data for exercise of an amount of token.
* @param tokenAmount Amount of tokens.
* @return The asset and the respective amount that should be sent to get the collateral.
*/
function getExerciseData(uint256 tokenAmount) public view returns(address, uint256) {
if (isCall) {
return (strikeAsset, _getTokenStrikePriceRelation(tokenAmount));
} else {
return (underlying, tokenAmount);
}
}
/**
* @dev Function to get the collateral asset.
* @return The address of the collateral asset.
*/
function collateral() public view returns(address) {
if (isCall) {
return underlying;
} else {
return strikeAsset;
}
}
/**
* @dev Function to mint tokens with Ether deposited as collateral.
* NOTE: The function only works when the token is NOT expired yet.
*/
function mintPayable() external payable {
require(_isEther(collateral()), "ACOToken::mintPayable: Invalid call");
_mintToken(msg.sender, msg.value);
}
/**
* @dev Function to mint tokens with Ether deposited as collateral to an informed account.
* However, the minted tokens are assigned to the transaction sender.
* NOTE: The function only works when the token is NOT expired yet.
* @param account Address of the account that will be the collateral owner.
*/
function mintToPayable(address account) external payable {
require(_isEther(collateral()), "ACOToken::mintToPayable: Invalid call");
_mintToken(account, msg.value);
}
/**
* @dev Function to mint tokens with ERC20 deposited as collateral.
* NOTE: The function only works when the token is NOT expired yet.
* @param collateralAmount Amount of collateral deposited.
*/
function mint(uint256 collateralAmount) external {
address _collateral = collateral();
require(!_isEther(_collateral), "ACOToken::mint: Invalid call");
require(IERC20(_collateral).transferFrom(msg.sender, address(this), collateralAmount), "ACOToken::mint: Invalid transfer");
_mintToken(msg.sender, collateralAmount);
}
/**
* @dev Function to mint tokens with ERC20 deposited as collateral to an informed account.
* However, the minted tokens are assigned to the transaction sender.
* NOTE: The function only works when the token is NOT expired yet.
* @param account Address of the account that will be the collateral owner.
* @param collateralAmount Amount of collateral deposited.
*/
function mintTo(address account, uint256 collateralAmount) external {
address _collateral = collateral();
require(!_isEther(_collateral), "ACOToken::mintTo: Invalid call");
require(IERC20(_collateral).transferFrom(msg.sender, address(this), collateralAmount), "ACOToken::mintTo: Invalid transfer");
_mintToken(account, collateralAmount);
}
/**
* @dev Function to burn tokens and get the collateral, not assigned, back.
* NOTE: The function only works when the token is NOT expired yet.
* @param tokenAmount Amount of tokens to be burned.
*/
function burn(uint256 tokenAmount) external {
_burn(msg.sender, tokenAmount);
}
/**
* @dev Function to burn tokens from a specific account and send the collateral to its address.
* The token allowance must be respected.
* The collateral is returned to the account address, not to the transaction sender.
* NOTE: The function only works when the token is NOT expired yet.
* @param account Address of the account.
* @param tokenAmount Amount of tokens to be burned.
*/
function burnFrom(address account, uint256 tokenAmount) external {
_burn(account, tokenAmount);
}
/**
* @dev Function to get the collateral, not assigned, back.
* NOTE: The function only works when the token IS expired.
*/
function redeem() external {
_redeem(msg.sender);
}
/**
* @dev Function to get the collateral from a specific account sent back to its address .
* The token allowance must be respected.
* The collateral is returned to the account address, not to the transaction sender.
* NOTE: The function only works when the token IS expired.
* @param account Address of the account.
*/
function redeemFrom(address account) external {
_redeem(account);
}
/**
* @dev Function to exercise the tokens, paying to get the equivalent collateral.
* The paid amount is sent to the collateral owners that were assigned.
* NOTE: The function only works when the token is NOT expired.
* @param tokenAmount Amount of tokens.
*/
function exercise(uint256 tokenAmount) external payable {
_exercise(msg.sender, tokenAmount);
}
/**
* @dev Function to exercise the tokens from an account, paying to get the equivalent collateral.
* The token allowance must be respected.
* The paid amount is sent to the collateral owners that were assigned.
* The collateral is transferred to the account address, not to the transaction sender.
* NOTE: The function only works when the token is NOT expired.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
*/
function exerciseFrom(address account, uint256 tokenAmount) external payable {
_exercise(account, tokenAmount);
}
/**
* @dev Function to exercise the tokens, paying to get the equivalent collateral.
* The paid amount is sent to the collateral owners (on accounts list) that were assigned.
* NOTE: The function only works when the token is NOT expired.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get collateral from.
*/
function exerciseAccounts(uint256 tokenAmount, address[] calldata accounts) external payable {
_exerciseFromAccounts(msg.sender, tokenAmount, accounts);
}
/**
* @dev Function to exercise the tokens from a specific account, paying to get the equivalent collateral sent to its address.
* The token allowance must be respected.
* The paid amount is sent to the collateral owners (on accounts list) that were assigned.
* The collateral is transferred to the account address, not to the transaction sender.
* NOTE: The function only works when the token is NOT expired.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get the deposited collateral.
*/
function exerciseAccountsFrom(address account, uint256 tokenAmount, address[] calldata accounts) external payable {
_exerciseFromAccounts(account, tokenAmount, accounts);
}
/**
* @dev Function to burn the tokens after expiration.
* It is an optional function to `clear` the account wallet from an expired and not functional token.
* NOTE: The function only works when the token IS expired.
*/
function clear() external {
_clear(msg.sender);
}
/**
* @dev Function to burn the tokens from an account after expiration.
* It is an optional function to `clear` the account wallet from an expired and not functional token.
* The token allowance must be respected.
* NOTE: The function only works when the token IS expired.
* @param account Address of the account.
*/
function clearFrom(address account) external {
_clear(account);
}
/**
* @dev Internal function to burn the tokens from an account after expiration.
* @param account Address of the account.
*/
function _clear(address account) internal {
require(!_notExpired(), "ACOToken::_clear: Token not expired yet");
require(!_accountHasCollateral(account), "ACOToken::_clear: Must call the redeem method");
_callBurn(account, balanceOf(account));
}
/**
* @dev Internal function to redeem respective collateral from an account.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
*/
function _redeemCollateral(address account, uint256 tokenAmount) internal {
require(_accountHasCollateral(account), "ACOToken::_redeemCollateral: No collateral available");
require(tokenAmount > 0, "ACOToken::_redeemCollateral: Invalid token amount");
TokenCollateralized storage data = tokenData[account];
data.amount = data.amount.sub(tokenAmount);
_removeCollateralDataIfNecessary(account);
_transferCollateral(account, getCollateralAmount(tokenAmount), false);
}
/**
* @dev Internal function to mint tokens.
* The tokens are minted for the transaction sender.
* @param account Address of the account.
* @param collateralAmount Amount of collateral deposited.
*/
function _mintToken(address account, uint256 collateralAmount) nonReentrant notExpired internal {
require(collateralAmount > 0, "ACOToken::_mintToken: Invalid collateral amount");
if (!_accountHasCollateral(account)) {
tokenData[account].index = _collateralOwners.length;
_collateralOwners.push(account);
}
uint256 tokenAmount = getTokenAmount(collateralAmount);
tokenData[account].amount = tokenData[account].amount.add(tokenAmount);
totalCollateral = totalCollateral.add(collateralAmount);
emit CollateralDeposit(account, collateralAmount);
super._mintAction(msg.sender, tokenAmount);
}
/**
* @dev Internal function to transfer tokens.
* The token transfer only works when the token is NOT expired.
* @param sender Source of the tokens.
* @param recipient Destination address for the tokens.
* @param amount Amount of tokens.
*/
function _transfer(address sender, address recipient, uint256 amount) notExpired internal override {
super._transferAction(sender, recipient, amount);
}
/**
* @dev Internal function to set the token permission from an account to another address.
* The token approval only works when the token is NOT expired.
* @param owner Address of the token owner.
* @param spender Address of the spender authorized.
* @param amount Amount of tokens authorized.
*/
function _approve(address owner, address spender, uint256 amount) notExpired internal override {
super._approveAction(owner, spender, amount);
}
/**
* @dev Internal function to transfer collateral.
* When there is a fee, the calculated fee is also transferred to the destination fee address.
* @param recipient Destination address for the collateral.
* @param collateralAmount Amount of collateral.
* @param hasFee Whether a fee should be applied to the collateral amount.
*/
function _transferCollateral(address recipient, uint256 collateralAmount, bool hasFee) internal {
require(recipient != address(0), "ACOToken::_transferCollateral: Invalid recipient");
totalCollateral = totalCollateral.sub(collateralAmount);
uint256 fee = 0;
if (hasFee) {
fee = collateralAmount.mul(acoFee).div(100000);
collateralAmount = collateralAmount.sub(fee);
}
address _collateral = collateral();
if (_isEther(_collateral)) {
payable(recipient).transfer(collateralAmount);
if (fee > 0) {
feeDestination.transfer(fee);
}
} else {
require(IERC20(_collateral).transfer(recipient, collateralAmount), "ACOToken::_transferCollateral: Invalid transfer");
if (fee > 0) {
require(IERC20(_collateral).transfer(feeDestination, fee), "ACOToken::_transferCollateral: Invalid transfer fee");
}
}
emit CollateralWithdraw(recipient, collateralAmount, fee);
}
/**
* @dev Internal function to exercise the tokens from an account.
* @param account Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
*/
function _exercise(address account, uint256 tokenAmount) nonReentrant internal {
_validateAndBurn(account, tokenAmount);
_exerciseOwners(account, tokenAmount);
_transferCollateral(account, getCollateralAmount(tokenAmount), true);
}
/**
* @dev Internal function to exercise the tokens from an account.
* @param account Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get the collateral from.
*/
function _exerciseFromAccounts(address account, uint256 tokenAmount, address[] memory accounts) nonReentrant internal {
_validateAndBurn(account, tokenAmount);
_exerciseAccounts(account, tokenAmount, accounts);
_transferCollateral(account, getCollateralAmount(tokenAmount), true);
}
/**
* @dev Internal function to exercise the assignable tokens from the stored list of collateral owners.
* @param exerciseAccount Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
*/
function _exerciseOwners(address exerciseAccount, uint256 tokenAmount) internal {
uint256 start = _collateralOwners.length - 1;
for (uint256 i = start; i >= 0; --i) {
if (tokenAmount == 0) {
break;
}
tokenAmount = _exerciseAccount(_collateralOwners[i], tokenAmount, exerciseAccount);
}
require(tokenAmount == 0, "ACOToken::_exerciseOwners: Invalid remaining amount");
}
/**
* @dev Internal function to exercise the assignable tokens from an accounts list.
* @param exerciseAccount Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get the collateral from.
*/
function _exerciseAccounts(address exerciseAccount, uint256 tokenAmount, address[] memory accounts) internal {
for (uint256 i = 0; i < accounts.length; ++i) {
if (tokenAmount == 0) {
break;
}
tokenAmount = _exerciseAccount(accounts[i], tokenAmount, exerciseAccount);
}
require(tokenAmount == 0, "ACOToken::_exerciseAccounts: Invalid remaining amount");
}
/**
* @dev Internal function to exercise the assignable tokens from an account and transfer to its address the respective payment.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
* @param exerciseAccount Address of the account that is exercising.
* @return Remaining amount of tokens.
*/
function _exerciseAccount(address account, uint256 tokenAmount, address exerciseAccount) internal returns(uint256) {
uint256 available = _getAssignableAmount(account);
if (available > 0) {
TokenCollateralized storage data = tokenData[account];
uint256 valueToTransfer;
if (available < tokenAmount) {
valueToTransfer = available;
tokenAmount = tokenAmount.sub(available);
} else {
valueToTransfer = tokenAmount;
tokenAmount = 0;
}
(address exerciseAsset, uint256 amount) = getExerciseData(valueToTransfer);
data.amount = data.amount.sub(valueToTransfer);
_removeCollateralDataIfNecessary(account);
if (_isEther(exerciseAsset)) {
payable(account).transfer(amount);
} else {
require(IERC20(exerciseAsset).transfer(account, amount), "ACOToken::_exerciseAccount: Invalid transfer");
}
emit Assigned(account, exerciseAccount, amount, valueToTransfer);
}
return tokenAmount;
}
/**
* @dev Internal function to validate the exercise operation and burn the respective tokens.
* @param account Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
*/
function _validateAndBurn(address account, uint256 tokenAmount) notExpired internal {
require(tokenAmount > 0, "ACOToken::_validateAndBurn: Invalid token amount");
// Whether an account has deposited collateral it only can exercise the extra amount of unassignable tokens.
if (_accountHasCollateral(account)) {
require(balanceOf(account) > tokenData[account].amount, "ACOToken::_validateAndBurn: Tokens compromised");
require(tokenAmount <= balanceOf(account).sub(tokenData[account].amount), "ACOToken::_validateAndBurn: Token amount not available");
}
_callBurn(account, tokenAmount);
(address exerciseAsset, uint256 expectedAmount) = getExerciseData(tokenAmount);
if (_isEther(exerciseAsset)) {
require(msg.value == expectedAmount, "ACOToken::_validateAndBurn: Invalid ether amount");
} else {
require(msg.value == 0, "ACOToken::_validateAndBurn: No ether expected");
require(IERC20(exerciseAsset).transferFrom(msg.sender, address(this), expectedAmount), "ACOToken::_validateAndBurn: Fail to receive asset");
}
}
/**
* @dev Internal function to calculate the token strike price relation.
* @param tokenAmount Amount of tokens.
* @return Calculated value with strike asset precision.
*/
function _getTokenStrikePriceRelation(uint256 tokenAmount) internal view returns(uint256) {
return tokenAmount.mul(strikePrice).div(underlyingPrecision);
}
/**
* @dev Internal function to get the collateral sent back from an account.
* Function to be called when the token IS expired.
* @param account Address of the account.
*/
function _redeem(address account) nonReentrant internal {
require(!_notExpired(), "ACOToken::_redeem: Token not expired yet");
_redeemCollateral(account, tokenData[account].amount);
super._burnAction(account, balanceOf(account));
}
/**
* @dev Internal function to burn tokens from an account and get the collateral, not assigned, back.
* @param account Address of the account.
* @param tokenAmount Amount of tokens to be burned.
*/
function _burn(address account, uint256 tokenAmount) nonReentrant notExpired internal {
_redeemCollateral(account, tokenAmount);
_callBurn(account, tokenAmount);
}
/**
* @dev Internal function to burn tokens.
* @param account Address of the account.
* @param tokenAmount Amount of tokens to be burned.
*/
function _callBurn(address account, uint256 tokenAmount) internal {
if (account == msg.sender) {
super._burnAction(account, tokenAmount);
} else {
super._burnFrom(account, tokenAmount);
}
}
/**
* @dev Internal function to get the amount of assignable token from an account.
* @param account Address of the account.
* @return The assignable amount of tokens.
*/
function _getAssignableAmount(address account) internal view returns(uint256) {
if (tokenData[account].amount > balanceOf(account)) {
return tokenData[account].amount.sub(balanceOf(account));
} else {
return 0;
}
}
/**
* @dev Internal function to remove the token data with collateral if its total amount was assigned.
* @param account Address of account.
*/
function _removeCollateralDataIfNecessary(address account) internal {
TokenCollateralized storage data = tokenData[account];
if (!_hasCollateral(data)) {
uint256 lastIndex = _collateralOwners.length - 1;
if (lastIndex != data.index) {
address last = _collateralOwners[lastIndex];
tokenData[last].index = data.index;
_collateralOwners[data.index] = last;
}
_collateralOwners.pop();
delete tokenData[account];
}
}
/**
* @dev Internal function to get if the token is not expired.
* @return Whether the token is NOT expired.
*/
function _notExpired() internal view returns(bool) {
return now <= expiryTime;
}
/**
* @dev Internal function to get if an account has collateral deposited.
* @param account Address of the account.
* @return Whether the account has collateral deposited.
*/
function _accountHasCollateral(address account) internal view returns(bool) {
return _hasCollateral(tokenData[account]);
}
/**
* @dev Internal function to get if an account has collateral deposited.
* @param data Token data from an account.
* @return Whether the account has collateral deposited.
*/
function _hasCollateral(TokenCollateralized storage data) internal view returns(bool) {
return data.amount > 0;
}
/**
* @dev Internal function to get if the address is for Ethereum (0x0).
* @param _address Address to be checked.
* @return Whether the address is for Ethereum.
*/
function _isEther(address _address) internal pure returns(bool) {
return _address == address(0);
}
/**
* @dev Internal function to get the token name.
* The token name is assembled with the token data:
* ACO UNDERLYING_SYMBOL-EXPIRYTIME-STRIKE_PRICE_STRIKE_ASSET_SYMBOL-TYPE
* @return The token name.
*/
function _name() internal view returns(string memory) {
return string(abi.encodePacked(
"ACO ",
underlyingSymbol,
"-",
_getFormattedStrikePrice(),
strikeAssetSymbol,
"-",
_getType(),
"-",
_getFormattedExpiryTime()
));
}
/**
* @dev Internal function to get the token type description.
* @return The token type description.
*/
function _getType() internal view returns(string memory) {
if (isCall) {
return "C";
} else {
return "P";
}
}
/**
* @dev Internal function to get the expiry time formatted.
* @return The expiry time formatted.
*/
function _getFormattedExpiryTime() internal view returns(string memory) {
(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute,) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(expiryTime);
return string(abi.encodePacked(
_getNumberWithTwoCaracters(day),
_getMonthFormatted(month),
_getYearFormatted(year),
"-",
_getNumberWithTwoCaracters(hour),
_getNumberWithTwoCaracters(minute),
"UTC"
));
}
/**
* @dev Internal function to get the year formatted with 2 characters.
* @return The year formatted.
*/
function _getYearFormatted(uint256 year) internal pure returns(string memory) {
bytes memory yearBytes = bytes(Strings.toString(year));
bytes memory result = new bytes(2);
uint256 startIndex = yearBytes.length - 2;
for (uint256 i = startIndex; i < yearBytes.length; i++) {
result[i - startIndex] = yearBytes[i];
}
return string(result);
}
/**
* @dev Internal function to get the month abbreviation.
* @return The month abbreviation.
*/
function _getMonthFormatted(uint256 month) internal pure returns(string memory) {
if (month == 1) {
return "JAN";
} else if (month == 2) {
return "FEB";
} else if (month == 3) {
return "MAR";
} else if (month == 4) {
return "APR";
} else if (month == 5) {
return "MAY";
} else if (month == 6) {
return "JUN";
} else if (month == 7) {
return "JUL";
} else if (month == 8) {
return "AUG";
} else if (month == 9) {
return "SEP";
} else if (month == 10) {
return "OCT";
} else if (month == 11) {
return "NOV";
} else if (month == 12) {
return "DEC";
} else {
return "INVALID";
}
}
/**
* @dev Internal function to get the number with 2 characters.
* @return The 2 characters for the number.
*/
function _getNumberWithTwoCaracters(uint256 number) internal pure returns(string memory) {
string memory _string = Strings.toString(number);
if (number < 10) {
return string(abi.encodePacked("0", _string));
} else {
return _string;
}
}
/**
* @dev Internal function to get the strike price formatted.
* @return The strike price formatted.
*/
function _getFormattedStrikePrice() internal view returns(string memory) {
uint256 digits;
uint256 count;
int256 representativeAt = -1;
uint256 addPointAt = 0;
uint256 temp = strikePrice;
uint256 number = strikePrice;
while (temp != 0) {
if (representativeAt == -1 && (temp % 10 != 0 || count == uint256(strikeAssetDecimals))) {
representativeAt = int256(digits);
number = temp;
}
if (representativeAt >= 0) {
if (count == uint256(strikeAssetDecimals)) {
addPointAt = digits;
}
digits++;
}
temp /= 10;
count++;
}
if (count <= uint256(strikeAssetDecimals)) {
digits = digits + 2 + uint256(strikeAssetDecimals) - count;
addPointAt = digits - 2;
} else if (addPointAt > 0) {
digits++;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = number;
for (uint256 i = 0; i < digits; ++i) {
if (i > 0 && i == addPointAt) {
buffer[index--] = byte(".");
} else if (number == 0) {
buffer[index--] = byte("0");
} else {
if (representativeAt <= int256(i)) {
buffer[index--] = byte(uint8(48 + number % 10));
}
number /= 10;
}
}
return string(buffer);
}
/**
* @dev Internal function to the asset decimals.
* @param asset Address of the asset.
* @return The asset decimals.
*/
function _getAssetDecimals(address asset) internal view returns(uint8) {
if (_isEther(asset)) {
return uint8(18);
} else {
(bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("decimals()"));
require(success, "ACOToken::_getAssetDecimals: Invalid asset decimals");
return abi.decode(returndata, (uint8));
}
}
/**
* @dev Internal function to the asset symbol.
* @param asset Address of the asset.
* @return The asset symbol.
*/
function _getAssetSymbol(address asset) internal view returns(string memory) {
if (_isEther(asset)) {
return "ETH";
} else {
(bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("symbol()"));
require(success, "ACOToken::_getAssetSymbol: Invalid asset symbol");
return abi.decode(returndata, (string));
}
}
}
|
Function to get the current amount of collateralized tokens for an account. account Address of the account. return The current amount of collateralized tokens./
|
function currentCollateralizedTokens(address account) public view returns(uint256) {
return tokenData[account].amount;
}
| 568,815
|
./partial_match/1/0x3A60F610268eAACb5572ADe1622A2197795dFF3C/sources/MultiPot.sol
|
sum up original payout amount (self.balance changes during payouts)
|
function payoutWinners() external returns (uint pendingPayouts) {
require(current_state == State.paying_out, "Not possible in current state.");
Pot storage winningPot = pots[uint8(lastWinningColor) + numPots * round];
uint totalPayoutAmount = 0;
for(uint8 j = 0; j < numPots; j++) {
totalPayoutAmount += pots[j + numPots * round].amount;
}
uint winningPotAmount = winningPot.amount;
for(uint i = winningPot.uniqueGamblers.length; i >= 1; i--) {
address payable gambler = winningPot.uniqueGamblers[i - 1];
winningPot.uniqueGamblers.pop();
uint stake = winningPot.stakes[gambler];
but do the multiplication before the division: */
uint profit = totalPayoutAmount * stake / winningPotAmount;
emit PayoutSuccessful(gambler, profit, round);
emit PayoutFailed(gambler, profit, round);
}
if(!(gasleft() > 26000)) {
pendingPayouts = i - 1;
break;
}
}
assert(current_state == State.paying_out);
emit WinnersPaid(round, totalPayoutAmount, lastWinningColor, winningPotAmount);
| 4,241,909
|
/*
This is a simple showcase smart contract example for trade finance / supply chain interactions.
It could be improved in several ways:
- add timeouts for state reversal (e.g. object is released by one party but not accepted by next)
= add escrow payments also for carriers, otherwise they can block forever
- add delivery dates for carriers, if not met their escrow balance will be punished
- add insurance interface for, e.g. transport delay or damage insurance
*/
contract TradeHandler {
address public seller;
address public carrier1;
address public carrier2;
address public buyer;
uint public purchasePrice;
uint public carrier1Fee;
uint public carrier2Fee;
enum WaitingFor {
BuyerEscrowPayment,
SellerEscrowPayment,
SellerRelease,
Carrier1Accept,
Carrier1Release,
Carrier2Accept,
Carrier2Release,
BuyerAccept,
Completed
}
WaitingFor state;
// constructor sets all actors and fees
function TradeHandler(
address _seller,
address _carrier1,
address _carrier2,
uint _carrier1Fee,
uint _carrier2Fee,
uint _purchasePrice)
{
buyer = msg.sender;
seller = _seller;
carrier1 = _carrier1;
carrier2 = _carrier2;
carrier1Fee = _carrier1Fee;
carrier2Fee = _carrier2Fee;
purchasePrice = _purchasePrice;
}
function reset(
address _seller,
address _carrier1,
address _carrier2,
uint _carrier1Fee,
uint _carrier2Fee,
uint _purchasePrice)
{
// only allow recylcing of contract if previous trade is completed
if (state != WaitingFor.Completed)
throw;
buyer = msg.sender;
seller = _seller;
carrier1 = _carrier1;
carrier2 = _carrier2;
carrier1Fee = _carrier1Fee;
carrier2Fee = _carrier2Fee;
purchasePrice = _purchasePrice;
}
function () payable {
// todo: one could check for timeouts and revert transitions if required
// once trade is completed, do not allow further interaction
if (state == WaitingFor.Completed)
throw;
// each actor is only responsible for their respective state transfer, reject all others
if (msg.sender == buyer && state != WaitingFor.BuyerEscrowPayment && state != WaitingFor.BuyerAccept)
throw;
if (msg.sender == seller && state != WaitingFor.SellerEscrowPayment && state != WaitingFor.SellerRelease)
throw;
if (msg.sender == carrier1 && state != WaitingFor.Carrier1Accept && state != WaitingFor.Carrier1Release)
throw;
if (msg.sender == carrier2 && state != WaitingFor.Carrier2Accept && state != WaitingFor.Carrier2Release)
throw;
// make sure that the right amounts are being paid into this escrow contract by buyer and seller
if (state == WaitingFor.BuyerEscrowPayment && msg.value != 2 * purchasePrice + carrier1Fee + carrier2Fee)
throw;
if (state == WaitingFor.SellerEscrowPayment && msg.value != purchasePrice)
throw;
// perform state transitions
if (state == WaitingFor.BuyerEscrowPayment)
state = WaitingFor.SellerEscrowPayment;
else if (state == WaitingFor.SellerEscrowPayment)
state = WaitingFor.SellerRelease;
else if (state == WaitingFor.SellerRelease)
state = WaitingFor.Carrier1Accept;
else if (state == WaitingFor.Carrier1Accept)
state = WaitingFor.Carrier1Release;
else if (state == WaitingFor.Carrier1Release)
state = WaitingFor.Carrier2Accept;
else if (state == WaitingFor.Carrier2Accept) {
state = WaitingFor.Carrier2Release;
carrier1.send(carrier1Fee);
} else if (state == WaitingFor.Carrier2Release)
state = WaitingFor.BuyerAccept;
else if (state == WaitingFor.BuyerAccept) {
state = WaitingFor.Completed;
carrier2.send(carrier2Fee);
seller.send(2 * purchasePrice);
buyer.send(purchasePrice);
}
}
}
|
constructor sets all actors and fees
|
function TradeHandler(
address _seller,
address _carrier1,
address _carrier2,
uint _carrier1Fee,
uint _carrier2Fee,
uint _purchasePrice)
{
buyer = msg.sender;
seller = _seller;
carrier1 = _carrier1;
carrier2 = _carrier2;
carrier1Fee = _carrier1Fee;
carrier2Fee = _carrier2Fee;
purchasePrice = _purchasePrice;
}
| 5,343,171
|
pragma solidity ^0.5.8;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "solidity-bytes-utils/contracts/BytesLib.sol";
import "./UsingLockedGold.sol";
import "./interfaces/IValidators.sol";
import "../common/Initializable.sol";
import "../common/FixidityLib.sol";
import "../common/linkedlists/AddressLinkedList.sol";
import "../common/linkedlists/AddressSortedLinkedList.sol";
/**
* @title A contract for registering and electing Validator Groups and Validators.
*/
contract Validators is IValidators, Ownable, ReentrancyGuard, Initializable, UsingLockedGold {
using FixidityLib for FixidityLib.Fraction;
using AddressLinkedList for LinkedList.List;
using AddressSortedLinkedList for SortedLinkedList.List;
using SafeMath for uint256;
using BytesLib for bytes;
// TODO(asa): These strings should be modifiable
struct ValidatorGroup {
string identifier;
string name;
string url;
LinkedList.List members;
}
// TODO(asa): These strings should be modifiable
struct Validator {
string identifier;
string name;
string url;
bytes publicKeysData;
address affiliation;
}
struct LockedGoldCommitment {
uint256 noticePeriod;
uint256 value;
}
mapping(address => ValidatorGroup) private groups;
mapping(address => Validator) private validators;
// TODO(asa): Implement abstaining
mapping(address => address) public voters;
address[] private _groups;
address[] private _validators;
SortedLinkedList.List private votes;
// TODO(asa): Support different requirements for groups vs. validators.
LockedGoldCommitment private registrationRequirement;
uint256 public minElectableValidators;
uint256 public maxElectableValidators;
address constant PROOF_OF_POSSESSION = address(0xff - 4);
event MinElectableValidatorsSet(
uint256 minElectableValidators
);
event MaxElectableValidatorsSet(
uint256 maxElectableValidators
);
event RegistrationRequirementSet(
uint256 value,
uint256 noticePeriod
);
event ValidatorRegistered(
address indexed validator,
string identifier,
string name,
string url,
bytes publicKeysData
);
event ValidatorDeregistered(
address indexed validator
);
event ValidatorAffiliated(
address indexed validator,
address indexed group
);
event ValidatorDeaffiliated(
address indexed validator,
address indexed group
);
event ValidatorGroupRegistered(
address indexed group,
string identifier,
string name,
string url
);
event ValidatorGroupDeregistered(
address indexed group
);
event ValidatorGroupMemberAdded(
address indexed group,
address indexed validator
);
event ValidatorGroupMemberRemoved(
address indexed group,
address indexed validator
);
event ValidatorGroupMemberReordered(
address indexed group,
address indexed validator
);
event ValidatorGroupEmptied(
address indexed group
);
event ValidatorGroupVoteCast(
address indexed account,
address indexed group,
uint256 weight
);
event ValidatorGroupVoteRevoked(
address indexed account,
address indexed group,
uint256 weight
);
/**
* @notice Initializes critical variables.
* @param registryAddress The address of the registry contract.
* @param _minElectableValidators The minimum number of validators that can be elected.
* @param _maxElectableValidators The maximum number of validators that can be elected.
* @param requirementValue The minimum Locked Gold commitment value to register a group or
validator.
* @param requirementNoticePeriod The minimum Locked Gold commitment notice period to register
* a group or validator.
* @dev Should be called only once.
*/
function initialize(
address registryAddress,
uint256 _minElectableValidators,
uint256 _maxElectableValidators,
uint256 requirementValue,
uint256 requirementNoticePeriod
)
external
initializer
{
require(_minElectableValidators > 0 && _maxElectableValidators >= _minElectableValidators);
_transferOwnership(msg.sender);
setRegistry(registryAddress);
minElectableValidators = _minElectableValidators;
maxElectableValidators = _maxElectableValidators;
registrationRequirement.value = requirementValue;
registrationRequirement.noticePeriod = requirementNoticePeriod;
}
/**
* @notice Updates the minimum number of validators that can be elected.
* @param _minElectableValidators The minimum number of validators that can be elected.
* @return True upon success.
*/
function setMinElectableValidators(
uint256 _minElectableValidators
)
external
onlyOwner
returns (bool)
{
require(
_minElectableValidators > 0 &&
_minElectableValidators != minElectableValidators &&
_minElectableValidators <= maxElectableValidators
);
minElectableValidators = _minElectableValidators;
emit MinElectableValidatorsSet(_minElectableValidators);
return true;
}
/**
* @notice Updates the maximum number of validators that can be elected.
* @param _maxElectableValidators The maximum number of validators that can be elected.
* @return True upon success.
*/
function setMaxElectableValidators(
uint256 _maxElectableValidators
)
external
onlyOwner
returns (bool)
{
require(
_maxElectableValidators != maxElectableValidators &&
_maxElectableValidators >= minElectableValidators
);
maxElectableValidators = _maxElectableValidators;
emit MaxElectableValidatorsSet(_maxElectableValidators);
return true;
}
/**
* @notice Updates the minimum bonding requirements to register a validator group or validator.
* @param value The minimum Locked Gold commitment value to register a group or validator.
* @param noticePeriod The minimum Locked Gold commitment notice period to register a group or
* validator.
* @return True upon success.
* @dev The new requirement is only enforced for future validator or group registrations.
*/
function setRegistrationRequirement(
uint256 value,
uint256 noticePeriod
)
external
onlyOwner
returns (bool)
{
require(
value != registrationRequirement.value ||
noticePeriod != registrationRequirement.noticePeriod
);
registrationRequirement.value = value;
registrationRequirement.noticePeriod = noticePeriod;
emit RegistrationRequirementSet(value, noticePeriod);
return true;
}
/**
* @notice Registers a validator unaffiliated with any validator group.
* @param identifier An identifier for this validator.
* @param name A name for the validator.
* @param url A URL for the validator.
* @param noticePeriod The notice period of the Locked Gold commitment that meets the
* requirements for validator registration.
* @param publicKeysData Comprised of three tightly-packed elements:
* - publicKey - The public key that the validator is using for consensus, should match
* msg.sender. 64 bytes.
* - blsPublicKey - The BLS public key that the validator is using for consensus, should pass
* proof of possession. 48 bytes.
* - blsPoP - The BLS public key proof of possession. 96 bytes.
* @return True upon success.
* @dev Fails if the account is already a validator or validator group.
* @dev Fails if the account does not have sufficient weight.
*/
function registerValidator(
string calldata identifier,
string calldata name,
string calldata url,
bytes calldata publicKeysData,
uint256 noticePeriod
)
external
nonReentrant
returns (bool)
{
require(
bytes(identifier).length > 0 &&
bytes(name).length > 0 &&
bytes(url).length > 0 &&
// secp256k1 public key + BLS public key + BLS proof of possession
publicKeysData.length == (64 + 48 + 96)
);
bytes memory proofOfPossessionBytes = publicKeysData.slice(64, 48 + 96);
require(checkProofOfPossession(proofOfPossessionBytes));
address account = getAccountFromValidator(msg.sender);
require(!isValidator(account) && !isValidatorGroup(account));
require(meetsRegistrationRequirements(account, noticePeriod));
Validator memory validator = Validator(identifier, name, url, publicKeysData, address(0));
validators[account] = validator;
_validators.push(account);
emit ValidatorRegistered(account, identifier, name, url, publicKeysData);
return true;
}
/**
* @notice Checks a BLS proof of possession.
* @param proofOfPossessionBytes The public key and signature of the proof of possession.
* @return True upon success.
*/
function checkProofOfPossession(bytes memory proofOfPossessionBytes) private returns (bool) {
bool success;
(success, ) = PROOF_OF_POSSESSION.call.value(0).gas(gasleft())(proofOfPossessionBytes);
return success;
}
/**
* @notice De-registers a validator, removing it from the group for which it is a member.
* @param index The index of this validator in the list of all validators.
* @return True upon success.
* @dev Fails if the account is not a validator.
*/
function deregisterValidator(uint256 index) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidator(account));
Validator storage validator = validators[account];
if (validator.affiliation != address(0)) {
_deaffiliate(validator, account);
}
delete validators[account];
deleteElement(_validators, account, index);
emit ValidatorDeregistered(account);
return true;
}
/**
* @notice Affiliates a validator with a group, allowing it to be added as a member.
* @param group The validator group with which to affiliate.
* @return True upon success.
* @dev De-affiliates with the previously affiliated group if present.
*/
function affiliate(address group) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidator(account) && isValidatorGroup(group));
Validator storage validator = validators[account];
if (validator.affiliation != address(0)) {
_deaffiliate(validator, account);
}
validator.affiliation = group;
emit ValidatorAffiliated(account, group);
return true;
}
/**
* @notice De-affiliates a validator, removing it from the group for which it is a member.
* @return True upon success.
* @dev Fails if the account is not a validator with non-zero affiliation.
*/
function deaffiliate() external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidator(account));
Validator storage validator = validators[account];
require(validator.affiliation != address(0));
_deaffiliate(validator, account);
return true;
}
/**
* @notice Registers a validator group with no member validators.
* @param identifier A identifier for this validator group.
* @param name A name for the validator group.
* @param url A URL for the validator group.
* @param noticePeriod The notice period of the Locked Gold commitment that meets the
* requirements for validator registration.
* @return True upon success.
* @dev Fails if the account is already a validator or validator group.
* @dev Fails if the account does not have sufficient weight.
*/
function registerValidatorGroup(
string calldata identifier,
string calldata name,
string calldata url,
uint256 noticePeriod
)
external
nonReentrant
returns (bool)
{
require(bytes(identifier).length > 0 && bytes(name).length > 0 && bytes(url).length > 0);
address account = getAccountFromValidator(msg.sender);
require(!isValidator(account) && !isValidatorGroup(account));
require(meetsRegistrationRequirements(account, noticePeriod));
ValidatorGroup storage group = groups[account];
group.identifier = identifier;
group.name = name;
group.url = url;
_groups.push(account);
emit ValidatorGroupRegistered(account, identifier, name, url);
return true;
}
/**
* @notice De-registers a validator group.
* @param index The index of this validator group in the list of all validator groups.
* @return True upon success.
* @dev Fails if the account is not a validator group with no members.
*/
function deregisterValidatorGroup(uint256 index) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
// Only empty Validator Groups can be deregistered.
require(isValidatorGroup(account) && groups[account].members.numElements == 0);
delete groups[account];
deleteElement(_groups, account, index);
emit ValidatorGroupDeregistered(account);
return true;
}
/**
* @notice Adds a member to the end of a validator group's list of members.
* @param validator The validator to add to the group
* @return True upon success.
* @dev Fails if `validator` has not set their affiliation to this account.
*/
function addMember(address validator) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidatorGroup(account) && isValidator(validator));
ValidatorGroup storage group = groups[account];
require(validators[validator].affiliation == account && !group.members.contains(validator));
group.members.push(validator);
emit ValidatorGroupMemberAdded(account, validator);
return true;
}
/**
* @notice Removes a member from a validator group.
* @param validator The validator to remove from the group
* @return True upon success.
* @dev Fails if `validator` is not a member of the account's group.
*/
function removeMember(address validator) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidatorGroup(account) && isValidator(validator));
return _removeMember(account, validator);
}
/**
* @notice Reorders a member within a validator group.
* @param validator The validator to reorder.
* @param lesserMember The member who will be behind `validator`, or 0 if `validator` will be the
* last member.
* @param greaterMember The member who will be ahead of `validator`, or 0 if `validator` will be
* the first member.
* @return True upon success.
* @dev Fails if `validator` is not a member of the account's validator group.
*/
function reorderMember(
address validator,
address lesserMember,
address greaterMember
)
external
nonReentrant
returns (bool)
{
address account = getAccountFromValidator(msg.sender);
require(isValidatorGroup(account) && isValidator(validator));
ValidatorGroup storage group = groups[account];
require(group.members.contains(validator));
group.members.update(validator, lesserMember, greaterMember);
emit ValidatorGroupMemberReordered(account, validator);
return true;
}
/**
* @notice Casts a vote for a validator group.
* @param group The validator group to vote for.
* @param lesser The group receiving fewer votes than `group`, or 0 if `group` has the
* fewest votes of any validator group.
* @param greater The group receiving more votes than `group`, or 0 if `group` has the
* most votes of any validator group.
* @return True upon success.
* @dev Fails if `group` is empty or not a validator group.
* @dev Fails if the account is frozen.
*/
function vote(
address group,
address lesser,
address greater
)
external
nonReentrant
returns (bool)
{
// Empty validator groups are not electable.
require(isValidatorGroup(group) && groups[group].members.numElements > 0);
address account = getAccountFromVoter(msg.sender);
require(!isVotingFrozen(account));
require(voters[account] == address(0));
uint256 weight = getAccountWeight(account);
require(weight > 0);
if (votes.contains(group)) {
votes.update(
group,
votes.getValue(group).add(uint256(weight)),
lesser,
greater
);
} else {
votes.insert(
group,
weight,
lesser,
greater
);
}
voters[account] = group;
emit ValidatorGroupVoteCast(account, group, weight);
return true;
}
/**
* @notice Revokes an outstanding vote for a validator group.
* @param lesser The group receiving fewer votes than the group for which the vote was revoked,
* or 0 if that group has the fewest votes of any validator group.
* @param greater The group receiving more votes than the group for which the vote was revoked,
* or 0 if that group has the most votes of any validator group.
* @return True upon success.
* @dev Fails if the account has not voted on a validator group.
*/
function revokeVote(
address lesser,
address greater
)
external
nonReentrant
returns (bool)
{
address account = getAccountFromVoter(msg.sender);
address group = voters[account];
require(group != address(0));
uint256 weight = getAccountWeight(account);
// If the group we had previously voted on removed all its members it is no longer eligible
// to receive votes and we don't have to worry about removing our vote.
if (votes.contains(group)) {
require(weight > 0);
uint256 newVoteTotal = votes.getValue(group).sub(uint256(weight));
if (newVoteTotal > 0) {
votes.update(
group,
newVoteTotal,
lesser,
greater
);
} else {
// Groups receiving no votes are not electable.
votes.remove(group);
}
}
voters[account] = address(0);
emit ValidatorGroupVoteRevoked(account, group, weight);
return true;
}
/**
* @notice Returns validator information.
* @param account The account that registered the validator.
* @return The unpacked validator struct.
*/
function getValidator(
address account
)
external
view
returns (
string memory identifier,
string memory name,
string memory url,
bytes memory publicKeysData,
address affiliation
)
{
require(isValidator(account));
Validator storage validator = validators[account];
return (
validator.identifier,
validator.name,
validator.url,
validator.publicKeysData,
validator.affiliation
);
}
/**
* @notice Returns validator group information.
* @param account The account that registered the validator group.
* @return The unpacked validator group struct.
*/
function getValidatorGroup(
address account
)
external
view
returns (string memory, string memory, string memory, address[] memory)
{
require(isValidatorGroup(account));
ValidatorGroup storage group = groups[account];
return (group.identifier, group.name, group.url, group.members.getKeys());
}
/**
* @notice Returns electable validator group addresses and their vote totals.
* @return Electable validator group addresses and their vote totals.
*/
function getValidatorGroupVotes() external view returns (address[] memory, uint256[] memory) {
return votes.getElements();
}
/**
* @notice Returns the number of votes a particular validator group has received.
* @param group The account that registered the validator group.
* @return The number of votes a particular validator group has received.
*/
function getVotesReceived(address group) external view returns (uint256) {
return votes.getValue(group);
}
/**
* @notice Returns the Locked Gold commitment requirements to register a validator or group.
* @return The minimum value and notice period for the Locked Gold commitment.
*/
function getRegistrationRequirement() external view returns (uint256, uint256) {
return (registrationRequirement.value, registrationRequirement.noticePeriod);
}
/**
* @notice Returns the list of registered validator accounts.
* @return The list of registered validator accounts.
*/
function getRegisteredValidators() external view returns (address[] memory) {
return _validators;
}
/**
* @notice Returns the list of registered validator group accounts.
* @return The list of registered validator group addresses.
*/
function getRegisteredValidatorGroups() external view returns (address[] memory) {
return _groups;
}
/**
* @notice Returns whether a particular account is a registered validator or validator group.
* @param account The account.
* @return Whether a particular account is a registered validator or validator group.
*/
function isValidating(address account) external view returns (bool) {
return isValidator(account) || isValidatorGroup(account);
}
/**
* @notice Returns whether a particular account is voting for a validator group.
* @param account The account.
* @return Whether a particular account is voting for a validator group.
*/
function isVoting(address account) external view returns (bool) {
return (voters[account] != address(0));
}
/**
* @notice Returns a list of elected validators with seats allocated to groups via the D'Hondt
* method.
* @return The list of elected validators.
* @dev See https://en.wikipedia.org/wiki/D%27Hondt_method#Allocation for more information.
*/
/* solhint-disable code-complexity */
function getValidators() external view returns (address[] memory) {
// Only members of these validator groups are eligible for election.
uint256 numElectionGroups = maxElectableValidators;
if (numElectionGroups > votes.list.numElements) {
numElectionGroups = votes.list.numElements;
}
address[] memory electionGroups = votes.list.headN(numElectionGroups);
// Holds the number of members elected for each of the eligible validator groups.
uint256[] memory numMembersElected = new uint256[](electionGroups.length);
uint256 totalNumMembersElected = 0;
bool memberElectedInRound = true;
// Assign a number of seats to each validator group.
while (totalNumMembersElected < maxElectableValidators && memberElectedInRound) {
memberElectedInRound = false;
uint256 groupIndex = 0;
FixidityLib.Fraction memory maxN = FixidityLib.wrap(0);
for (uint256 i = 0; i < electionGroups.length; i = i.add(1)) {
bool isWinningestGroupInRound = false;
(maxN, isWinningestGroupInRound) = dHondt(maxN, electionGroups[i], numMembersElected[i]);
if (isWinningestGroupInRound) {
memberElectedInRound = true;
groupIndex = i;
}
}
if (memberElectedInRound) {
numMembersElected[groupIndex] = numMembersElected[groupIndex].add(1);
totalNumMembersElected = totalNumMembersElected.add(1);
}
}
require(totalNumMembersElected >= minElectableValidators);
// Grab the top validators from each group that won seats.
address[] memory electedValidators = new address[](totalNumMembersElected);
totalNumMembersElected = 0;
for (uint256 i = 0; i < electionGroups.length; i = i.add(1)) {
address[] memory electedGroupMembers = groups[electionGroups[i]].members.headN(
numMembersElected[i]
);
for (uint256 j = 0; j < electedGroupMembers.length; j = j.add(1)) {
// We use the validating delegate if one is set.
electedValidators[totalNumMembersElected] = getValidatorFromAccount(electedGroupMembers[j]);
totalNumMembersElected = totalNumMembersElected.add(1);
}
}
return electedValidators;
}
/* solhint-enable code-complexity */
/**
* @notice Returns whether a particular account has a registered validator group.
* @param account The account.
* @return Whether a particular address is a registered validator group.
*/
function isValidatorGroup(address account) public view returns (bool) {
return bytes(groups[account].identifier).length > 0;
}
/**
* @notice Returns whether a particular account has a registered validator.
* @param account The account.
* @return Whether a particular address is a registered validator.
*/
function isValidator(address account) public view returns (bool) {
return bytes(validators[account].identifier).length > 0;
}
/**
* @notice Returns whether an account meets the requirements to register a validator or group.
* @param account The account.
* @param noticePeriod The notice period of the Locked Gold commitment that meets the
* requirements.
* @return Whether an account meets the requirements to register a validator or group.
*/
function meetsRegistrationRequirements(
address account,
uint256 noticePeriod
)
public
view
returns (bool)
{
uint256 value = getLockedCommitmentValue(account, noticePeriod);
return (
value >= registrationRequirement.value &&
noticePeriod >= registrationRequirement.noticePeriod
);
}
/**
* @notice Deletes an element from a list of addresses.
* @param list The list of addresses.
* @param element The address to delete.
* @param index The index of `element` in the list.
*/
function deleteElement(address[] storage list, address element, uint256 index) private {
require(index < list.length && list[index] == element);
uint256 lastIndex = list.length.sub(1);
list[index] = list[lastIndex];
list[lastIndex] = address(0);
list.length = lastIndex;
}
/**
* @notice Removes a member from a validator group.
* @param group The group from which the member should be removed.
* @param validator The validator to remove from the group.
* @return True upon success.
* @dev If `validator` was the only member of `group`, `group` becomes unelectable.
* @dev Fails if `validator` is not a member of `group`.
*/
function _removeMember(address group, address validator) private returns (bool) {
ValidatorGroup storage _group = groups[group];
require(validators[validator].affiliation == group && _group.members.contains(validator));
_group.members.remove(validator);
emit ValidatorGroupMemberRemoved(group, validator);
// Empty validator groups are not electable.
if (groups[group].members.numElements == 0) {
if (votes.contains(group)) {
votes.remove(group);
}
emit ValidatorGroupEmptied(group);
}
return true;
}
/**
* @notice De-affiliates a validator, removing it from the group for which it is a member.
* @param validator The validator to deaffiliate from their affiliated validator group.
* @param validatorAccount The LockedGold account of the validator.
* @return True upon success.
*/
function _deaffiliate(
Validator storage validator,
address validatorAccount
)
private
returns (bool)
{
address affiliation = validator.affiliation;
ValidatorGroup storage group = groups[affiliation];
if (group.members.contains(validatorAccount)) {
_removeMember(affiliation, validatorAccount);
}
emit ValidatorDeaffiliated(validatorAccount, affiliation);
validator.affiliation = address(0);
return true;
}
/**
* @notice Runs D'Hondt for a validator group.
* @param maxN The maximum number of votes per elected seat for a group in this round.
* @param groupAddress The address of the validator group.
* @param numMembersElected The number of members elected so far for this group.
* @dev See https://en.wikipedia.org/wiki/D%27Hondt_method#Allocation for more information.
* @return The new `maxN` and whether or not the group should win a seat in this round thus far.
*/
function dHondt(
FixidityLib.Fraction memory maxN,
address groupAddress,
uint256 numMembersElected
)
private
view
returns (FixidityLib.Fraction memory, bool)
{
ValidatorGroup storage group = groups[groupAddress];
// Only consider groups with members left to be elected.
if (group.members.numElements > numMembersElected) {
FixidityLib.Fraction memory n = FixidityLib.newFixed(votes.getValue(groupAddress)).divide(
FixidityLib.newFixed(numMembersElected.add(1))
);
if (n.gt(maxN)) {
return (n, true);
}
}
return (maxN, false);
}
}
|
Returns whether a particular account has a registered validator. account The account. return Whether a particular address is a registered validator./
|
function isValidator(address account) public view returns (bool) {
return bytes(validators[account].identifier).length > 0;
}
| 5,467,139
|
// Goji Token Locking Contract
pragma solidity ^0.4.26;
//
// token contract functions
//
contract Token {
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function approveAndCall(address spender, uint tokens, bytes data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function ceil(uint256 a, uint256 m) internal pure returns (uint256) {
uint256 c = add(a,m);
uint256 d = sub(c,1);
return mul(div(d,m),m);
}
}
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract GojiLock is owned{
using SafeMath for uint256;
//
// token deposit varibles
//
struct Items {
address tokenAddress;
address withdrawalAddress;
uint256 tokenAmount;
uint256 unlockTime;
bool withdrawn;
}
uint256 public depositId;
uint256[] public allDepositIds;
mapping (address => uint256[]) public depositsByWithdrawalAddress;
mapping (uint256 => Items) public lockedToken;
mapping (address => mapping(address => uint256)) public walletTokenBalance;
event LogWithdrawal(address SentToAddress, uint256 AmountTransferred);
//
// lock tokens functions
//
function lockTokens(address _tokenAddress, address _withdrawalAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0);
require(_unlockTime < 10000000000);
//update balance in address
walletTokenBalance[_tokenAddress][_withdrawalAddress] = walletTokenBalance[_tokenAddress][_withdrawalAddress].add(_amount);
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amount;
lockedToken[_id].unlockTime = _unlockTime;
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
// transfer tokens into contract
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount));
}
//
// Create multiple locks function
//
function createMultipleLocks(address _tokenAddress, address _withdrawalAddress, uint256[] _amounts, uint256[] _unlockTimes) public returns (uint256 _id) {
require(_amounts.length > 0);
require(_amounts.length == _unlockTimes.length);
uint256 i;
for(i=0; i<_amounts.length; i++){
require(_amounts[i] > 0);
require(_unlockTimes[i] < 10000000000);
//update balance in address
walletTokenBalance[_tokenAddress][_withdrawalAddress] = walletTokenBalance[_tokenAddress][_withdrawalAddress].add(_amounts[i]);
_id = ++depositId;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amounts[i];
lockedToken[_id].unlockTime = _unlockTimes[i];
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
//transfer tokens into contract
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amounts[i]));
}
}
//
// Extend lock Duration function
//
function extendLockDuration(uint256 _id, uint256 _unlockTime) public {
require(_unlockTime < 10000000000);
require(_unlockTime > lockedToken[_id].unlockTime);
require(!lockedToken[_id].withdrawn);
require(msg.sender == lockedToken[_id].withdrawalAddress);
//set new unlock time
lockedToken[_id].unlockTime = _unlockTime;
}
//
// transfer locked tokens
//
function transferLocks(uint256 _id, address _receiverAddress) public {
require(!lockedToken[_id].withdrawn);
require(msg.sender == lockedToken[_id].withdrawalAddress);
// decrease sender's token balance
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
// increase receiver's token balance
walletTokenBalance[lockedToken[_id].tokenAddress][_receiverAddress] = walletTokenBalance[lockedToken[_id].tokenAddress][_receiverAddress].add(lockedToken[_id].tokenAmount);
// remove this id from sender address
uint256 j;
uint256 arrLength = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length;
for (j=0; j<arrLength; j++) {
if (depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id) {
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][arrLength - 1];
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
//Assign this id to receiver address
lockedToken[_id].withdrawalAddress = _receiverAddress;
depositsByWithdrawalAddress[_receiverAddress].push(_id);
}
//
// withdraw tokens function
//
function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime);
require(msg.sender == lockedToken[_id].withdrawalAddress);
require(!lockedToken[_id].withdrawn);
lockedToken[_id].withdrawn = true;
// update balance in address of wallet
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
// remove this id from this address
uint256 j;
uint256 arrLength = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length;
for (j=0; j<arrLength; j++) {
if (depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id) {
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][arrLength - 1];
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
// transfer tokens to wallet address
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount));
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
// *******************************************************
// ********** Read Contract Functions ********************
// *******************************************************
//
// get total token balance in contract
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
{
return Token(_tokenAddress).balanceOf(this);
}
// get total token balance by address function
function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
// get all Deposit Ids function
function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
// get Deposit Details function
function getDepositDetails(uint256 _id) view public returns (address _tokenAddress, address _withdrawalAddress, uint256 _tokenAmount, uint256 _unlockTime, bool _withdrawn)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
// get Deposits By Withdrawal Address function
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
}
|
get Deposits By Withdrawal Address function
|
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
| 398,455
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
struct Tx {
address user;
address originAddress;
uint256 IDs;
// uint16 chainID;
// uint16 destChainID;
// uint16 originChainID;
uint256 nonce;
uint256 amount;
string name;
string symbol;
}
interface LayerZero {
function sendTxInfo(
/* Layer 0 info */
uint16 _dstChainId, bytes calldata _dstCounterMockAddress,
/* Tx Info */
address _user,
uint256 IDs,
//uint16 _chainID,
uint256 _nonce,
//uint16 _destChainID,
uint256 _amount,
//uint16 _originChainID,
address _originAddress,
string memory _name,
string memory _symbol
) external payable;
function resetTxInfo(address _user) external;
function txs(address _user) external view returns (Tx memory);
}
|
uint16 _chainID,uint16 _destChainID,uint16 _originChainID,
|
interface LayerZero {
function sendTxInfo(
uint16 _dstChainId, bytes calldata _dstCounterMockAddress,
address _user,
uint256 IDs,
uint256 _nonce,
uint256 _amount,
address _originAddress,
string memory _name,
string memory _symbol
) external payable;
function resetTxInfo(address _user) external;
function txs(address _user) external view returns (Tx memory);
}
| 13,089,321
|
/**
*Submitted for verification at Etherscan.io on 2020-07-23
*/
pragma solidity ^0.5.1;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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) {
assert(b > 0);
uint256 c = a / b;
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;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
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 Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Owned {
address internal owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor(address _owner) public {
owner = _owner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _owner) onlyOwner public {
require(_owner != address(0));
owner = _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit OwnershipTransferred(owner, _owner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
contract ERC20Token is ERC20, Owned {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
// True if transfers are allowed
bool internal transferable = true;
modifier canTransfer() {
require(transferable == true);
_;
}
function setTransferable(bool _transferable) onlyOwner public {
transferable = _transferable; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @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) canTransfer public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[msg.sender] = balances[msg.sender].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_to] = balances[_to].add(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
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 balance) {
return balances[_owner]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @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) canTransfer public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(_value <= allowed[_from][msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_from] = balances[_from].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balances[_to] = balances[_to].add(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Transfer(_from, _to, _value);
return true;
}
// Allow `_spender` to withdraw from your account, multiple times.
function approve(address _spender, uint _value) public 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)) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
revert();
}
allowed[msg.sender][_spender] = _value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
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]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function () external payable {
revert();
}
}
contract SealToken is ERC20Token{
string public name = "SealSC";
string public symbol = "SEAL";
uint8 public decimals = 18;
uint256 public totalSupplyCap = 10 * 10**8 * 10**uint256(decimals);
constructor(address _issuer) public Owned(_issuer) {
totalSupply = totalSupplyCap;
balances[msg.sender] = totalSupplyCap;
emit Transfer(address(0), msg.sender, totalSupplyCap);
}
}
|
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) canTransfer public returns (bool) {
require(_to != address(0));
emit Transfer(_from, _to, _value);
return true;
}
| 14,103,104
|
pragma solidity ^0.5.0;
// // @title IERC1643 Document Management (part of the ERC1400 Security Token Standards)
// /// @dev See https://github.com/SecurityTokenStandard/EIP-Spec
// interface IERC1643 {
// // Document Management
// function getDocument(bytes32 _name) external view returns (string memory, bytes32, uint256);
// function setDocument(bytes32 _name, string calldata _uri, bytes32 _documentHash) external;
// function removeDocument(bytes32 _name) external;
// function getAllDocuments() external view returns (bytes32[] memory);
// // Document Events
// event DocumentRemoved(bytes32 indexed _name, string _uri, bytes32 _documentHash);
// event DocumentUpdated(bytes32 indexed _name, string _uri, bytes32 _documentHash);
// }
/**
* @title WhiteList implementation of ERC1643 Document management
*/
contract WhiteListDocuments {
event AddToWhiteList(address indexed _added, address _by, uint256 _timestamp);
event RemoveFromWhiteList(address indexed _removed, address _by, uint256 _timestamp);
event TransferOwner(address indexed _newOwner, address _oldOwner, uint256 _timestamp);
// Document Events
event DocumentRemoved(bytes32 indexed _name, string _uri, bytes32 _documentHash);
event DocumentUpdated(bytes32 indexed _name, string _uri, bytes32 _documentHash);
struct Document {
bytes32 docHash;
uint256 lastModified; // Timestamp.
string uri; // location of the document that exist off-chain.
}
// owner of the contract.
address public owner;
// mapping to store authorized users.
mapping(address => bool) public whiteList;
// mapping from document name to the Document details.
mapping(bytes32 => Document) public documents;
// Array use to store all the document names present in the contracts.
bytes32[] documentNames;
/// Initialize contract.
constructor() public {
owner = msg.sender;
whiteList[owner] = true;
emit AddToWhiteList(msg.sender, address(this), now);
}
modifier onlyOwner() {
require(msg.sender == owner, "You are not the owner.");
_;
}
modifier onlyWhiteList() {
require(whiteList[msg.sender], "You are not on the white list.");
_;
}
// Transfer ownership of the contract.
function transferOwner(address _newOwner) public onlyOwner {
if (!whiteList[_newOwner]) {
whiteList[_newOwner] = true;
}
whiteList[owner] = false;
emit RemoveFromWhiteList(owner, _newOwner, now);
emit TransferOwner(_newOwner, owner, now);
owner = _newOwner;
}
// Add user to the white list.
function addToWhiteList(address _add) public onlyOwner {
whiteList[_add] = true;
emit AddToWhiteList(_add, owner, now);
}
// Remove user from the white list.
function removeFromWhiteList(address _remove) public onlyOwner {
whiteList[_remove] = false;
emit RemoveFromWhiteList(_remove, owner, now);
}
// Add/Update document.
function setDocument(bytes32 _name, string calldata _uri, bytes32 _documentHash) external onlyWhiteList {
if (documents[_name].lastModified == 0) documentNames.push(_name);
documents[_name] = Document(_documentHash, now, _uri);
emit DocumentUpdated(_name, _uri, _documentHash);
}
// Remove document.
function removeDocument(bytes32 _name) external onlyWhiteList {
require(documents[_name].lastModified != uint256(0), "Document does not exist.");
// Find element's index.
for (uint i=0; i<documentNames.length; i++) {
if (documentNames[i] == _name) {
// If element is not the last index, swap positions.
if (i < documentNames.length - 1) {
documentNames[i] = documentNames[documentNames.length - 1];
}
break;
}
}
// Delete element.
documentNames.pop();
emit DocumentRemoved(_name, documents[_name].uri, documents[_name].docHash);
// Delete document.
delete documents[_name];
}
// Get document details.
function getDocument(bytes32 _name) external view returns (string memory, bytes32, uint256) {
return (documents[_name].uri, documents[_name].docHash, documents[_name].lastModified);
}
// Return array of all document names.
function getAllDocuments() external view returns (bytes32[] memory) {
return documentNames;
}
}
|
Return array of all document names.
|
function getAllDocuments() external view returns (bytes32[] memory) {
return documentNames;
}
| 2,513,023
|
./partial_match/4/0x2F674500a367583D6Aaef312478a7cC1941a1977/sources/FECORE.sol
|
Destroys `amount` tokens from `account`, deducting from the caller's allowance. See {ERC20-_burn} and {ERC20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least `amount`./
|
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(
amount,
"ERC20: burn amount exceeds allowance"
);
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
| 8,664,304
|
./full_match/1/0x42b255be54d2a38b13ca7e242898134469c3EF08/sources/contracts/Market.sol
|
Accepts a bid from a particular bidder. Can only be called by the media contract. See {_finalizeNFTTransfer} Provided bid must match a bid in storage. This is to prevent a race condition where a bid may change while the acceptBid call is in transit. A bid cannot be accepted if it cannot be split equally into its shareholders. This should only revert in rare instances (example, a low bid with a zero-decimal token), but is necessary to ensure fairness to all shareholders./
|
function acceptBid(uint256 tokenId, Bid calldata expectedBid)
external
override
onlyMediaCaller
{
Bid memory bid = _tokenBidders[tokenId][expectedBid.bidder];
require(bid.amount > 0, "Market: cannot accept bid of 0");
require(
bid.amount == expectedBid.amount &&
bid.currency == expectedBid.currency &&
bid.sellOnShare.value == expectedBid.sellOnShare.value &&
bid.recipient == expectedBid.recipient,
"Market: Unexpected bid found."
);
require(
isValidBid(tokenId, bid.amount),
"Market: Bid invalid for share splitting"
);
_finalizeNFTTransfer(tokenId, bid.bidder);
}
| 3,046,382
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "hardhat/console.sol";
/**
* @title DEX Template
* @author stevepham.eth and m00npapi.eth
* @notice Empty DEX.sol that just outlines what features could be part of the challenge (up to you!)
* @dev We want to create an automatic market where our contract will hold reserves of both ETH and 🎈 Balloons. These reserves will provide liquidity that allows anyone to swap between the assets.
* NOTE: functions outlined here are what work with the front end of this branch/repo. Also return variable names that may need to be specified exactly may be referenced (if you are confused, see solutions folder in this repo and/or cross reference with front-end code).
*/
contract DEX {
/* ========== GLOBAL VARIABLES ========== */
using SafeMath for uint256; //outlines use of SafeMath for uint256 variables
IERC20 token; //instantiates the imported contract
uint256 public totalLiquidity;
mapping(address => uint256) public liquidity;
/* ========== EVENTS ========== */
/**
* @notice Emitted when ethToToken() swap transacted
*/
event EthToTokenSwap(
address recipient,
string message,
uint256 ethAmount,
uint256 tokenAmount
);
/**
* @notice Emitted when tokenToEth() swap transacted
*/
event TokenToEthSwap(
address recipient,
string message,
uint256 ethAmount,
uint256 tokenAmount
);
/**
* @notice Emitted when liquidity provided to DEX and mints LPTs.
*/
event LiquidityProvided(
address recipient,
uint256 liquidityMinted,
uint256 ethAmount,
uint256 tokenAmount
);
/**
* @notice Emitted when liquidity removed from DEX and decreases LPT count within DEX.
*/
event LiquidityRemoved(
address recipient,
uint256 liquidityRemoved,
uint256 ethAmount,
uint256 tokenAmount
);
/* ========== CONSTRUCTOR ========== */
constructor(address token_addr) public {
token = IERC20(token_addr); //specifies the token address that will hook into the interface and be used through the variable 'token'
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice initializes amount of tokens that will be transferred to the DEX itself from the erc20 contract mintee (and only them based on how Balloons.sol is written). Loads contract up with both ETH and Balloons.
* @param tokens amount to be transferred to DEX
* @return totalLiquidity is the number of LPTs minting as a result of deposits made to DEX contract
* NOTE: since ratio is 1:1, this is fine to initialize the totalLiquidity (wrt to balloons) as equal to eth balance of contract.
*/
function init(uint256 tokens) public payable returns (uint256) {
require(totalLiquidity == 0, "Already initialised");
totalLiquidity = address(this).balance; // no. of ETH sent to this contract
liquidity[msg.sender] = totalLiquidity;
require(token.transferFrom(msg.sender, address(this), tokens));
return totalLiquidity;
}
/**
* @notice returns yOutput, or yDelta for xInput (or xDelta)
* @dev Follow along with the [original tutorial](https://medium.com/@austin_48503/%EF%B8%8F-minimum-viable-exchange-d84f30bd0c90) Price section for an understanding of the DEX's pricing model and for a price function to add to your contract. You may need to update the Solidity syntax (e.g. use + instead of .add, * instead of .mul, etc). Deploy when you are done.
*/
function price(
uint256 xInput,
uint256 xReserves,
uint256 yReserves
) public view returns (uint256 yOutput) {
// xReserves * yReserves = k;
uint256 inputAmountWithFee = xInput * 997;
uint256 numerator = inputAmountWithFee * yReserves;
uint256 denominator = xReserves * 1000 + inputAmountWithFee;
return numerator / denominator;
}
/**
* @notice returns liquidity for a user. Note this is not needed typically due to the `liquidity()` mapping variable being public and having a getter as a result. This is left though as it is used within the front end code (App.jsx).
*/
function getLiquidity(address lp) public view returns (uint256) {
return liquidity[lp];
}
/**
* @notice sends Ether to DEX in exchange for $BAL
*/
function ethToToken() public payable returns (uint256 tokenOutput) {
require(msg.value > 0, "You need to send some ETH");
uint256 preTxnReserves = address(this).balance - msg.value;
uint256 tokenReserves = token.balanceOf(address(this));
tokenOutput = this.price(msg.value, preTxnReserves, tokenReserves);
require(token.transfer(msg.sender, tokenOutput));
emit EthToTokenSwap(
msg.sender,
"Eth -> Balloons",
msg.value,
tokenOutput
);
return tokenOutput;
}
/**
* @notice sends $BAL tokens to DEX in exchange for Ether
*/
function tokenToEth(uint256 tokenInput) public returns (uint256 ethOutput) {
require(tokenInput > 0, "You need to specify amount of tokens to swap");
uint256 ethReserves = address(this).balance;
uint256 tokenReserves = token.balanceOf(address(this));
ethOutput = this.price(tokenInput, tokenReserves, ethReserves);
require(
token.transferFrom(msg.sender, address(this), tokenInput),
"Token transfer failed. Check allowance"
);
(bool sent, ) = msg.sender.call{value: ethOutput}("");
require(sent, "Unable to transfer ETH to you");
emit TokenToEthSwap(
msg.sender,
"Balloons -> ETH",
ethOutput,
tokenInput
);
return ethOutput;
}
/**
* @notice allows deposits of $BAL and $ETH to liquidity pool
* NOTE: parameter is the msg.value sent with this function call. That amount is used to determine the amount of $BAL needed as well and taken from the depositor.
* NOTE: user has to make sure to give DEX approval to spend their tokens on their behalf by calling approve function prior to this function call.
* NOTE: Equal parts of both assets will be removed from the user's wallet with respect to the price outlined by the AMM.
*/
function deposit() public payable returns (uint256 tokensDeposited) {
require(msg.value > 0, "You need to send some ETH");
uint256 preTxnReserves = address(this).balance - msg.value;
uint256 tokenReserves = token.balanceOf(address(this));
uint256 tokenInput = (msg.value * tokenReserves) / preTxnReserves + 1;
uint256 liquidityMinted = (msg.value * totalLiquidity) / preTxnReserves;
totalLiquidity = totalLiquidity + liquidityMinted;
liquidity[msg.sender] = liquidity[msg.sender] + liquidityMinted;
uint256 allowance = token.allowance(msg.sender, address(this));
console.log("tokenInput", tokenInput);
console.log("allowance", allowance);
require(
token.transferFrom(msg.sender, address(this), tokenInput),
"Token transfer failed. Check allowance"
);
emit LiquidityProvided(
msg.sender,
liquidityMinted,
msg.value,
tokenInput
);
tokensDeposited = tokenInput;
return tokensDeposited;
}
/**
* @notice allows withdrawal of $BAL and $ETH from liquidity pool
* NOTE: with this current code, the msg caller could end up getting very little back if the liquidity is super low in the pool. I guess they could see that with the UI.
*/
function withdraw(uint256 amount)
public
returns (uint256 ethAmount, uint256 tokenAmount)
{
require(
liquidity[msg.sender] >= amount,
"You have no liquidity in the pool"
);
uint256 tokenReserve = token.balanceOf(address(this));
uint256 ethReserve = address(this).balance;
uint256 tokenAmount = (amount * tokenReserve) / totalLiquidity;
uint256 ethAmount = (amount * ethReserve) / totalLiquidity;
liquidity[msg.sender] = liquidity[msg.sender] - amount;
totalLiquidity = totalLiquidity - amount;
(bool sent, ) = payable(msg.sender).call{value: ethAmount}("");
require(sent, "Unable to transfer ETH back to you");
require(
token.transfer(msg.sender, tokenAmount),
"Unable to tranfer Balloons back to you"
);
emit LiquidityRemoved(msg.sender, amount, ethAmount, tokenAmount);
return (ethAmount, tokenAmount);
}
}
|
allows withdrawal of $BAL and $ETH from liquidity pool NOTE: with this current code, the msg caller could end up getting very little back if the liquidity is super low in the pool. I guess they could see that with the UI./
|
function withdraw(uint256 amount)
public
returns (uint256 ethAmount, uint256 tokenAmount)
{
require(
liquidity[msg.sender] >= amount,
"You have no liquidity in the pool"
);
uint256 tokenReserve = token.balanceOf(address(this));
uint256 ethReserve = address(this).balance;
uint256 tokenAmount = (amount * tokenReserve) / totalLiquidity;
uint256 ethAmount = (amount * ethReserve) / totalLiquidity;
liquidity[msg.sender] = liquidity[msg.sender] - amount;
totalLiquidity = totalLiquidity - amount;
require(sent, "Unable to transfer ETH back to you");
require(
token.transfer(msg.sender, tokenAmount),
"Unable to tranfer Balloons back to you"
);
emit LiquidityRemoved(msg.sender, amount, ethAmount, tokenAmount);
return (ethAmount, tokenAmount);
}
| 14,033,016
|
pragma solidity 0.4.24;
import "../utils/Math.sol";
import "../utils/Ownable.sol";
contract DailyVolumeUpdater is Ownable {
using Math for uint256;
uint256 public dailyVolume;
uint256 public dailyVolumeCap;
uint256 private lastDay;
constructor()
public
{
dailyVolume = 0;
dailyVolumeCap = 1000 ether;
lastDay = today();
}
/**
* @dev Allows the owner to change the daily volume capacity.
* @param _dailyVolumeCap uint256 representing the daily volume capacity
*/
function setDailyVolumeCap(uint256 _dailyVolumeCap)
public
onlyOwner
{
dailyVolumeCap = _dailyVolumeCap;
}
/**
* @dev Internal function that increments the daily volume.
* @param _volume uint256 representing the amount of volume increasement.
*/
function updateVolume(uint256 _volume)
internal
{
if(today() > lastDay) {
dailyVolume = _volume;
lastDay = today();
} else {
dailyVolume = dailyVolume.add(_volume);
}
}
/**
* @dev Internal function to check if the volume capacity is reached.
* @return Whether the volume is reached or not.
*/
function isVolumeReached()
internal
view
returns(bool)
{
return dailyVolume >= dailyVolumeCap;
}
/**
* @dev Private function to determine today's index
* @return uint256 of today's index.
*/
function today()
private
view
returns(uint256)
{
return block.timestamp.div(1 days);
}
}
|
Allows the owner to change the daily volume capacity. _dailyVolumeCap uint256 representing the daily volume capacity/
|
function setDailyVolumeCap(uint256 _dailyVolumeCap)
public
onlyOwner
{
dailyVolumeCap = _dailyVolumeCap;
}
| 5,344,854
|
// ____ ___ ____ ___ _ _ __ __
// | _ \ / _ \| _ \_ _| | | | \/ |
// | |_) | | | | | | | || | | | |\/| |
// | __/| |_| | |_| | || |_| | | | |
// |_| \___/|____/___|\___/|_| |_|
//
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/* ----------------------------------------------------------------------------
* Staking for the Podium Genesis NFT
* Note this allows for staking and calculation. No withdrawal exists yet.
* This will be in another contract. Allow people to start earning ASAP.
* Daily staking rate set to 100 as round number. Rate will be multiplied/devided
* With ERC20 implementation
*
/ -------------------------------------------------------------------------- */
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract PodiumGenesisStaking is ERC721Holder, ReentrancyGuard, Ownable, Pausable {
// Declerations
// ------------------------------------------------------------------------
IERC721 public PodiumGenesis; // Podium Genesis NFT to be staked
uint256 public rewardRate = 66; // Daily reward rate. See above.
mapping(address => bool) public teamMember;
address withdrawContract;
uint256 public totalStaked;
mapping(address => uint256) public balanceOfStaked; // Count of staked by Address
mapping(uint256 => address) public stakedAssetsByToken; // Staked assets and owner
mapping(address => uint256[]) public stakedAssetsByAddr; // Staked assets and owner
mapping(address => uint256) public earnedRewards; // Earned so far
mapping(address => uint256) public dataLastUpdated; // when was address data updated
mapping(bytes4 => bool) public functionLocked;
constructor(address _PodiumGenesis)
{
PodiumGenesis = IERC721(_PodiumGenesis);
teamMember[msg.sender] = true;
}
event Staked(
address indexed addressSender,
uint256 quantity,
uint256[] tokenIds
);
event UnStaked(
address indexed addressSender,
uint256 quantity,
uint256[] tokenIds
);
// Staking functions and helpers
// ------------------------------------------------------------------------
/*
* @notice Stake 1 or more NFTs
* @param `tokenIds` a list of NFTs to be staked
*/
function stake(uint256[] memory tokenIds) external nonReentrant whenNotPaused updateRewardData {
require(tokenIds.length > 0, "Need to provide tokenIds");
uint256 quantity; // Do not use length as safeTransfer check not performed
for (uint256 i = 0; i < tokenIds.length; i += 1) {
PodiumGenesis.safeTransferFrom(msg.sender, address(this), tokenIds[i]);
stakedAssetsByToken[tokenIds[i]] = msg.sender;
stakedAssetsByAddr[msg.sender].push(tokenIds[i]);
quantity++;
}
totalStaked += quantity;
balanceOfStaked[msg.sender] += quantity;
emit Staked(msg.sender, quantity, tokenIds);
}
/*
* @notice Withdraw 1 or more NFTs
* @param `tokenIds` a list of NFTs to be unstaked
*/
function unstake(uint256[] memory tokenIds) public nonReentrant whenNotPaused updateRewardData {
require(tokenIds.length != 0, "Staking: No tokenIds provided");
uint256 quantity;
for (uint256 i = 0; i < tokenIds.length; i += 1) {
// Confirm ownership
require(
stakedAssetsByToken[tokenIds[i]] == msg.sender,
"Staking: Not the staker of the token"
);
// Replace the unstake with the last in the list
uint256 popped = stakedAssetsByAddr[msg.sender][balanceOfStaked[msg.sender] - 1];
stakedAssetsByAddr[msg.sender].pop();
if (popped != tokenIds[i]) {
uint256 tokenStakeIndex = 0;
while (stakedAssetsByAddr[msg.sender][tokenStakeIndex] != tokenIds[i]) {
tokenStakeIndex++;
}
stakedAssetsByAddr[msg.sender][tokenStakeIndex] = popped;
}
stakedAssetsByToken[tokenIds[i]] = address(0);
quantity++;
// Send back the NFT
PodiumGenesis.safeTransferFrom(address(this), msg.sender, tokenIds[i]);
balanceOfStaked[msg.sender]--;
}
totalStaked -= quantity;
emit UnStaked(msg.sender, quantity, tokenIds);
}
/*
* @notice Modifier called to updateRewards when needed (by stake and unstake, write them)
*/
modifier updateRewardData() {
earnedRewards[msg.sender] += _getPending(msg.sender);
dataLastUpdated[msg.sender] = block.timestamp;
_;
}
/*
* @notice Update rewards rate for tokens
* @param `_newReward` new reward value
*/
function updateRewardRate(uint256 _newReward) public onlyTeamMember {
rewardRate = _newReward;
}
/*
* @notice How many pending tokens are earned
* Note this is used internally and added to earned set later
* @param `account` The address of the staker account
* @return The amount of pending tokens
*/
function _getPending(address account) internal view returns (uint256) {
return
(
(balanceOfStaked[account] * rewardRate) *
((block.timestamp - dataLastUpdated[account]) / 1 days)
);
}
/*
* @notice Withdraw funds from the child contract
* @param account for which withdrawal will be done
* returns amount to be withdrawn
*/
function withdraw(address account) external onlyWithdrawContract updateRewardData nonReentrant returns(uint256) {
uint256 withdrawAmount = getEarnedAmount(account);
earnedRewards[account] = 0;
return withdrawAmount;
}
/*
* @notice Total ammount earned
* @param `account` The address of the staker account
* @return The total ammount earned
*/
function getEarnedAmount(address account) public view returns (uint256) {
return earnedRewards[account] + _getPending(account);
}
/*
* @notice Pause used to pause staking if needed
*/
function pause() external onlyTeamMember {
_pause();
}
/*
* @notice Unpause used to unpause staking if needed
*/
function unpause() external onlyTeamMember {
_unpause();
}
/**
* @dev Throws if called by any account other than team members
*/
modifier onlyTeamMember() {
require(teamMember[msg.sender], "Caller is not an owner");
_;
}
/**
* Add new team meber role with admin permissions
*/
function addTeamMemberAdmin(address newMember) external onlyTeamMember {
teamMember[newMember] = true;
}
/**
* Remove team meber role from admin permissions
*/
function removeTeamMemberAdmin(address newMember) external onlyTeamMember {
teamMember[newMember] = false;
}
/**
* Returns true if address is team member
*/
function isTeamMemberAdmin(address checkAddress) public view onlyTeamMember returns (bool) {
return teamMember[checkAddress];
}
/**
* @dev Throws if called by any account other than team members
*/
modifier onlyWithdrawContract() {
require(withdrawContract == msg.sender, "Caller is not withdraw contract");
_;
}
/**
* Updates contract that can withdraw
*/
function updateWithdrawContract(address _newWithdrawContract) external lockable onlyTeamMember {
withdrawContract = _newWithdrawContract;
}
/**
* @notice Modifier applied to functions that will be disabled when they're no longer needed
*/
modifier lockable() {
require(!functionLocked[msg.sig], "Function has been locked");
_;
}
/**
* @notice Lock individual functions that are no longer needed
* @dev Only affects functions with the lockable modifier
* @param id First 4 bytes of the calldata (i.e. function identifier)
*/
function lockFunction(bytes4 id) public onlyTeamMember {
functionLocked[id] = true;
}
/**
* Recover tokens accidentally sent to contract without explicit owner
*/
function strandedRecovery(address to, uint256 tokenId) external onlyTeamMember {
require(stakedAssetsByToken[tokenId] == address(0), "Token is not in limbo");
PodiumGenesis.safeTransferFrom(address(this), to, tokenId);
}
}
// 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/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev 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: 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 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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 (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;
}
}
|
Update rewards rate for tokens `_newReward` new reward value/
|
function updateRewardRate(uint256 _newReward) public onlyTeamMember {
rewardRate = _newReward;
}
| 13,467,206
|
./partial_match/56/0xfeD19a0e68ad5bBC4eA09751BFDFB0C273A2b0cb/sources/Butter.sol
|
See {IERC20-totalSupply}./
|
function _getMaxTxAmount() public view returns(uint256){
return _max_tx_size;
}
| 11,177,979
|
./partial_match/137/0x848B092A4182A134919d9BF32333600e900Ae6B1/sources/lib/call-simulation/src/SimulationAdapter.sol
|
Executes a call agains this contract and reverts with the result This is meant to be used internally, do not call! _call The call to simulate/ solhint-disable-next-line avoid-low-level-calls
|
function simulateAndRevert(bytes calldata _call) external {
uint256 _gasAtStart = gasleft();
(bool _success, bytes memory _result) = address(this).delegatecall(_call);
uint256 _gasSpent = _gasAtStart - gasleft();
}
| 3,516,639
|
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/math/Math.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { IController } from "../../interfaces/IController.sol";
import { IIndexExchangeAdapter } from "../../interfaces/IIndexExchangeAdapter.sol";
import { Invoke } from "../lib/Invoke.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { IWETH } from "../../interfaces/external/IWETH.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { Position } from "../lib/Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { Uint256ArrayUtils } from "../../lib/Uint256ArrayUtils.sol";
/**
* @title GeneralIndexModule
* @author Set Protocol
*
* Smart contract that facilitates rebalances for indices. Manager can update allocation by calling startRebalance().
* There is no "end" to a rebalance, however once there are no more tokens to sell the rebalance is effectively over
* until the manager calls startRebalance() again with a new allocation. Once a new allocation is passed in, allowed
* traders can submit rebalance transactions by calling trade() and specifying the component they wish to rebalance.
* All parameterizations for a trade are set by the manager ahead of time, including max trade size, coolOffPeriod bet-
* ween trades, and exchange to trade on. WETH is used as the quote asset for all trades, near the end of rebalance
* tradeRemaingingWETH() or raiseAssetTargets() can be called to clean up any excess WETH positions. Once a component's
* target allocation is met any further attempted trades of that component will revert.
*
* SECURITY ASSUMPTION:
* - Works with following modules: StreamingFeeModule, BasicIssuanceModule (any other module additions to Sets using
* this module need to be examined separately)
*/
contract GeneralIndexModule is ModuleBase, ReentrancyGuard {
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using Position for uint256;
using Math for uint256;
using Position for ISetToken;
using Invoke for ISetToken;
using AddressArrayUtils for address[];
using AddressArrayUtils for IERC20[];
using Uint256ArrayUtils for uint256[];
/* ============ Struct ============ */
struct TradeExecutionParams {
uint256 targetUnit; // Target unit of component for Set
uint256 maxSize; // Max trade size in precise units
uint256 coolOffPeriod; // Required time between trades for the asset
uint256 lastTradeTimestamp; // Timestamp of last trade
string exchangeName; // Name of exchange adapter
bytes exchangeData; // Arbitrary data that can be used to encode exchange specific settings (fee tier) or features (multi-hop)
}
struct TradePermissionInfo {
bool anyoneTrade; // Boolean indicating if anyone can execute a trade
address[] tradersHistory; // Tracks permissioned traders to be deleted on module removal
mapping(address => bool) tradeAllowList; // Mapping indicating which addresses are allowed to execute trade
}
struct RebalanceInfo {
uint256 positionMultiplier; // Position multiplier at the beginning of rebalance
uint256 raiseTargetPercentage; // Amount to raise all unit targets by if allowed (in precise units)
address[] rebalanceComponents; // Array of components involved in rebalance
}
struct TradeInfo {
ISetToken setToken; // Instance of SetToken
IIndexExchangeAdapter exchangeAdapter; // Instance of Exchange Adapter
address sendToken; // Address of token being sold
address receiveToken; // Address of token being bought
bool isSendTokenFixed; // Boolean indicating fixed asset is send token
uint256 setTotalSupply; // Total supply of Set (in precise units)
uint256 totalFixedQuantity; // Total quantity of fixed asset being traded
uint256 sendQuantity; // Units of component sent to the exchange
uint256 floatingQuantityLimit; // Max/min amount of floating token spent/received during trade
uint256 preTradeSendTokenBalance; // Total initial balance of token being sold
uint256 preTradeReceiveTokenBalance; // Total initial balance of token being bought
bytes exchangeData; // Arbitrary data for executing trade on given exchange
}
/* ============ Events ============ */
event TradeMaximumUpdated(ISetToken indexed _setToken, address indexed _component, uint256 _newMaximum);
event AssetExchangeUpdated(ISetToken indexed _setToken, address indexed _component, string _newExchangeName);
event CoolOffPeriodUpdated(ISetToken indexed _setToken, address indexed _component, uint256 _newCoolOffPeriod);
event ExchangeDataUpdated(ISetToken indexed _setToken, address indexed _component, bytes _newExchangeData);
event RaiseTargetPercentageUpdated(ISetToken indexed _setToken, uint256 indexed _raiseTargetPercentage);
event AssetTargetsRaised(ISetToken indexed _setToken, uint256 indexed positionMultiplier);
event AnyoneTradeUpdated(ISetToken indexed _setToken, bool indexed _status);
event TraderStatusUpdated(ISetToken indexed _setToken, address indexed _trader, bool _status);
event TradeExecuted(
ISetToken indexed _setToken,
address indexed _sellComponent,
address indexed _buyComponent,
IIndexExchangeAdapter _exchangeAdapter,
address _executor,
uint256 _netAmountSold,
uint256 _netAmountReceived,
uint256 _protocolFee
);
event RebalanceStarted(
ISetToken indexed _setToken,
address[] aggregateComponents,
uint256[] aggregateTargetUnits,
uint256 indexed positionMultiplier
);
/* ============ Constants ============ */
uint256 private constant GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX = 0; // Id of protocol fee % assigned to this module in the Controller
/* ============ State Variables ============ */
mapping(ISetToken => mapping(IERC20 => TradeExecutionParams)) public executionInfo; // Mapping of SetToken to execution parameters of each asset on SetToken
mapping(ISetToken => TradePermissionInfo) public permissionInfo; // Mapping of SetToken to trading permissions
mapping(ISetToken => RebalanceInfo) public rebalanceInfo; // Mapping of SetToken to relevant data for current rebalance
IWETH public immutable weth; // Weth contract address
/* ============ Modifiers ============ */
modifier onlyAllowedTrader(ISetToken _setToken) {
_validateOnlyAllowedTrader(_setToken);
_;
}
modifier onlyEOAIfUnrestricted(ISetToken _setToken) {
_validateOnlyEOAIfUnrestricted(_setToken);
_;
}
/* ============ Constructor ============ */
constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) {
weth = _weth;
}
/* ============ External Functions ============ */
/**
* MANAGER ONLY: Changes the target allocation of the Set, opening it up for trading by the Sets designated traders. The manager
* must pass in any new components and their target units (units defined by the amount of that component the manager wants in 10**18
* units of a SetToken). Old component target units must be passed in, in the current order of the components array on the
* SetToken. If a component is being removed it's index in the _oldComponentsTargetUnits should be set to 0. Additionally, the
* positionMultiplier is passed in, in order to adjust the target units in the event fees are accrued or some other activity occurs
* that changes the positionMultiplier of the Set. This guarantees the same relative allocation between all the components.
*
* @param _setToken Address of the SetToken to be rebalanced
* @param _newComponents Array of new components to add to allocation
* @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array
* @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of
* _setToken.getComponents() array, if component being removed set to 0.
* @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units
* if fees accrued
*/
function startRebalance(
ISetToken _setToken,
address[] calldata _newComponents,
uint256[] calldata _newComponentsTargetUnits,
uint256[] calldata _oldComponentsTargetUnits,
uint256 _positionMultiplier
)
external
onlyManagerAndValidSet(_setToken)
{
( address[] memory aggregateComponents, uint256[] memory aggregateTargetUnits ) = _getAggregateComponentsAndUnits(
_setToken.getComponents(),
_newComponents,
_newComponentsTargetUnits,
_oldComponentsTargetUnits
);
for (uint256 i = 0; i < aggregateComponents.length; i++) {
require(!_setToken.hasExternalPosition(aggregateComponents[i]), "External positions not allowed");
executionInfo[_setToken][IERC20(aggregateComponents[i])].targetUnit = aggregateTargetUnits[i];
}
rebalanceInfo[_setToken].rebalanceComponents = aggregateComponents;
rebalanceInfo[_setToken].positionMultiplier = _positionMultiplier;
emit RebalanceStarted(_setToken, aggregateComponents, aggregateTargetUnits, _positionMultiplier);
}
/**
* ACCESS LIMITED: Calling trade() pushes the current component units closer to the target units defined by the manager in startRebalance().
* Only approved addresses can call, if anyoneTrade is false then contracts are allowed to call otherwise calling address must be EOA.
*
* Trade can be called at anytime but will revert if the passed component's target unit is met or cool off period hasn't passed. Trader can pass
* in a max/min amount of ETH spent/received in the trade based on if the component is being bought/sold in order to prevent sandwich attacks.
* The parameters defined by the manager are used to determine which exchange will be used and the size of the trade. Trade size will default
* to max trade size unless the max trade size would exceed the target, then an amount that would match the target unit is traded. Protocol fees,
* if enabled, are collected in the token received in a trade.
*
* @param _setToken Address of the SetToken
* @param _component Address of SetToken component to trade
* @param _ethQuantityLimit Max/min amount of ETH spent/received during trade
*/
function trade(
ISetToken _setToken,
IERC20 _component,
uint256 _ethQuantityLimit
)
external
nonReentrant
onlyAllowedTrader(_setToken)
onlyEOAIfUnrestricted(_setToken)
virtual
{
_validateTradeParameters(_setToken, _component);
TradeInfo memory tradeInfo = _createTradeInfo(_setToken, _component, _ethQuantityLimit);
_executeTrade(tradeInfo);
uint256 protocolFee = _accrueProtocolFee(tradeInfo);
(uint256 netSendAmount, uint256 netReceiveAmount) = _updatePositionStateAndTimestamp(tradeInfo, _component);
emit TradeExecuted(
tradeInfo.setToken,
tradeInfo.sendToken,
tradeInfo.receiveToken,
tradeInfo.exchangeAdapter,
msg.sender,
netSendAmount,
netReceiveAmount,
protocolFee
);
}
/**
* ACCESS LIMITED: Only callable when 1) there are no more components to be sold and, 2) entire remaining WETH amount (above WETH target) can be
* traded such that resulting inflows won't exceed component's maxTradeSize nor overshoot the target unit. To be used near the end of rebalances
* when a component's calculated trade size is greater in value than remaining WETH.
*
* Only approved addresses can call, if anyoneTrade is false then contracts are allowed to call otherwise calling address must be EOA. Trade
* can be called at anytime but will revert if the passed component's target unit is met or cool off period hasn't passed. Like with trade()
* a minimum component receive amount can be set.
*
* @param _setToken Address of the SetToken
* @param _component Address of the SetToken component to trade
* @param _minComponentReceived Min amount of component received during trade
*/
function tradeRemainingWETH(
ISetToken _setToken,
IERC20 _component,
uint256 _minComponentReceived
)
external
nonReentrant
onlyAllowedTrader(_setToken)
onlyEOAIfUnrestricted(_setToken)
virtual
{
require(_noTokensToSell(_setToken), "Sell other set components first");
require(
executionInfo[_setToken][weth].targetUnit < _getDefaultPositionRealUnit(_setToken, weth),
"WETH is below target unit"
);
_validateTradeParameters(_setToken, _component);
TradeInfo memory tradeInfo = _createTradeRemainingInfo(_setToken, _component, _minComponentReceived);
_executeTrade(tradeInfo);
uint256 protocolFee = _accrueProtocolFee(tradeInfo);
(uint256 netSendAmount, uint256 netReceiveAmount) = _updatePositionStateAndTimestamp(tradeInfo, _component);
require(
netReceiveAmount.add(protocolFee) < executionInfo[_setToken][_component].maxSize,
"Trade amount > max trade size"
);
_validateComponentPositionUnit(_setToken, _component);
emit TradeExecuted(
tradeInfo.setToken,
tradeInfo.sendToken,
tradeInfo.receiveToken,
tradeInfo.exchangeAdapter,
msg.sender,
netSendAmount,
netReceiveAmount,
protocolFee
);
}
/**
* ACCESS LIMITED: For situation where all target units met and remaining WETH, uniformly raise targets by same percentage by applying
* to logged positionMultiplier in RebalanceInfo struct, in order to allow further trading. Can be called multiple times if necessary,
* targets are increased by amount specified by raiseAssetTargetsPercentage as set by manager. In order to reduce tracking error
* raising the target by a smaller amount allows greater granularity in finding an equilibrium between the excess ETH and components
* that need to be bought. Raising the targets too much could result in vastly under allocating to WETH as more WETH than necessary is
* spent buying the components to meet their new target.
*
* @param _setToken Address of the SetToken
*/
function raiseAssetTargets(ISetToken _setToken) external onlyAllowedTrader(_setToken) virtual {
require(
_allTargetsMet(_setToken)
&& _getDefaultPositionRealUnit(_setToken, weth) > _getNormalizedTargetUnit(_setToken, weth),
"Targets not met or ETH =~ 0"
);
// positionMultiplier / (10^18 + raiseTargetPercentage)
// ex: (10 ** 18) / ((10 ** 18) + ether(.0025)) => 997506234413965087
rebalanceInfo[_setToken].positionMultiplier = rebalanceInfo[_setToken].positionMultiplier.preciseDiv(
PreciseUnitMath.preciseUnit().add(rebalanceInfo[_setToken].raiseTargetPercentage)
);
emit AssetTargetsRaised(_setToken, rebalanceInfo[_setToken].positionMultiplier);
}
/**
* MANAGER ONLY: Set trade maximums for passed components of the SetToken. Can be called at anytime.
* Note: Trade maximums must be set before rebalance can begin properly - they are zero by
* default and trades will not execute if a component's trade size is greater than the maximum.
*
* @param _setToken Address of the SetToken
* @param _components Array of components
* @param _tradeMaximums Array of trade maximums mapping to correct component
*/
function setTradeMaximums(
ISetToken _setToken,
address[] memory _components,
uint256[] memory _tradeMaximums
)
external
onlyManagerAndValidSet(_setToken)
{
_components.validatePairsWithArray(_tradeMaximums);
for (uint256 i = 0; i < _components.length; i++) {
executionInfo[_setToken][IERC20(_components[i])].maxSize = _tradeMaximums[i];
emit TradeMaximumUpdated(_setToken, _components[i], _tradeMaximums[i]);
}
}
/**
* MANAGER ONLY: Set exchange for passed components of the SetToken. Can be called at anytime.
*
* @param _setToken Address of the SetToken
* @param _components Array of components
* @param _exchangeNames Array of exchange names mapping to correct component
*/
function setExchanges(
ISetToken _setToken,
address[] memory _components,
string[] memory _exchangeNames
)
external
onlyManagerAndValidSet(_setToken)
{
_components.validatePairsWithArray(_exchangeNames);
for (uint256 i = 0; i < _components.length; i++) {
if (_components[i] != address(weth)) {
require(
controller.getIntegrationRegistry().isValidIntegration(address(this), _exchangeNames[i]),
"Unrecognized exchange name"
);
executionInfo[_setToken][IERC20(_components[i])].exchangeName = _exchangeNames[i];
emit AssetExchangeUpdated(_setToken, _components[i], _exchangeNames[i]);
}
}
}
/**
* MANAGER ONLY: Set cool off periods for passed components of the SetToken. Can be called at any time.
*
* @param _setToken Address of the SetToken
* @param _components Array of components
* @param _coolOffPeriods Array of cool off periods to correct component
*/
function setCoolOffPeriods(
ISetToken _setToken,
address[] memory _components,
uint256[] memory _coolOffPeriods
)
external
onlyManagerAndValidSet(_setToken)
{
_components.validatePairsWithArray(_coolOffPeriods);
for (uint256 i = 0; i < _components.length; i++) {
executionInfo[_setToken][IERC20(_components[i])].coolOffPeriod = _coolOffPeriods[i];
emit CoolOffPeriodUpdated(_setToken, _components[i], _coolOffPeriods[i]);
}
}
/**
* MANAGER ONLY: Set arbitrary byte data on a per asset basis that can be used to pass exchange specific settings (i.e. specifying
* fee tiers) or exchange specific features (enabling multi-hop trades). Can be called at any time.
*
* @param _setToken Address of the SetToken
* @param _components Array of components
* @param _exchangeData Array of exchange specific arbitrary bytes data
*/
function setExchangeData(
ISetToken _setToken,
address[] memory _components,
bytes[] memory _exchangeData
)
external
onlyManagerAndValidSet(_setToken)
{
_components.validatePairsWithArray(_exchangeData);
for (uint256 i = 0; i < _components.length; i++) {
executionInfo[_setToken][IERC20(_components[i])].exchangeData = _exchangeData[i];
emit ExchangeDataUpdated(_setToken, _components[i], _exchangeData[i]);
}
}
/**
* MANAGER ONLY: Set amount by which all component's targets units would be raised. Can be called at any time.
*
* @param _setToken Address of the SetToken
* @param _raiseTargetPercentage Amount to raise all component's unit targets by (in precise units)
*/
function setRaiseTargetPercentage(
ISetToken _setToken,
uint256 _raiseTargetPercentage
)
external
onlyManagerAndValidSet(_setToken)
{
require(_raiseTargetPercentage > 0, "Target percentage must be > 0");
rebalanceInfo[_setToken].raiseTargetPercentage = _raiseTargetPercentage;
emit RaiseTargetPercentageUpdated(_setToken, _raiseTargetPercentage);
}
/**
* MANAGER ONLY: Toggles ability for passed addresses to call trade() or tradeRemainingWETH(). Can be called at any time.
*
* @param _setToken Address of the SetToken
* @param _traders Array trader addresses to toggle status
* @param _statuses Booleans indicating if matching trader can trade
*/
function setTraderStatus(
ISetToken _setToken,
address[] memory _traders,
bool[] memory _statuses
)
external
onlyManagerAndValidSet(_setToken)
{
_traders.validatePairsWithArray(_statuses);
for (uint256 i = 0; i < _traders.length; i++) {
_updateTradersHistory(_setToken, _traders[i], _statuses[i]);
permissionInfo[_setToken].tradeAllowList[_traders[i]] = _statuses[i];
emit TraderStatusUpdated(_setToken, _traders[i], _statuses[i]);
}
}
/**
* MANAGER ONLY: Toggle whether anyone can trade, if true bypasses the traderAllowList. Can be called at anytime.
*
* @param _setToken Address of the SetToken
* @param _status Boolean indicating if anyone can trade
*/
function setAnyoneTrade(ISetToken _setToken, bool _status) external onlyManagerAndValidSet(_setToken) {
permissionInfo[_setToken].anyoneTrade = _status;
emit AnyoneTradeUpdated(_setToken, _status);
}
/**
* MANAGER ONLY: Called to initialize module to SetToken in order to allow GeneralIndexModule access for rebalances.
* Grabs the current units for each asset in the Set and set's the targetUnit to that unit in order to prevent any
* trading until startRebalance() is explicitly called. Position multiplier is also logged in order to make sure any
* position multiplier changes don't unintentionally open the Set for rebalancing.
*
* @param _setToken Address of the Set Token
*/
function initialize(ISetToken _setToken)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
ISetToken.Position[] memory positions = _setToken.getPositions();
for (uint256 i = 0; i < positions.length; i++) {
ISetToken.Position memory position = positions[i];
require(position.positionState == 0, "External positions not allowed");
executionInfo[_setToken][IERC20(position.component)].targetUnit = position.unit.toUint256();
executionInfo[_setToken][IERC20(position.component)].lastTradeTimestamp = 0;
}
rebalanceInfo[_setToken].positionMultiplier = _setToken.positionMultiplier().toUint256();
_setToken.initializeModule();
}
/**
* Called by a SetToken to notify that this module was removed from the SetToken.
* Clears the rebalanceInfo and permissionsInfo of the calling SetToken.
* IMPORTANT: SetToken's execution settings, including trade maximums and exchange names,
* are NOT DELETED. Restoring a previously removed module requires that care is taken to
* initialize execution settings appropriately.
*/
function removeModule() external override {
TradePermissionInfo storage tokenPermissionInfo = permissionInfo[ISetToken(msg.sender)];
for (uint i = 0; i < tokenPermissionInfo.tradersHistory.length; i++) {
tokenPermissionInfo.tradeAllowList[tokenPermissionInfo.tradersHistory[i]] = false;
}
delete rebalanceInfo[ISetToken(msg.sender)];
delete permissionInfo[ISetToken(msg.sender)];
}
/* ============ External View Functions ============ */
/**
* Get the array of SetToken components involved in rebalance.
*
* @param _setToken Address of the SetToken
*
* @return address[] Array of _setToken components involved in rebalance
*/
function getRebalanceComponents(ISetToken _setToken)
external
view
onlyValidAndInitializedSet(_setToken)
returns (address[] memory)
{
return rebalanceInfo[_setToken].rebalanceComponents;
}
/**
* Calculates the amount of a component that is going to be traded and whether the component is being bought
* or sold. If currentUnit and targetUnit are the same, function will revert.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
*
* @return isSendTokenFixed Boolean indicating fixed asset is send token
* @return componentQuantity Amount of component being traded
*/
function getComponentTradeQuantityAndDirection(
ISetToken _setToken,
IERC20 _component
)
external
view
onlyValidAndInitializedSet(_setToken)
returns (bool, uint256)
{
require(
rebalanceInfo[_setToken].rebalanceComponents.contains(address(_component)),
"Component not recognized"
);
uint256 totalSupply = _setToken.totalSupply();
return _calculateTradeSizeAndDirection(_setToken, _component, totalSupply);
}
/**
* Get if a given address is an allowed trader.
*
* @param _setToken Address of the SetToken
* @param _trader Address of the trader
*
* @return bool True if _trader is allowed to trade, else false
*/
function getIsAllowedTrader(ISetToken _setToken, address _trader)
external
view
onlyValidAndInitializedSet(_setToken)
returns (bool)
{
return _isAllowedTrader(_setToken, _trader);
}
/**
* Get the list of traders who are allowed to call trade(), tradeRemainingWeth(), and raiseAssetTarget()
*
* @param _setToken Address of the SetToken
*
* @return address[]
*/
function getAllowedTraders(ISetToken _setToken)
external
view
onlyValidAndInitializedSet(_setToken)
returns (address[] memory)
{
return permissionInfo[_setToken].tradersHistory;
}
/* ============ Internal Functions ============ */
/**
* A rebalance is a multi-step process in which current Set components are sold for a
* bridge asset (WETH) before buying target components in the correct amount to achieve
* the desired balance between elements in the set.
*
* Step 1 | Step 2
* -------------------------------------------
* Component --> WETH | WETH --> Component
* -------------------------------------------
*
* The syntax we use frames this as trading from a "fixed" amount of one component to a
* "fixed" amount of another via a "floating limit" which is *either* the maximum size of
* the trade we want to make (trades may be tranched to avoid moving markets) OR the minimum
* amount of tokens we expect to receive. The different meanings of the floating limit map to
* the trade sequence as below:
*
* Step 1: Component --> WETH
* ----------------------------------------------------------
* | Fixed | Floating limit |
* ----------------------------------------------------------
* send (Component) | YES | |
* recieve (WETH) | | Min WETH to receive |
* ----------------------------------------------------------
*
* Step 2: WETH --> Component
* ----------------------------------------------------------
* | Fixed | Floating limit |
* ----------------------------------------------------------
* send (WETH) | NO | Max WETH to send |
* recieve (Component) | YES | |
* ----------------------------------------------------------
*
* Additionally, there is an edge case where price volatility during a rebalance
* results in remaining WETH which needs to be allocated proportionately. In this case
* the values are as below:
*
* Edge case: Remaining WETH --> Component
* ----------------------------------------------------------
* | Fixed | Floating limit |
* ----------------------------------------------------------
* send (WETH) | YES | |
* recieve (Component) | | Min component to receive |
* ----------------------------------------------------------
*/
/**
* Create and return TradeInfo struct. This function reverts if the target has already been met.
* If this is a trade from component into WETH, sell the total fixed component quantity
* and expect to receive an ETH amount the user has specified (or more). If it's a trade from
* WETH into a component, sell the lesser of: the user's WETH limit OR the SetToken's
* remaining WETH balance and expect to receive a fixed component quantity.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
* @param _ethQuantityLimit Max/min amount of weth spent/received during trade
*
* @return tradeInfo Struct containing data for trade
*/
function _createTradeInfo(
ISetToken _setToken,
IERC20 _component,
uint256 _ethQuantityLimit
)
internal
view
virtual
returns (TradeInfo memory tradeInfo)
{
tradeInfo = _getDefaultTradeInfo(_setToken, _component, true);
if (tradeInfo.isSendTokenFixed){
tradeInfo.sendQuantity = tradeInfo.totalFixedQuantity;
tradeInfo.floatingQuantityLimit = _ethQuantityLimit;
} else {
tradeInfo.sendQuantity = _ethQuantityLimit.min(tradeInfo.preTradeSendTokenBalance);
tradeInfo.floatingQuantityLimit = tradeInfo.totalFixedQuantity;
}
}
/**
* Create and return TradeInfo struct. This function does NOT check if the WETH target has been met.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
* @param _minComponentReceived Min amount of component received during trade
*
* @return tradeInfo Struct containing data for tradeRemaining info
*/
function _createTradeRemainingInfo(
ISetToken _setToken,
IERC20 _component,
uint256 _minComponentReceived
)
internal
view
returns (TradeInfo memory tradeInfo)
{
tradeInfo = _getDefaultTradeInfo(_setToken, _component, false);
(,,
uint256 currentNotional,
uint256 targetNotional
) = _getUnitsAndNotionalAmounts(_setToken, weth, tradeInfo.setTotalSupply);
tradeInfo.sendQuantity = currentNotional.sub(targetNotional);
tradeInfo.floatingQuantityLimit = _minComponentReceived;
tradeInfo.isSendTokenFixed = true;
}
/**
* Create and returns a partial TradeInfo struct with all fields that overlap between `trade`
* and `tradeRemaining` info constructors filled in. Values for `sendQuantity` and `floatingQuantityLimit`
* are derived separately, outside this method. `trade` requires that trade size and direction are
* calculated, whereas `tradeRemaining` automatically sets WETH as the sendToken and _component
* as receiveToken.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
* @param calculateTradeDirection Indicates whether method should calculate trade size and direction
*
* @return tradeInfo Struct containing partial data for trade
*/
function _getDefaultTradeInfo(ISetToken _setToken, IERC20 _component, bool calculateTradeDirection)
internal
view
returns (TradeInfo memory tradeInfo)
{
tradeInfo.setToken = _setToken;
tradeInfo.setTotalSupply = _setToken.totalSupply();
tradeInfo.exchangeAdapter = _getExchangeAdapter(_setToken, _component);
tradeInfo.exchangeData = executionInfo[_setToken][_component].exchangeData;
if(calculateTradeDirection){
(
tradeInfo.isSendTokenFixed,
tradeInfo.totalFixedQuantity
) = _calculateTradeSizeAndDirection(_setToken, _component, tradeInfo.setTotalSupply);
}
if (tradeInfo.isSendTokenFixed){
tradeInfo.sendToken = address(_component);
tradeInfo.receiveToken = address(weth);
} else {
tradeInfo.sendToken = address(weth);
tradeInfo.receiveToken = address(_component);
}
tradeInfo.preTradeSendTokenBalance = IERC20(tradeInfo.sendToken).balanceOf(address(_setToken));
tradeInfo.preTradeReceiveTokenBalance = IERC20(tradeInfo.receiveToken).balanceOf(address(_setToken));
}
/**
* Function handles all interactions with exchange. All GeneralIndexModule adapters must allow for selling or buying a fixed
* quantity of a token in return for a non-fixed (floating) quantity of a token. If `isSendTokenFixed` is true then the adapter
* will choose the exchange interface associated with inputting a fixed amount, otherwise it will select the interface used for
* receiving a fixed amount. Any other exchange specific data can also be created by calling generateDataParam function.
*
* @param _tradeInfo Struct containing trade information used in internal functions
*/
function _executeTrade(TradeInfo memory _tradeInfo) internal virtual {
_tradeInfo.setToken.invokeApprove(
_tradeInfo.sendToken,
_tradeInfo.exchangeAdapter.getSpender(),
_tradeInfo.sendQuantity
);
(
address targetExchange,
uint256 callValue,
bytes memory methodData
) = _tradeInfo.exchangeAdapter.getTradeCalldata(
_tradeInfo.sendToken,
_tradeInfo.receiveToken,
address(_tradeInfo.setToken),
_tradeInfo.isSendTokenFixed,
_tradeInfo.sendQuantity,
_tradeInfo.floatingQuantityLimit,
_tradeInfo.exchangeData
);
_tradeInfo.setToken.invoke(targetExchange, callValue, methodData);
}
/**
* Retrieve fee from controller and calculate total protocol fee and send from SetToken to protocol recipient.
* The protocol fee is collected from the amount of received token in the trade.
*
* @param _tradeInfo Struct containing trade information used in internal functions
*
* @return protocolFee Amount of receive token taken as protocol fee
*/
function _accrueProtocolFee(TradeInfo memory _tradeInfo) internal returns (uint256 protocolFee) {
uint256 exchangedQuantity = IERC20(_tradeInfo.receiveToken)
.balanceOf(address(_tradeInfo.setToken))
.sub(_tradeInfo.preTradeReceiveTokenBalance);
protocolFee = getModuleFee(GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX, exchangedQuantity);
payProtocolFeeFromSetToken(_tradeInfo.setToken, _tradeInfo.receiveToken, protocolFee);
}
/**
* Update SetToken positions and executionInfo's last trade timestamp. This function is intended
* to be called after the fees have been accrued, hence it returns the amount of tokens bought net of fees.
*
* @param _tradeInfo Struct containing trade information used in internal functions
* @param _component IERC20 component which was traded
*
* @return netSendAmount Amount of sendTokens used in the trade
* @return netReceiveAmount Amount of receiveTokens received in the trade (net of fees)
*/
function _updatePositionStateAndTimestamp(TradeInfo memory _tradeInfo, IERC20 _component)
internal
returns (uint256 netSendAmount, uint256 netReceiveAmount)
{
(uint256 postTradeSendTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition(
_tradeInfo.sendToken,
_tradeInfo.setTotalSupply,
_tradeInfo.preTradeSendTokenBalance
);
(uint256 postTradeReceiveTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition(
_tradeInfo.receiveToken,
_tradeInfo.setTotalSupply,
_tradeInfo.preTradeReceiveTokenBalance
);
netSendAmount = _tradeInfo.preTradeSendTokenBalance.sub(postTradeSendTokenBalance);
netReceiveAmount = postTradeReceiveTokenBalance.sub(_tradeInfo.preTradeReceiveTokenBalance);
executionInfo[_tradeInfo.setToken][_component].lastTradeTimestamp = block.timestamp;
}
/**
* Adds or removes newly permissioned trader to/from permissionsInfo traderHistory. It's
* necessary to verify that traderHistory contains the address because AddressArrayUtils will
* throw when attempting to remove a non-element and it's possible someone can set a new
* trader's status to false.
*
* @param _setToken Instance of the SetToken
* @param _trader Trader whose permission is being set
* @param _status Boolean permission being set
*/
function _updateTradersHistory(ISetToken _setToken, address _trader, bool _status) internal {
if (_status && !permissionInfo[_setToken].tradersHistory.contains(_trader)) {
permissionInfo[_setToken].tradersHistory.push(_trader);
} else if(!_status && permissionInfo[_setToken].tradersHistory.contains(_trader)) {
permissionInfo[_setToken].tradersHistory.removeStorage(_trader);
}
}
/**
* Calculates the amount of a component is going to be traded and whether the component is being bought or sold.
* If currentUnit and targetUnit are the same, function will revert.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
* @param _totalSupply Total supply of _setToken
*
* @return isSendTokenFixed Boolean indicating fixed asset is send token
* @return totalFixedQuantity Amount of fixed token to send or receive
*/
function _calculateTradeSizeAndDirection(
ISetToken _setToken,
IERC20 _component,
uint256 _totalSupply
)
internal
view
returns (bool isSendTokenFixed, uint256 totalFixedQuantity)
{
uint256 protocolFee = controller.getModuleFee(address(this), GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX);
uint256 componentMaxSize = executionInfo[_setToken][_component].maxSize;
(
uint256 currentUnit,
uint256 targetUnit,
uint256 currentNotional,
uint256 targetNotional
) = _getUnitsAndNotionalAmounts(_setToken, _component, _totalSupply);
require(currentUnit != targetUnit, "Target already met");
isSendTokenFixed = targetNotional < currentNotional;
// In order to account for fees taken by protocol when buying the notional difference between currentUnit
// and targetUnit is divided by (1 - protocolFee) to make sure that targetUnit can be met. Failure to
// do so would lead to never being able to meet target of components that need to be bought.
//
// ? - lesserOf: (componentMaxSize, (currentNotional - targetNotional))
// : - lesserOf: (componentMaxSize, (targetNotional - currentNotional) / 10 ** 18 - protocolFee)
totalFixedQuantity = isSendTokenFixed
? componentMaxSize.min(currentNotional.sub(targetNotional))
: componentMaxSize.min(targetNotional.sub(currentNotional).preciseDiv(PreciseUnitMath.preciseUnit().sub(protocolFee)));
}
/**
* Check if all targets are met.
*
* @param _setToken Instance of the SetToken to be rebalanced
*
* @return bool True if all component's target units have been met, otherwise false
*/
function _allTargetsMet(ISetToken _setToken) internal view returns (bool) {
address[] memory rebalanceComponents = rebalanceInfo[_setToken].rebalanceComponents;
for (uint256 i = 0; i < rebalanceComponents.length; i++) {
if (_targetUnmet(_setToken, rebalanceComponents[i])) { return false; }
}
return true;
}
/**
* Determine if passed address is allowed to call trade for the SetToken. If anyoneTrade set to true anyone can call otherwise
* needs to be approved.
*
* @param _setToken Instance of SetToken to be rebalanced
* @param _trader Address of the trader who called contract function
*
* @return bool True if trader is an approved trader for the SetToken
*/
function _isAllowedTrader(ISetToken _setToken, address _trader) internal view returns (bool) {
TradePermissionInfo storage permissions = permissionInfo[_setToken];
return permissions.anyoneTrade || permissions.tradeAllowList[_trader];
}
/**
* Checks if sell conditions are met. The component cannot be WETH and its normalized target
* unit must be less than its default position real unit
*
* @param _setToken Instance of the SetToken to be rebalanced
* @param _component Component evaluated for sale
*
* @return bool True if sell allowed, false otherwise
*/
function _canSell(ISetToken _setToken, address _component) internal view returns(bool) {
return (
_component != address(weth) &&
(
_getNormalizedTargetUnit(_setToken, IERC20(_component)) <
_getDefaultPositionRealUnit(_setToken,IERC20(_component))
)
);
}
/**
* Check if there are any more tokens to sell. Since we allow WETH to float around it's target during rebalances it is not checked.
*
* @param _setToken Instance of the SetToken to be rebalanced
*
* @return bool True if there is not any component that can be sold, otherwise false
*/
function _noTokensToSell(ISetToken _setToken) internal view returns (bool) {
address[] memory rebalanceComponents = rebalanceInfo[_setToken].rebalanceComponents;
for (uint256 i = 0; i < rebalanceComponents.length; i++) {
if (_canSell(_setToken, rebalanceComponents[i]) ) { return false; }
}
return true;
}
/**
* Determines if a target is met. Due to small rounding errors converting between virtual and
* real unit on SetToken we allow for a 1 wei buffer when checking if target is met. In order to
* avoid subtraction overflow errors targetUnits of zero check for an exact amount. WETH is not
* checked as it is allowed to float around its target.
*
* @param _setToken Instance of the SetToken to be rebalanced
* @param _component Component whose target is evaluated
*
* @return bool True if component's target units are met, false otherwise
*/
function _targetUnmet(ISetToken _setToken, address _component) internal view returns(bool) {
if (_component == address(weth)) return false;
uint256 normalizedTargetUnit = _getNormalizedTargetUnit(_setToken, IERC20(_component));
uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, IERC20(_component));
return (normalizedTargetUnit > 0)
? !(normalizedTargetUnit.approximatelyEquals(currentUnit, 1))
: normalizedTargetUnit != currentUnit;
}
/**
* Validate component position unit has not exceeded it's target unit. This is used during tradeRemainingWETH() to make sure
* the amount of component bought does not exceed the targetUnit.
*
* @param _setToken Instance of the SetToken
* @param _component IERC20 component whose position units are to be validated
*/
function _validateComponentPositionUnit(ISetToken _setToken, IERC20 _component) internal view {
uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, _component);
uint256 targetUnit = _getNormalizedTargetUnit(_setToken, _component);
require(currentUnit <= targetUnit, "Can not exceed target unit");
}
/**
* Validate that component is a valid component and enough time has elapsed since component's last trade. Traders
* cannot explicitly trade WETH, it may only implicitly be traded by being the quote asset for other component trades.
*
* @param _setToken Instance of the SetToken
* @param _component IERC20 component to be validated
*/
function _validateTradeParameters(ISetToken _setToken, IERC20 _component) internal view virtual {
require(address(_component) != address(weth), "Can not explicitly trade WETH");
require(
rebalanceInfo[_setToken].rebalanceComponents.contains(address(_component)),
"Component not part of rebalance"
);
TradeExecutionParams memory componentInfo = executionInfo[_setToken][_component];
require(
componentInfo.lastTradeTimestamp.add(componentInfo.coolOffPeriod) <= block.timestamp,
"Component cool off in progress"
);
require(!_setToken.hasExternalPosition(address(_component)), "External positions not allowed");
}
/**
* Extends and/or updates the current component set and its target units with new components and targets,
* Validates inputs, requiring that that new components and new target units arrays are the same size, and
* that the number of old components target units matches the number of current components. Throws if
* a duplicate component has been added.
*
* @param _currentComponents Complete set of current SetToken components
* @param _newComponents Array of new components to add to allocation
* @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array
* @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of
* _setToken.getComponents() array, if component being removed set to 0.
*
* @return aggregateComponents Array of current components extended by new components, without duplicates
* @return aggregateTargetUnits Array of old component target units extended by new target units, without duplicates
*/
function _getAggregateComponentsAndUnits(
address[] memory _currentComponents,
address[] calldata _newComponents,
uint256[] calldata _newComponentsTargetUnits,
uint256[] calldata _oldComponentsTargetUnits
)
internal
pure
returns (address[] memory aggregateComponents, uint256[] memory aggregateTargetUnits)
{
// Don't use validate arrays because empty arrays are valid
require(_newComponents.length == _newComponentsTargetUnits.length, "Array length mismatch");
require(_currentComponents.length == _oldComponentsTargetUnits.length, "Old Components targets missing");
aggregateComponents = _currentComponents.extend(_newComponents);
aggregateTargetUnits = _oldComponentsTargetUnits.extend(_newComponentsTargetUnits);
require(!aggregateComponents.hasDuplicate(), "Cannot duplicate components");
}
/**
* Get the SetToken's default position as uint256
*
* @param _setToken Instance of the SetToken
* @param _component IERC20 component to fetch the default position for
*
* return uint256 Real unit position
*/
function _getDefaultPositionRealUnit(ISetToken _setToken, IERC20 _component) internal view returns (uint256) {
return _setToken.getDefaultPositionRealUnit(address(_component)).toUint256();
}
/**
* Gets exchange adapter address for a component after checking that it exists in the
* IntegrationRegistry. This method is called during a trade and must validate the adapter
* because its state may have changed since it was set in a separate transaction.
*
* @param _setToken Instance of the SetToken to be rebalanced
* @param _component IERC20 component whose exchange adapter is fetched
*
* @return IExchangeAdapter Adapter address
*/
function _getExchangeAdapter(ISetToken _setToken, IERC20 _component) internal view returns(IIndexExchangeAdapter) {
return IIndexExchangeAdapter(getAndValidateAdapter(executionInfo[_setToken][_component].exchangeName));
}
/**
* Calculates and returns the normalized target unit value.
*
* @param _setToken Instance of the SetToken to be rebalanced
* @param _component IERC20 component whose normalized target unit is required
*
* @return uint256 Normalized target unit of the component
*/
function _getNormalizedTargetUnit(ISetToken _setToken, IERC20 _component) internal view returns(uint256) {
// (targetUnit * current position multiplier) / position multiplier when rebalance started
return executionInfo[_setToken][_component]
.targetUnit
.mul(_setToken.positionMultiplier().toUint256())
.div(rebalanceInfo[_setToken].positionMultiplier);
}
/**
* Gets unit and notional amount values for current position and target. These are necessary
* to calculate the trade size and direction for regular trades and the `sendQuantity` for
* remainingWEth trades.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to calculate notional amounts for
* @param _totalSupply SetToken total supply
*
* @return uint256 Current default position real unit of component
* @return uint256 Normalized unit of the trade target
* @return uint256 Current notional amount: total notional amount of SetToken default position
* @return uint256 Target notional amount: Total SetToken supply * targetUnit
*/
function _getUnitsAndNotionalAmounts(ISetToken _setToken, IERC20 _component, uint256 _totalSupply)
internal
view
returns (uint256, uint256, uint256, uint256)
{
uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, _component);
uint256 targetUnit = _getNormalizedTargetUnit(_setToken, _component);
return (
currentUnit,
targetUnit,
_totalSupply.getDefaultTotalNotional(currentUnit),
_totalSupply.preciseMulCeil(targetUnit)
);
}
/* ============== Modifier Helpers ===============
* Internal functions used to reduce bytecode size
*/
/*
* Trader must be permissioned for SetToken
*/
function _validateOnlyAllowedTrader(ISetToken _setToken) internal view {
require(_isAllowedTrader(_setToken, msg.sender), "Address not permitted to trade");
}
/*
* Trade must be an EOA if `anyoneTrade` has been enabled for SetToken on the module.
*/
function _validateOnlyEOAIfUnrestricted(ISetToken _setToken) internal view {
if(permissionInfo[_setToken].anyoneTrade) {
require(msg.sender == tx.origin, "Caller must be EOA Address");
}
}
}
// 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;
/**
* @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);
}
}
// 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: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted 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 Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// 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, 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) {
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;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*
* CHANGELOG:
* - 4/21/21: Added validatePairsWithArray methods
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IIndexExchangeAdapter {
function getSpender() external view returns(address);
/**
* Returns calldata for executing trade on given adapter's exchange when using the GeneralIndexModule.
*
* @param _sourceToken Address of source token to be sold
* @param _destinationToken Address of destination token to buy
* @param _destinationAddress Address that assets should be transferred to
* @param _isSendTokenFixed Boolean indicating if the send quantity is fixed, used to determine correct trade interface
* @param _sourceQuantity Fixed/Max amount of source token to sell
* @param _destinationQuantity Min/Fixed amount of destination tokens to receive
* @param _data Arbitrary bytes that can be used to store exchange specific parameters or logic
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Trade calldata
*/
function getTradeCalldata(
address _sourceToken,
address _destinationToken,
address _destinationAddress,
bool _isSendTokenFixed,
uint256 _sourceQuantity,
uint256 _destinationQuantity,
bytes memory _data
)
external
view
returns (address, uint256, bytes memory);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
/**
* @title Invoke
* @author Set Protocol
*
* A collection of common utility functions for interacting with the SetToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the SetToken to set approvals of the ERC20 token to a spender.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the SetToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_setToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
* The new SetToken balance must equal the existing balance less the quantity transferred
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the SetToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));
Invoke.invokeTransfer(_setToken, _token, _to, _quantity);
// Get new balance of transferred token for SetToken
uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the SetToken to unwrap the passed quantity of WETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_setToken.invoke(_weth, 0, callData);
}
/**
* Instructs the SetToken to wrap the passed quantity of ETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Set Protocol
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol";
import { IController } from "../../interfaces/IController.sol";
import { IModule } from "../../interfaces/IModule.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { Invoke } from "./Invoke.sol";
import { Position } from "./Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "./ResourceIdentifier.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title ModuleBase
* @author Set Protocol
*
* Abstract class that houses common Module-related state and functions.
*
* CHANGELOG:
* - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size
*
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidSet(ISetToken _setToken) {
_validateOnlyManagerAndValidSet(_setToken);
_;
}
modifier onlySetManager(ISetToken _setToken, address _caller) {
_validateOnlySetManager(_setToken, _caller);
_;
}
modifier onlyValidAndInitializedSet(ISetToken _setToken) {
_validateOnlyValidAndInitializedSet(_setToken);
_;
}
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule(ISetToken _setToken) {
_validateOnlyModule(_setToken);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the SetToken is valid
*/
modifier onlyValidAndPendingSet(ISetToken _setToken) {
_validateOnlyValidAndPendingSet(_setToken);
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the SetToken
*/
function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {
return _setToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the SetToken's manager
*/
function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {
return _setToken.manager() == _toCheck;
}
/**
* Returns true if SetToken must be enabled on the controller
* and module is registered on the SetToken
*/
function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {
return controller.isSet(address(_setToken)) &&
_setToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
/* ============== Modifier Helpers ===============
* Internal functions used to reduce bytecode size
*/
/**
* Caller must SetToken manager and SetToken must be valid and initialized
*/
function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view {
require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager");
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
}
/**
* Caller must SetToken manager
*/
function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view {
require(isSetManager(_setToken, _caller), "Must be the SetToken manager");
}
/**
* SetToken must be valid and initialized
*/
function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view {
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
}
/**
* Caller must be initialized module and module must be enabled on the controller
*/
function _validateOnlyModule(ISetToken _setToken) internal view {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
/**
* SetToken must be in a pending state and module must be in pending state
*/
function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title Position
* @author Set Protocol
*
* Collection of helper functions for handling and updating SetToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the SetToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the SetToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ISetToken _setToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the SetToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _setToken Address of SetToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_setToken, _component)) {
_setToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) {
_setToken.removeComponent(_component);
}
}
_setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _setToken SetToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
_setToken.addExternalPositionModule(_component, _module);
} else if (!_setToken.isExternalPositionModule(_component, _module)) {
_setToken.addExternalPositionModule(_component, _module);
}
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
_setToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _setToken.getExternalPositionModules(_component);
if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_setToken.removeComponent(_component);
}
_setToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _setTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @param _setTotalSupply Current SetToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ISetToken _setToken,
address _component,
uint256 _setTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_setTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_setToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of SetToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
* - 4/21/21: Added approximatelyEquals function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
/**
* @dev Returns true if a =~ b within range, false otherwise.
*/
function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) {
return a <= b.add(range) && a >= b.sub(range);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title Uint256ArrayUtils
* @author Set Protocol
*
* Utility functions to handle Uint256 Arrays
*/
library Uint256ArrayUtils {
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
uint256[] memory newUints = new uint256[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newUints[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newUints[aLength + j] = B[j];
}
return newUints;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ExplicitERC20
* @author Set Protocol
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Set Protocol
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IController } from "../../interfaces/IController.sol";
import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
import { IPriceOracle } from "../../interfaces/IPriceOracle.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
/**
* @title ResourceIdentifier
* @author Set Protocol
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// SetValuer resource will always be resource ID 2 in the system
uint256 constant internal SET_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller
*/
function getSetValuer(IController _controller) internal view returns (ISetValuer) {
return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @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) {
// 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;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @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) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// 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);
}
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);
}
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Set Protocol
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "../interfaces/ISetToken.sol";
interface ISetValuer {
function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);
}
|
Checks if sell conditions are met. The component cannot be WETH and its normalized target unit must be less than its default position real unit _setToken Instance of the SetToken to be rebalanced _component Component evaluated for sale return bool True if sell allowed, false otherwise/
|
function _canSell(ISetToken _setToken, address _component) internal view returns(bool) {
return (
_component != address(weth) &&
(
_getNormalizedTargetUnit(_setToken, IERC20(_component)) <
_getDefaultPositionRealUnit(_setToken,IERC20(_component))
)
);
}
| 6,960,912
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "./Bridgebase.sol";
import "hardhat/console.sol";
contract ETHBridge is BridgeBase {
constructor(address token, address _admin) BridgeBase(token, _admin) {}
function depositTokens(
uint256 amount,
address recipient,
// uint256 nonce,
string memory _transactionID
) external override {
address sender = msg.sender;
require(
!whiteListOn || isWhiteList[msg.sender],
"ETHBridge: Forbidden in White List mode"
);
// require(
// !processedNonces[msg.sender][nonce],
// "ETHBridge: transfer already processed"
// );
//processedNonces[msg.sender][nonce] = true;
uint256 AmountwithFees = amount;
nonce[sender] += 1;
token.burn(sender, AmountwithFees);
emit TokenDeposit(
sender,
recipient,
AmountwithFees,
nonce[sender],
_transactionID
);
}
function withdrawTokens(
address from,
address to,
uint256 amount,
uint256 nonce,
bytes calldata signature
) external override {
address sender = msg.sender;
require(
!whiteListOn || isWhiteList[sender],
"ETHBridge: Forbidden in White List mode"
);
require(sender == from, "Irrelevant sender");
address signAddress;
bytes32 message = prefixed(
keccak256(abi.encodePacked(from, to, amount, nonce))
);
signAddress = recoverSigner(message, signature);
require(admin == signAddress, "ETHBridge: wrong signature");
require(
!processedNonces[sender][nonce],
"ETHBridge: transfer already processed"
);
processedNonces[sender][nonce] = true;
token.mint(to, amount);
emit TokenWithdraw(from, to, amount, nonce, signature);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IToken.sol";
// import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IERC20.sol";
import "hardhat/console.sol";
abstract contract BridgeBase is Ownable {
address public admin;
IToken public token;
uint256 internal fees;
// address public owner;
bool public whiteListOn;
mapping(address => mapping(uint256 => bool)) public processedNonces;
mapping(address => bool) public isWhiteList;
mapping(address => uint256) public nonce;
event TokenDeposit(
address indexed from,
address indexed to,
uint256 amount,
uint256 nonce,
string transactionID
);
event TokenWithdraw(
address indexed from,
address indexed to,
uint256 amount,
uint256 nonce,
bytes sign
);
event WhiteListToggled(bool state);
event WhiteListAddressToggled(
address _user,
address _bridgeAddress,
bool _state
);
constructor(address _token, address _admin) {
require(_token != address(0), "Token cannot be 0 address");
require(_admin != address(0), "Admin cannot be 0 address");
token = IToken(_token);
fees = 1;
admin = _admin;
// owner = msg.sender;
whiteListOn = !whiteListOn;
}
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return recover(message, v, r, s);
}
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// 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 in {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.
require(
uint256(s) <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "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;
}
function splitSignature(bytes memory sig)
internal
pure
returns (
uint8,
bytes32,
bytes32
)
{
require(sig.length == 65, "sig length invalid");
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function depositTokens(
uint256 amount,
address recipient,
// uint256 nonce,
string memory _transactionID
) external virtual;
function withdrawTokens(
address from,
address to,
uint256 amount,
uint256 nonce,
bytes calldata signature
) external virtual;
function toggleWhiteListOnly() external onlyOwner {
//require(msg.sender == owner, "Sender not Owner");
whiteListOn = !whiteListOn;
emit WhiteListToggled(whiteListOn);
}
function toggleWhiteListAddress(address[] calldata _addresses)
external
onlyOwner
{
// require(msg.sender == owner, "Sender not Owner");
require(_addresses.length <= 200, "Addresses length exceeded");
for (uint256 i = 0; i < _addresses.length; i++) {
isWhiteList[_addresses[i]] = !isWhiteList[_addresses[i]];
emit WhiteListAddressToggled(
_addresses[i],
address(this),
isWhiteList[_addresses[i]]
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
interface IToken {
function transferOwnership(address newOwner) external;
function mint(address to, uint256 amount) external;
function burn(address owner, uint256 amount) external;
function transfer(address recipient, uint256 amount) external;
function transferFrom(
address sender,
address recipient,
uint256 amount
) external;
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 tokens)
external
returns (bool success);
}
// 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
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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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 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);
}
|
require(msg.sender == owner, "Sender not Owner");
|
function toggleWhiteListAddress(address[] calldata _addresses)
external
onlyOwner
{
require(_addresses.length <= 200, "Addresses length exceeded");
for (uint256 i = 0; i < _addresses.length; i++) {
isWhiteList[_addresses[i]] = !isWhiteList[_addresses[i]];
emit WhiteListAddressToggled(
_addresses[i],
address(this),
isWhiteList[_addresses[i]]
);
}
}
| 14,640,689
|
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./PoolTokensContainer.sol";
import "./LiquidityPoolV2ConverterCustomFactory.sol";
import "../../LiquidityPoolConverter.sol";
import "../../interfaces/IConverterFactory.sol";
import "../../../utility/interfaces/IPriceOracle.sol";
/**
* @dev Liquidity Pool v2 Converter
*
* The liquidity pool v2 converter is a specialized version of a converter that uses
* price oracles to rebalance the reserve weights in such a way that the primary token
* balance always strives to match the staked balance.
*
* This type of liquidity pool always has 2 reserves and the reserve weights are dynamic.
*/
contract LiquidityPoolV2Converter is LiquidityPoolConverter {
uint32 internal constant HIGH_FEE_UPPER_BOUND = 997500; // high fee upper bound in PPM units
uint256 internal constant MAX_RATE_FACTOR_LOWER_BOUND = 1e30;
struct Fraction {
uint256 n; // numerator
uint256 d; // denominator
}
IPriceOracle public priceOracle; // external price oracle
IERC20Token public primaryReserveToken; // primary reserve in the pool
IERC20Token public secondaryReserveToken; // secondary reserve in the pool (cache)
mapping (IERC20Token => uint256) private stakedBalances; // tracks the staked liquidity in the pool plus the fees
mapping (IERC20Token => ISmartToken) private reservesToPoolTokens; // maps each reserve to its pool token
mapping (ISmartToken => IERC20Token) private poolTokensToReserves; // maps each pool token to its reserve
uint8 public amplificationFactor = 20; // factor to use for conversion calculations (reduces slippage)
uint256 public externalRatePropagationTime = 1 hours; // the time it takes for the external rate to fully take effect
uint256 public prevConversionTime; // previous conversion time in seconds
// factors used in fee calculations
uint32 public lowFeeFactor = 200000;
uint32 public highFeeFactor = 800000;
// used by the temp liquidity limit mechanism during the beta
mapping (IERC20Token => uint256) public maxStakedBalances;
bool public maxStakedBalanceEnabled = true;
/**
* @dev triggered when the amplification factor is updated
*
* @param _prevAmplificationFactor previous amplification factor
* @param _newAmplificationFactor new amplification factor
*/
event AmplificationFactorUpdate(uint8 _prevAmplificationFactor, uint8 _newAmplificationFactor);
/**
* @dev triggered when the external rate propagation time is updated
*
* @param _prevPropagationTime previous external rate propagation time, in seconds
* @param _newPropagationTime new external rate propagation time, in seconds
*/
event ExternalRatePropagationTimeUpdate(uint256 _prevPropagationTime, uint256 _newPropagationTime);
/**
* @dev triggered when the fee factors are updated
*
* @param _prevLowFactor previous low factor percentage, represented in ppm
* @param _newLowFactor new low factor percentage, represented in ppm
* @param _prevHighFactor previous high factor percentage, represented in ppm
* @param _newHighFactor new high factor percentage, represented in ppm
*/
event FeeFactorsUpdate(uint256 _prevLowFactor, uint256 _newLowFactor, uint256 _prevHighFactor, uint256 _newHighFactor);
/**
* @dev initializes a new LiquidityPoolV2Converter instance
*
* @param _poolTokensContainer pool tokens container governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(IPoolTokensContainer _poolTokensContainer, IContractRegistry _registry, uint32 _maxConversionFee)
public LiquidityPoolConverter(_poolTokensContainer, _registry, _maxConversionFee)
{
}
// ensures the address is a pool token
modifier validPoolToken(ISmartToken _address) {
_validPoolToken(_address);
_;
}
// error message binary size optimization
function _validPoolToken(ISmartToken _address) internal view {
require(address(poolTokensToReserves[_address]) != address(0), "ERR_INVALID_POOL_TOKEN");
}
/**
* @dev returns the converter type
*
* @return see the converter types in the the main contract doc
*/
function converterType() public override pure returns (uint16) {
return 2;
}
/**
* @dev returns true if the converter is active, false otherwise
*
* @return true if the converter is active, false otherwise
*/
function isActive() public override view returns (bool) {
return super.isActive() && address(priceOracle) != address(0);
}
/**
* @dev sets the pool's primary reserve token / price oracles and activates the pool
* each oracle must be able to provide the rate for each reserve token
* note that the oracle must be whitelisted prior to the call
* can only be called by the owner while the pool is inactive
*
* @param _primaryReserveToken address of the pool's primary reserve token
* @param _primaryReserveOracle address of a chainlink price oracle for the primary reserve token
* @param _secondaryReserveOracle address of a chainlink price oracle for the secondary reserve token
*/
function activate(
IERC20Token _primaryReserveToken,
IChainlinkPriceOracle _primaryReserveOracle,
IChainlinkPriceOracle _secondaryReserveOracle)
public
inactive
ownerOnly
validReserve(_primaryReserveToken)
notThis(address(_primaryReserveOracle))
notThis(address(_secondaryReserveOracle))
validAddress(address(_primaryReserveOracle))
validAddress(address(_secondaryReserveOracle))
{
// validate anchor ownership
require(anchor.owner() == address(this), "ERR_ANCHOR_NOT_OWNED");
// validate oracles
IWhitelist oracleWhitelist = IWhitelist(addressOf(CHAINLINK_ORACLE_WHITELIST));
require(oracleWhitelist.isWhitelisted(address(_primaryReserveOracle)) &&
oracleWhitelist.isWhitelisted(address(_secondaryReserveOracle)), "ERR_INVALID_ORACLE");
// create the converter's pool tokens if they don't already exist
createPoolTokens();
// sets the primary & secondary reserve tokens
primaryReserveToken = _primaryReserveToken;
if (_primaryReserveToken == reserveTokens[0])
secondaryReserveToken = reserveTokens[1];
else
secondaryReserveToken = reserveTokens[0];
// creates and initalizes the price oracle and sets initial rates
LiquidityPoolV2ConverterCustomFactory customFactory =
LiquidityPoolV2ConverterCustomFactory(address(IConverterFactory(addressOf(CONVERTER_FACTORY)).customFactories(converterType())));
priceOracle = customFactory.createPriceOracle(
_primaryReserveToken,
secondaryReserveToken,
_primaryReserveOracle,
_secondaryReserveOracle);
// if we are upgrading from an older converter, make sure that reserve balances are in-sync and rebalance
uint256 primaryReserveStakedBalance = reserveStakedBalance(primaryReserveToken);
uint256 primaryReserveBalance = reserveBalance(primaryReserveToken);
uint256 secondaryReserveBalance = reserveBalance(secondaryReserveToken);
if (primaryReserveStakedBalance == primaryReserveBalance) {
if (primaryReserveStakedBalance > 0 || secondaryReserveBalance > 0) {
rebalance();
}
}
else if (primaryReserveStakedBalance > 0 && primaryReserveBalance > 0 && secondaryReserveBalance > 0) {
rebalance();
}
emit Activation(converterType(), anchor, true);
}
/**
* @dev returns the staked balance of a given reserve token
*
* @param _reserveToken reserve token address
*
* @return staked balance
*/
function reserveStakedBalance(IERC20Token _reserveToken)
public
view
validReserve(_reserveToken)
returns (uint256)
{
return stakedBalances[_reserveToken];
}
/**
* @dev returns the amplified balance of a given reserve token
*
* @param _reserveToken reserve token address
*
* @return amplified balance
*/
function reserveAmplifiedBalance(IERC20Token _reserveToken)
public
view
validReserve(_reserveToken)
returns (uint256)
{
return amplifiedBalance(_reserveToken);
}
/**
* @dev sets the reserve's staked balance
* can only be called by the upgrader contract while the upgrader is the owner
*
* @param _reserveToken reserve token address
* @param _balance new reserve staked balance
*/
function setReserveStakedBalance(IERC20Token _reserveToken, uint256 _balance)
public
ownerOnly
only(CONVERTER_UPGRADER)
validReserve(_reserveToken)
{
stakedBalances[_reserveToken] = _balance;
}
/**
* @dev sets the max staked balance for both reserves
* available as a temporary mechanism during the beta
* can only be called by the owner
*
* @param _reserve1MaxStakedBalance max staked balance for reserve 1
* @param _reserve2MaxStakedBalance max staked balance for reserve 2
*/
function setMaxStakedBalances(uint256 _reserve1MaxStakedBalance, uint256 _reserve2MaxStakedBalance) public ownerOnly {
maxStakedBalances[reserveTokens[0]] = _reserve1MaxStakedBalance;
maxStakedBalances[reserveTokens[1]] = _reserve2MaxStakedBalance;
}
/**
* @dev disables the max staked balance mechanism
* available as a temporary mechanism during the beta
* once disabled, it cannot be re-enabled
* can only be called by the owner
*/
function disableMaxStakedBalances() public ownerOnly {
maxStakedBalanceEnabled = false;
}
/**
* @dev returns the pool token address by the reserve token address
*
* @param _reserveToken reserve token address
*
* @return pool token address
*/
function poolToken(IERC20Token _reserveToken) public view returns (ISmartToken) {
return reservesToPoolTokens[_reserveToken];
}
/**
* @dev returns the maximum number of pool tokens that can currently be liquidated
*
* @param _poolToken address of the pool token
*
* @return liquidation limit
*/
function liquidationLimit(ISmartToken _poolToken) public view returns (uint256) {
// get the pool token supply
uint256 poolTokenSupply = _poolToken.totalSupply();
// get the reserve token associated with the pool token and its balance / staked balance
IERC20Token reserveToken = poolTokensToReserves[_poolToken];
uint256 balance = reserveBalance(reserveToken);
uint256 stakedBalance = stakedBalances[reserveToken];
// calculate the amount that's available for liquidation
return balance.mul(poolTokenSupply).div(stakedBalance);
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive and
* 2 reserves aren't defined yet
*
* @param _token address of the reserve token
* @param _weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IERC20Token _token, uint32 _weight) public override ownerOnly {
// verify that the converter doesn't have 2 reserves yet
require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT");
super.addReserve(_token, _weight);
}
/**
* @dev returns the effective rate of 1 primary token in secondary tokens
*
* @return rate of 1 primary token in secondary tokens (numerator)
* @return rate of 1 primary token in secondary tokens (denominator)
*/
function effectiveTokensRate() public view returns (uint256, uint256) {
Fraction memory rate = rateFromPrimaryWeight(effectivePrimaryWeight());
return (rate.n, rate.d);
}
/**
* @dev returns the effective reserve tokens weights
*
* @return reserve1 weight
* @return reserve2 weight
*/
function effectiveReserveWeights() public view returns (uint256, uint256) {
uint32 primaryReserveWeight = effectivePrimaryWeight();
if (primaryReserveToken == reserveTokens[0]) {
return (primaryReserveWeight, inverseWeight(primaryReserveWeight));
}
return (inverseWeight(primaryReserveWeight), primaryReserveWeight);
}
/**
* @dev updates the amplification factor
* can only be called by the contract owner
*
* @param _amplificationFactor new amplification factor
*/
function setAmplificationFactor(uint8 _amplificationFactor) public ownerOnly {
emit AmplificationFactorUpdate(amplificationFactor, _amplificationFactor);
amplificationFactor = _amplificationFactor;
}
/**
* @dev updates the external rate propagation time
* can only be called by the contract owner
*
* @param _propagationTime new rate propagation time, in seconds
*/
function setExternalRatePropagationTime(uint256 _propagationTime) public ownerOnly {
emit ExternalRatePropagationTimeUpdate(externalRatePropagationTime, _propagationTime);
externalRatePropagationTime = _propagationTime;
}
/**
* @dev updates the fee factors
* can only be called by the contract owner
*
* @param _lowFactor new low fee factor, represented in ppm
* @param _highFactor new high fee factor, represented in ppm
*/
function setFeeFactors(uint32 _lowFactor, uint32 _highFactor) public ownerOnly {
require(_lowFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR");
require(_highFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR");
emit FeeFactorsUpdate(lowFeeFactor, _lowFactor, highFeeFactor, _highFactor);
lowFeeFactor = _lowFactor;
highFeeFactor = _highFactor;
}
/**
* @dev returns the expected target amount of converting one reserve to another along with the fee
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _amount amount of tokens received from the user
*
* @return expected target amount
* @return expected fee
*/
function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount)
public
override
view
active
validReserve(_sourceToken)
validReserve(_targetToken)
returns (uint256, uint256)
{
// validate input
require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
// get the external rate between the reserves along with its update time
Fraction memory externalRate;
uint256 externalRateUpdateTime;
(externalRate.n, externalRate.d, externalRateUpdateTime) =
priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken);
// get the source token effective / external weights
(uint32 sourceTokenWeight, uint32 externalSourceTokenWeight) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime);
if (_targetToken == primaryReserveToken) {
sourceTokenWeight = inverseWeight(sourceTokenWeight);
externalSourceTokenWeight = inverseWeight(externalSourceTokenWeight);
}
// return the target amount and the fee using the updated reserve weights
return targetAmountAndFee(
_sourceToken, _targetToken,
sourceTokenWeight, inverseWeight(sourceTokenWeight),
externalRate, inverseWeight(externalSourceTokenWeight),
_amount);
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary)
internal
override
active
validReserve(_sourceToken)
validReserve(_targetToken)
returns (uint256)
{
// convert and get the target amount and fee
(uint256 amount, uint256 fee) = doConvert(_sourceToken, _targetToken, _amount);
// update the previous conversion time
prevConversionTime = time();
// transfer funds to the beneficiary in the to reserve token
if (_targetToken == ETH_RESERVE_ADDRESS) {
_beneficiary.transfer(amount);
}
else {
safeTransfer(_targetToken, _beneficiary, amount);
}
// dispatch the conversion event
dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);
// dispatch rate updates for the pool / reserve tokens
dispatchRateEvents(_sourceToken, _targetToken, reserves[_sourceToken].weight, reserves[_targetToken].weight);
// return the conversion result amount
return amount;
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
*
* @return amount of target tokens received
* @return fee amount
*/
function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) private returns (uint256, uint256) {
// get the external rate between the reserves along with its update time
Fraction memory externalRate;
uint256 externalRateUpdateTime;
(externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken);
// pre-conversion preparation - update the weights if needed and get the target amount and feee
(uint256 targetAmount, uint256 fee) = prepareConversion(_sourceToken, _targetToken, _amount, externalRate, externalRateUpdateTime);
// ensure that the trade gives something in return
require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT");
// ensure that the trade won't deplete the reserve balance
uint256 targetReserveBalance = reserves[_targetToken].balance;
require(targetAmount < targetReserveBalance, "ERR_TARGET_AMOUNT_TOO_HIGH");
// ensure that the input amount was already deposited
if (_sourceToken == ETH_RESERVE_ADDRESS)
require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
else
require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserves[_sourceToken].balance) >= _amount, "ERR_INVALID_AMOUNT");
// sync the reserve balances
syncReserveBalance(_sourceToken);
reserves[_targetToken].balance = targetReserveBalance.sub(targetAmount);
// if the pool is in deficit, add half the fee to the target staked balance, otherwise add all
stakedBalances[_targetToken] = stakedBalances[_targetToken].add(calculateDeficit(externalRate) == 0 ? fee : fee / 2);
// return a tuple of [target amount (excluding fee), fee]
return (targetAmount, fee);
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
*
* @param _reserveToken address of the reserve token to add liquidity to
* @param _amount amount of liquidity to add
* @param _minReturn minimum return-amount of pool tokens
*
* @return amount of pool tokens minted
*/
function addLiquidity(IERC20Token _reserveToken, uint256 _amount, uint256 _minReturn)
public
payable
protected
active
validReserve(_reserveToken)
greaterThanZero(_amount)
greaterThanZero(_minReturn)
returns (uint256)
{
// verify that msg.value is identical to the provided amount for ETH reserve, or 0 otherwise
require(_reserveToken == ETH_RESERVE_ADDRESS ? msg.value == _amount : msg.value == 0, "ERR_ETH_AMOUNT_MISMATCH");
// sync the reserve balances just in case
syncReserveBalances();
// for ETH reserve, deduct the amount that was just synced (since it's already in the converter)
if (_reserveToken == ETH_RESERVE_ADDRESS) {
reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value);
}
// get the reserve staked balance before adding the liquidity to it
uint256 initialStakedBalance = stakedBalances[_reserveToken];
// during the beta, ensure that the new staked balance isn't greater than the max limit
if (maxStakedBalanceEnabled) {
require(maxStakedBalances[_reserveToken] == 0 || initialStakedBalance.add(_amount) <= maxStakedBalances[_reserveToken], "ERR_MAX_STAKED_BALANCE_REACHED");
}
// get the pool token associated with the reserve and its supply
ISmartToken reservePoolToken = reservesToPoolTokens[_reserveToken];
uint256 poolTokenSupply = reservePoolToken.totalSupply();
// for non ETH reserve, transfer the funds from the user to the pool
if (_reserveToken != ETH_RESERVE_ADDRESS)
safeTransferFrom(_reserveToken, msg.sender, address(this), _amount);
// get the rate before updating the staked balance
Fraction memory rate = rebalanceRate();
// sync the reserve balance / staked balance
reserves[_reserveToken].balance = reserves[_reserveToken].balance.add(_amount);
stakedBalances[_reserveToken] = initialStakedBalance.add(_amount);
// calculate how many pool tokens to mint
// for an empty pool, the price is 1:1, otherwise the price is based on the ratio
// between the pool token supply and the staked balance
uint256 poolTokenAmount = 0;
if (initialStakedBalance == 0 || poolTokenSupply == 0)
poolTokenAmount = _amount;
else
poolTokenAmount = _amount.mul(poolTokenSupply).div(initialStakedBalance);
require(poolTokenAmount >= _minReturn, "ERR_RETURN_TOO_LOW");
// mint new pool tokens to the caller
IPoolTokensContainer(address(anchor)).mint(reservePoolToken, msg.sender, poolTokenAmount);
// rebalance the pool's reserve weights
rebalance(rate);
// dispatch the LiquidityAdded event
emit LiquidityAdded(msg.sender, _reserveToken, _amount, initialStakedBalance.add(_amount), poolTokenSupply.add(poolTokenAmount));
// dispatch the `TokenRateUpdate` event for the pool token
dispatchPoolTokenRateUpdateEvent(reservePoolToken, poolTokenSupply.add(poolTokenAmount), _reserveToken);
// dispatch the `TokenRateUpdate` event for the reserve tokens
dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0);
// return the amount of pool tokens minted
return poolTokenAmount;
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
*
* @param _poolToken address of the pool token
* @param _amount amount of pool tokens to burn
* @param _minReturn minimum return-amount of reserve tokens
*
* @return amount of liquidity removed
*/
function removeLiquidity(ISmartToken _poolToken, uint256 _amount, uint256 _minReturn)
public
protected
active
validPoolToken(_poolToken)
greaterThanZero(_amount)
greaterThanZero(_minReturn)
returns (uint256)
{
// sync the reserve balances just in case
syncReserveBalances();
// get the pool token supply before burning the caller's shares
uint256 initialPoolSupply = _poolToken.totalSupply();
// get the reserve token return before burning the caller's shares
(uint256 reserveAmount, ) = removeLiquidityReturnAndFee(_poolToken, _amount);
require(reserveAmount >= _minReturn, "ERR_RETURN_TOO_LOW");
// get the reserve token associated with the pool token
IERC20Token reserveToken = poolTokensToReserves[_poolToken];
// burn the caller's pool tokens
IPoolTokensContainer(address(anchor)).burn(_poolToken, msg.sender, _amount);
// get the rate before updating the staked balance
Fraction memory rate = rebalanceRate();
// sync the reserve balance / staked balance
reserves[reserveToken].balance = reserves[reserveToken].balance.sub(reserveAmount);
uint256 newStakedBalance = stakedBalances[reserveToken].sub(reserveAmount);
stakedBalances[reserveToken] = newStakedBalance;
// transfer the reserve amount to the caller
if (reserveToken == ETH_RESERVE_ADDRESS)
msg.sender.transfer(reserveAmount);
else
safeTransfer(reserveToken, msg.sender, reserveAmount);
// rebalance the pool's reserve weights
rebalance(rate);
uint256 newPoolTokenSupply = initialPoolSupply.sub(_amount);
// dispatch the LiquidityRemoved event
emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newStakedBalance, newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
dispatchPoolTokenRateUpdateEvent(_poolToken, newPoolTokenSupply, reserveToken);
// dispatch the `TokenRateUpdate` event for the reserve tokens
dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0);
// return the amount of liquidity removed
return reserveAmount;
}
/**
* @dev calculates the amount of reserve tokens entitled for a given amount of pool tokens
* note that a fee is applied according to the equilibrium level of the primary reserve token
*
* @param _poolToken address of the pool token
* @param _amount amount of pool tokens
*
* @return amount after fee and fee, in reserve token units
*/
function removeLiquidityReturnAndFee(ISmartToken _poolToken, uint256 _amount) public view returns (uint256, uint256) {
uint256 totalSupply = _poolToken.totalSupply();
uint256 stakedBalance = stakedBalances[poolTokensToReserves[_poolToken]];
if (_amount < totalSupply) {
(uint256 min, uint256 max) = tokensRateAccuracy();
uint256 amountBeforeFee = _amount.mul(stakedBalance).div(totalSupply);
uint256 amountAfterFee = amountBeforeFee.mul(min).div(max);
return (amountAfterFee, amountBeforeFee - amountAfterFee);
}
return (stakedBalance, 0);
}
/**
* @dev calculates the tokens-rate accuracy
*
* @return the tokens-rate accuracy as a tuple of numerator and denominator
*/
function tokensRateAccuracy() internal view returns (uint256, uint256) {
uint32 weight = reserves[primaryReserveToken].weight;
Fraction memory poolRate = tokensRate(primaryReserveToken, secondaryReserveToken, weight, inverseWeight(weight));
(uint256 n, uint256 d) = effectiveTokensRate();
(uint256 x, uint256 y) = reducedRatio(poolRate.n.mul(d), poolRate.d.mul(n), MAX_RATE_FACTOR_LOWER_BOUND);
return x < y ? (x, y) : (y, x);
}
/**
* @dev returns the expected target amount of converting one reserve to another along with the fee
* this version of the function expects the reserve weights as an input (gas optimization)
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _sourceWeight source reserve token weight
* @param _targetWeight target reserve token weight
* @param _externalRate external rate of 1 primary token in secondary tokens
* @param _targetExternalWeight target reserve token weight based on external rate
* @param _amount amount of tokens received from the user
*
* @return expected target amount
* @return expected fee
*/
function targetAmountAndFee(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint32 _sourceWeight,
uint32 _targetWeight,
Fraction memory _externalRate,
uint32 _targetExternalWeight,
uint256 _amount)
private
view
returns (uint256, uint256)
{
// get the tokens amplified balances
uint256 sourceBalance = amplifiedBalance(_sourceToken);
uint256 targetBalance = amplifiedBalance(_targetToken);
// get the target amount
uint256 targetAmount = IBancorFormula(addressOf(BANCOR_FORMULA)).crossReserveTargetAmount(
sourceBalance,
_sourceWeight,
targetBalance,
_targetWeight,
_amount
);
// if the target amount is larger than the target reserve balance, return 0
// this can happen due to the amplification
require(targetAmount <= reserves[_targetToken].balance, "ERR_TARGET_AMOUNT_TOO_HIGH");
// return a tuple of [target amount (excluding fee), fee]
uint256 fee = calculateFee(_sourceToken, _targetToken, _sourceWeight, _targetWeight, _externalRate, _targetExternalWeight, targetAmount);
return (targetAmount - fee, fee);
}
/**
* @dev returns the fee amount for a given target amount
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _sourceWeight source reserve token weight
* @param _targetWeight target reserve token weight
* @param _externalRate external rate of 1 primary token in secondary tokens
* @param _targetExternalWeight target reserve token weight based on external rate
* @param _targetAmount target amount
*
* @return fee amount
*/
function calculateFee(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint32 _sourceWeight,
uint32 _targetWeight,
Fraction memory _externalRate,
uint32 _targetExternalWeight,
uint256 _targetAmount)
internal view returns (uint256)
{
// get the external rate of 1 source token in target tokens
Fraction memory targetExternalRate;
if (_targetToken == primaryReserveToken) {
(targetExternalRate.n, targetExternalRate.d) = (_externalRate.n, _externalRate.d);
}
else {
(targetExternalRate.n, targetExternalRate.d) = (_externalRate.d, _externalRate.n);
}
// get the token pool rate
Fraction memory currentRate = tokensRate(_targetToken, _sourceToken, _targetWeight, _sourceWeight);
if (compareRates(currentRate, targetExternalRate) < 0) {
uint256 lo = currentRate.n.mul(targetExternalRate.d);
uint256 hi = targetExternalRate.n.mul(currentRate.d);
(lo, hi) = reducedRatio(hi - lo, hi, MAX_RATE_FACTOR_LOWER_BOUND);
// apply the high fee only if the ratio between the effective weight and the external (target) weight is below the high fee upper bound
uint32 feeFactor;
if (uint256(_targetWeight).mul(PPM_RESOLUTION) < uint256(_targetExternalWeight).mul(HIGH_FEE_UPPER_BOUND)) {
feeFactor = highFeeFactor;
}
else {
feeFactor = lowFeeFactor;
}
return _targetAmount.mul(lo).mul(feeFactor).div(hi.mul(PPM_RESOLUTION));
}
return 0;
}
/**
* @dev calculates the deficit in the pool (in secondary reserve token amount)
*
* @param _externalRate external rate of 1 primary token in secondary tokens
*
* @return the deficit in the pool
*/
function calculateDeficit(Fraction memory _externalRate) internal view returns (uint256) {
IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization
IERC20Token secondaryReserveTokenLocal = secondaryReserveToken; // gas optimization
// get the amount of primary balances in secondary tokens using the external rate
uint256 primaryBalanceInSecondary = reserves[primaryReserveTokenLocal].balance.mul(_externalRate.n).div(_externalRate.d);
uint256 primaryStakedInSecondary = stakedBalances[primaryReserveTokenLocal].mul(_externalRate.n).div(_externalRate.d);
// if the total balance is lower than the total staked balance, return the delta
uint256 totalBalance = primaryBalanceInSecondary.add(reserves[secondaryReserveTokenLocal].balance);
uint256 totalStaked = primaryStakedInSecondary.add(stakedBalances[secondaryReserveTokenLocal]);
if (totalBalance < totalStaked) {
return totalStaked - totalBalance;
}
return 0;
}
/**
* @dev updates the weights based on the effective weights calculation if needed
* and returns the target amount and fee
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _externalRate external rate of 1 primary token in secondary tokens
* @param _externalRateUpdateTime external rate update time
*
* @return expected target amount
* @return expected fee
*/
function prepareConversion(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount,
Fraction memory _externalRate,
uint256 _externalRateUpdateTime)
internal
returns (uint256, uint256)
{
// get the source token effective / external weights
(uint32 effectiveSourceReserveWeight, uint32 externalSourceReserveWeight) =
effectiveAndExternalPrimaryWeight(_externalRate, _externalRateUpdateTime);
if (_targetToken == primaryReserveToken) {
effectiveSourceReserveWeight = inverseWeight(effectiveSourceReserveWeight);
externalSourceReserveWeight = inverseWeight(externalSourceReserveWeight);
}
// check if the weights need to be updated
if (reserves[_sourceToken].weight != effectiveSourceReserveWeight) {
// update the weights
reserves[_sourceToken].weight = effectiveSourceReserveWeight;
reserves[_targetToken].weight = inverseWeight(effectiveSourceReserveWeight);
}
// get expected target amount and fee
return targetAmountAndFee(
_sourceToken, _targetToken,
effectiveSourceReserveWeight, inverseWeight(effectiveSourceReserveWeight),
_externalRate, inverseWeight(externalSourceReserveWeight),
_amount);
}
/**
* @dev creates the converter's pool tokens
* note that technically pool tokens can be created on deployment but gas limit
* might get too high for a block, so creating them on first activation
*
*/
function createPoolTokens() internal {
IPoolTokensContainer container = IPoolTokensContainer(address(anchor));
ISmartToken[] memory poolTokens = container.poolTokens();
bool initialSetup = poolTokens.length == 0;
uint256 reserveCount = reserveTokens.length;
for (uint256 i = 0; i < reserveCount; i++) {
ISmartToken reservePoolToken;
if (initialSetup) {
reservePoolToken = container.createToken();
}
else {
reservePoolToken = poolTokens[i];
}
// cache the pool token address (gas optimization)
reservesToPoolTokens[reserveTokens[i]] = reservePoolToken;
poolTokensToReserves[reservePoolToken] = reserveTokens[i];
}
}
/**
* @dev returns the effective primary reserve token weight
*
* @return effective primary reserve weight
*/
function effectivePrimaryWeight() internal view returns (uint32) {
// get the external rate between the reserves along with its update time
Fraction memory externalRate;
uint256 externalRateUpdateTime;
(externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken);
(uint32 effectiveWeight,) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime);
return effectiveWeight;
}
/**
* @dev returns the effective and the external primary reserve token weights
*
* @param _externalRate external rate of 1 primary token in secondary tokens
* @param _externalRateUpdateTime external rate update time
*
* @return effective primary reserve weight
* @return external primary reserve weight
*/
function effectiveAndExternalPrimaryWeight(Fraction memory _externalRate, uint256 _externalRateUpdateTime)
internal
view
returns
(uint32, uint32)
{
// get the external rate primary reserve weight
uint32 externalPrimaryReserveWeight = primaryWeightFromRate(_externalRate);
// get the primary reserve weight
IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization
uint32 primaryReserveWeight = reserves[primaryReserveTokenLocal].weight;
// if the weights are already at their target, return current weights
if (primaryReserveWeight == externalPrimaryReserveWeight) {
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
// get the elapsed time since the last conversion time and the external rate update time
uint256 referenceTime = prevConversionTime;
if (referenceTime < _externalRateUpdateTime) {
referenceTime = _externalRateUpdateTime;
}
// limit the reference time by current time
uint256 currentTime = time();
if (referenceTime > currentTime) {
referenceTime = currentTime;
}
// if no time has passed since the reference time, return current weights (also ensures a single update per block)
uint256 elapsedTime = currentTime - referenceTime;
if (elapsedTime == 0) {
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
// find the token whose weight is lower than the target weight and get its pool rate - if it's
// lower than external rate, update the weights
Fraction memory poolRate = tokensRate(
primaryReserveTokenLocal,
secondaryReserveToken,
primaryReserveWeight,
inverseWeight(primaryReserveWeight));
bool updateWeights = false;
if (primaryReserveWeight < externalPrimaryReserveWeight) {
updateWeights = compareRates(poolRate, _externalRate) < 0;
}
else {
updateWeights = compareRates(poolRate, _externalRate) > 0;
}
if (!updateWeights) {
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
// if the elapsed time since the reference rate is equal or larger than the propagation time,
// the external rate should take full effect
if (elapsedTime >= externalRatePropagationTime) {
return (externalPrimaryReserveWeight, externalPrimaryReserveWeight);
}
// move the weights towards their target by the same proportion of elapsed time out of the rate propagation time
primaryReserveWeight = uint32(weightedAverageIntegers(
primaryReserveWeight, externalPrimaryReserveWeight,
elapsedTime, externalRatePropagationTime));
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
/**
* @dev returns the current rate for add/remove liquidity rebalancing
* only used to circumvent the `stack too deep` compiler error
*
* @return effective rate
*/
function rebalanceRate() private view returns (Fraction memory) {
// if one of the balances is 0, return the external rate
if (reserves[primaryReserveToken].balance == 0 || reserves[secondaryReserveToken].balance == 0) {
Fraction memory externalRate;
(externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken);
return externalRate;
}
// return the rate based on the current rate
return tokensRate(primaryReserveToken, secondaryReserveToken, 0, 0);
}
/**
* @dev updates the reserve weights based on the external rate
*/
function rebalance() private {
// get the external rate
Fraction memory externalRate;
(externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken);
// rebalance the weights based on the external rate
rebalance(externalRate);
}
/**
* @dev updates the reserve weights based on the given rate
*
* @param _rate rate of 1 primary token in secondary tokens
*/
function rebalance(Fraction memory _rate) private {
// get the new primary reserve weight
uint256 a = amplifiedBalance(primaryReserveToken).mul(_rate.n);
uint256 b = amplifiedBalance(secondaryReserveToken).mul(_rate.d);
(uint256 x, uint256 y) = normalizedRatio(a, b, PPM_RESOLUTION);
// update the reserve weights with the new values
reserves[primaryReserveToken].weight = uint32(x);
reserves[secondaryReserveToken].weight = uint32(y);
}
/**
* @dev returns the amplified balance of a given reserve token
* this version skips the input validation (gas optimization)
*
* @param _reserveToken reserve token address
*
* @return amplified balance
*/
function amplifiedBalance(IERC20Token _reserveToken) internal view returns (uint256) {
return stakedBalances[_reserveToken].mul(amplificationFactor - 1).add(reserves[_reserveToken].balance);
}
/**
* @dev returns the effective primary reserve weight based on the staked balance, current balance and given rate
*
* @param _rate rate of 1 primary token in secondary tokens
*
* @return primary reserve weight
*/
function primaryWeightFromRate(Fraction memory _rate) private view returns (uint32) {
uint256 a = stakedBalances[primaryReserveToken].mul(_rate.n);
uint256 b = stakedBalances[secondaryReserveToken].mul(_rate.d);
(uint256 x,) = normalizedRatio(a, b, PPM_RESOLUTION);
return uint32(x);
}
/**
* @dev returns the effective rate based on the staked balance, current balance and given primary reserve weight
*
* @param _primaryReserveWeight primary reserve weight
*
* @return effective rate of 1 primary token in secondary tokens
*/
function rateFromPrimaryWeight(uint32 _primaryReserveWeight) private view returns (Fraction memory) {
uint256 n = stakedBalances[secondaryReserveToken].mul(_primaryReserveWeight);
uint256 d = stakedBalances[primaryReserveToken].mul(inverseWeight(_primaryReserveWeight));
(n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND);
return Fraction(n, d);
}
/**
* @dev calculates and returns the rate between two reserve tokens
*
* @param _token1 contract address of the token to calculate the rate of one unit of
* @param _token2 contract address of the token to calculate the rate of one `_token1` unit in
* @param _token1Weight reserve weight of token1
* @param _token2Weight reserve weight of token2
*
* @return rate
*/
function tokensRate(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private view returns (Fraction memory) {
if (_token1Weight == 0) {
_token1Weight = reserves[_token1].weight;
}
if (_token2Weight == 0) {
_token2Weight = inverseWeight(_token1Weight);
}
uint256 n = amplifiedBalance(_token2).mul(_token1Weight);
uint256 d = amplifiedBalance(_token1).mul(_token2Weight);
(n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND);
return Fraction(n, d);
}
/**
* @dev dispatches rate events for both reserve tokens and for the target pool token
* only used to circumvent the `stack too deep` compiler error
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _sourceWeight source reserve token weight
* @param _targetWeight target reserve token weight
*/
function dispatchRateEvents(IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight) private {
dispatchTokenRateUpdateEvent(_sourceToken, _targetToken, _sourceWeight, _targetWeight);
// dispatch the `TokenRateUpdate` event for the pool token
// the target reserve pool token rate is the only one that's affected
// by conversions since conversion fees are applied to the target reserve
ISmartToken targetPoolToken = poolToken(_targetToken);
uint256 targetPoolTokenSupply = targetPoolToken.totalSupply();
dispatchPoolTokenRateUpdateEvent(targetPoolToken, targetPoolTokenSupply, _targetToken);
}
/**
* @dev dispatches token rate update event
* only used to circumvent the `stack too deep` compiler error
*
* @param _token1 contract address of the token to calculate the rate of one unit of
* @param _token2 contract address of the token to calculate the rate of one `_token1` unit in
* @param _token1Weight reserve weight of token1
* @param _token2Weight reserve weight of token2
*/
function dispatchTokenRateUpdateEvent(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private {
// dispatch token rate update event
Fraction memory rate = tokensRate(_token1, _token2, _token1Weight, _token2Weight);
emit TokenRateUpdate(_token1, _token2, rate.n, rate.d);
}
/**
* @dev dispatches the `TokenRateUpdate` for the pool token
* only used to circumvent the `stack too deep` compiler error
*
* @param _poolToken address of the pool token
* @param _poolTokenSupply total pool token supply
* @param _reserveToken address of the reserve token
*/
function dispatchPoolTokenRateUpdateEvent(ISmartToken _poolToken, uint256 _poolTokenSupply, IERC20Token _reserveToken) private {
emit TokenRateUpdate(_poolToken, _reserveToken, stakedBalances[_reserveToken], _poolTokenSupply);
}
// utilities
/**
* @dev returns the inverse weight for a given weight
*
* @param _weight reserve token weight
*
* @return reserve weight
*/
function inverseWeight(uint32 _weight) internal pure returns (uint32) {
return PPM_RESOLUTION - _weight;
}
/**
* @dev returns the current time
*/
function time() internal virtual view returns (uint256) {
return now;
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)".
*/
function normalizedRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) {
if (_a == _b)
return (_scale / 2, _scale / 2);
if (_a < _b)
return accurateRatio(_a, _b, _scale);
(uint256 y, uint256 x) = accurateRatio(_b, _a, _scale);
return (x, y);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a < b".
*/
function accurateRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) {
uint256 maxVal = uint256(-1) / _scale;
if (_a > maxVal) {
uint256 c = _a / (maxVal + 1) + 1;
_a /= c;
_b /= c;
}
uint256 x = roundDiv(_a * _scale, _a.add(_b));
uint256 y = _scale - x;
return (x, y);
}
/**
* @dev computes a reduced-scalar ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _max maximum desired scalar
*
* @return ratio's numerator and denominator
*/
function reducedRatio(uint256 _n, uint256 _d, uint256 _max) internal pure returns (uint256, uint256) {
if (_n > _max || _d > _max)
return normalizedRatio(_n, _d, _max);
return (_n, _d);
}
/**
* @dev computes the nearest integer to a given quotient without overflowing or underflowing.
*/
function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
return _n / _d + _n % _d / (_d - _d / 2);
}
/**
* @dev calculates the weighted-average of two integers
*
* @param _x first integer
* @param _y second integer
* @param _n factor numerator
* @param _d factor denominator
*
* @return the weighted-average of the given integers
*/
function weightedAverageIntegers(uint256 _x, uint256 _y, uint256 _n, uint256 _d) internal pure returns (uint256) {
return _x.mul(_d).add(_y.mul(_n)).sub(_x.mul(_n)).div(_d);
}
/**
* @dev compares two rates
*
* @param _rate1 first rate to compare
* @param _rate2 second rate to compare
*
* @return `-1` if `_rate1` is lower than `_rate2`, `1` if `_rate1` is higher than `_rate2`, 0 if the rates are identical
*/
function compareRates(Fraction memory _rate1, Fraction memory _rate2) internal pure returns (int8) {
uint256 x = _rate1.n.mul(_rate2.d);
uint256 y = _rate2.n.mul(_rate1.d);
if (x < y)
return -1;
if (x > y)
return 1;
return 0;
}
}
|
calculates and returns the rate between two reserve tokens _token1 contract address of the token to calculate the rate of one unit of _token2 contract address of the token to calculate the rate of one `_token1` unit in _token1Weight reserve weight of token1 _token2Weight reserve weight of token2 return rate/
|
function tokensRate(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private view returns (Fraction memory) {
if (_token1Weight == 0) {
_token1Weight = reserves[_token1].weight;
}
if (_token2Weight == 0) {
_token2Weight = inverseWeight(_token1Weight);
}
uint256 n = amplifiedBalance(_token2).mul(_token1Weight);
uint256 d = amplifiedBalance(_token1).mul(_token2Weight);
(n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND);
return Fraction(n, d);
}
| 1,066,853
|
/*
Copyright 2020 Empty Set Squad <emptysetsquad@protonmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Setters.sol";
import "../external/Require.sol";
contract Comptroller is Setters {
using SafeMath for uint256;
bytes32 private constant FILE = "Comptroller";
function mintToAccount(address account, uint256 amount) internal {
dollar().mint(account, amount);
if (!bootstrappingAt(epoch())) {
increaseDebt(amount);
}
balanceCheck();
}
function burnFromAccount(address account, uint256 amount) internal {
dollar().transferFrom(account, address(this), amount);
dollar().burn(amount);
decrementTotalDebt(amount, "Comptroller: not enough outstanding debt");
balanceCheck();
}
function redeemToAccount(address account, uint256 amount) internal {
dollar().transfer(account, amount);
decrementTotalRedeemable(amount, "Comptroller: not enough redeemable balance");
balanceCheck();
}
function burnRedeemable(uint256 amount) internal {
dollar().burn(amount);
decrementTotalRedeemable(amount, "Comptroller: not enough redeemable balance");
balanceCheck();
}
function increaseDebt(uint256 amount) internal {
incrementTotalDebt(amount);
resetDebt(Constants.getDebtRatioCap());
balanceCheck();
}
function decreaseDebt(uint256 amount) internal {
decrementTotalDebt(amount, "Comptroller: not enough debt");
balanceCheck();
}
function increaseSupply(uint256 newSupply) internal returns (uint256, uint256, uint256) {
(uint256 newRedeemable, uint256 lessDebt) = (0, 0);
// 1. True up redeemable pool
uint256 totalRedeemable = totalRedeemable();
uint256 totalCoupons = totalCoupons();
if (totalRedeemable < totalCoupons) {
newRedeemable = totalCoupons.sub(totalRedeemable);
newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable;
mintToRedeemable(newRedeemable);
newSupply = newSupply.sub(newRedeemable);
}
// 2. Eliminate debt
uint256 totalDebt = totalDebt();
if (newSupply > 0 && totalDebt > 0) {
lessDebt = totalDebt > newSupply ? newSupply : totalDebt;
decreaseDebt(lessDebt);
newSupply = newSupply.sub(lessDebt);
}
// 3. Payout to bonded
if (totalBonded() == 0) {
newSupply = 0;
}
if (newSupply > 0) {
mintToBonded(newSupply);
}
return (newRedeemable, lessDebt, newSupply);
}
function resetDebt(Decimal.D256 memory targetDebtRatio) internal {
uint256 targetDebt = targetDebtRatio.mul(dollar().totalSupply()).asUint256();
uint256 currentDebt = totalDebt();
if (currentDebt > targetDebt) {
uint256 lessDebt = currentDebt.sub(targetDebt);
decreaseDebt(lessDebt);
}
}
function balanceCheck() private {
Require.that(
dollar().balanceOf(address(this)) >= totalBonded().add(totalStaged()).add(totalRedeemable()),
FILE,
"Inconsistent balances"
);
}
function mintToBonded(uint256 amount) private {
Require.that(
totalBonded() > 0,
FILE,
"Cant mint to empty pool"
);
uint256 poolAmount = amount.mul(Constants.getOraclePoolRatio()).div(100);
uint256 daoAmount = amount > poolAmount ? amount.sub(poolAmount) : 0;
if (poolAmount > 0) {
dollar().mint(pool(), poolAmount);
}
if (daoAmount > 0) {
dollar().mint(address(this), daoAmount);
incrementTotalBonded(daoAmount);
}
balanceCheck();
}
function mintToRedeemable(uint256 amount) private {
dollar().mint(address(this), amount);
incrementTotalRedeemable(amount);
balanceCheck();
}
}
|
1. True up redeemable pool 3. Payout to bonded
|
function increaseSupply(uint256 newSupply) internal returns (uint256, uint256, uint256) {
(uint256 newRedeemable, uint256 lessDebt) = (0, 0);
uint256 totalRedeemable = totalRedeemable();
uint256 totalCoupons = totalCoupons();
if (totalRedeemable < totalCoupons) {
newRedeemable = totalCoupons.sub(totalRedeemable);
newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable;
mintToRedeemable(newRedeemable);
newSupply = newSupply.sub(newRedeemable);
}
if (newSupply > 0 && totalDebt > 0) {
lessDebt = totalDebt > newSupply ? newSupply : totalDebt;
decreaseDebt(lessDebt);
newSupply = newSupply.sub(lessDebt);
}
if (totalBonded() == 0) {
newSupply = 0;
}
if (newSupply > 0) {
mintToBonded(newSupply);
}
return (newRedeemable, lessDebt, newSupply);
}
| 13,089,533
|
./full_match/1/0xeFFe069b1c62c2f55F41A501eCc3c6Ff4dB6D70a/sources/src/modules/price-router/PriceRouter.sol
|
Get the exchange rates between multiple assets and another asset. baseAssets addresses of the assets to get the exchange rates of in terms of the quote asset quoteAsset address of the asset that the base assets are exchanged for return exchangeRates rate of exchange between the base assets and the quote asset/ Create an empty Price Cache.
|
function getExchangeRates(ERC20[] memory baseAssets, ERC20 quoteAsset)
external
view
returns (uint256[] memory exchangeRates)
{
uint8 quoteAssetDecimals = quoteAsset.decimals();
AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];
if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset));
PriceCache[PRICE_CACHE_SIZE] memory cache;
uint256 numOfAssets = baseAssets.length;
exchangeRates = new uint256[](numOfAssets);
for (uint256 i; i < numOfAssets; i++) {
AssetSettings memory baseSettings = getAssetSettings[baseAssets[i]];
if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAssets[i]));
exchangeRates[i] = _getExchangeRate(
baseAssets[i],
baseSettings,
quoteAsset,
quoteSettings,
quoteAssetDecimals,
cache
);
}
}
| 3,124,343
|
// SPDX-License-Identifier: MIT
// 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 disstributed 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.3;
// Finds new Curves! logs their addresses and provides `isCurve(address) -> (bool)`
import "./Curve.sol";
import "./interfaces/IFreeFromUpTo.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract CurveFactory is Ownable {
event NewCurve(address indexed caller, bytes32 indexed id, address indexed curve);
mapping(bytes32 => address) public curves;
function getCurve(address _baseCurrency, address _quoteCurrency) external view returns (address) {
bytes32 curveId = keccak256(abi.encode(_baseCurrency, _quoteCurrency));
return (curves[curveId]);
}
function newCurve(
string memory _name,
string memory _symbol,
address _baseCurrency,
address _quoteCurrency,
uint256 _baseWeight,
uint256 _quoteWeight,
address _baseAssimilator,
address _quoteAssimilator
) public onlyOwner returns (Curve) {
bytes32 curveId = keccak256(abi.encode(_baseCurrency, _quoteCurrency));
if (curves[curveId] != address(0)) revert("CurveFactory/currency-pair-already-exists");
address[] memory _assets = new address[](10);
uint256[] memory _assetWeights = new uint256[](2);
// Base Currency
_assets[0] = _baseCurrency;
_assets[1] = _baseAssimilator;
_assets[2] = _baseCurrency;
_assets[3] = _baseAssimilator;
_assets[4] = _baseCurrency;
// Quote Currency (typically USDC)
_assets[5] = _quoteCurrency;
_assets[6] = _quoteAssimilator;
_assets[7] = _quoteCurrency;
_assets[8] = _quoteAssimilator;
_assets[9] = _quoteCurrency;
// Weights
_assetWeights[0] = _baseWeight;
_assetWeights[1] = _quoteWeight;
// New curve
Curve curve = new Curve(_name, _symbol, _assets, _assetWeights);
curve.transferOwnership(msg.sender);
curves[curveId] = address(curve);
emit NewCurve(msg.sender, curveId, address(curve));
return curve;
}
}
// SPDX-License-Identifier: MIT
// 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.3;
import "./lib/ABDKMath64x64.sol";
import "./Orchestrator.sol";
import "./ProportionalLiquidity.sol";
import "./Swaps.sol";
import "./ViewLiquidity.sol";
import "./Storage.sol";
import "./MerkleProver.sol";
import "./interfaces/IFreeFromUpTo.sol";
library Curves {
using ABDKMath64x64 for int128;
event Approval(address indexed _owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function add(
uint256 x,
uint256 y,
string memory errorMessage
) private pure returns (uint256 z) {
require((z = x + y) >= x, errorMessage);
}
function sub(
uint256 x,
uint256 y,
string memory errorMessage
) private pure returns (uint256 z) {
require((z = x - y) <= x, errorMessage);
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(
Storage.Curve storage curve,
address recipient,
uint256 amount
) external returns (bool) {
_transfer(curve, msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(
Storage.Curve storage curve,
address spender,
uint256 amount
) external returns (bool) {
_approve(curve, 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(
Storage.Curve storage curve,
address sender,
address recipient,
uint256 amount
) external returns (bool) {
_transfer(curve, sender, recipient, amount);
_approve(
curve,
sender,
msg.sender,
sub(curve.allowances[sender][msg.sender], amount, "Curve/insufficient-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(
Storage.Curve storage curve,
address spender,
uint256 addedValue
) external returns (bool) {
_approve(
curve,
msg.sender,
spender,
add(curve.allowances[msg.sender][spender], addedValue, "Curve/approval-overflow")
);
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(
Storage.Curve storage curve,
address spender,
uint256 subtractedValue
) external returns (bool) {
_approve(
curve,
msg.sender,
spender,
sub(curve.allowances[msg.sender][spender], subtractedValue, "Curve/allowance-decrease-underflow")
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is public 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(
Storage.Curve storage curve,
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
curve.balances[sender] = sub(curve.balances[sender], amount, "Curve/insufficient-balance");
curve.balances[recipient] = add(curve.balances[recipient], amount, "Curve/transfer-overflow");
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `_owner`s tokens.
*
* This is public 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(
Storage.Curve storage curve,
address _owner,
address spender,
uint256 amount
) private {
require(_owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
curve.allowances[_owner][spender] = amount;
emit Approval(_owner, spender, amount);
}
}
contract Curve is Storage, MerkleProver {
using SafeMath for uint256;
event Approval(address indexed _owner, address indexed spender, uint256 value);
event ParametersSet(uint256 alpha, uint256 beta, uint256 delta, uint256 epsilon, uint256 lambda);
event AssetIncluded(address indexed numeraire, address indexed reserve, uint256 weight);
event AssimilatorIncluded(
address indexed derivative,
address indexed numeraire,
address indexed reserve,
address assimilator
);
event PartitionRedeemed(address indexed token, address indexed redeemer, uint256 value);
event OwnershipTransfered(address indexed previousOwner, address indexed newOwner);
event FrozenSet(bool isFrozen);
event EmergencyAlarm(bool isEmergency);
event WhitelistingStopped();
event Trade(
address indexed trader,
address indexed origin,
address indexed target,
uint256 originAmount,
uint256 targetAmount
);
event Transfer(address indexed from, address indexed to, uint256 value);
modifier onlyOwner() {
require(msg.sender == owner, "Curve/caller-is-not-owner");
_;
}
modifier nonReentrant() {
require(notEntered, "Curve/re-entered");
notEntered = false;
_;
notEntered = true;
}
modifier transactable() {
require(!frozen, "Curve/frozen-only-allowing-proportional-withdraw");
_;
}
modifier isEmergency() {
require(emergency, "Curve/emergency-only-allowing-emergency-proportional-withdraw");
_;
}
modifier deadline(uint256 _deadline) {
require(block.timestamp < _deadline, "Curve/tx-deadline-passed");
_;
}
modifier inWhitelistingStage() {
require(whitelistingStage, "Curve/whitelist-stage-on-going");
_;
}
modifier notInWhitelistingStage() {
require(!whitelistingStage, "Curve/whitelist-stage-stopped");
_;
}
modifier underCap(uint256 amount) {
( uint256 total_, ) = liquidity();
require(curve.cap == 0 || curve.cap > amount.add(total_), "Curve/amount-too-large");
_;
}
constructor(
string memory _name,
string memory _symbol,
address[] memory _assets,
uint256[] memory _assetWeights
) {
owner = msg.sender;
name = _name;
symbol = _symbol;
emit OwnershipTransfered(address(0), msg.sender);
Orchestrator.initialize(curve, numeraires, reserves, derivatives, _assets, _assetWeights);
}
/// @notice sets the parameters for the pool
/// @param _alpha the value for alpha (halt threshold) must be less than or equal to 1 and greater than 0
/// @param _beta the value for beta must be less than alpha and greater than 0
/// @param _feeAtHalt the maximum value for the fee at the halt point
/// @param _epsilon the base fee for the pool
/// @param _lambda the value for lambda must be less than or equal to 1 and greater than zero
function setParams(
uint256 _alpha,
uint256 _beta,
uint256 _feeAtHalt,
uint256 _epsilon,
uint256 _lambda
) external onlyOwner {
Orchestrator.setParams(curve, _alpha, _beta, _feeAtHalt, _epsilon, _lambda);
}
/// @notice excludes an assimilator from the curve
/// @param _derivative the address of the assimilator to exclude
function excludeDerivative(address _derivative) external onlyOwner {
for (uint256 i = 0; i < numeraires.length; i++) {
if (_derivative == numeraires[i]) revert("Curve/cannot-delete-numeraire");
if (_derivative == reserves[i]) revert("Curve/cannot-delete-reserve");
}
delete curve.assimilators[_derivative];
}
/// @notice view the current parameters of the curve
/// @return alpha_ the current alpha value
/// beta_ the current beta value
/// delta_ the current delta value
/// epsilon_ the current epsilon value
/// lambda_ the current lambda value
/// omega_ the current omega value
function viewCurve()
external
view
returns (
uint256 alpha_,
uint256 beta_,
uint256 delta_,
uint256 epsilon_,
uint256 lambda_
)
{
return Orchestrator.viewCurve(curve);
}
function turnOffWhitelisting() external onlyOwner {
emit WhitelistingStopped();
whitelistingStage = false;
}
function setEmergency(bool _emergency) external onlyOwner {
emit EmergencyAlarm(_emergency);
emergency = _emergency;
}
function setFrozen(bool _toFreezeOrNotToFreeze) external onlyOwner {
emit FrozenSet(_toFreezeOrNotToFreeze);
frozen = _toFreezeOrNotToFreeze;
}
function transferOwnership(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "Curve/new-owner-cannot-be-zeroth-address");
emit OwnershipTransfered(owner, _newOwner);
owner = _newOwner;
}
/// @notice swap a dynamic origin amount for a fixed target amount
/// @param _origin the address of the origin
/// @param _target the address of the target
/// @param _originAmount the origin amount
/// @param _minTargetAmount the minimum target amount
/// @param _deadline deadline in block number after which the trade will not execute
/// @return targetAmount_ the amount of target that has been swapped for the origin amount
function originSwap(
address _origin,
address _target,
uint256 _originAmount,
uint256 _minTargetAmount,
uint256 _deadline
) external deadline(_deadline) transactable nonReentrant returns (uint256 targetAmount_) {
targetAmount_ = Swaps.originSwap(curve, _origin, _target, _originAmount, msg.sender);
require(targetAmount_ >= _minTargetAmount, "Curve/below-min-target-amount");
}
/// @notice view how much target amount a fixed origin amount will swap for
/// @param _origin the address of the origin
/// @param _target the address of the target
/// @param _originAmount the origin amount
/// @return targetAmount_ the target amount that would have been swapped for the origin amount
function viewOriginSwap(
address _origin,
address _target,
uint256 _originAmount
) external view transactable returns (uint256 targetAmount_) {
targetAmount_ = Swaps.viewOriginSwap(curve, _origin, _target, _originAmount);
}
/// @notice swap a dynamic origin amount for a fixed target amount
/// @param _origin the address of the origin
/// @param _target the address of the target
/// @param _maxOriginAmount the maximum origin amount
/// @param _targetAmount the target amount
/// @param _deadline deadline in block number after which the trade will not execute
/// @return originAmount_ the amount of origin that has been swapped for the target
function targetSwap(
address _origin,
address _target,
uint256 _maxOriginAmount,
uint256 _targetAmount,
uint256 _deadline
) external deadline(_deadline) transactable nonReentrant returns (uint256 originAmount_) {
originAmount_ = Swaps.targetSwap(curve, _origin, _target, _targetAmount, msg.sender);
require(originAmount_ <= _maxOriginAmount, "Curve/above-max-origin-amount");
}
/// @notice view how much of the origin currency the target currency will take
/// @param _origin the address of the origin
/// @param _target the address of the target
/// @param _targetAmount the target amount
/// @return originAmount_ the amount of target that has been swapped for the origin
function viewTargetSwap(
address _origin,
address _target,
uint256 _targetAmount
) external view transactable returns (uint256 originAmount_) {
originAmount_ = Swaps.viewTargetSwap(curve, _origin, _target, _targetAmount);
}
/// @notice deposit into the pool with no slippage from the numeraire assets the pool supports
/// @param index Index corresponding to the merkleProof
/// @param account Address coorresponding to the merkleProof
/// @param amount Amount coorresponding to the merkleProof, should always be 1
/// @param merkleProof Merkle proof
/// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst
/// the numeraire assets of the pool
/// @return (the amount of curves you receive in return for your deposit,
/// the amount deposited for each numeraire)
function depositWithWhitelist(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
uint256 _deposit,
uint256 _deadline
) external deadline(_deadline) transactable nonReentrant inWhitelistingStage returns (uint256, uint256[] memory) {
require(isWhitelisted(index, account, amount, merkleProof), "Curve/not-whitelisted");
require(msg.sender == account, "Curve/not-approved-user");
(uint256 curvesMinted_, uint256[] memory deposits_) =
ProportionalLiquidity.proportionalDeposit(curve, _deposit);
whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].add(curvesMinted_);
// 10k max deposit
if (whitelistedDeposited[msg.sender] > 10000e18) {
revert("Curve/exceed-whitelist-maximum-deposit");
}
return (curvesMinted_, deposits_);
}
/// @notice deposit into the pool with no slippage from the numeraire assets the pool supports
/// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst
/// the numeraire assets of the pool
/// @return (the amount of curves you receive in return for your deposit,
/// the amount deposited for each numeraire)
function deposit(uint256 _deposit, uint256 _deadline)
external
deadline(_deadline)
transactable
nonReentrant
notInWhitelistingStage
underCap(_deposit)
returns (uint256, uint256[] memory)
{
return ProportionalLiquidity.proportionalDeposit(curve, _deposit);
}
/// @notice view deposits and curves minted a given deposit would return
/// @param _deposit the full amount of stablecoins you want to deposit. Divided evenly according to the
/// prevailing proportions of the numeraire assets of the pool
/// @return (the amount of curves you receive in return for your deposit,
/// the amount deposited for each numeraire)
function viewDeposit(uint256 _deposit) external view transactable underCap(_deposit) returns (uint256, uint256[] memory) {
// curvesToMint_, depositsToMake_
return ProportionalLiquidity.viewProportionalDeposit(curve, _deposit);
}
/// @notice Emergency withdraw tokens in the event that the oracle somehow bugs out
/// and no one is able to withdraw due to the invariant check
/// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the
/// numeraire assets of the pool
/// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool
function emergencyWithdraw(uint256 _curvesToBurn, uint256 _deadline)
external
isEmergency
deadline(_deadline)
nonReentrant
returns (uint256[] memory withdrawals_)
{
return ProportionalLiquidity.emergencyProportionalWithdraw(curve, _curvesToBurn);
}
/// @notice withdrawas amount of curve tokens from the the pool equally from the numeraire assets of the pool with no slippage
/// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the
/// numeraire assets of the pool
/// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool
function withdraw(uint256 _curvesToBurn, uint256 _deadline)
external
deadline(_deadline)
nonReentrant
returns (uint256[] memory withdrawals_)
{
if (whitelistingStage) {
whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].sub(_curvesToBurn);
}
return ProportionalLiquidity.proportionalWithdraw(curve, _curvesToBurn);
}
/// @notice views the withdrawal information from the pool
/// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the
/// numeraire assets of the pool
/// @return the amonnts of numeraire assets withdrawn from the pool
function viewWithdraw(uint256 _curvesToBurn) external view transactable returns (uint256[] memory) {
return ProportionalLiquidity.viewProportionalWithdraw(curve, _curvesToBurn);
}
function supportsInterface(bytes4 _interface) public pure returns (bool supports_) {
supports_ =
this.supportsInterface.selector == _interface || // erc165
bytes4(0x7f5828d0) == _interface || // eip173
bytes4(0x36372b07) == _interface; // erc20
}
/// @notice transfers curve tokens
/// @param _recipient the address of where to send the curve tokens
/// @param _amount the amount of curve tokens to send
/// @return success_ the success bool of the call
function transfer(address _recipient, uint256 _amount) public nonReentrant returns (bool success_) {
success_ = Curves.transfer(curve, _recipient, _amount);
}
/// @notice transfers curve tokens from one address to another address
/// @param _sender the account from which the curve tokens will be sent
/// @param _recipient the account to which the curve tokens will be sent
/// @param _amount the amount of curve tokens to transfer
/// @return success_ the success bool of the call
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public nonReentrant returns (bool success_) {
success_ = Curves.transferFrom(curve, _sender, _recipient, _amount);
}
/// @notice approves a user to spend curve tokens on their behalf
/// @param _spender the account to allow to spend from msg.sender
/// @param _amount the amount to specify the spender can spend
/// @return success_ the success bool of this call
function approve(address _spender, uint256 _amount) public nonReentrant returns (bool success_) {
success_ = Curves.approve(curve, _spender, _amount);
}
/// @notice view the curve token balance of a given account
/// @param _account the account to view the balance of
/// @return balance_ the curve token ballance of the given account
function balanceOf(address _account) public view returns (uint256 balance_) {
balance_ = curve.balances[_account];
}
/// @notice views the total curve supply of the pool
/// @return totalSupply_ the total supply of curve tokens
function totalSupply() public view returns (uint256 totalSupply_) {
totalSupply_ = curve.totalSupply;
}
/// @notice views the total allowance one address has to spend from another address
/// @param _owner the address of the owner
/// @param _spender the address of the spender
/// @return allowance_ the amount the owner has allotted the spender
function allowance(address _owner, address _spender) public view returns (uint256 allowance_) {
allowance_ = curve.allowances[_owner][_spender];
}
/// @notice views the total amount of liquidity in the curve in numeraire value and format - 18 decimals
/// @return total_ the total value in the curve
/// @return individual_ the individual values in the curve
function liquidity() public view returns (uint256 total_, uint256[] memory individual_) {
return ViewLiquidity.viewLiquidity(curve);
}
/// @notice view the assimilator address for a derivative
/// @return assimilator_ the assimilator address
function assimilator(address _derivative) public view returns (address assimilator_) {
assimilator_ = curve.assimilators[_derivative].addr;
}
function setCap(uint256 _cap) public onlyOwner {
require(_cap != curve.cap, "Curve/cap is already set");
curve.cap = _cap;
emit CapChanged(_cap);
}
event CapChanged(uint256 _cap);
}
// SPDX-License-Identifier: MIT
// 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.3;
interface IFreeFromUpTo {
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/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 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: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^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) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
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 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 x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
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 xe = msb - 127;
if (xe > 0) x >>= uint256 (xe);
else x <<= uint256 (-xe);
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= uint256 (re);
else if (re < 0) result >>= uint256 (-re);
return 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
// 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.3;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./lib/ABDKMath64x64.sol";
import "./Storage.sol";
import "./CurveMath.sol";
library Orchestrator {
using SafeERC20 for IERC20;
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
int128 private constant ONE_WEI = 0x12;
event ParametersSet(uint256 alpha, uint256 beta, uint256 delta, uint256 epsilon, uint256 lambda);
event AssetIncluded(address indexed numeraire, address indexed reserve, uint256 weight);
event AssimilatorIncluded(
address indexed derivative,
address indexed numeraire,
address indexed reserve,
address assimilator
);
function setParams(
Storage.Curve storage curve,
uint256 _alpha,
uint256 _beta,
uint256 _feeAtHalt,
uint256 _epsilon,
uint256 _lambda
) external {
require(0 < _alpha && _alpha < 1e18, "Curve/parameter-invalid-alpha");
require(_beta < _alpha, "Curve/parameter-invalid-beta");
require(_feeAtHalt <= 5e17, "Curve/parameter-invalid-max");
require(_epsilon <= 1e16, "Curve/parameter-invalid-epsilon");
require(_lambda <= 1e18, "Curve/parameter-invalid-lambda");
int128 _omega = getFee(curve);
curve.alpha = (_alpha + 1).divu(1e18);
curve.beta = (_beta + 1).divu(1e18);
curve.delta = (_feeAtHalt).divu(1e18).div(uint256(2).fromUInt().mul(curve.alpha.sub(curve.beta))) + ONE_WEI;
curve.epsilon = (_epsilon + 1).divu(1e18);
curve.lambda = (_lambda + 1).divu(1e18);
int128 _psi = getFee(curve);
require(_omega >= _psi, "Curve/parameters-increase-fee");
emit ParametersSet(_alpha, _beta, curve.delta.mulu(1e18), _epsilon, _lambda);
}
function getFee(Storage.Curve storage curve) private view returns (int128 fee_) {
int128 _gLiq;
// Always pairs
int128[] memory _bals = new int128[](2);
for (uint256 i = 0; i < _bals.length; i++) {
int128 _bal = Assimilators.viewNumeraireBalance(curve.assets[i].addr);
_bals[i] = _bal;
_gLiq += _bal;
}
fee_ = CurveMath.calculateFee(_gLiq, _bals, curve.beta, curve.delta, curve.weights);
}
function initialize(
Storage.Curve storage curve,
address[] storage numeraires,
address[] storage reserves,
address[] storage derivatives,
address[] calldata _assets,
uint256[] calldata _assetWeights
) external {
require(_assetWeights.length == 2, "Curve/assetWeights-must-be-length-two");
require(_assets.length % 5 == 0, "Curve/assets-must-be-divisible-by-five");
for (uint256 i = 0; i < _assetWeights.length; i++) {
uint256 ix = i * 5;
numeraires.push(_assets[ix]);
derivatives.push(_assets[ix]);
reserves.push(_assets[2 + ix]);
if (_assets[ix] != _assets[2 + ix]) derivatives.push(_assets[2 + ix]);
includeAsset(
curve,
_assets[ix], // numeraire
_assets[1 + ix], // numeraire assimilator
_assets[2 + ix], // reserve
_assets[3 + ix], // reserve assimilator
_assets[4 + ix], // reserve approve to
_assetWeights[i]
);
}
}
function includeAsset(
Storage.Curve storage curve,
address _numeraire,
address _numeraireAssim,
address _reserve,
address _reserveAssim,
address _reserveApproveTo,
uint256 _weight
) private {
require(_numeraire != address(0), "Curve/numeraire-cannot-be-zeroth-address");
require(_numeraireAssim != address(0), "Curve/numeraire-assimilator-cannot-be-zeroth-address");
require(_reserve != address(0), "Curve/reserve-cannot-be-zeroth-address");
require(_reserveAssim != address(0), "Curve/reserve-assimilator-cannot-be-zeroth-address");
require(_weight < 1e18, "Curve/weight-must-be-less-than-one");
if (_numeraire != _reserve) IERC20(_numeraire).safeApprove(_reserveApproveTo, uint256(-1));
Storage.Assimilator storage _numeraireAssimilator = curve.assimilators[_numeraire];
_numeraireAssimilator.addr = _numeraireAssim;
_numeraireAssimilator.ix = uint8(curve.assets.length);
Storage.Assimilator storage _reserveAssimilator = curve.assimilators[_reserve];
_reserveAssimilator.addr = _reserveAssim;
_reserveAssimilator.ix = uint8(curve.assets.length);
int128 __weight = _weight.divu(1e18).add(uint256(1).divu(1e18));
curve.weights.push(__weight);
curve.assets.push(_numeraireAssimilator);
emit AssetIncluded(_numeraire, _reserve, _weight);
emit AssimilatorIncluded(_numeraire, _numeraire, _reserve, _numeraireAssim);
if (_numeraireAssim != _reserveAssim) {
emit AssimilatorIncluded(_reserve, _numeraire, _reserve, _reserveAssim);
}
}
function includeAssimilator(
Storage.Curve storage curve,
address _derivative,
address _numeraire,
address _reserve,
address _assimilator,
address _derivativeApproveTo
) private {
require(_derivative != address(0), "Curve/derivative-cannot-be-zeroth-address");
require(_numeraire != address(0), "Curve/numeraire-cannot-be-zeroth-address");
require(_reserve != address(0), "Curve/numeraire-cannot-be-zeroth-address");
require(_assimilator != address(0), "Curve/assimilator-cannot-be-zeroth-address");
IERC20(_numeraire).safeApprove(_derivativeApproveTo, uint256(-1));
Storage.Assimilator storage _numeraireAssim = curve.assimilators[_numeraire];
curve.assimilators[_derivative] = Storage.Assimilator(_assimilator, _numeraireAssim.ix);
emit AssimilatorIncluded(_derivative, _numeraire, _reserve, _assimilator);
}
function viewCurve(Storage.Curve storage curve)
external
view
returns (
uint256 alpha_,
uint256 beta_,
uint256 delta_,
uint256 epsilon_,
uint256 lambda_
)
{
alpha_ = curve.alpha.mulu(1e18);
beta_ = curve.beta.mulu(1e18);
delta_ = curve.delta.mulu(1e18);
epsilon_ = curve.epsilon.mulu(1e18);
lambda_ = curve.lambda.mulu(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./Assimilators.sol";
import "./Storage.sol";
import "./lib/UnsafeMath64x64.sol";
import "./lib/ABDKMath64x64.sol";
import "./CurveMath.sol";
library ProportionalLiquidity {
using ABDKMath64x64 for uint256;
using ABDKMath64x64 for int128;
using UnsafeMath64x64 for int128;
event Transfer(address indexed from, address indexed to, uint256 value);
int128 public constant ONE = 0x10000000000000000;
int128 public constant ONE_WEI = 0x12;
function proportionalDeposit(Storage.Curve storage curve, uint256 _deposit)
external
returns (uint256 curves_, uint256[] memory)
{
int128 __deposit = _deposit.divu(1e18);
uint256 _length = curve.assets.length;
uint256[] memory deposits_ = new uint256[](_length);
(int128 _oGLiq, int128[] memory _oBals) = getGrossLiquidityAndBalancesForDeposit(curve);
// Needed to calculate liquidity invariant
(int128 _oGLiqProp, int128[] memory _oBalsProp) = getGrossLiquidityAndBalances(curve);
// No liquidity, oracle sets the ratio
if (_oGLiq == 0) {
for (uint256 i = 0; i < _length; i++) {
// Variable here to avoid stack-too-deep errors
int128 _d = __deposit.mul(curve.weights[i]);
deposits_[i] = Assimilators.intakeNumeraire(curve.assets[i].addr, _d.add(ONE_WEI));
}
} else {
// We already have an existing pool ratio
// which must be respected
int128 _multiplier = __deposit.div(_oGLiq);
uint256 _baseWeight = curve.weights[0].mulu(1e18);
uint256 _quoteWeight = curve.weights[1].mulu(1e18);
for (uint256 i = 0; i < _length; i++) {
deposits_[i] = Assimilators.intakeNumeraireLPRatio(
curve.assets[i].addr,
_baseWeight,
_quoteWeight,
_oBals[i].mul(_multiplier).add(ONE_WEI)
);
}
}
int128 _totalShells = curve.totalSupply.divu(1e18);
int128 _newShells = __deposit;
if (_totalShells > 0) {
_newShells = __deposit.div(_oGLiq);
_newShells = _newShells.mul(_totalShells);
}
requireLiquidityInvariant(curve, _totalShells, _newShells, _oGLiqProp, _oBalsProp);
mint(curve, msg.sender, curves_ = _newShells.mulu(1e18));
return (curves_, deposits_);
}
function viewProportionalDeposit(Storage.Curve storage curve, uint256 _deposit)
external
view
returns (uint256 curves_, uint256[] memory)
{
int128 __deposit = _deposit.divu(1e18);
uint256 _length = curve.assets.length;
(int128 _oGLiq, int128[] memory _oBals) = getGrossLiquidityAndBalancesForDeposit(curve);
uint256[] memory deposits_ = new uint256[](_length);
// No liquidity
if (_oGLiq == 0) {
for (uint256 i = 0; i < _length; i++) {
deposits_[i] = Assimilators.viewRawAmount(
curve.assets[i].addr,
__deposit.mul(curve.weights[i]).add(ONE_WEI)
);
}
} else {
// We already have an existing pool ratio
// this must be respected
int128 _multiplier = __deposit.div(_oGLiq);
uint256 _baseWeight = curve.weights[0].mulu(1e18);
uint256 _quoteWeight = curve.weights[1].mulu(1e18);
// Deposits into the pool is determined by existing LP ratio
for (uint256 i = 0; i < _length; i++) {
deposits_[i] = Assimilators.viewRawAmountLPRatio(
curve.assets[i].addr,
_baseWeight,
_quoteWeight,
_oBals[i].mul(_multiplier).add(ONE_WEI)
);
}
}
int128 _totalShells = curve.totalSupply.divu(1e18);
int128 _newShells = __deposit;
if (_totalShells > 0) {
_newShells = __deposit.div(_oGLiq);
_newShells = _newShells.mul(_totalShells);
}
curves_ = _newShells.mulu(1e18);
return (curves_, deposits_);
}
function emergencyProportionalWithdraw(Storage.Curve storage curve, uint256 _withdrawal)
external
returns (uint256[] memory)
{
uint256 _length = curve.assets.length;
(, int128[] memory _oBals) = getGrossLiquidityAndBalances(curve);
uint256[] memory withdrawals_ = new uint256[](_length);
int128 _totalShells = curve.totalSupply.divu(1e18);
int128 __withdrawal = _withdrawal.divu(1e18);
int128 _multiplier = __withdrawal.div(_totalShells);
for (uint256 i = 0; i < _length; i++) {
withdrawals_[i] = Assimilators.outputNumeraire(
curve.assets[i].addr,
msg.sender,
_oBals[i].mul(_multiplier)
);
}
burn(curve, msg.sender, _withdrawal);
return withdrawals_;
}
function proportionalWithdraw(Storage.Curve storage curve, uint256 _withdrawal)
external
returns (uint256[] memory)
{
uint256 _length = curve.assets.length;
(int128 _oGLiq, int128[] memory _oBals) = getGrossLiquidityAndBalances(curve);
uint256[] memory withdrawals_ = new uint256[](_length);
int128 _totalShells = curve.totalSupply.divu(1e18);
int128 __withdrawal = _withdrawal.divu(1e18);
int128 _multiplier = __withdrawal.div(_totalShells);
for (uint256 i = 0; i < _length; i++) {
withdrawals_[i] = Assimilators.outputNumeraire(
curve.assets[i].addr,
msg.sender,
_oBals[i].mul(_multiplier)
);
}
requireLiquidityInvariant(curve, _totalShells, __withdrawal.neg(), _oGLiq, _oBals);
burn(curve, msg.sender, _withdrawal);
return withdrawals_;
}
function viewProportionalWithdraw(Storage.Curve storage curve, uint256 _withdrawal)
external
view
returns (uint256[] memory)
{
uint256 _length = curve.assets.length;
(, int128[] memory _oBals) = getGrossLiquidityAndBalances(curve);
uint256[] memory withdrawals_ = new uint256[](_length);
int128 _multiplier = _withdrawal.divu(1e18).div(curve.totalSupply.divu(1e18));
for (uint256 i = 0; i < _length; i++) {
withdrawals_[i] = Assimilators.viewRawAmount(curve.assets[i].addr, _oBals[i].mul(_multiplier));
}
return withdrawals_;
}
function getGrossLiquidityAndBalancesForDeposit(Storage.Curve storage curve)
internal
view
returns (int128 grossLiquidity_, int128[] memory)
{
uint256 _length = curve.assets.length;
int128[] memory balances_ = new int128[](_length);
uint256 _baseWeight = curve.weights[0].mulu(1e18);
uint256 _quoteWeight = curve.weights[1].mulu(1e18);
for (uint256 i = 0; i < _length; i++) {
int128 _bal = Assimilators.viewNumeraireBalanceLPRatio(_baseWeight, _quoteWeight, curve.assets[i].addr);
balances_[i] = _bal;
grossLiquidity_ += _bal;
}
return (grossLiquidity_, balances_);
}
function getGrossLiquidityAndBalances(Storage.Curve storage curve)
internal
view
returns (int128 grossLiquidity_, int128[] memory)
{
uint256 _length = curve.assets.length;
int128[] memory balances_ = new int128[](_length);
for (uint256 i = 0; i < _length; i++) {
int128 _bal = Assimilators.viewNumeraireBalance(curve.assets[i].addr);
balances_[i] = _bal;
grossLiquidity_ += _bal;
}
return (grossLiquidity_, balances_);
}
function requireLiquidityInvariant(
Storage.Curve storage curve,
int128 _curves,
int128 _newShells,
int128 _oGLiq,
int128[] memory _oBals
) private view {
(int128 _nGLiq, int128[] memory _nBals) = getGrossLiquidityAndBalances(curve);
int128 _beta = curve.beta;
int128 _delta = curve.delta;
int128[] memory _weights = curve.weights;
int128 _omega = CurveMath.calculateFee(_oGLiq, _oBals, _beta, _delta, _weights);
int128 _psi = CurveMath.calculateFee(_nGLiq, _nBals, _beta, _delta, _weights);
CurveMath.enforceLiquidityInvariant(_curves, _newShells, _oGLiq, _nGLiq, _omega, _psi);
}
function burn(
Storage.Curve storage curve,
address account,
uint256 amount
) private {
curve.balances[account] = burnSub(curve.balances[account], amount);
curve.totalSupply = burnSub(curve.totalSupply, amount);
emit Transfer(msg.sender, address(0), amount);
}
function mint(
Storage.Curve storage curve,
address account,
uint256 amount
) private {
curve.totalSupply = mintAdd(curve.totalSupply, amount);
curve.balances[account] = mintAdd(curve.balances[account], amount);
emit Transfer(address(0), msg.sender, amount);
}
function mintAdd(uint256 x, uint256 y) private pure returns (uint256 z) {
require((z = x + y) >= x, "Curve/mint-overflow");
}
function burnSub(uint256 x, uint256 y) private pure returns (uint256 z) {
require((z = x - y) <= x, "Curve/burn-underflow");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./Assimilators.sol";
import "./Storage.sol";
import "./CurveMath.sol";
import "./lib/UnsafeMath64x64.sol";
import "./lib/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Swaps {
using ABDKMath64x64 for int128;
using UnsafeMath64x64 for int128;
using ABDKMath64x64 for uint256;
using SafeMath for uint256;
event Trade(
address indexed trader,
address indexed origin,
address indexed target,
uint256 originAmount,
uint256 targetAmount
);
int128 public constant ONE = 0x10000000000000000;
function getOriginAndTarget(
Storage.Curve storage curve,
address _o,
address _t
) private view returns (Storage.Assimilator memory, Storage.Assimilator memory) {
Storage.Assimilator memory o_ = curve.assimilators[_o];
Storage.Assimilator memory t_ = curve.assimilators[_t];
require(o_.addr != address(0), "Curve/origin-not-supported");
require(t_.addr != address(0), "Curve/target-not-supported");
return (o_, t_);
}
function originSwap(
Storage.Curve storage curve,
address _origin,
address _target,
uint256 _originAmount,
address _recipient
) external returns (uint256 tAmt_) {
(Storage.Assimilator memory _o, Storage.Assimilator memory _t) = getOriginAndTarget(curve, _origin, _target);
if (_o.ix == _t.ix)
return Assimilators.outputNumeraire(_t.addr, _recipient, Assimilators.intakeRaw(_o.addr, _originAmount));
(int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals) =
getOriginSwapData(curve, _o.ix, _t.ix, _o.addr, _originAmount);
_amt = CurveMath.calculateTrade(curve, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _t.ix);
_amt = _amt.us_mul(ONE - curve.epsilon);
tAmt_ = Assimilators.outputNumeraire(_t.addr, _recipient, _amt);
emit Trade(msg.sender, _origin, _target, _originAmount, tAmt_);
}
function viewOriginSwap(
Storage.Curve storage curve,
address _origin,
address _target,
uint256 _originAmount
) external view returns (uint256 tAmt_) {
(Storage.Assimilator memory _o, Storage.Assimilator memory _t) = getOriginAndTarget(curve, _origin, _target);
if (_o.ix == _t.ix)
return Assimilators.viewRawAmount(_t.addr, Assimilators.viewNumeraireAmount(_o.addr, _originAmount));
(int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _nBals, int128[] memory _oBals) =
viewOriginSwapData(curve, _o.ix, _t.ix, _originAmount, _o.addr);
_amt = CurveMath.calculateTrade(curve, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _t.ix);
_amt = _amt.us_mul(ONE - curve.epsilon);
tAmt_ = Assimilators.viewRawAmount(_t.addr, _amt.abs());
}
function targetSwap(
Storage.Curve storage curve,
address _origin,
address _target,
uint256 _targetAmount,
address _recipient
) external returns (uint256 oAmt_) {
(Storage.Assimilator memory _o, Storage.Assimilator memory _t) = getOriginAndTarget(curve, _origin, _target);
if (_o.ix == _t.ix)
return Assimilators.intakeNumeraire(_o.addr, Assimilators.outputRaw(_t.addr, _recipient, _targetAmount));
// If the origin is the quote currency (i.e. usdc)
// we need to make sure to massage the _targetAmount
// by dividing it by the exchange rate (so it gets
// multiplied later to reach the same target amount).
// Inelegant solution, but this way we don't need to
// re-write large chunks of the code-base
// curve.assets[1].addr = quoteCurrency
// no variable assignment due to stack too deep
if (curve.assets[1].addr == _o.addr) {
_targetAmount = _targetAmount.mul(1e8).div(Assimilators.getRate(_t.addr));
}
(int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals) =
getTargetSwapData(curve, _t.ix, _o.ix, _t.addr, _recipient, _targetAmount);
_amt = CurveMath.calculateTrade(curve, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _o.ix);
// If the origin is the quote currency (i.e. usdc)
// we need to make sure to massage the _amt too
// curve.assets[1].addr = quoteCurrency
if (curve.assets[1].addr == _o.addr) {
_amt = _amt.mul(Assimilators.getRate(_t.addr).divu(1e8));
}
_amt = _amt.us_mul(ONE + curve.epsilon);
oAmt_ = Assimilators.intakeNumeraire(_o.addr, _amt);
emit Trade(msg.sender, _origin, _target, oAmt_, _targetAmount);
}
function viewTargetSwap(
Storage.Curve storage curve,
address _origin,
address _target,
uint256 _targetAmount
) external view returns (uint256 oAmt_) {
(Storage.Assimilator memory _o, Storage.Assimilator memory _t) = getOriginAndTarget(curve, _origin, _target);
if (_o.ix == _t.ix)
return Assimilators.viewRawAmount(_o.addr, Assimilators.viewNumeraireAmount(_t.addr, _targetAmount));
// If the origin is the quote currency (i.e. usdc)
// we need to make sure to massage the _targetAmount
// by dividing it by the exchange rate (so it gets
// multiplied later to reach the same target amount).
// Inelegant solution, but this way we don't need to
// re-write large chunks of the code-base
// curve.assets[1].addr = quoteCurrency
// no variable assignment due to stack too deep
if (curve.assets[1].addr == _o.addr) {
_targetAmount = _targetAmount.mul(1e8).div(Assimilators.getRate(_t.addr));
}
(int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _nBals, int128[] memory _oBals) =
viewTargetSwapData(curve, _t.ix, _o.ix, _targetAmount, _t.addr);
_amt = CurveMath.calculateTrade(curve, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _o.ix);
// If the origin is the quote currency (i.e. usdc)
// we need to make sure to massage the _amt too
// curve.assets[1].addr = quoteCurrency
if (curve.assets[1].addr == _o.addr) {
_amt = _amt.mul(Assimilators.getRate(_t.addr).divu(1e8));
}
_amt = _amt.us_mul(ONE + curve.epsilon);
oAmt_ = Assimilators.viewRawAmount(_o.addr, _amt);
}
function getOriginSwapData(
Storage.Curve storage curve,
uint256 _inputIx,
uint256 _outputIx,
address _assim,
uint256 _amt
)
private
returns (
int128 amt_,
int128 oGLiq_,
int128 nGLiq_,
int128[] memory,
int128[] memory
)
{
uint256 _length = curve.assets.length;
int128[] memory oBals_ = new int128[](_length);
int128[] memory nBals_ = new int128[](_length);
Storage.Assimilator[] memory _reserves = curve.assets;
for (uint256 i = 0; i < _length; i++) {
if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(_reserves[i].addr);
else {
int128 _bal;
(amt_, _bal) = Assimilators.intakeRawAndGetBalance(_assim, _amt);
oBals_[i] = _bal.sub(amt_);
nBals_[i] = _bal;
}
oGLiq_ += oBals_[i];
nGLiq_ += nBals_[i];
}
nGLiq_ = nGLiq_.sub(amt_);
nBals_[_outputIx] = ABDKMath64x64.sub(nBals_[_outputIx], amt_);
return (amt_, oGLiq_, nGLiq_, oBals_, nBals_);
}
function getTargetSwapData(
Storage.Curve storage curve,
uint256 _inputIx,
uint256 _outputIx,
address _assim,
address _recipient,
uint256 _amt
)
private
returns (
int128 amt_,
int128 oGLiq_,
int128 nGLiq_,
int128[] memory,
int128[] memory
)
{
uint256 _length = curve.assets.length;
int128[] memory oBals_ = new int128[](_length);
int128[] memory nBals_ = new int128[](_length);
Storage.Assimilator[] memory _reserves = curve.assets;
for (uint256 i = 0; i < _length; i++) {
if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(_reserves[i].addr);
else {
int128 _bal;
(amt_, _bal) = Assimilators.outputRawAndGetBalance(_assim, _recipient, _amt);
oBals_[i] = _bal.sub(amt_);
nBals_[i] = _bal;
}
oGLiq_ += oBals_[i];
nGLiq_ += nBals_[i];
}
nGLiq_ = nGLiq_.sub(amt_);
nBals_[_outputIx] = ABDKMath64x64.sub(nBals_[_outputIx], amt_);
return (amt_, oGLiq_, nGLiq_, oBals_, nBals_);
}
function viewOriginSwapData(
Storage.Curve storage curve,
uint256 _inputIx,
uint256 _outputIx,
uint256 _amt,
address _assim
)
private
view
returns (
int128 amt_,
int128 oGLiq_,
int128 nGLiq_,
int128[] memory,
int128[] memory
)
{
uint256 _length = curve.assets.length;
int128[] memory nBals_ = new int128[](_length);
int128[] memory oBals_ = new int128[](_length);
for (uint256 i = 0; i < _length; i++) {
if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(curve.assets[i].addr);
else {
int128 _bal;
(amt_, _bal) = Assimilators.viewNumeraireAmountAndBalance(_assim, _amt);
oBals_[i] = _bal;
nBals_[i] = _bal.add(amt_);
}
oGLiq_ += oBals_[i];
nGLiq_ += nBals_[i];
}
nGLiq_ = nGLiq_.sub(amt_);
nBals_[_outputIx] = ABDKMath64x64.sub(nBals_[_outputIx], amt_);
return (amt_, oGLiq_, nGLiq_, nBals_, oBals_);
}
function viewTargetSwapData(
Storage.Curve storage curve,
uint256 _inputIx,
uint256 _outputIx,
uint256 _amt,
address _assim
)
private
view
returns (
int128 amt_,
int128 oGLiq_,
int128 nGLiq_,
int128[] memory,
int128[] memory
)
{
uint256 _length = curve.assets.length;
int128[] memory nBals_ = new int128[](_length);
int128[] memory oBals_ = new int128[](_length);
for (uint256 i = 0; i < _length; i++) {
if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(curve.assets[i].addr);
else {
int128 _bal;
(amt_, _bal) = Assimilators.viewNumeraireAmountAndBalance(_assim, _amt);
amt_ = amt_.neg();
oBals_[i] = _bal;
nBals_[i] = _bal.add(amt_);
}
oGLiq_ += oBals_[i];
nGLiq_ += nBals_[i];
}
nGLiq_ = nGLiq_.sub(amt_);
nBals_[_outputIx] = ABDKMath64x64.sub(nBals_[_outputIx], amt_);
return (amt_, oGLiq_, nGLiq_, nBals_, oBals_);
}
}
// SPDX-License-Identifier: MIT
// 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.3;
import "./Storage.sol";
import "./Assimilators.sol";
import "./lib/ABDKMath64x64.sol";
library ViewLiquidity {
using ABDKMath64x64 for int128;
function viewLiquidity(Storage.Curve storage curve)
external
view
returns (uint256 total_, uint256[] memory individual_)
{
uint256 _length = curve.assets.length;
individual_ = new uint256[](_length);
for (uint256 i = 0; i < _length; i++) {
uint256 _liquidity = Assimilators.viewNumeraireBalance(curve.assets[i].addr).mulu(1e18);
total_ += _liquidity;
individual_[i] = _liquidity;
}
return (total_, individual_);
}
}
// SPDX-License-Identifier: MIT
// 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.3;
import "./interfaces/IOracle.sol";
import "./Assimilators.sol";
contract Storage {
struct Curve {
// Curve parameters
int128 alpha;
int128 beta;
int128 delta;
int128 epsilon;
int128 lambda;
int128[] weights;
uint256 cap;
// Assets and their assimilators
Assimilator[] assets;
mapping(address => Assimilator) assimilators;
// Oracles to determine the price
// Note that 0'th index should always be USDC 1e18
// Oracle's pricing should be denominated in Currency/USDC
mapping(address => IOracle) oracles;
// ERC20 Interface
uint256 totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowances;
}
struct Assimilator {
address addr;
uint8 ix;
}
// Curve parameters
Curve public curve;
// Ownable
address public owner;
string public name;
string public symbol;
uint8 public constant decimals = 18;
address[] public derivatives;
address[] public numeraires;
address[] public reserves;
// Curve operational state
bool public frozen = false;
bool public emergency = false;
bool public whitelistingStage = true;
bool internal notEntered = true;
mapping(address => uint256) public whitelistedDeposited;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract MerkleProver {
bytes32 public immutable merkleRoot = bytes32(0xf4dbd0fb1957570029a847490cb3d731a45962072953ba7da80ff132ccd97d51);
function isWhitelisted(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) public view returns (bool) {
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, account, amount));
return MerkleProof.verify(merkleProof, merkleRoot, node);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/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 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(_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 {
_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.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
// 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.3;
import "./Storage.sol";
import "./lib/UnsafeMath64x64.sol";
import "./lib/ABDKMath64x64.sol";
library CurveMath {
int128 private constant ONE = 0x10000000000000000;
int128 private constant MAX = 0x4000000000000000; // .25 in layman's terms
int128 private constant MAX_DIFF = -0x10C6F7A0B5EE;
int128 private constant ONE_WEI = 0x12;
using ABDKMath64x64 for int128;
using UnsafeMath64x64 for int128;
using ABDKMath64x64 for uint256;
// This is used to prevent stack too deep errors
function calculateFee(
int128 _gLiq,
int128[] memory _bals,
Storage.Curve storage curve,
int128[] memory _weights
) internal view returns (int128 psi_) {
int128 _beta = curve.beta;
int128 _delta = curve.delta;
psi_ = calculateFee(_gLiq, _bals, _beta, _delta, _weights);
}
function calculateFee(
int128 _gLiq,
int128[] memory _bals,
int128 _beta,
int128 _delta,
int128[] memory _weights
) internal pure returns (int128 psi_) {
uint256 _length = _bals.length;
for (uint256 i = 0; i < _length; i++) {
int128 _ideal = _gLiq.mul(_weights[i]);
psi_ += calculateMicroFee(_bals[i], _ideal, _beta, _delta);
}
}
function calculateMicroFee(
int128 _bal,
int128 _ideal,
int128 _beta,
int128 _delta
) private pure returns (int128 fee_) {
if (_bal < _ideal) {
int128 _threshold = _ideal.mul(ONE - _beta);
if (_bal < _threshold) {
int128 _feeMargin = _threshold - _bal;
fee_ = _feeMargin.div(_ideal);
fee_ = fee_.mul(_delta);
if (fee_ > MAX) fee_ = MAX;
fee_ = fee_.mul(_feeMargin);
} else fee_ = 0;
} else {
int128 _threshold = _ideal.mul(ONE + _beta);
if (_bal > _threshold) {
int128 _feeMargin = _bal - _threshold;
fee_ = _feeMargin.div(_ideal);
fee_ = fee_.mul(_delta);
if (fee_ > MAX) fee_ = MAX;
fee_ = fee_.mul(_feeMargin);
} else fee_ = 0;
}
}
function calculateTrade(
Storage.Curve storage curve,
int128 _oGLiq,
int128 _nGLiq,
int128[] memory _oBals,
int128[] memory _nBals,
int128 _inputAmt,
uint256 _outputIndex
) internal view returns (int128 outputAmt_) {
outputAmt_ = -_inputAmt;
int128 _lambda = curve.lambda;
int128[] memory _weights = curve.weights;
int128 _omega = calculateFee(_oGLiq, _oBals, curve, _weights);
int128 _psi;
for (uint256 i = 0; i < 32; i++) {
_psi = calculateFee(_nGLiq, _nBals, curve, _weights);
int128 prevAmount;
{
prevAmount = outputAmt_;
outputAmt_ = _omega < _psi ? -(_inputAmt + _omega - _psi) : -(_inputAmt + _lambda.mul(_omega - _psi));
}
if (outputAmt_ / 1e13 == prevAmount / 1e13) {
_nGLiq = _oGLiq + _inputAmt + outputAmt_;
_nBals[_outputIndex] = _oBals[_outputIndex] + outputAmt_;
enforceHalts(curve, _oGLiq, _nGLiq, _oBals, _nBals, _weights);
enforceSwapInvariant(_oGLiq, _omega, _nGLiq, _psi);
return outputAmt_;
} else {
_nGLiq = _oGLiq + _inputAmt + outputAmt_;
_nBals[_outputIndex] = _oBals[_outputIndex].add(outputAmt_);
}
}
revert("Curve/swap-convergence-failed");
}
function calculateLiquidityMembrane(
Storage.Curve storage curve,
int128 _oGLiq,
int128 _nGLiq,
int128[] memory _oBals,
int128[] memory _nBals
) internal view returns (int128 curves_) {
enforceHalts(curve, _oGLiq, _nGLiq, _oBals, _nBals, curve.weights);
int128 _omega;
int128 _psi;
{
int128 _beta = curve.beta;
int128 _delta = curve.delta;
int128[] memory _weights = curve.weights;
_omega = calculateFee(_oGLiq, _oBals, _beta, _delta, _weights);
_psi = calculateFee(_nGLiq, _nBals, _beta, _delta, _weights);
}
int128 _feeDiff = _psi.sub(_omega);
int128 _liqDiff = _nGLiq.sub(_oGLiq);
int128 _oUtil = _oGLiq.sub(_omega);
int128 _totalShells = curve.totalSupply.divu(1e18);
int128 _curveMultiplier;
if (_totalShells == 0) {
curves_ = _nGLiq.sub(_psi);
} else if (_feeDiff >= 0) {
_curveMultiplier = _liqDiff.sub(_feeDiff).div(_oUtil);
} else {
_curveMultiplier = _liqDiff.sub(curve.lambda.mul(_feeDiff));
_curveMultiplier = _curveMultiplier.div(_oUtil);
}
if (_totalShells != 0) {
curves_ = _totalShells.mul(_curveMultiplier);
enforceLiquidityInvariant(_totalShells, curves_, _oGLiq, _nGLiq, _omega, _psi);
}
}
function enforceSwapInvariant(
int128 _oGLiq,
int128 _omega,
int128 _nGLiq,
int128 _psi
) private pure {
int128 _nextUtil = _nGLiq - _psi;
int128 _prevUtil = _oGLiq - _omega;
int128 _diff = _nextUtil - _prevUtil;
require(0 < _diff || _diff >= MAX_DIFF, "Curve/swap-invariant-violation");
}
function enforceLiquidityInvariant(
int128 _totalShells,
int128 _newShells,
int128 _oGLiq,
int128 _nGLiq,
int128 _omega,
int128 _psi
) internal pure {
if (_totalShells == 0 || 0 == _totalShells + _newShells) return;
int128 _prevUtilPerShell = _oGLiq.sub(_omega).div(_totalShells);
int128 _nextUtilPerShell = _nGLiq.sub(_psi).div(_totalShells.add(_newShells));
int128 _diff = _nextUtilPerShell - _prevUtilPerShell;
require(0 < _diff || _diff >= MAX_DIFF, "Curve/liquidity-invariant-violation");
}
function enforceHalts(
Storage.Curve storage curve,
int128 _oGLiq,
int128 _nGLiq,
int128[] memory _oBals,
int128[] memory _nBals,
int128[] memory _weights
) private view {
uint256 _length = _nBals.length;
int128 _alpha = curve.alpha;
for (uint256 i = 0; i < _length; i++) {
int128 _nIdeal = _nGLiq.mul(_weights[i]);
if (_nBals[i] > _nIdeal) {
int128 _upperAlpha = ONE + _alpha;
int128 _nHalt = _nIdeal.mul(_upperAlpha);
if (_nBals[i] > _nHalt) {
int128 _oHalt = _oGLiq.mul(_weights[i]).mul(_upperAlpha);
if (_oBals[i] < _oHalt) revert("Curve/upper-halt");
if (_nBals[i] - _nHalt > _oBals[i] - _oHalt) revert("Curve/upper-halt");
}
} else {
int128 _lowerAlpha = ONE - _alpha;
int128 _nHalt = _nIdeal.mul(_lowerAlpha);
if (_nBals[i] < _nHalt) {
int128 _oHalt = _oGLiq.mul(_weights[i]);
_oHalt = _oHalt.mul(_lowerAlpha);
if (_oBals[i] > _oHalt) revert("Curve/lower-halt");
if (_nHalt - _nBals[i] > _oHalt - _oBals[i]) revert("Curve/lower-halt");
}
}
}
}
}
// 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: 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, 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) {
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;
}
}
// 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);
}
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
// 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.3;
interface IOracle {
function acceptOwnership() external;
function accessController() external view returns (address);
function aggregator() external view returns (address);
function confirmAggregator(address _aggregator) external;
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function getAnswer(uint256 _roundId) external view returns (int256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function getTimestamp(uint256 _roundId) external view returns (uint256);
function latestAnswer() external view returns (int256);
function latestRound() external view returns (uint256);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestTimestamp() external view returns (uint256);
function owner() external view returns (address);
function phaseAggregators(uint16) external view returns (address);
function phaseId() external view returns (uint16);
function proposeAggregator(address _aggregator) external;
function proposedAggregator() external view returns (address);
function proposedGetRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function proposedLatestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function setController(address _accessController) external;
function transferOwnership(address _to) external;
function version() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// 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.3;
import "@openzeppelin/contracts/utils/Address.sol";
import "./interfaces/IAssimilator.sol";
import "./lib/ABDKMath64x64.sol";
library Assimilators {
using ABDKMath64x64 for int128;
using Address for address;
IAssimilator public constant iAsmltr = IAssimilator(address(0));
function delegate(address _callee, bytes memory _data) internal returns (bytes memory) {
require(_callee.isContract(), "Assimilators/callee-is-not-a-contract");
// solhint-disable-next-line
(bool _success, bytes memory returnData_) = _callee.delegatecall(_data);
// solhint-disable-next-line
assembly {
if eq(_success, 0) {
revert(add(returnData_, 0x20), returndatasize())
}
}
return returnData_;
}
function getRate(address _assim) internal view returns (uint256 amount_) {
amount_ = IAssimilator(_assim).getRate();
}
function viewRawAmount(address _assim, int128 _amt) internal view returns (uint256 amount_) {
amount_ = IAssimilator(_assim).viewRawAmount(_amt);
}
function viewRawAmountLPRatio(
address _assim,
uint256 _baseWeight,
uint256 _quoteWeight,
int128 _amount
) internal view returns (uint256 amount_) {
amount_ = IAssimilator(_assim).viewRawAmountLPRatio(_baseWeight, _quoteWeight, address(this), _amount);
}
function viewNumeraireAmount(address _assim, uint256 _amt) internal view returns (int128 amt_) {
amt_ = IAssimilator(_assim).viewNumeraireAmount(_amt);
}
function viewNumeraireAmountAndBalance(address _assim, uint256 _amt)
internal
view
returns (int128 amt_, int128 bal_)
{
(amt_, bal_) = IAssimilator(_assim).viewNumeraireAmountAndBalance(address(this), _amt);
}
function viewNumeraireBalance(address _assim) internal view returns (int128 bal_) {
bal_ = IAssimilator(_assim).viewNumeraireBalance(address(this));
}
function viewNumeraireBalanceLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _assim
) internal view returns (int128 bal_) {
bal_ = IAssimilator(_assim).viewNumeraireBalanceLPRatio(_baseWeight, _quoteWeight, address(this));
}
function intakeRaw(address _assim, uint256 _amt) internal returns (int128 amt_) {
bytes memory data = abi.encodeWithSelector(iAsmltr.intakeRaw.selector, _amt);
amt_ = abi.decode(delegate(_assim, data), (int128));
}
function intakeRawAndGetBalance(address _assim, uint256 _amt) internal returns (int128 amt_, int128 bal_) {
bytes memory data = abi.encodeWithSelector(iAsmltr.intakeRawAndGetBalance.selector, _amt);
(amt_, bal_) = abi.decode(delegate(_assim, data), (int128, int128));
}
function intakeNumeraire(address _assim, int128 _amt) internal returns (uint256 amt_) {
bytes memory data = abi.encodeWithSelector(iAsmltr.intakeNumeraire.selector, _amt);
amt_ = abi.decode(delegate(_assim, data), (uint256));
}
function intakeNumeraireLPRatio(
address _assim,
uint256 _baseWeight,
uint256 _quoteWeight,
int128 _amount
) internal returns (uint256 amt_) {
bytes memory data =
abi.encodeWithSelector(
iAsmltr.intakeNumeraireLPRatio.selector,
_baseWeight,
_quoteWeight,
address(this),
_amount
);
amt_ = abi.decode(delegate(_assim, data), (uint256));
}
function outputRaw(
address _assim,
address _dst,
uint256 _amt
) internal returns (int128 amt_) {
bytes memory data = abi.encodeWithSelector(iAsmltr.outputRaw.selector, _dst, _amt);
amt_ = abi.decode(delegate(_assim, data), (int128));
amt_ = amt_.neg();
}
function outputRawAndGetBalance(
address _assim,
address _dst,
uint256 _amt
) internal returns (int128 amt_, int128 bal_) {
bytes memory data = abi.encodeWithSelector(iAsmltr.outputRawAndGetBalance.selector, _dst, _amt);
(amt_, bal_) = abi.decode(delegate(_assim, data), (int128, int128));
amt_ = amt_.neg();
}
function outputNumeraire(
address _assim,
address _dst,
int128 _amt
) internal returns (uint256 amt_) {
bytes memory data = abi.encodeWithSelector(iAsmltr.outputNumeraire.selector, _dst, _amt.abs());
amt_ = abi.decode(delegate(_assim, data), (uint256));
}
}
// SPDX-License-Identifier: MIT
// 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.3;
interface IAssimilator {
function getRate() external view returns (uint256);
function intakeRaw(uint256 amount) external returns (int128);
function intakeRawAndGetBalance(uint256 amount) external returns (int128, int128);
function intakeNumeraire(int128 amount) external returns (uint256);
function intakeNumeraireLPRatio(
uint256,
uint256,
address,
int128
) external returns (uint256);
function outputRaw(address dst, uint256 amount) external returns (int128);
function outputRawAndGetBalance(address dst, uint256 amount) external returns (int128, int128);
function outputNumeraire(address dst, int128 amount) external returns (uint256);
function viewRawAmount(int128) external view returns (uint256);
function viewRawAmountLPRatio(
uint256,
uint256,
address,
int128
) external view returns (uint256);
function viewNumeraireAmount(uint256) external view returns (int128);
function viewNumeraireBalanceLPRatio(
uint256,
uint256,
address
) external view returns (int128);
function viewNumeraireBalance(address) external view returns (int128);
function viewNumeraireAmountAndBalance(address, uint256) external view returns (int128, int128);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
library UnsafeMath64x64 {
/**
* Calculate x * y 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 us_mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
return int128 (result);
}
/**
* 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 us_div (int128 x, int128 y) internal pure returns (int128) {
int256 result = (int256 (x) << 64) / y;
return int128 (result);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
|
view deposits and curves minted a given deposit would return _deposit the full amount of stablecoins you want to deposit. Divided evenly according to the prevailing proportions of the numeraire assets of the pool return (the amount of curves you receive in return for your deposit, the amount deposited for each numeraire) curvesToMint_, depositsToMake_
|
function viewDeposit(uint256 _deposit) external view transactable underCap(_deposit) returns (uint256, uint256[] memory) {
return ProportionalLiquidity.viewProportionalDeposit(curve, _deposit);
}
| 1,539,420
|
/*
__ __ .__ .___ _____
/ \ / \___________| | __| _/ _____/ ____\
\ \/\/ / _ \_ __ \ | / __ | / _ \ __\
\ ( <_> ) | \/ |__/ /_/ | ( <_> ) |
\__/\ / \____/|__| |____/\____ | \____/|__|
\/ \/
__ __.__ .__ __ ________ .___
/ \ / \ |__ |__|/ |_ ____ \______ \ __ __ __| _/____ ______
\ \/\/ / | \| \ __\/ __ \ | | \| | \/ __ |/ __ \ / ___/
\ /| Y \ || | \ ___/ | ` \ | / /_/ \ ___/ \___ \
\__/\ / |___| /__||__| \___ > /_______ /____/\____ |\___ >____ >
\/ \/ \/ \/ \/ \/ \/
More like World of White DAOudes imho
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
library SafeCast {
function toUint224(uint256 value) internal pure returns (uint224) {
require(
value <= type(uint224).max,
"SafeCast: value doesn't fit in 224 bits"
);
return uint224(value);
}
function toUint128(uint256 value) internal pure returns (uint128) {
require(
value <= type(uint128).max,
"SafeCast: value doesn't fit in 128 bits"
);
return uint128(value);
}
function toUint96(uint256 value) internal pure returns (uint96) {
require(
value <= type(uint96).max,
"SafeCast: value doesn't fit in 96 bits"
);
return uint96(value);
}
function toUint64(uint256 value) internal pure returns (uint64) {
require(
value <= type(uint64).max,
"SafeCast: value doesn't fit in 64 bits"
);
return uint64(value);
}
function toUint32(uint256 value) internal pure returns (uint32) {
require(
value <= type(uint32).max,
"SafeCast: value doesn't fit in 32 bits"
);
return uint32(value);
}
function toUint16(uint256 value) internal pure returns (uint16) {
require(
value <= type(uint16).max,
"SafeCast: value doesn't fit in 16 bits"
);
return uint16(value);
}
function toUint8(uint256 value) internal pure returns (uint8) {
require(
value <= type(uint8).max,
"SafeCast: value doesn't fit in 8 bits"
);
return uint8(value);
}
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
function toInt128(int256 value) internal pure returns (int128) {
require(
value >= type(int128).min && value <= type(int128).max,
"SafeCast: value doesn't fit in 128 bits"
);
return int128(value);
}
function toInt64(int256 value) internal pure returns (int64) {
require(
value >= type(int64).min && value <= type(int64).max,
"SafeCast: value doesn't fit in 64 bits"
);
return int64(value);
}
function toInt32(int256 value) internal pure returns (int32) {
require(
value >= type(int32).min && value <= type(int32).max,
"SafeCast: value doesn't fit in 32 bits"
);
return int32(value);
}
function toInt16(int256 value) internal pure returns (int16) {
require(
value >= type(int16).min && value <= type(int16).max,
"SafeCast: value doesn't fit in 16 bits"
);
return int16(value);
}
function toInt8(int256 value) internal pure returns (int8) {
require(
value >= type(int8).min && value <= type(int8).max,
"SafeCast: value doesn't fit in 8 bits"
);
return int8(value);
}
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(
value <= uint256(type(int256).max),
"SafeCast: value doesn't fit in an int256"
);
return int256(value);
}
}
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
function tryRecover(bytes32 hash, bytes memory signature)
internal
pure
returns (address, RecoverError)
{
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
function recover(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(
vs,
0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (
uint256(s) >
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
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)
);
}
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
}
}
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(
typeHash,
hashedName,
hashedVersion
);
_TYPE_HASH = typeHash;
}
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return
_buildDomainSeparator(
_TYPE_HASH,
_HASHED_NAME,
_HASHED_VERSION
);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return
keccak256(
abi.encode(
typeHash,
nameHash,
versionHash,
block.chainid,
address(this)
)
);
}
function _hashTypedDataV4(bytes32 structHash)
internal
view
virtual
returns (bytes32)
{
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
library Address {
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;
}
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"
);
}
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"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
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);
}
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
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);
}
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);
}
}
}
}
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
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);
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
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);
}
}
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
abstract contract ERC165 is IERC165 {
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
library Timers {
struct Timestamp {
uint64 _deadline;
}
function getDeadline(Timestamp memory timer)
internal
pure
returns (uint64)
{
return timer._deadline;
}
function setDeadline(Timestamp storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(Timestamp storage timer) internal {
timer._deadline = 0;
}
function isUnset(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(Timestamp memory timer) internal view returns (bool) {
return timer._deadline > block.timestamp;
}
function isExpired(Timestamp memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.timestamp;
}
struct BlockNumber {
uint64 _deadline;
}
function getDeadline(BlockNumber memory timer)
internal
pure
returns (uint64)
{
return timer._deadline;
}
function setDeadline(BlockNumber storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(BlockNumber storage timer) internal {
timer._deadline = 0;
}
function isUnset(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(BlockNumber memory timer) internal view returns (bool) {
return timer._deadline > block.number;
}
function isExpired(BlockNumber memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.number;
}
}
abstract contract IGovernor is IERC165 {
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/**
* @dev Emitted when a proposal is created.
*/
event ProposalCreated(
uint256 proposalId,
address proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/**
* @dev Emitted when a proposal is canceled.
*/
event ProposalCanceled(uint256 proposalId);
/**
* @dev Emitted when a proposal is executed.
*/
event ProposalExecuted(uint256 proposalId);
/**
* @dev Emitted when a vote is cast.
*
* Note: `support` values should be seen as buckets. There interpretation depends on the voting module used.
*/
event VoteCast(
address indexed voter,
uint256 proposalId,
uint8 support,
uint256 weight,
string reason
);
event Shout(string mouthVomit);
/**
* @notice module:core
* @dev Name of the governor instance (used in building the ERC712 domain separator).
*/
function name() public view virtual returns (string memory);
/**
* @notice module:core
* @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
*/
function version() public view virtual returns (string memory);
/**
* @notice module:voting
* @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to
* be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of
* key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
*
* There are 2 standard keys: `support` and `quorum`.
*
* - `support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`.
* - `quorum=bravo` means that only For votes are counted towards quorum.
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
*
* NOTE: The string can be decoded by the standard
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
* JavaScript class.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual returns (string memory);
/**
* @notice module:core
* @dev Hashing function used to (re)build the proposal id from the proposal details..
*/
function hashProposal(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata calldatas,
bytes32 descriptionHash
) public pure virtual returns (uint256);
/**
* @notice module:core
* @dev Current state of a proposal, following Compound's convention
*/
function state(uint256 proposalId)
public
view
virtual
returns (ProposalState);
/**
* @notice module:core
* @dev block number used to retrieve user's votes and quorum.
*/
function proposalSnapshot(uint256 proposalId)
public
view
virtual
returns (uint256);
/**
* @notice module:core
* @dev timestamp at which votes close.
*/
function proposalDeadline(uint256 proposalId)
public
view
virtual
returns (uint256);
/**
* @notice module:user-config
* @dev delay, in number of block, between the proposal is created and the vote starts. This can be increassed to
* leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
*/
function votingDelay() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev delay, in number of blocks, between the vote start and vote ends.
*
* Note: the {votingDelay} can delay the start of the vote. This must be considered when setting the voting
* duration compared to the voting delay.
*/
function votingPeriod() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Minimum number of cast voted required for a proposal to be successful.
*
* Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the
* quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).
*/
function quorum(uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:reputation
* @dev Voting power of an `account` at a specific `blockNumber`.
*
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
* multiple), {ERC20Votes} tokens.
*/
function getVotes(address account, uint256 blockNumber)
public
view
virtual
returns (uint256);
/**
* @notice module:voting
* @dev Returns weither `account` has cast a vote on `proposalId`.
*/
function hasVoted(uint256 proposalId, address account)
public
view
virtual
returns (bool);
/**
* @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends
* {IGovernor-votingPeriod} blocks after the voting starts.
*
* Emits a {ProposalCreated} event.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256 proposalId);
/**
* @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the
* deadline to be reached.
*
* Emits a {ProposalExecuted} event.
*
* Note: some module can modify the requirements for execution, for example by adding an additional timelock.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual returns (uint256 proposalId);
/**
* @dev Cast a vote
*
* Emits a {VoteCast} event.
*/
function castVote(uint256 proposalId, uint8 support)
public
virtual
returns (uint256 balance);
/**
* @dev Cast a with a reason
*
* Emits a {VoteCast} event.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual returns (uint256 balance);
/**
* @dev Cast a vote using the user cryptographic signature.
*
* Emits a {VoteCast} event.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (uint256 balance);
}
interface IWorldOfWhiteDudes {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
function totalSupply() external view returns (uint256);
function maxSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @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);
function walletOfOwner(address owner)
external
view
returns (uint256[] memory);
}
abstract contract BoolPacker {
function getBoolean(uint256 _packedBools, uint256 _boolNumber)
internal
pure
returns (bool)
{
uint256 flag = (_packedBools >> _boolNumber) & uint256(1);
return (flag == 1 ? true : false);
}
function setBoolean(
uint256 _packedBools,
uint256 _boolNumber,
bool _value
) internal pure returns (uint256) {
if (_value) return _packedBools | (uint256(1) << _boolNumber);
else return _packedBools & ~(uint256(1) << _boolNumber);
}
}
abstract contract Governor is Ownable, ERC165, EIP712, IGovernor, BoolPacker {
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
IWorldOfWhiteDudes public immutable token =
IWorldOfWhiteDudes(0xD00D1e06a2680E02919f4F5c5EC5dC45d67bB0b5);
bytes32 public constant BALLOT_TYPEHASH =
keccak256("Ballot(uint256 proposalId,uint8 support)");
struct ProposalVote {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
uint16 againstVotes;
uint16 forVotes;
uint16 abstainVotes;
uint16 maxVotes;
//mapping(address => uint16) voteCount;
//mapping(uint256 => bool) tokenHasVoted;
//uint8[10000] tokenHasVoted;
uint256[40] tokenHasVoted;
}
function getTokenHasVoted(uint256 proposalId, uint256 tokenId)
public
view
returns (bool hasTokenVoted)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return
getBoolean(proposalvote.tokenHasVoted[tokenId / 40], tokenId % 256);
}
string private _name;
uint256 public totalProposals;
mapping(uint256 => uint256) public proposalIndexes;
mapping(uint256 => string) public proposalTitles;
mapping(uint256 => ProposalVote) internal _proposals;
/**
* @dev Restrict access to governor executing address. Some module might override the _executor function to make
* sure this modifier is consistant with the execution model.
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
_;
}
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status = _NOT_ENTERED;
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
/**
* @dev Sets the value for {name} and {version}
*/
constructor(string memory name_) EIP712(name_, version()) {
_name = name_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC165)
returns (bool)
{
return
interfaceId == type(IGovernor).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* accross multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return
uint256(
keccak256(
abi.encode(targets, values, calldatas, descriptionHash)
)
);
}
function state(uint256 proposalId)
public
view
virtual
override
returns (ProposalState)
{
ProposalVote storage proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
} else if (proposal.canceled) {
return ProposalState.Canceled;
} else if (proposal.voteStart.isPending()) {
return ProposalState.Pending;
} else if (proposal.voteEnd.isPending()) {
return ProposalState.Active;
} else if (proposal.voteEnd.isExpired()) {
return
_quorumReached(proposalId) && _voteSucceeded(proposalId)
? ProposalState.Succeeded
: ProposalState.Defeated;
} else {
revert("Governor: unknown proposal id");
}
}
function proposalSnapshot(uint256 proposalId)
public
view
virtual
override
returns (uint256)
{
return _proposals[proposalId].voteStart.getDeadline();
}
function proposalDeadline(uint256 proposalId)
public
view
virtual
override
returns (uint256)
{
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId)
internal
view
virtual
returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId)
internal
view
virtual
returns (bool);
function _countVote(
uint256 proposalId,
address account,
uint8 support
) internal virtual returns (uint16);
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
string memory blank;
return NewPropose(targets, values, calldatas, blank, description);
}
function NewPropose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory title,
string memory description
) public virtual returns (uint256) {
uint256 proposalId = hashProposal(
targets,
values,
calldatas,
keccak256(bytes(description))
);
require(
targets.length == values.length,
"Governor: invalid proposal length"
);
require(
targets.length == calldatas.length,
"Governor: invalid proposal length"
);
require(targets.length > 0, "Governor: empty proposal");
ProposalVote storage proposal = _proposals[proposalId];
require(
proposal.voteStart.isUnset(),
"Governor: proposal already exists"
);
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
proposal.maxVotes = uint16(token.totalSupply());
proposalIndexes[totalProposals] = proposalId;
proposalTitles[proposalId] = title;
totalProposals += 1;
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override nonReentrant returns (uint256) {
uint256 proposalId = hashProposal(
targets,
values,
calldatas,
descriptionHash
);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_execute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{
value: values[i]
}(calldatas[i]);
Address._verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(
targets,
values,
calldatas,
descriptionHash
);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled &&
status != ProposalState.Expired &&
status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support)
public
virtual
override
returns (uint256)
{
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(
keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))
),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
require(
state(proposalId) == ProposalState.Active,
"Governor: vote not currently active"
);
uint256 weight = _countVote(proposalId, account, support);
emit VoteCast(account, proposalId, support, weight, reason);
return weight;
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
}
abstract contract GovernorProposalThreshold is Governor {
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(msg.sender, block.number - 1) >= proposalThreshold(),
"GovernorCompatibilityBravo: proposer votes below proposal threshold"
);
return super.propose(targets, values, calldatas, description);
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256);
}
abstract contract GovernorCountingSimple is Governor {
/**
* @dev Supported vote types. Matches Governor Bravo ordering.
*/
enum VoteType {
Against,
For,
Abstain
}
/**
* @dev See {IGovernor-COUNTING_MODE}.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE()
public
pure
virtual
override
returns (string memory)
{
return "support=bravo&quorum=for,abstain";
}
function getVotes(address account, uint256)
public
view
virtual
override
returns (uint256)
{
return token.balanceOf(account);
}
function votesLeft(uint256 proposalId, address account)
public
view
virtual
returns (uint256 voteAmount)
{
uint256 tokenCount = token.balanceOf(account);
uint256 tokenId;
ProposalVote storage proposalvote = _proposals[proposalId];
for (uint256 i = 0; i < tokenCount; i++) {
tokenId = token.tokenOfOwnerByIndex(account, i);
if (
!getTokenHasVoted(proposalId, tokenId) &&
//proposalvote.tokenHasVoted[tokenId] == 0 &&
tokenId < proposalvote.maxVotes
) {
voteAmount += 1;
}
}
return voteAmount;
}
/**
* @dev See {IGovernor-hasVoted}.
*/
function hasVoted(uint256, address)
public
view
virtual
override
returns (bool)
{
require(false, "Don't use this method");
return false;
//return _proposals[proposalId].voteCount[account] > 0;
}
/**
* @dev Accessor to the internal vote counts.
*/
function proposalVotes(uint256 proposalId)
public
view
virtual
returns (
uint256 againstVotes,
uint256 forVotes,
uint256 abstainVotes
)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return (
proposalvote.againstVotes,
proposalvote.forVotes,
proposalvote.abstainVotes
);
}
function getProposal(uint256 proposalId)
public
view
virtual
returns (
string memory title,
string memory currentState,
uint256 againstVotes,
uint256 forVotes,
uint256 abstainVotes,
uint256 totalVotes,
uint256 currentQuorum,
uint256 minQuorum,
uint256 maxVotes
)
{
string[8] memory proposalStates;
proposalStates = [
"Pending",
"Active",
"Canceled",
"Defeated",
"Succeeded",
"Queued",
"Expired",
"Executed"
];
ProposalVote storage proposalvote = _proposals[proposalId];
return (
proposalTitles[proposalId],
proposalStates[uint256(state(proposalId))],
proposalvote.againstVotes,
proposalvote.forVotes,
proposalvote.abstainVotes,
proposalvote.againstVotes +
proposalvote.forVotes +
proposalvote.abstainVotes,
proposalvote.forVotes + proposalvote.abstainVotes,
quorum(proposalvote.maxVotes),
proposalvote.maxVotes
);
}
/*
function getProposalAccountVotes(uint256 proposalId, address owner)
public
view
virtual
returns (uint256 ownerVoteCount)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return (proposalvote.voteCount[owner]);
}
*/
function hasTokenVoted(uint256 proposalId, uint256 tokenId)
public
view
virtual
returns (bool tokenVoted)
{
//ProposalVote storage proposalvote = _proposals[proposalId];
//return (proposalvote.tokenHasVoted[tokenId] == 1);
return getTokenHasVoted(proposalId, tokenId);
}
function _quorumReached(uint256 proposalId)
internal
view
virtual
override
returns (bool)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return
quorum(_proposals[proposalId].maxVotes) <=
proposalvote.forVotes + proposalvote.abstainVotes;
}
function _voteSucceeded(uint256 proposalId)
internal
view
virtual
override
returns (bool)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return proposalvote.forVotes > proposalvote.againstVotes;
}
function _countVote(
uint256 proposalId,
address account,
uint8 support
) internal virtual override returns (uint16 voteAmount) {
ProposalVote storage proposalvote = _proposals[proposalId];
uint256[40] storage vState = proposalvote.tokenHasVoted;
uint256[] memory tokens = token.walletOfOwner(account);
uint256 tokenId;
uint256 idxInt;
uint256 idxBool;
for (uint256 i = 0; i < tokens.length; i++) {
tokenId = tokens[i];
idxInt = tokenId / 40;
idxBool = tokenId % 256;
if (
((vState[idxInt] >> idxBool) & uint256(1)) != 1 &&
tokenId < proposalvote.maxVotes
) {
vState[idxInt] = vState[idxInt] | (uint256(1) << idxBool);
voteAmount += 1;
}
}
require(voteAmount > 0, "GovernorVotingSimple: No votes left");
if (support == uint8(VoteType.Against)) {
proposalvote.againstVotes += voteAmount;
} else if (support == uint8(VoteType.For)) {
proposalvote.forVotes += voteAmount;
} else if (support == uint8(VoteType.Abstain)) {
proposalvote.abstainVotes += voteAmount;
} else {
revert("GovernorVotingSimple: invalid value for enum VoteType");
}
}
}
abstract contract GovernorVotesQuorumFraction is Governor {
uint256 private _quorumNumerator;
event QuorumNumeratorUpdated(
uint256 oldQuorumNumerator,
uint256 newQuorumNumerator
);
constructor(uint256 quorumNumeratorValue) {
_updateQuorumNumerator(quorumNumeratorValue);
}
function quorumNumerator() public view virtual returns (uint256) {
return _quorumNumerator;
}
function quorumDenominator() public view virtual returns (uint256) {
return 100;
}
function quorum(uint256 totalVotes)
public
view
virtual
override
returns (uint256)
{
return (totalVotes * quorumNumerator()) / quorumDenominator();
}
function updateQuorumNumerator(uint256 newQuorumNumerator)
external
virtual
onlyGovernance
{
_updateQuorumNumerator(newQuorumNumerator);
}
function _updateQuorumNumerator(uint256 newQuorumNumerator)
internal
virtual
{
require(
newQuorumNumerator <= quorumDenominator(),
"GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator"
);
uint256 oldQuorumNumerator = _quorumNumerator;
_quorumNumerator = newQuorumNumerator;
emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator);
}
}
contract WOWDGovernor is
Governor,
GovernorProposalThreshold,
GovernorCountingSimple,
GovernorVotesQuorumFraction
{
uint256 private _votingPeriod = 90000; // Mainnet 90000 15 days, Testnet 1.5 9000
uint256 private _proposalThreshold = 11;
constructor() Governor("WOWDGovernor") GovernorVotesQuorumFraction(18) {}
function votingDelay() public pure override returns (uint256) {
return 1; // 1 block
}
function votingPeriod() public view override returns (uint256) {
return _votingPeriod;
}
function setVotingPeriod(uint256 newPeriod) external onlyGovernance {
_votingPeriod = newPeriod;
}
function proposalThreshold() public view override returns (uint256) {
return _proposalThreshold;
}
function setProposalThreshold(uint256 newThreshhold)
external
onlyGovernance
{
_proposalThreshold = newThreshhold;
}
// The following functions are overrides required by Solidity.
function quorum(uint256 totalVotes)
public
view
override(IGovernor, GovernorVotesQuorumFraction)
returns (uint256)
{
return super.quorum(totalVotes);
}
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernor, GovernorCountingSimple)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function shoutOut(string memory mouthVomit) external onlyGovernance {
emit Shout(mouthVomit);
}
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public override(Governor, GovernorProposalThreshold) returns (uint256) {
return super.propose(targets, values, calldatas, description);
}
function proposeShout(string memory title, string memory description)
public
returns (uint256)
{
return _proShout(title, description, 0);
}
function executeShout(string memory title, string memory description)
public
returns (uint256)
{
return _proShout(title, description, 1);
}
function _proShout(
string memory title,
string memory description,
uint256 exec
) internal returns (uint256) {
bytes[] memory payload = new bytes[](1);
payload[0] = abi.encodeWithSignature("shoutOut(string)", description);
address[] memory targets = new address[](1);
targets[0] = address(this);
uint256[] memory values = new uint256[](1);
values[0] = 0;
if (exec == 1) {
return
execute(
targets,
values,
payload,
keccak256(bytes(description))
);
}
return NewPropose(targets, values, payload, title, description);
}
function proposeNominate(
string memory title,
address recipient,
uint256 amountWei,
string memory description
) public returns (uint256) {
return _proNominate(title, recipient, amountWei, description, 0);
}
function executeNominate(
string memory title,
address recipient,
uint256 amountWei,
string memory description
) public returns (uint256) {
return _proNominate(title, recipient, amountWei, description, 1);
}
function _proNominate(
string memory title,
address recipient,
uint256 amountWei,
string memory description,
uint256 exec
) private returns (uint256) {
bytes[] memory payload = new bytes[](1);
address[] memory targets = new address[](1);
targets[0] = payable(recipient);
uint256[] memory values = new uint256[](1);
values[0] = amountWei;
if (exec == 1) {
return
execute(
targets,
values,
payload,
keccak256(bytes(description))
);
}
return NewPropose(targets, values, payload, title, description);
}
function deposit() external payable {}
fallback() external payable {}
receive() external payable {}
}
|
Accessor to the internal vote counts./
|
function proposalVotes(uint256 proposalId)
public
view
virtual
returns (
uint256 againstVotes,
uint256 forVotes,
uint256 abstainVotes
)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return (
proposalvote.againstVotes,
proposalvote.forVotes,
proposalvote.abstainVotes
);
}
| 285,496
|
./partial_match/42/0x526dBb7270DcE7982a957f5C159177f2474342aB/sources/DFG.sol
|
uint256 ethForMarketBuyRFI = totalETHContributed.div(1000).mul(875); uint256 amountOut = getEstimatedRFIforETHTEST(ethForMarketBuyRFI); address pair = uniswapFactory.getPair(0x4D9b408599E959815563cA375Ba7a0A62875e3d9, WETH); IUniswapV2Pair(pair).swap(amountOut, 0, address(this), "");
|
function addEthLiquidityLGETEST3(uint amount)public payable {
address WETH = uniswapRouterV2.WETH();
IWETH(WETH).approve(address(uniswapRouterV2), uint256(-1));
uniswapRouterV2.swapExactTokensForTokens(
amount,
0,
);
}
| 3,297,640
|
./partial_match/4/0xd02236E844c5787e5B30F8b736A622E99D36DBc4/sources/poolerToken.sol
|
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.adocusing-hooks[Using Hooks]./ handle premium round settlement before token transfer
|
function _beforeTokenTransfer(address from, address to, uint256) internal {
if (from != address(0)) {
_pool.settlePremiumByPoolerToken(from);
}
if (to != address(0)) {
_pool.settlePremiumByPoolerToken(to);
}
}
| 8,707,244
|
./partial_match/3/0x08C3aB4307a6bE4DB6dF04c9e4a4b5E62ee82A6d/sources/PXPv2Token.sol
|
transferFrom function to tansfer tokens when token is not paused/
|
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
return super.transferFrom(_from, _to, _value);
}
| 5,289,960
|
./full_match/77/0x804A40d12FdeD71D41cD69a0054d371a80Cc84da/sources/deploy/contracts/synthereum-pool/v5/LiquidityPoolLib.sol
|
Mint synthetic tokens using fixed amount of collateral This calculate the price using on chain price feed User must approve collateral transfer for the mint request to succeed self Data type the library is attached to lpPosition Position of the LP (see LPPosition struct) feeStatus Actual status of fee gained (see FeeStatus struct) mintParams Input parameters for minting (see MintParams struct) sender Sender of the mint transaction return syntheticTokensMinted Amount of synthetic tokens minted by a user return feePaid Amount of collateral paid by the user as fee/
|
function mint(
ISynthereumLiquidityPoolStorage.Storage storage self,
ISynthereumLiquidityPoolStorage.LPPosition storage lpPosition,
ISynthereumLiquidityPoolStorage.FeeStatus storage feeStatus,
ISynthereumLiquidityPool.MintParams calldata mintParams,
address sender
) external returns (uint256 syntheticTokensMinted, uint256 feePaid) {
FixedPoint.Unsigned memory totCollateralAmount =
FixedPoint.Unsigned(mintParams.collateralAmount);
(
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory feeAmount,
FixedPoint.Unsigned memory numTokens
) = self.mintCalculation(totCollateralAmount);
require(
numTokens.rawValue >= mintParams.minNumTokens,
'Number of tokens less than minimum limit'
);
checkExpiration(mintParams.expiration);
self.executeMint(
lpPosition,
feeStatus,
ExecuteMintParams(
numTokens,
collateralAmount,
feeAmount,
totCollateralAmount,
mintParams.recipient,
sender
)
);
syntheticTokensMinted = numTokens.rawValue;
feePaid = feeAmount.rawValue;
}
| 5,046,494
|
./partial_match/56/0xF7Cb81E39bE4778B8f950F949edB4f5461B6036F/sources/MasterDrunk.sol
|
Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
|
function updateEmissionRate(uint256 _drunkPerBlock) public onlyOwner {
massUpdatePools();
drunkPerBlock = _drunkPerBlock;
}
| 11,141,573
|
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
struct Airline {
string airlineName;
bool isRegistered;
bool isFunded;
address airline;
// Added for consensus
//address[] multiCalls; // = new address[](0);
}
mapping(address => Airline) airlines;
Airline[] airlineArray;
struct Flight {
string flightName;
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
//mapping(address => Flight) private flights;
//mapping(bytes32 => Flight) private flights;
mapping(string => Flight) private flights;
Flight[] flightArray;
struct Passenger {
bool isRegistered;
address passenger;
uint fund;
string flightNumber;
//address[] airlines; // = new address[](0);
}
mapping(address => Passenger) private passengers;
Passenger[] passengerArray;
uint tokenId = 1;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event FundWithdrawn(address addr, uint value);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor() public {
contractOwner = msg.sender;
address newAirline = msg.sender; //0xee9fd8f530906e74c9639b107837dba24e542fa8;
airlines[newAirline].isRegistered = true;
airlines[newAirline].airlineName = "JAL";
airlines[newAirline].isFunded = false;
airlines[newAirline].airline = newAirline;
airlineArray.push(airlines[newAirline]);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns(bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external requireContractOwner {
operational = mode;
}
function isAirline(address airline) public view returns(bool) {
require(airline != address(0), "airline address must be a valid address.");
return airlines[airline].isRegistered;
}
function isFlightRegistered(string name) public view returns(bool) {
//require(airline != address(0), "airline address must be a valid address.");
return flights[name].isRegistered;
}
function countRegisteredAirlies() public view returns(uint) {
return airlineArray.length;
}
function getRegisteredAirlieInfo(uint index) public view returns(string, bool, bool, address) {
return (
airlineArray[index].airlineName,
airlineArray[index].isRegistered,
airlineArray[index].isFunded,
airlineArray[index].airline
);
}
function getRegisteredFlightInfo(uint index) public view returns(string, bool, uint, uint, address) {
return (
flightArray[index].flightName,
flightArray[index].isRegistered,
flightArray[index].statusCode,
flightArray[index].updatedTimestamp,
flightArray[index].airline
);
}
function countRegisteredFlights() public view returns(uint) {
return flightArray.length;
}
function getPassengerInfo(address passenger) public view returns (bool, address, uint, string) {
return (
passengers[passenger].isRegistered,
passengers[passenger].passenger,
passengers[passenger].fund,
passengers[passenger].flightNumber
);
}
function getFlightInfo(string flightName) public view returns(string, bool, uint, uint, address) {
return (
flights[flightName].flightName,
flights[flightName].isRegistered,
flights[flightName].statusCode,
flights[flightName].updatedTimestamp,
flights[flightName].airline
);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address newAirline, string name) external requireIsOperational {
airlines[newAirline].isRegistered = true;
airlines[newAirline].airlineName = name;
airlines[newAirline].isFunded = false;
airlines[newAirline].airline = newAirline;
airlineArray.push(airlines[newAirline]);
tokenId ++;
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(string name, address airline) external requireIsOperational {
require(!flights[name].isRegistered, "The flight is already registered");
flights[name].flightName = name;
flights[name].isRegistered = true;
flights[name].statusCode = STATUS_CODE_UNKNOWN;
flights[name].updatedTimestamp = now;
flights[name].airline = airline;
flightArray.push(flights[name]);
}
function changeFlightStatus(string name, address airline, uint256 timestamp, uint8 statusCode) external requireIsOperational {
require(flights[name].isRegistered, "The flight should be registered");
require(keccak256(abi.encodePacked(flights[name].flightName)) == keccak256(abi.encodePacked(name)), "The flight name should be identical");
require(flights[name].airline == airline, "The flight airline should be identical");
flights[name].statusCode = statusCode;
flights[name].updatedTimestamp = timestamp;
//flightArray.push(flights[name]);
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(string flightName) external payable requireIsOperational {
require(this.isFlightRegistered(flightName), "The flight needs to be registered first.");
require(msg.value <= 1 ether, "Too much fund");
passengers[msg.sender].isRegistered = true;
passengers[msg.sender].passenger = msg.sender;
passengers[msg.sender].flightNumber = flightName;
passengers[msg.sender].fund += msg.value;
passengerArray.push(passengers[msg.sender]);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(string flightName) external requireIsOperational {
for (uint c = 0; c < passengerArray.length; c++) {
if (keccak256(abi.encodePacked(passengerArray[c].flightNumber)) == keccak256(abi.encodePacked(flightName)) && passengerArray[c].isRegistered) {
address passengerAddr = passengerArray[c].passenger;
uint value = passengers[passengerAddr].fund;
passengers[passengerAddr].fund = (value * 3)/2;
passengerArray[c] = passengers[passengerAddr];
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(uint256 amount) external requireIsOperational {
// Checks
require(passengers[msg.sender].fund >= amount, "Insufficient fund");
// Effects
uint256 value = passengers[msg.sender].fund;
passengers[msg.sender].fund = value.sub(amount);
//Interraction
msg.sender.transfer(amount);
emit FundWithdrawn(msg.sender, amount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund() public payable requireIsOperational {
uint requiredFund = 10 ether;
uint256 value = msg.value;
uint refund = 0;
if(msg.value > requiredFund) {
refund = value.sub(requiredFund);
}
contractOwner.transfer(msg.value - refund);
}
function getFlightKey(address airline, string memory flight, uint256 timestamp) pure internal returns(bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {
fund();
}
}
|
Register a future flight for insuring./
|
function registerFlight(string name, address airline) external requireIsOperational {
require(!flights[name].isRegistered, "The flight is already registered");
flights[name].flightName = name;
flights[name].isRegistered = true;
flights[name].statusCode = STATUS_CODE_UNKNOWN;
flights[name].updatedTimestamp = now;
flights[name].airline = airline;
flightArray.push(flights[name]);
}
| 15,806,762
|
/**
*Submitted for verification at Etherscan.io on 2019-09-28
*/
/*
* website: https://exclusiveplatform.com
*/
pragma solidity ^0.5.11;
/**
* @title SafeMath
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
}
contract ERC20Interface {
function totalSupply() public view returns (uint256);
uint256 counter_re_ent21 =0;
function callme_re_ent21() public{
require(counter_re_ent21<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent21 += 1;
}
function balanceOf(address tokenOwner) public view returns (uint256 balance);
mapping(address => uint) balances_re_ent10;
function withdrawFunds_re_ent10 (uint256 _weiToWithdraw) public {
require(balances_re_ent10[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent10[msg.sender] -= _weiToWithdraw;
}
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining);
mapping(address => uint) balances_re_ent21;
function withdraw_balances_re_ent21 () public {
(bool success,)= msg.sender.call.value(balances_re_ent21[msg.sender ])("");
if (success)
balances_re_ent21[msg.sender] = 0;
}
function transfer(address to, uint256 tokens) public returns (bool success);
mapping(address => uint) userBalance_re_ent12;
function withdrawBalance_re_ent12() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent12[msg.sender]) ) ){
revert();
}
userBalance_re_ent12[msg.sender] = 0;
}
function approve(address spender, uint256 tokens) public returns (bool success);
mapping(address => uint) redeemableEther_re_ent11;
function claimReward_re_ent11() public {
// ensure there is a reward to give
require(redeemableEther_re_ent11[msg.sender] > 0);
uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender];
msg.sender.transfer(transferValue_re_ent11); //bug
redeemableEther_re_ent11[msg.sender] = 0;
}
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
mapping(address => uint) balances_re_ent1;
function withdraw_balances_re_ent1 () public {
(bool success,) =msg.sender.call.value(balances_re_ent1[msg.sender ])("");
if (success)
balances_re_ent1[msg.sender] = 0;
}
uint256 counter_re_ent35 =0;
function callme_re_ent35() public{
require(counter_re_ent35<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent35 += 1;
}
event Transfer(address indexed from, address indexed to, uint256 tokens);
mapping(address => uint) userBalance_re_ent40;
function withdrawBalance_re_ent40() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
(bool success,)=msg.sender.call.value(userBalance_re_ent40[msg.sender])("");
if( ! success ){
revert();
}
userBalance_re_ent40[msg.sender] = 0;
}
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
contract Owned {
mapping(address => uint) redeemableEther_re_ent18;
function claimReward_re_ent18() public {
// ensure there is a reward to give
require(redeemableEther_re_ent18[msg.sender] > 0);
uint transferValue_re_ent18 = redeemableEther_re_ent18[msg.sender];
msg.sender.transfer(transferValue_re_ent18); //bug
redeemableEther_re_ent18[msg.sender] = 0;
}
address payable public owner;
mapping(address => uint) userBalance_re_ent33;
function withdrawBalance_re_ent33() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
(bool success,)= msg.sender.call.value(userBalance_re_ent33[msg.sender])("");
if( ! success ){
revert();
}
userBalance_re_ent33[msg.sender] = 0;
}
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;
}
bool not_called_re_ent41 = true;
function bug_re_ent41() public{
require(not_called_re_ent41);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent41 = false;
}
/**
* @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 payable newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
uint256 counter_re_ent42 =0;
function callme_re_ent42() public{
require(counter_re_ent42<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent42 += 1;
}
}
contract ExclusivePlatform is ERC20Interface, Owned {
using SafeMath for uint256;
mapping(address => uint) balances_re_ent29;
function withdraw_balances_re_ent29 () public {
if (msg.sender.send(balances_re_ent29[msg.sender ]))
balances_re_ent29[msg.sender] = 0;
}
mapping (address => uint256) balances;
bool not_called_re_ent6 = true;
function bug_re_ent6() public{
require(not_called_re_ent6);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent6 = false;
}
mapping (address => mapping (address => uint256)) allowed;
address payable lastPlayer_re_ent16;
uint jackpot_re_ent16;
function buyTicket_re_ent16() public{
if (!(lastPlayer_re_ent16.send(jackpot_re_ent16)))
revert();
lastPlayer_re_ent16 = msg.sender;
jackpot_re_ent16 = address(this).balance;
}
string public name = "Exclusive Platform";
mapping(address => uint) balances_re_ent24;
function withdrawFunds_re_ent24 (uint256 _weiToWithdraw) public {
require(balances_re_ent24[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent24[msg.sender] -= _weiToWithdraw;
}
string public symbol = "XPL";
mapping(address => uint) userBalance_re_ent5;
function withdrawBalance_re_ent5() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent5[msg.sender]) ) ){
revert();
}
userBalance_re_ent5[msg.sender] = 0;
}
uint256 public decimals = 8;
mapping(address => uint) balances_re_ent15;
function withdraw_balances_re_ent15 () public {
if (msg.sender.send(balances_re_ent15[msg.sender ]))
balances_re_ent15[msg.sender] = 0;
}
uint256 public _totalSupply;
uint256 counter_re_ent28 =0;
function callme_re_ent28() public{
require(counter_re_ent28<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent28 += 1;
}
uint256 public XPLPerEther = 8000000e8;
uint256 public minimumBuy = 1 ether / 100;
bool not_called_re_ent34 = true;
function bug_re_ent34() public{
require(not_called_re_ent34);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent34 = false;
}
bool public crowdsaleIsOn = true;
//mitigates the ERC20 short address attack
//suggested by izqui9 @ http://bit.ly/2NMMCNv
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
constructor () public {
_totalSupply = 10000000000e8;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
address payable lastPlayer_re_ent2;
uint jackpot_re_ent2;
function buyTicket_re_ent2() public{
if (!(lastPlayer_re_ent2.send(jackpot_re_ent2)))
revert();
lastPlayer_re_ent2 = msg.sender;
jackpot_re_ent2 = address(this).balance;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
mapping(address => uint) balances_re_ent17;
function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public {
require(balances_re_ent17[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
(bool success,)=msg.sender.call.value(_weiToWithdraw)("");
require(success); //bug
balances_re_ent17[msg.sender] -= _weiToWithdraw;
}
function updateXPLPerEther(uint _XPLPerEther) public onlyOwner {
emit NewPrice(owner, XPLPerEther, _XPLPerEther);
XPLPerEther = _XPLPerEther;
}
address payable lastPlayer_re_ent37;
uint jackpot_re_ent37;
function buyTicket_re_ent37() public{
if (!(lastPlayer_re_ent37.send(jackpot_re_ent37)))
revert();
lastPlayer_re_ent37 = msg.sender;
jackpot_re_ent37 = address(this).balance;
}
function switchCrowdsale() public onlyOwner {
crowdsaleIsOn = !(crowdsaleIsOn);
}
mapping(address => uint) balances_re_ent3;
function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public {
require(balances_re_ent3[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
(bool success,)= msg.sender.call.value(_weiToWithdraw)("");
require(success); //bug
balances_re_ent3[msg.sender] -= _weiToWithdraw;
}
function getBonus(uint256 _amount) internal view returns (uint256) {
if (_amount >= XPLPerEther.mul(5)) {
/*
* 20% bonus for 5 eth above
*/
return ((20 * _amount).div(100)).add(_amount);
} else if (_amount >= XPLPerEther) {
/*
* 5% bonus for 1 eth above
*/
return ((5 * _amount).div(100)).add(_amount);
}
return _amount;
}
address payable lastPlayer_re_ent9;
uint jackpot_re_ent9;
function buyTicket_re_ent9() public{
(bool success,) = lastPlayer_re_ent9.call.value(jackpot_re_ent9)("");
if (!success)
revert();
lastPlayer_re_ent9 = msg.sender;
jackpot_re_ent9 = address(this).balance;
}
function () payable external {
require(crowdsaleIsOn && msg.value >= minimumBuy);
uint256 totalBuy = (XPLPerEther.mul(msg.value)).div(1 ether);
totalBuy = getBonus(totalBuy);
doTransfer(owner, msg.sender, totalBuy);
}
mapping(address => uint) redeemableEther_re_ent25;
function claimReward_re_ent25() public {
// ensure there is a reward to give
require(redeemableEther_re_ent25[msg.sender] > 0);
uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender];
msg.sender.transfer(transferValue_re_ent25); //bug
redeemableEther_re_ent25[msg.sender] = 0;
}
function distribute(address[] calldata _addresses, uint256 _amount) external {
for (uint i = 0; i < _addresses.length; i++) {transfer(_addresses[i], _amount);}
}
mapping(address => uint) userBalance_re_ent19;
function withdrawBalance_re_ent19() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){
revert();
}
userBalance_re_ent19[msg.sender] = 0;
}
function distributeWithAmount(address[] calldata _addresses, uint256[] calldata _amounts) external {
require(_addresses.length == _amounts.length);
for (uint i = 0; i < _addresses.length; i++) {transfer(_addresses[i], _amounts[i]);}
}
mapping(address => uint) userBalance_re_ent26;
function withdrawBalance_re_ent26() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
(bool success,)= msg.sender.call.value(userBalance_re_ent26[msg.sender])("");
if( ! success ){
revert();
}
userBalance_re_ent26[msg.sender] = 0;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount) internal {
// Do not allow transfer to 0x0 or the token contract itself
require((_to != address(0)));
require(_amount <= balances[_from]);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
}
bool not_called_re_ent20 = true;
function bug_re_ent20() public{
require(not_called_re_ent20);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent20 = false;
}
function balanceOf(address _owner) view public returns (uint256) {
return balances[_owner];
}
mapping(address => uint) redeemableEther_re_ent32;
function claimReward_re_ent32() public {
// ensure there is a reward to give
require(redeemableEther_re_ent32[msg.sender] > 0);
uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender];
msg.sender.transfer(transferValue_re_ent32); //bug
redeemableEther_re_ent32[msg.sender] = 0;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
doTransfer(msg.sender, _to, _amount);
return true;
}
mapping(address => uint) balances_re_ent38;
function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public {
require(balances_re_ent38[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent38[msg.sender] -= _weiToWithdraw;
}
/// @return The balance of `_owner`
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
doTransfer(_from, _to, _amount);
return true;
}
mapping(address => uint) redeemableEther_re_ent4;
function claimReward_re_ent4() public {
// ensure there is a reward to give
require(redeemableEther_re_ent4[msg.sender] > 0);
uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender];
msg.sender.transfer(transferValue_re_ent4); //bug
redeemableEther_re_ent4[msg.sender] = 0;
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public 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
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
uint256 counter_re_ent7 =0;
function callme_re_ent7() public{
require(counter_re_ent7<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent7 += 1;
}
function allowance(address _owner, address _spender) view public returns (uint256) {
return allowed[_owner][_spender];
}
address payable lastPlayer_re_ent23;
uint jackpot_re_ent23;
function buyTicket_re_ent23() public{
if (!(lastPlayer_re_ent23.send(jackpot_re_ent23)))
revert();
lastPlayer_re_ent23 = msg.sender;
jackpot_re_ent23 = address(this).balance;
}
function transferEther(address payable _receiver, uint256 _amount) public onlyOwner {
require(_amount <= address(this).balance);
emit TransferEther(address(this), _receiver, _amount);
_receiver.transfer(_amount);
}
uint256 counter_re_ent14 =0;
function callme_re_ent14() public{
require(counter_re_ent14<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent14 += 1;
}
function withdrawFund() onlyOwner public {
uint256 balance = address(this).balance;
owner.transfer(balance);
}
address payable lastPlayer_re_ent30;
uint jackpot_re_ent30;
function buyTicket_re_ent30() public{
if (!(lastPlayer_re_ent30.send(jackpot_re_ent30)))
revert();
lastPlayer_re_ent30 = msg.sender;
jackpot_re_ent30 = address(this).balance;
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(burner, _value);
}
mapping(address => uint) balances_re_ent8;
function withdraw_balances_re_ent8 () public {
(bool success,) = msg.sender.call.value(balances_re_ent8[msg.sender ])("");
if (success)
balances_re_ent8[msg.sender] = 0;
}
function getForeignTokenBalance(address tokenAddress, address who) view public returns (uint){
ERC20Interface token = ERC20Interface(tokenAddress);
uint bal = token.balanceOf(who);
return bal;
}
mapping(address => uint) redeemableEther_re_ent39;
function claimReward_re_ent39() public {
// ensure there is a reward to give
require(redeemableEther_re_ent39[msg.sender] > 0);
uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender];
msg.sender.transfer(transferValue_re_ent39); //bug
redeemableEther_re_ent39[msg.sender] = 0;
}
function withdrawForeignTokens(address tokenAddress) onlyOwner public returns (bool) {
ERC20Interface token = ERC20Interface(tokenAddress);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
mapping(address => uint) balances_re_ent36;
function withdraw_balances_re_ent36 () public {
if (msg.sender.send(balances_re_ent36[msg.sender ]))
balances_re_ent36[msg.sender] = 0;
}
bool not_called_re_ent27 = true;
function bug_re_ent27() public{
require(not_called_re_ent27);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent27 = false;
}
event TransferEther(address indexed _from, address indexed _to, uint256 _value);
mapping(address => uint) balances_re_ent31;
function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public {
require(balances_re_ent31[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent31[msg.sender] -= _weiToWithdraw;
}
event NewPrice(address indexed _changer, uint256 _lastPrice, uint256 _newPrice);
bool not_called_re_ent13 = true;
function bug_re_ent13() public{
require(not_called_re_ent13);
(bool success,)=msg.sender.call.value(1 ether)("");
if( ! success ){
revert();
}
not_called_re_ent13 = false;
}
event Burn(address indexed _burner, uint256 value);
}
|
This is the actual transfer function in the token contract, it can only be called by other functions in this contract. _from The address holding the tokens being transferred _to The address of the recipient _amount The amount of tokens to be transferred return True if the transfer was successful Do not allow transfer to 0x0 or the token contract itself
|
function doTransfer(address _from, address _to, uint _amount) internal {
require((_to != address(0)));
require(_amount <= balances[_from]);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
}
bool not_called_re_ent20 = true;
| 12,951,623
|
./full_match/42161/0xc925e4F265daD6C515fD728b95d9561F3057Ba47/sources/project:/contracts/ArbitrumLife.sol
|
Compute the total price without buying. Used by the app to give a price estimate before the user buys
|
function estimateCells(
BuyRequest[] calldata reqs
) public view returns (uint256 price) {
uint reqsLength = reqs.length;
uint total = 0;
for (uint i = 0; i < reqsLength; i++) {
(uint toOwner, , uint toDeveloper, , ) = estimateRequest(reqs[i]);
total += toDeveloper + toOwner;
}
return total;
}
| 16,298,252
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @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;
}
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/**
* @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);
}
}
/**
* @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);
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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}. 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 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.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,
uint256 tokenId
) internal virtual {}
}
/**
* @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);
}
/**
* @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);
}
/**
* @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 Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default 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");
unchecked {
_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");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `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");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
/**
* @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);
}
// OpenZeppelin Contracts v4.3.2 (token/ERC721/extensions/ERC721Enumerable.sol)
/**
* @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();
}
}
//Version Mainnet
//**************** MAIN CONTRACT ****************************
//Who? A3g1X. When? The Fall before the Fall, 2021
contract CryptagionLaboratory is ERC721Enumerable{
event NewEthogen(uint indexed ethogenID, uint16 dtypeID, uint8 rarity);
//consts
uint constant DEC18 = 10 ** 18;
uint8 constant maxBaseStat = 200;
using Counters for Counters.Counter;
using Address for address;
uint upgradefee = 0.001 ether;
uint silverpackfee = 0.002 ether;
uint legendarypackfee = 3 ether;
uint sickpackfee = 0.2 ether;
uint16 sickbonusbase = 400;
uint16 sickfeebase = 1000;
uint16 userxpgainbase = 200;
uint16 founderpackcap1 = 800;
uint8 founderpackcap2 = 230;
uint8 founderpackcap3 = 80;
uint16 xpDivisor = 400;
uint8 sickburndivisor = 10;
// Base URI
string private _baseURIextended;
string private _contractURI;
Counters.Counter private _tokenIdTracker;
address payable private owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerOf(uint _ethogenID) {
require(msg.sender == ownerOf(_ethogenID));
_;
}
//main erc20 currency SICK
ERC20Burnable public sicktoken;
//dtypes - types of ethogens - owner can add new types with rarity caps
struct dtype{
uint16 raritycap1;
uint16 raritycap2;
uint16 raritycap3;
uint8 raritycap4;
uint8 raritycap5;
uint8 baseinfect;
uint8 basemort;
uint8 baseresist;
uint8 basestealth;
uint8 classtype;
uint8 legendarymaxcap;
}
dtype[] public dtypes;
//main token type: ethogen
struct Ethogen {
uint birthday;
uint birthblock;
uint16 dtype;
uint16 xp;
uint8 rarity;
uint8 level;
uint8 baseinfect;
uint8 basemort;
uint8 baseresist;
uint8 basestealth;
}
Ethogen[] public ethogens;
//additional stats 1:1 with Ethogen
struct EthogenStats {
uint8 modinfect;
uint8 modmort;
uint8 modresist;
uint8 modstealth;
uint8 boostinfect;
uint8 boostmort;
uint8 boostresist;
uint8 booststealth;
uint8 mutation;
uint8 trait;
uint8 special;
}
EthogenStats[] public ethogenstats;
//user stats
struct User {
uint incubating1;
uint incubating1date;
uint incubating2;
uint incubating2date;
uint incubating3;
uint incubating3date;
uint16 xp;
uint8 level;
}
mapping (address => User) public users;
//constructor
constructor() ERC721('Cryptagion Ethogen', 'ETHOGEN') {
_baseURIextended = "https://lab.cryptagion.com/tokenmeta/getmetadata.php?tokenid=";
_contractURI = "https://lab.cryptagion.com/tokenmeta/contractmetadata";
owner = payable(msg.sender);
setCurrency(0x3aA22ff4781D61FD3dbb820e0e2D9533bf908d5C);
//initial types
addType(92,56,45,181,14,6);
addType(107,16,38,132,21,8);
addType(55,62,152,43,41,10);
addType(74,157,63,31,35,6);
addType(130,41,86,78,12,8);
addType(56,77,133,87,41,6);
addType(142,26,21,173,22,8);
addType(72,64,98,95,33,10);
//mint a common as #0
mintRandom(62,1,1);
mintRandom(5,5,5);
}
//set and return URIs
function setBaseURI(string memory baseURI_) external onlyOwner() {
_baseURIextended = baseURI_;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
function setContractURI(string memory contractURI_) external onlyOwner() {
_contractURI = contractURI_;
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
//************************* SETTERS ******************************************
//this sets contract address of Cryptagion (SICK)
function setCurrency(address _token) public onlyOwner {
sicktoken = ERC20Burnable(_token);
}
//add new ethogen type
function addType ( uint8 _baseinfect, uint8 _basemort, uint8 _baseresist, uint8 _basestealth, uint8 _classtype,uint8 _legendarycap) public onlyOwner{
require (_legendarycap <=20, " Max is 20");
require (_basemort <=maxBaseStat && _baseinfect <=maxBaseStat && _basestealth <=maxBaseStat && _baseresist <=maxBaseStat, " Max Base Stat");
//proportion of mint caps in relation to legendary
uint16 commoncap = uint16(_legendarycap) * 150;
uint16 uncommoncap = uint16(_legendarycap) * 70;
uint16 rarecap = uint16(_legendarycap) * 20;
uint8 epiccap = uint8(_legendarycap) * 5;
dtypes.push(dtype(commoncap,uncommoncap,rarecap,epiccap,_legendarycap,_baseinfect,_basemort,_baseresist, _basestealth, _classtype,_legendarycap));
}
//overwrite ethogen type in case of f**k ups
function overwriteType (uint8 _baseinfect, uint8 _basemort, uint8 _baseresist, uint8 _basestealth, uint8 _classtype,uint _overwriteindex) external onlyOwner{
require (_basemort <=maxBaseStat && _baseinfect <=maxBaseStat && _basestealth <=maxBaseStat && _baseresist <=maxBaseStat, " Max Base Stat");
dtypes[_overwriteindex].baseresist = _baseresist;
dtypes[_overwriteindex].basestealth = _basestealth;
dtypes[_overwriteindex].baseinfect = _baseinfect;
dtypes[_overwriteindex].basemort = _basemort;
dtypes[_overwriteindex].classtype = _classtype;
}
//************************* THE MINT ******************************************
//mint random card with weighted rarity chances if _raritymin is 0, otherwise set the rarity
function mintRandom(uint _randomadd,uint8 _raritymin, uint8 _raritymax) private {
uint randNonce = 3 + _randomadd;
uint16 randomtype;
uint8 randomweight;
uint8 finalrarity;
//200 tries to get one that's not capped out.. just prevent endless loop
while (randNonce < _randomadd + 200){
randomtype = uint16(uint(keccak256(abi.encodePacked(block.number, msg.sender, randNonce))) % dtypes.length );
randNonce++;
if(_raritymin == 0){
randomweight = uint8(uint(keccak256(abi.encodePacked(block.number + _tokenIdTracker.current() , msg.sender, randNonce))) % 100 + 1);
if(_raritymax == 2)
{
if (randomweight < 66){finalrarity = 1;}
else {finalrarity = 2;}
}
else if(_raritymax == 3)
{
if (randomweight < 60){finalrarity = 1;}
else if (randomweight < 90){finalrarity = 2;}
else {finalrarity = 3;}
}
}
else{
finalrarity = _raritymin;
}
//particular mintcap?
if(checkmintcaps(randomtype,finalrarity)){
_mintEthogen(msg.sender, randomtype, finalrarity);
return;
}
randNonce++;
}
//massive fail
revert("No Cap, Try again") ;
}
//mint new ethogen
function _mintEthogen(address _to, uint16 _dtypeID, uint8 _rarity) private {
uint16 tmpfactor;
//set base stats based on rarity
if(_rarity == 1){tmpfactor = 1000;}
else if(_rarity == 2){tmpfactor = 1030;}
else if(_rarity == 3){tmpfactor = 1100;}
else if(_rarity == 4){tmpfactor = 1180;}
else if(_rarity == 5){tmpfactor = 1275;}
else {revert("Bad Rarity");}
//the real minting
uint256 newNftTokenId = _tokenIdTracker.current();
_mint(_to, newNftTokenId);
//percents increase based on rarity
uint8 finalinfect = uint8((uint32(dtypes[_dtypeID].baseinfect) * uint32(tmpfactor))/1000);
uint8 finalmort = uint8((uint32(dtypes[_dtypeID].basemort) * uint32(tmpfactor))/1000);
uint8 finalresist = uint8((uint32(dtypes[_dtypeID].baseresist) * uint32(tmpfactor))/1000);
uint8 finalstealth = uint8((uint32(dtypes[_dtypeID].basestealth) * uint32(tmpfactor))/1000);
//main Ethogen
ethogens.push(Ethogen(block.timestamp,block.number,_dtypeID, 0, _rarity, 0,finalinfect,finalmort,finalresist,finalstealth));
//random shizen
uint8 randommutation = uint8(uint(keccak256(abi.encodePacked(block.number + _tokenIdTracker.current() + 11, msg.sender))) % 255 + 1);
uint8 randomtrait = uint8(uint(keccak256(abi.encodePacked(block.timestamp + _tokenIdTracker.current() + 5, msg.sender))) % 255 + 1);
uint8 randomspecial = uint8(uint(keccak256(abi.encodePacked(block.timestamp + _tokenIdTracker.current() + 3, msg.sender))) % 255 + 1);
//EthogenStats 1:1 with Ethogens
ethogenstats.push(EthogenStats(1,1,1,1,0,0,0,0,randommutation,randomtrait,randomspecial));
_tokenIdTracker.increment();
//decrement specific value in mintcaps mapping and raritycaps array
if(_rarity == 1){dtypes[_dtypeID].raritycap1--;}
if(_rarity == 2){dtypes[_dtypeID].raritycap2--;}
if(_rarity == 3){dtypes[_dtypeID].raritycap3--;}
if(_rarity == 4){dtypes[_dtypeID].raritycap4--;}
if(_rarity == 5){dtypes[_dtypeID].raritycap5--;}
//emit the event
emit NewEthogen(newNftTokenId, _dtypeID, _rarity);
}
//mint a specific ethogen
function mintOwner(address _to, uint16 _dtypeID, uint8 _rarity) external onlyOwner {
require (checkmintcaps(_dtypeID,_rarity), "Cap reached");
_mintEthogen(_to, _dtypeID, _rarity);
}
//************************* SET FEES ******************************************
//set the upgradefee
function setUpgradeFee(uint _fee) external onlyOwner {
upgradefee = _fee;
}
//set the silver fee
function setSilverpackFee(uint _fee) external onlyOwner {
silverpackfee = _fee;
}
//set the legendary fee
function setLegendarypackFee(uint _fee) external onlyOwner {
legendarypackfee = _fee;
}
//set the sickpack fee
function setSickpackFee(uint _fee) external onlyOwner {
sickpackfee = _fee;
}
//set the userxpgainbase
function setUserXPgainBase(uint16 _newval) external onlyOwner {
userxpgainbase = _newval;
}
//set the sickbonusbase
function setSickBonusBase(uint16 _newval) external onlyOwner {
sickbonusbase = _newval;
}
//set the sickfeebase
function setSickFeeBase(uint16 _newval) external onlyOwner {
sickfeebase = _newval;
}
//set the sickburndivisor
function setSickBurnDivisor(uint8 _newval) external onlyOwner {
sickburndivisor = _newval;
}
//set the xpDivisor
function setXpDivisor(uint16 _newval) external onlyOwner {
xpDivisor = _newval;
}
//************************* PAYABLES ******************************************
//buy a pack
function buyCardPack(uint8 _packtype) external payable {
require((msg.value == silverpackfee || msg.value == 10 * silverpackfee || msg.value == 100 * silverpackfee || msg.value == sickpackfee || msg.value == legendarypackfee ) ," Fee must match one listed");
uint16 sickgain;
uint16 xpgain;
if(msg.value == silverpackfee && _packtype == 1){
//first uncom
mintRandom(13,2,2);
mintRandom(17,1,1);
if(founderpackcap1 > 0){
mintRandom(3,1,1);
sickgain = sickbonusbase * 2;
xpgain = userxpgainbase * 2;
founderpackcap1 --;
}
else{
sickgain = sickbonusbase;
xpgain = userxpgainbase;
}
}
else if(msg.value == silverpackfee * 10 && _packtype == 2){
//first rare
mintRandom(7,3,3);
mintRandom(4,2,2);
if(founderpackcap2 > 0){
mintRandom(13,0,2);
sickgain = sickbonusbase * 5;
xpgain = userxpgainbase * 3;
founderpackcap2 --;
}
else{
sickgain = sickbonusbase * 2;
xpgain = userxpgainbase * 2;
}
}
else if(msg.value == silverpackfee * 100 && _packtype == 3){
//first epic
mintRandom(24,4,4);
mintRandom(12,0,3);
if(founderpackcap3 > 0){
mintRandom(23,0,2);
sickgain = sickbonusbase * 10;
xpgain = userxpgainbase * 6;
founderpackcap3 --;
}
else{
sickgain = sickbonusbase * 5;
xpgain = userxpgainbase * 4;
}
}
else if(msg.value == sickpackfee && _packtype == 200){
mintRandom(9,0,2);
sickgain = sickbonusbase * 10;
xpgain = userxpgainbase * 2;
}
else if(msg.value == legendarypackfee && _packtype == 250){
mintRandom(7,5,5);
mintRandom(11,4,4);
mintRandom(5,3,3);
sickgain = sickbonusbase * 20;
xpgain = userxpgainbase * 10;
}
else if(msg.value == legendarypackfee && _packtype == 253){
mintRandom(13,5,5);
sickgain = sickbonusbase * 10;
xpgain = userxpgainbase * 5;
}
else{
revert("Wrong Amount ");
}
//give Sick, burn Sick, gain XP
sicktoken.transfer(msg.sender,sickgain * DEC18);
sicktoken.burn((sickgain * DEC18 ) / sickburndivisor);
useraddxp(uint16(xpgain));
}
//************************* SICK PAYABLE ******************************************
// buy user xp with sicktoken
function buyXPwithSick(uint16 _sicktokens) external {
require (_sicktokens > 0 && _sicktokens <= 32000 && (users[msg.sender].xp + _sicktokens) <= 32000 , "No_Max SICK");
sicktoken.transferFrom(address(msg.sender), address(this), _sicktokens * DEC18);
useraddxp(_sicktokens);
}
// buy small pack with SICK
function buyPackwithSick(uint8 _pack) external {
uint16 xpgain;
uint16 sickfee;
if(_pack == 1){
sickfee = sickfeebase;
xpgain = sickfeebase/2;
mintRandom(14,0,2);
}
else{
sickfee = sickfeebase * 10;
xpgain = sickfeebase * 5;
mintRandom(12,4,4);
}
sicktoken.transferFrom(address(msg.sender), address(this), sickfee * DEC18);
useraddxp(xpgain);
mintRandom(13,2,2);
}
// mutate with SICK
function mutate(uint _ethogenID, uint16 _rand) external onlyOwnerOf(_ethogenID){
sicktoken.transferFrom(address(msg.sender), address(this), sickfeebase * 5 * DEC18);
sicktoken.burn((sickfeebase * DEC18) / sickburndivisor);
useraddxp(sickfeebase);
ethogenstats[_ethogenID].mutation = uint8(uint(keccak256(abi.encodePacked(block.number + _tokenIdTracker.current() + _rand, msg.sender))) % 255 + 1);
}
//************************* EXTERNAL ETHOGEN UPDATES ******************************************
// boost an ethogen with SickToken
function boostStat(uint _ethogenID,uint8 _sicktokens,uint8 _stat) external onlyOwnerOf(_ethogenID){
uint8 finalfee;
if (_stat == 1){
if(uint16(ethogenstats[_ethogenID].boostinfect) + uint16(_sicktokens) > 255){
finalfee = uint8(255 - ethogenstats[_ethogenID].boostinfect);
ethogenstats[_ethogenID].boostinfect = 255;
}
else{
ethogenstats[_ethogenID].boostinfect = uint8(ethogenstats[_ethogenID].boostinfect + _sicktokens);
finalfee = _sicktokens;
}
}
else if (_stat == 2){
if(uint16(ethogenstats[_ethogenID].boostmort) + uint16(_sicktokens) > 255){
finalfee = uint8(255 - ethogenstats[_ethogenID].boostmort);
ethogenstats[_ethogenID].boostmort = 255;
}
else{
ethogenstats[_ethogenID].boostmort = uint8(ethogenstats[_ethogenID].boostmort + _sicktokens);
finalfee = _sicktokens;
}
}
else if (_stat == 3){
if(uint16(ethogenstats[_ethogenID].boostresist) + uint16(_sicktokens) > 255){
finalfee = uint8(255 - ethogenstats[_ethogenID].boostresist);
ethogenstats[_ethogenID].boostresist = 255;
}
else{
ethogenstats[_ethogenID].boostresist = uint8(ethogenstats[_ethogenID].boostresist + _sicktokens);
finalfee = _sicktokens;
}
}
else if (_stat == 4){
if(uint16(ethogenstats[_ethogenID].booststealth) + uint16(_sicktokens) > 255){
finalfee = uint8(255 - ethogenstats[_ethogenID].booststealth);
ethogenstats[_ethogenID].booststealth = 255;
}
else{
ethogenstats[_ethogenID].booststealth = uint8(ethogenstats[_ethogenID].booststealth + _sicktokens);
finalfee = _sicktokens;
}
}
//take some SICK for the boost
if(finalfee > 0){sicktoken.transferFrom(address(msg.sender), address(this), finalfee * DEC18);}
}
//************************* INCUBATE ******************************************
//lock token in incubator for upgrade fee
function incubatein1(uint _ethogenID) external payable onlyOwnerOf(_ethogenID){
require (users[msg.sender].incubating1 == 0 , " Full");
require(msg.value == upgradefee);
users[msg.sender].incubating1date = uint(block.timestamp);
users[msg.sender].incubating1 = _ethogenID;
}
function incubatein2(uint _ethogenID) external payable onlyOwnerOf(_ethogenID){
require (users[msg.sender].incubating2 == 0 , " Full");
require (users[msg.sender].level >= 50 , " Level 50");
require(msg.value == upgradefee);
users[msg.sender].incubating2date = uint(block.timestamp);
users[msg.sender].incubating2 = _ethogenID;
}
function incubatein3(uint _ethogenID) external payable onlyOwnerOf(_ethogenID){
require (users[msg.sender].incubating3 == 0 , " Full");
require(msg.value == upgradefee*3);
users[msg.sender].incubating3date = uint(block.timestamp);
users[msg.sender].incubating3 = _ethogenID;
}
//take out of incubator
function incubateout(uint8 _whichone) external {
uint ethogenID;
uint16 xpgained;
if(_whichone == 1){
if(users[msg.sender].incubating1 == 0){revert("Empty");}
ethogenID = users[msg.sender].incubating1;
users[msg.sender].incubating1 = 0;
xpgained = uint16((block.timestamp - users[msg.sender].incubating1date)/xpDivisor);
}
else if(_whichone == 2){
if(users[msg.sender].incubating2 == 0){revert("Empty");}
ethogenID = users[msg.sender].incubating2;
users[msg.sender].incubating2 = 0;
xpgained = uint16((block.timestamp - users[msg.sender].incubating2date)/xpDivisor);
}
else if(_whichone == 3){
if(users[msg.sender].incubating3 == 0){revert("Empty");}
ethogenID = users[msg.sender].incubating3;
users[msg.sender].incubating3 = 0;
xpgained = uint16((block.timestamp - users[msg.sender].incubating3date) * 3 /xpDivisor);
}
if(ownerOf(ethogenID) == msg.sender){
addxp(ethogenID,xpgained);
}
}
//************************* XP AND LEVELS ******************************************
//add xp check Max
function addxp(uint _ethogenID,uint16 _xp) private onlyOwnerOf(_ethogenID){
if(_xp > 32000){_xp=32000;}
if(ethogens[_ethogenID].xp + _xp > 32000){
ethogens[_ethogenID].xp = 32000;
}
else{
ethogens[_ethogenID].xp += _xp;
}
uint8 newlevel = calclevel(ethogens[_ethogenID].xp);
uint8 newmod = uint8(5 + (newlevel * 2) + (10 *ethogens[_ethogenID].rarity));
ethogens[_ethogenID].level = newlevel;
uint8 debuff = uint8(newlevel/4);
uint8 debuff2 = uint8(newlevel/8);
ethogenstats[_ethogenID].modmort = newmod;
ethogenstats[_ethogenID].modinfect = newmod;
ethogenstats[_ethogenID].modstealth = newmod;
ethogenstats[_ethogenID].modresist = newmod;
if (dtypes[ethogens[_ethogenID].dtype].classtype < 20){ ethogenstats[_ethogenID].modmort = newmod - 1;ethogenstats[_ethogenID].modstealth = newmod - debuff2;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 30){ethogenstats[_ethogenID].modinfect = newmod - debuff;ethogenstats[_ethogenID].modresist = newmod - 1;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 40){ethogenstats[_ethogenID].modstealth = newmod - debuff;ethogenstats[_ethogenID].modinfect = newmod - 1;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 50){ethogenstats[_ethogenID].modresist = newmod - debuff;ethogenstats[_ethogenID].modmort = newmod - debuff2;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 60){ethogenstats[_ethogenID].modresist = newmod - 1;ethogenstats[_ethogenID].modinfect = newmod - debuff2;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 70){ethogenstats[_ethogenID].modmort = newmod - debuff;ethogenstats[_ethogenID].modresist = newmod - debuff2;}
}
//add xp check Max
function useraddxp(uint16 _xp) private {
if(_xp > 32000){_xp=32000;}
//max xp 32k
if(users[msg.sender].xp + _xp > 32000){
users[msg.sender].xp = 32000;
}
else{
users[msg.sender].xp += _xp;
}
users[msg.sender].level = calclevel(users[msg.sender].xp);
}
//************************* GETTERS ******************************************
//showfees
function getfees() external view returns (uint,uint,uint,uint) {
return(upgradefee,silverpackfee,sickpackfee,legendarypackfee);
}
//show founder caps
function getfoundercaps() external view returns (uint16,uint8,uint8) {
return(founderpackcap1,founderpackcap2,founderpackcap3);
}
//show bases
function getbasenumbers() external view returns (uint16,uint16,uint16,uint8,uint16) {
return(userxpgainbase,sickbonusbase,sickfeebase,sickburndivisor,xpDivisor);
}
//************************* PRIVATE ******************************************
//check if cap is reached
function checkmintcaps(uint16 _dtypeID,uint8 _rarity) private view returns (bool){
if(_rarity == 1 && dtypes[_dtypeID].raritycap1<=0){return false;}
if(_rarity == 2 && dtypes[_dtypeID].raritycap2<=0){return false;}
if(_rarity == 3 && dtypes[_dtypeID].raritycap3<=0){return false;}
if(_rarity == 4 && dtypes[_dtypeID].raritycap4<=0){return false;}
if(_rarity == 5 && dtypes[_dtypeID].raritycap5<=0){return false;}
return true;
}
//square root yo
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
//get level from xp
function calclevel(uint16 _xp) internal pure returns (uint8) {
return uint8(sqrt(5*uint32(_xp)) / 4);
}
//************************* STEP 3 ******************************************
//step 3: (from the underpants)
function collectDonations(address payable _shareholder1,address payable _shareholder2,uint _divamount) external onlyOwner {
_shareholder1.transfer(_divamount /2);
_shareholder2.transfer(_divamount /2);
}
function collectSick(uint _sickamount) external onlyOwner {
sicktoken.transfer(owner, _sickamount * DEC18);
}
//end contract
}
|
SICK PAYABLE buy user xp with sicktoken
|
function buyXPwithSick(uint16 _sicktokens) external {
require (_sicktokens > 0 && _sicktokens <= 32000 && (users[msg.sender].xp + _sicktokens) <= 32000 , "No_Max SICK");
sicktoken.transferFrom(address(msg.sender), address(this), _sicktokens * DEC18);
useraddxp(_sicktokens);
}
| 1,186,649
|
pragma solidity ^0.4.18;
/**
* @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;
}
}
/// @title ServiceAllowance.
///
/// Provides a way to delegate operation allowance decision to a service contract
contract ServiceAllowance {
function isTransferAllowed(address _from, address _to, address _sender, address _token, uint _value) public view returns (bool);
}
contract ATxPlatformInterface {
mapping(bytes32 => address) public proxies;
function name(bytes32 _symbol) public view returns (string);
function setProxy(address _address, bytes32 _symbol) public returns (uint errorCode);
function isOwner(address _owner, bytes32 _symbol) public view returns (bool);
function totalSupply(bytes32 _symbol) public view returns (uint);
function balanceOf(address _holder, bytes32 _symbol) public view returns (uint);
function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint);
function baseUnit(bytes32 _symbol) public view returns (uint8);
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns (uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint errorCode);
function reissueAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function revokeAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function isReissuable(bytes32 _symbol) public view returns (bool);
function changeOwnership(bytes32 _symbol, address _newOwner) public returns (uint errorCode);
}
/**
* @title Owned contract with safe ownership pass.
*
* Note: all the non constant functions return false instead of throwing in case if state change
* didn't happen yet.
*/
contract Owned {
/**
* Contract owner address
*/
address public contractOwner;
/**
* Contract owner address
*/
address public pendingContractOwner;
function Owned() {
contractOwner = msg.sender;
}
/**
* @dev Owner check modifier
*/
modifier onlyContractOwner() {
if (contractOwner == msg.sender) {
_;
}
}
/**
* @dev Destroy contract and scrub a data
* @notice Only owner can call it
*/
function destroy() onlyContractOwner {
suicide(msg.sender);
}
/**
* Prepares ownership pass.
*
* Can only be called by current owner.
*
* @param _to address of the next owner. 0x0 is not allowed.
*
* @return success.
*/
function changeContractOwnership(address _to) onlyContractOwner() returns(bool) {
if (_to == 0x0) {
return false;
}
pendingContractOwner = _to;
return true;
}
/**
* Finalize ownership pass.
*
* Can only be called by pending owner.
*
* @return success.
*/
function claimContractOwnership() returns(bool) {
if (pendingContractOwner != msg.sender) {
return false;
}
contractOwner = pendingContractOwner;
delete pendingContractOwner;
return true;
}
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
/**
* @title Generic owned destroyable contract
*/
contract Object is Owned {
/**
* Common result code. Means everything is fine.
*/
uint constant OK = 1;
uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8;
function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) {
for(uint i=0;i<tokens.length;i++) {
address token = tokens[i];
uint balance = ERC20Interface(token).balanceOf(this);
if(balance != 0)
ERC20Interface(token).transfer(_to,balance);
}
return OK;
}
function checkOnlyContractOwner() internal constant returns(uint) {
if (contractOwner == msg.sender) {
return OK;
}
return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER;
}
}
/// @title Provides possibility manage holders? country limits and limits for holders.
contract DataControllerInterface {
/// @notice Checks user is holder.
/// @param _address - checking address.
/// @return `true` if _address is registered holder, `false` otherwise.
function isHolderAddress(address _address) public view returns (bool);
function allowance(address _user) public view returns (uint);
function changeAllowance(address _holder, uint _value) public returns (uint);
}
/// @title ServiceController
///
/// Base implementation
/// Serves for managing service instances
contract ServiceControllerInterface {
/// @notice Check target address is service
/// @param _address target address
/// @return `true` when an address is a service, `false` otherwise
function isService(address _address) public view returns (bool);
}
contract ATxAssetInterface {
DataControllerInterface public dataController;
ServiceControllerInterface public serviceController;
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool);
function __approve(address _spender, uint _value, address _sender) public returns (bool);
function __process(bytes /*_data*/, address /*_sender*/) payable public {
revert();
}
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
contract Platform {
mapping(bytes32 => address) public proxies;
function name(bytes32 _symbol) public view returns (string);
function setProxy(address _address, bytes32 _symbol) public returns (uint errorCode);
function isOwner(address _owner, bytes32 _symbol) public view returns (bool);
function totalSupply(bytes32 _symbol) public view returns (uint);
function balanceOf(address _holder, bytes32 _symbol) public view returns (uint);
function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint);
function baseUnit(bytes32 _symbol) public view returns (uint8);
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns (uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint errorCode);
function reissueAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function revokeAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function isReissuable(bytes32 _symbol) public view returns (bool);
function changeOwnership(bytes32 _symbol, address _newOwner) public returns (uint errorCode);
}
contract ATxAssetProxy is ERC20, Object, ServiceAllowance {
using SafeMath for uint;
/**
* Indicates an upgrade freeze-time start, and the next asset implementation contract.
*/
event UpgradeProposal(address newVersion);
// Current asset implementation contract address.
address latestVersion;
// Assigned platform, immutable.
Platform public platform;
// Assigned symbol, immutable.
bytes32 public smbl;
// Assigned name, immutable.
string public name;
/**
* Only platform is allowed to call.
*/
modifier onlyPlatform() {
if (msg.sender == address(platform)) {
_;
}
}
/**
* Only current asset owner is allowed to call.
*/
modifier onlyAssetOwner() {
if (platform.isOwner(msg.sender, smbl)) {
_;
}
}
/**
* Only asset implementation contract assigned to sender is allowed to call.
*/
modifier onlyAccess(address _sender) {
if (getLatestVersion() == msg.sender) {
_;
}
}
/**
* Resolves asset implementation contract for the caller and forwards there transaction data,
* along with the value. This allows for proxy interface growth.
*/
function() public payable {
_getAsset().__process.value(msg.value)(msg.data, msg.sender);
}
/**
* Sets platform address, assigns symbol and name.
*
* Can be set only once.
*
* @param _platform platform contract address.
* @param _symbol assigned symbol.
* @param _name assigned name.
*
* @return success.
*/
function init(Platform _platform, string _symbol, string _name) public returns (bool) {
if (address(platform) != 0x0) {
return false;
}
platform = _platform;
symbol = _symbol;
smbl = stringToBytes32(_symbol);
name = _name;
return true;
}
/**
* Returns asset total supply.
*
* @return asset total supply.
*/
function totalSupply() public view returns (uint) {
return platform.totalSupply(smbl);
}
/**
* Returns asset balance for a particular holder.
*
* @param _owner holder address.
*
* @return holder balance.
*/
function balanceOf(address _owner) public view returns (uint) {
return platform.balanceOf(_owner, smbl);
}
/**
* Returns asset allowance from one holder to another.
*
* @param _from holder that allowed spending.
* @param _spender holder that is allowed to spend.
*
* @return holder to spender allowance.
*/
function allowance(address _from, address _spender) public view returns (uint) {
return platform.allowance(_from, _spender, smbl);
}
/**
* Returns asset decimals.
*
* @return asset decimals.
*/
function decimals() public view returns (uint8) {
return platform.baseUnit(smbl);
}
/**
* Transfers asset balance from the caller to specified receiver.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transfer(address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, "");
}
else {
return false;
}
}
/**
* Transfers asset balance from the caller to specified receiver adding specified comment.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
*
* @return success.
*/
function transferWithReference(address _to, uint _value, string _reference) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, _reference);
}
else {
return false;
}
}
/**
* Performs transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK;
}
/**
* Prforms allowance transfer of asset balance between holders.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK;
}
/**
* Sets asset spending allowance for a specified spender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
*
* @return success.
*/
function approve(address _spender, uint _value) public returns (bool) {
if (_spender != 0x0) {
return _getAsset().__approve(_spender, _value, msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance setting call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
* @param _sender initial caller.
*
* @return success.
*/
function __approve(address _spender, uint _value, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyApprove(_spender, _value, smbl, _sender) == OK;
}
/**
* Emits ERC20 Transfer event on this contract.
*
* Can only be, and, called by assigned platform when asset transfer happens.
*/
function emitTransfer(address _from, address _to, uint _value) public onlyPlatform() {
Transfer(_from, _to, _value);
}
/**
* Emits ERC20 Approval event on this contract.
*
* Can only be, and, called by assigned platform when asset allowance set happens.
*/
function emitApprove(address _from, address _spender, uint _value) public onlyPlatform() {
Approval(_from, _spender, _value);
}
/**
* Returns current asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getLatestVersion() public view returns (address) {
return latestVersion;
}
/**
* Propose next asset implementation contract address.
*
* Can only be called by current asset owner.
*
* Note: freeze-time should not be applied for the initial setup.
*
* @param _newVersion asset implementation contract address.
*
* @return success.
*/
function proposeUpgrade(address _newVersion) public onlyAssetOwner returns (bool) {
// New version address should be other than 0x0.
if (_newVersion == 0x0) {
return false;
}
latestVersion = _newVersion;
UpgradeProposal(_newVersion);
return true;
}
function isTransferAllowed(address, address, address, address, uint) public view returns (bool) {
return true;
}
/**
* Returns asset implementation contract for current caller.
*
* @return asset implementation contract.
*/
function _getAsset() internal view returns (ATxAssetInterface) {
return ATxAssetInterface(getLatestVersion());
}
/**
* Resolves asset implementation contract for the caller and forwards there arguments along with
* the caller address.
*
* @return success.
*/
function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
}
contract ATxBuybackInterface {
event EtherReceived(uint amount);
event TokenExchanged(
address recepient,
address token,
uint tokenAmount,
uint etherAmount,
uint feeAmount,
address feeReceiver,
uint price
);
}
/// @title Token Buyback contract.
/// @notice Plays role of token exchange to Ether.
/// Has only one token at a contract. To support other tokens
/// there should be created other ATxBuyback contracts.
contract ATxBuyback is Object, ATxBuybackInterface, ServiceAllowance {
using SafeMath for uint;
struct FeeData {
uint feeValue;
uint feeDecimals;
}
/// @dev Redemption fee collector address
address public rdCollectorAddress;
/// @dev Fee value
FeeData rdFee;
/// @dev Token to exchange.
ATxAssetProxy public token;
/// @dev Price for 1 token
uint public price;
/// @dev Active flag
bool public active;
/// @dev Guards from invocation only when state is active
modifier onlyActive {
if (active) {
_;
}
}
function ATxBuyback(ATxAssetProxy _token) public {
require(address(_token) != 0x0);
token = _token;
}
/// @notice Sets a price (in wei) for selling one token
/// @param _price "in wei" = 1 ATx
function setPrice(uint _price) onlyContractOwner external returns (uint) {
price = _price;
return OK;
}
/// @notice Sets contract to active/non active state.
/// Should be performed only by contract owner.
/// @param _active next state of contract. True to activate a contract
/// @return result code of an operation
function setActive(bool _active) onlyContractOwner external returns (uint) {
if (active == _active) {
return;
}
active = _active;
return OK;
}
/// @notice Setup redemption destination address
/// @param _collectorAddress address where all redemptiom fee will be directed
/// @return result code of an operation
function setRdCollectorAddress(address _collectorAddress) onlyContractOwner external returns (uint) {
require(_collectorAddress != 0x0);
rdCollectorAddress = _collectorAddress;
return OK;
}
/// @notice Setup redemption fee value
/// @param _feeValue fee amount; the minimal value is 1
/// @param _feeDecimals fee decimals, sets a precision for fee value
/// @return result code of an operation
function setRdFee(uint _feeValue, uint _feeDecimals) onlyContractOwner external returns (uint) {
require(_validFee(_feeValue, _feeDecimals));
rdFee = FeeData(_feeValue, _feeDecimals);
return OK;
}
/// @notice Gets redemption fee value
/// @return {
/// "_value": "amount of percents",
/// "_decimals": "percent's precision"
/// }
function getRdFee() public view returns (uint _value, uint _decimals) {
FeeData memory _fee = rdFee;
return (_fee.feeValue, _fee.feeDecimals);
}
/// @notice Withdraws all Ether from buyback contract to specified address.
/// Allowed only for contract owner.
/// @param _to destination address to send Ether
/// @return result code of an operation
function withdrawAllEth(address _to) onlyContractOwner external returns (uint) {
uint _balance = address(this).balance;
if (_balance == 0) {
return 0;
}
_to.transfer(_balance);
return OK;
}
/// ServiceAllowance
///
/// @notice ServiceAllowance interface implementation
/// @dev Should cover conditions for allowance of transfers
function isTransferAllowed(address, address _to, address, address _token, uint) onlyActive public view returns (bool) {
if (_token == address(token) && _to == address(this)) {
return true;
}
}
/// @notice Fallback function for ERC223 standard.
/// Allowed to work only in active state.
/// @param _sender original sender of token transfer
/// @param _value amount of tokens that has been sent
function tokenFallback(address _sender, uint _value, bytes) external {
/// Don't allow to transfer and exchange tokens when Buyback contract
/// is not in 'active' state
if (!active) {
revert();
}
/// This call should be produced by AssetProxy's backend - an Asset contract.
/// Any other call will be followed by revert()
ATxAssetProxy _token = token;
if (msg.sender != _token.getLatestVersion()) {
revert();
}
/// Need to check available ETH balance in order to fulfill holder's request
/// about exchanging ATx Token to ETH equivalent
uint _etherToExchange = _value.mul(price) / (10 ** uint(_token.decimals()));
if (this.balance < _etherToExchange) {
revert();
}
/// To prevent double spending we revoke transferred assets from foundation platform,
ATxPlatformInterface _platform = ATxPlatformInterface(address(_token.platform()));
require(OK == _platform.revokeAsset(_token.smbl(), _value));
/// Take redemption fee and return left amount of Ether to transfer it to a holder
uint _restEther = _takeRdFee(_etherToExchange);
/// Transfer the rest to holder's account
_sender.transfer(_restEther);
/// Voila! Just emit the event to say to the world that one more exchange action was finished
TokenExchanged(_sender, _token, _value, _restEther, _etherToExchange.sub(_restEther), rdCollectorAddress, price);
}
/// @notice Accepts Ether and emits EtherReceived event
function() payable external {
if (msg.value > 0) {
EtherReceived(msg.value);
}
}
/* Internal */
function _takeRdFee(uint _fromValue) private returns (uint _restValue) {
/// Here we check if redemption fee was setup after the contract initialization
FeeData memory _fee = rdFee;
require(_validFee(_fee.feeValue, _fee.feeDecimals));
/// Calculate amount of redemption fee that we have to take from the whole sum
uint _rdFeeEther;
_rdFeeEther = _fromValue.mul(_fee.feeValue).div(10 ** _fee.feeDecimals);
_restValue = _fromValue.sub(_rdFeeEther);
/// At first use method collector.transfer() to ensure that if this move is not possible
/// then revert all changes
address _rdCollectorAddress = rdCollectorAddress;
require(_rdCollectorAddress != 0x0);
_rdCollectorAddress.transfer(_rdFeeEther);
}
function _validFee(uint _value, uint _decimals) private pure returns (bool) {
return _value != 0 && _value / 10 ** _decimals.sub(1) >= 0 && _value / 10 ** _decimals.sub(1) < 10;
}
}
|
Accepts Ether and emits EtherReceived event
|
function() payable external {
if (msg.value > 0) {
EtherReceived(msg.value);
}
}
| 5,396,532
|
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../libs/LibNativeOrder.sol";
import "../libs/LibSignature.sol";
/// @dev Feature for interacting with OTC orders.
interface IOtcOrdersFeature {
/// @dev Emitted whenever an `OtcOrder` is filled.
/// @param orderHash The canonical hash of the order.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param makerTokenFilledAmount How much maker token was filled.
/// @param takerTokenFilledAmount How much taker token was filled.
event OtcOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address makerToken,
address takerToken,
uint128 makerTokenFilledAmount,
uint128 takerTokenFilledAmount
);
/// @dev Fill an OTC order for up to `takerTokenFillAmount` taker tokens.
/// @param order The OTC order.
/// @param makerSignature The order signature from the maker.
/// @param takerTokenFillAmount Maximum taker token amount to fill this
/// order with.
/// @return takerTokenFilledAmount How much taker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOtcOrder(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
uint128 takerTokenFillAmount
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an OTC order for up to `takerTokenFillAmount` taker tokens.
/// Unwraps bought WETH into ETH before sending it to
/// the taker.
/// @param order The OTC order.
/// @param makerSignature The order signature from the maker.
/// @param takerTokenFillAmount Maximum taker token amount to fill this
/// order with.
/// @return takerTokenFilledAmount How much taker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOtcOrderForEth(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
uint128 takerTokenFillAmount
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an OTC order whose taker token is WETH for up
/// to `msg.value`.
/// @param order The OTC order.
/// @param makerSignature The order signature from the maker.
/// @return takerTokenFilledAmount How much taker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOtcOrderWithEth(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fully fill an OTC order. "Meta-transaction" variant,
/// requires order to be signed by both maker and taker.
/// @param order The OTC order.
/// @param makerSignature The order signature from the maker.
/// @param takerSignature The order signature from the taker.
function fillTakerSignedOtcOrder(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
LibSignature.Signature calldata takerSignature
)
external;
/// @dev Fully fill an OTC order. "Meta-transaction" variant,
/// requires order to be signed by both maker and taker.
/// Unwraps bought WETH into ETH before sending it to
/// the taker.
/// @param order The OTC order.
/// @param makerSignature The order signature from the maker.
/// @param takerSignature The order signature from the taker.
function fillTakerSignedOtcOrderForEth(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
LibSignature.Signature calldata takerSignature
)
external;
/// @dev Fills multiple taker-signed OTC orders.
/// @param orders Array of OTC orders.
/// @param makerSignatures Array of maker signatures for each order.
/// @param takerSignatures Array of taker signatures for each order.
/// @param unwrapWeth Array of booleans representing whether or not
/// to unwrap bought WETH into ETH for each order. Should be set
/// to false if the maker token is not WETH.
/// @return successes Array of booleans representing whether or not
/// each order in `orders` was filled successfully.
function batchFillTakerSignedOtcOrders(
LibNativeOrder.OtcOrder[] calldata orders,
LibSignature.Signature[] calldata makerSignatures,
LibSignature.Signature[] calldata takerSignatures,
bool[] calldata unwrapWeth
)
external
returns (bool[] memory successes);
/// @dev Fill an OTC order for up to `takerTokenFillAmount` taker tokens.
/// Internal variant.
/// @param order The OTC order.
/// @param makerSignature The order signature from the maker.
/// @param takerTokenFillAmount Maximum taker token amount to fill this
/// order with.
/// @param taker The address to fill the order in the context of.
/// @param useSelfBalance Whether to use the Exchange Proxy's balance
/// of input tokens.
/// @param recipient The recipient of the bought maker tokens.
/// @return takerTokenFilledAmount How much taker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillOtcOrder(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
uint128 takerTokenFillAmount,
address taker,
bool useSelfBalance,
address recipient
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Get the order info for an OTC order.
/// @param order The OTC order.
/// @return orderInfo Info about the order.
function getOtcOrderInfo(LibNativeOrder.OtcOrder calldata order)
external
view
returns (LibNativeOrder.OtcOrderInfo memory orderInfo);
/// @dev Get the canonical hash of an OTC order.
/// @param order The OTC order.
/// @return orderHash The order hash.
function getOtcOrderHash(LibNativeOrder.OtcOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the last nonce used for a particular
/// tx.origin address and nonce bucket.
/// @param txOrigin The address.
/// @param nonceBucket The nonce bucket index.
/// @return lastNonce The last nonce value used.
function lastOtcTxOriginNonce(address txOrigin, uint64 nonceBucket)
external
view
returns (uint128 lastNonce);
}
|
Feature for interacting with OTC orders.
|
interface IOtcOrdersFeature {
event OtcOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address makerToken,
address takerToken,
uint128 makerTokenFilledAmount,
uint128 takerTokenFilledAmount
);
function fillOtcOrder(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
uint128 takerTokenFillAmount
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
function fillOtcOrderForEth(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
uint128 takerTokenFillAmount
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
function fillOtcOrderWithEth(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
function fillTakerSignedOtcOrder(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
LibSignature.Signature calldata takerSignature
)
external;
function fillTakerSignedOtcOrderForEth(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
LibSignature.Signature calldata takerSignature
)
external;
function batchFillTakerSignedOtcOrders(
LibNativeOrder.OtcOrder[] calldata orders,
LibSignature.Signature[] calldata makerSignatures,
LibSignature.Signature[] calldata takerSignatures,
bool[] calldata unwrapWeth
)
external
returns (bool[] memory successes);
function _fillOtcOrder(
LibNativeOrder.OtcOrder calldata order,
LibSignature.Signature calldata makerSignature,
uint128 takerTokenFillAmount,
address taker,
bool useSelfBalance,
address recipient
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
function getOtcOrderInfo(LibNativeOrder.OtcOrder calldata order)
external
view
returns (LibNativeOrder.OtcOrderInfo memory orderInfo);
function getOtcOrderHash(LibNativeOrder.OtcOrder calldata order)
external
view
returns (bytes32 orderHash);
function lastOtcTxOriginNonce(address txOrigin, uint64 nonceBucket)
external
view
returns (uint128 lastNonce);
}
| 12,715,582
|
pragma solidity ^0.5.15;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Context {
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
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);
}
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);
}
function _burn(address account, uint256 amount) internal {
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);
}
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);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
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) {
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
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;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
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 {
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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
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");
}
}
}
interface WETH {
function deposit() external payable;
function withdraw(uint wad) external;
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
}
interface Controller {
function withdraw(address, uint) external;
function balanceOf(address) external view returns (uint);
function earn(address, uint) external;
function rewards() external view returns (address);
}
contract VaultETH {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
IERC20 public YFToken; // YF合约地址
uint public min = 9500;
uint public constant max = 10000;
uint public earnLowerlimit; // 池内空余资金到这个值就自动earn
address public governance;
address public controller;
struct Player {
uint256 stake; // 质押总数
uint256 payout; // 支出
uint256 total_out; // 已经领取的分红
}
mapping(address => Player) public player_; // (player => data) player data
struct Global {
uint256 total_stake; // 总质押总数
uint256 total_out; // 总分红金额
uint256 earnings_per_share; // 每股分红
}
mapping(uint256 => Global) public global_; // (global => data) global data
mapping (address => uint256) public deposittime;
uint256 constant internal magnitude = 10**40; // 10的40次方
address constant public yf = address(0x96F9632b25f874769969ff91219fCCb6ceDf26D2);
string public getName;
constructor (address _token) public {
token = IERC20(_token);
getName = string(abi.encodePacked("yf:Vault:", ERC20Detailed(_token).name()));
YFToken = IERC20(yf);
governance = tx.origin;
controller = 0xcC8d36211374a08fC61d74ed2E48e22b922C9D7C;
}
function balance() public view returns (uint) {
return token.balanceOf(address(this))
.add(Controller(controller).balanceOf(address(token)));
}
function setMin(uint _min) external {
require(msg.sender == governance, "!governance");
min = _min;
}
// 设置治理地址,必须验证原来治理地址的签名
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
// 设置目标token
function setToken(address _token) public {
require(msg.sender == governance, "!governance");
token = IERC20(_token);
}
// 设置控制器地址,必须验证治理地址的签名
function setController(address _controller) public {
require(msg.sender == governance, "!governance");
controller = _controller;
}
function setEarnLowerlimit(uint256 _earnLowerlimit) public{
require(msg.sender == governance, "!governance");
earnLowerlimit = _earnLowerlimit;
}
// Custom logic in here for how much the vault allows to be borrowed
// Sets minimum required on-hand to keep small withdrawals cheap
function available() public view returns (uint) {
return token.balanceOf(address(this)).mul(min).div(max);
}
// 抵押代币给Strategy合约进行理财,代币路径如下 vault->controller->strategy
function earn() public {
uint _bal = available(); // 获取最小需要转给机枪池进行获取收益的代币个数
token.safeTransfer(controller, _bal); // 转账给控制合约
Controller(controller).earn(address(token), _bal); // 抵押代币给Strategy合约进行理财
}
// 存款 可以追加存款
function deposit(uint amount) public payable {
// uint _before = token.balanceOf(address(this));
// uint amount = msg.value;
// WETH(address(token)).deposit.value(amount)();
// uint _after = token.balanceOf(address(this));
// amount = _after.sub(_before); // Additional check for deflationary tokens
WETH(address(token)).deposit.value(amount)(); //Convert ETH into the WETH
// 增加该用户的存款总数
player_[msg.sender].stake = player_[msg.sender].stake.add(amount);
// 如果每股分红为0
if (global_[0].earnings_per_share != 0) {
player_[msg.sender].payout = player_[msg.sender].payout.add(
global_[0].earnings_per_share.mul(amount).sub(1).div(magnitude).add(1) // (((earnings_per_share*amount)-1)/magnitude)+1
);
}
// 增加全局已抵押的总量
global_[0].total_stake = global_[0].total_stake.add(amount);
// 如果当前池子合约中已经抵押的数量大于自动赚取收益的值时,自动将合约中的代币去第三方平台抵押
if (token.balanceOf(address(this)) > earnLowerlimit){
earn();
}
// 更新用户抵押时间
deposittime[msg.sender] = now;
}
// No rebalance implementation for lower fees and faster swaps
// 取款
function withdraw(uint amount) external {
claim(); // 首先获取当前未领取的收益
require(amount <= player_[msg.sender].stake, "!balance");
uint r = amount;
// Check balance
uint b = token.balanceOf(address(this));
if (b < r) { // 如果vault合约中代币余额小于用户取款的余额,则需要去Strategy合约取款获得对应的代币
uint _withdraw = r.sub(b);
Controller(controller).withdraw(address(token), _withdraw); // 取款
uint _after = token.balanceOf(address(this));
uint _diff = _after.sub(b);
if (_diff < _withdraw) { // 策略器有可能会返回的代币变多,所以需要更新vault合约中的余额
r = b.add(_diff);
}
}
// 更新用户的已提取余额并且更新全局的每股收益
player_[msg.sender].payout = player_[msg.sender].payout.sub(
global_[0].earnings_per_share.mul(amount).div(magnitude)
);
// 更新全局存款量和用户存款量
player_[msg.sender].stake = player_[msg.sender].stake.sub(amount);
global_[0].total_stake = global_[0].total_stake.sub(amount);
// 转账给用户取款的代币
WETH(address(token)).withdraw(r);
address(msg.sender).transfer(r);
}
// Strategy.harvest 触发分红()
function make_profit(uint256 amount) public {
require(amount > 0, "not 0");
YFToken.safeTransferFrom(msg.sender, address(this), amount); // 挖矿收益存入当前合约(已扣除10%的手续费,90%的利润存进来)
global_[0].earnings_per_share = global_[0].earnings_per_share.add(
amount.mul(magnitude).div(global_[0].total_stake)
);
// 增加总分红金额
global_[0].total_out = global_[0].total_out.add(amount);
}
// 用户可领取的分红
function cal_out(address user) public view returns (uint256) {
uint256 _cal = global_[0].earnings_per_share.mul(player_[user].stake).div(magnitude);
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.sub(player_[user].payout);
}
}
// 某个用户在路上的分红(也就是分红还没有从挖矿合约领取.只能看到,无法领取,等harvest触发后就可以领取了)
function cal_out_pending(uint256 _pendingBalance,address user) public view returns (uint256) {
uint256 _earnings_per_share = global_[0].earnings_per_share.add(
_pendingBalance.mul(magnitude).div(global_[0].total_stake)
);
uint256 _cal = _earnings_per_share.mul(player_[user].stake).div(magnitude);
_cal = _cal.sub(cal_out(user));
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.sub(player_[user].payout);
}
}
// 用户领取分红
function claim() public {
uint256 out = cal_out(msg.sender);
player_[msg.sender].payout = global_[0].earnings_per_share.mul(player_[msg.sender].stake).div(magnitude);
player_[msg.sender].total_out = player_[msg.sender].total_out.add(out);
if (out > 0) {
uint256 _depositTime = now - deposittime[msg.sender];
if (_depositTime < 1 days) { // deposit in 24h
uint256 actually_out = _depositTime.mul(out).mul(1e18).div(1 days).div(1e18);
uint256 to_team = out.sub(actually_out);
YFToken.safeTransfer(Controller(controller).rewards(), to_team);
out = actually_out;
}
YFToken.safeTransfer(msg.sender, out);
}
}
// 合约的fallback函数调用了deposit方法(存款),这也意味着使用imtoken这样的钱包,直接给该合约地址转账以太币就能够完成兑换WETH
function () external payable {
if (msg.sender != address(token)) {
deposit(msg.value);
}
}
}
|
Strategy.harvest 触发分红() 增加总分红金额
|
function make_profit(uint256 amount) public {
require(amount > 0, "not 0");
global_[0].earnings_per_share = global_[0].earnings_per_share.add(
amount.mul(magnitude).div(global_[0].total_stake)
);
global_[0].total_out = global_[0].total_out.add(amount);
player_[msg.sender].payout = player_[msg.sender].payout.sub(
player_[msg.sender].stake = player_[msg.sender].stake.sub(amount);
WETH(address(token)).withdraw(r);
}
| 566,980
|
pragma solidity ^0.4.18;
/**
* @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;
}
}
/**
* @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.
*/
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 relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
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));
OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
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);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @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 Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
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));
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 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];
}
}
/**
* @title LimitedTransferToken
* @dev LimitedTransferToken defines the generic interface and the implementation to limit token
* transferability for different events. It is intended to be used as a base class for other token
* contracts.
* LimitedTransferToken has been designed to allow for different limiting factors,
* this can be achieved by recursively calling super.transferableTokens() until the base class is
* hit. For example:
* function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
* return min256(unlockedTokens, super.transferableTokens(holder, time));
* }
* A working example is VestedToken.sol:
* https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol
*/
contract LimitedTransferToken is ERC20 {
/**
* @dev Checks whether it can transfer or otherwise throws.
*/
modifier canTransfer(address _sender, uint256 _value) {
require(_value <= transferableTokens(_sender, uint64(block.timestamp)));
_;
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _from The address that will send the tokens.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Default transferable tokens function returns all tokens for a holder (no limit).
* @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the
* specific logic for limiting token transferability for a holder over time.
*/
function transferableTokens(address holder, uint64 time) public view returns (uint256) {
return balanceOf(holder);
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @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];
}
/**
* @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 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(_value <= balances[msg.sender]);
require(_to != address(0));
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) {
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(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
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 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)
{
uint256 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 Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Claimable {
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
)
public
hasMintPermission
canMint
returns (bool)
{
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() public onlyOwner canMint returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/*
Smart Token interface
*/
contract ISmartToken {
// =================================================================================================================
// Members
// =================================================================================================================
bool public transfersEnabled = false;
// =================================================================================================================
// Event
// =================================================================================================================
// triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event NewSmartToken(address _token);
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
// =================================================================================================================
// Functions
// =================================================================================================================
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
/**
BancorSmartToken
*/
contract LimitedTransferBancorSmartToken is MintableToken, ISmartToken, LimitedTransferToken {
// =================================================================================================================
// Modifiers
// =================================================================================================================
/**
* @dev Throws if destroy flag is not enabled.
*/
modifier canDestroy() {
require(destroyEnabled);
_;
}
// =================================================================================================================
// Members
// =================================================================================================================
// We add this flag to avoid users and owner from destroy tokens during crowdsale,
// This flag is set to false by default and blocks destroy function,
// We enable destroy option on finalize, so destroy will be possible after the crowdsale.
bool public destroyEnabled = false;
// =================================================================================================================
// Public Functions
// =================================================================================================================
function setDestroyEnabled(bool _enable) onlyOwner public {
destroyEnabled = _enable;
}
// =================================================================================================================
// Impl ISmartToken
// =================================================================================================================
//@Override
function disableTransfers(bool _disable) onlyOwner public {
transfersEnabled = !_disable;
}
//@Override
function issue(address _to, uint256 _amount) onlyOwner public {
require(super.mint(_to, _amount));
Issuance(_amount);
}
//@Override
function destroy(address _from, uint256 _amount) canDestroy public {
require(msg.sender == _from || msg.sender == owner); // validate input
balances[_from] = balances[_from].sub(_amount);
totalSupply_ = totalSupply_.sub(_amount);
Destruction(_amount);
Transfer(_from, 0x0, _amount);
}
// =================================================================================================================
// Impl LimitedTransferToken
// =================================================================================================================
// Enable/Disable token transfer
// Tokens will be locked in their wallets until the end of the Crowdsale.
// @holder - token`s owner
// @time - not used (framework unneeded functionality)
//
// @Override
function transferableTokens(address holder, uint64 time) public constant returns (uint256) {
require(transfersEnabled);
return super.transferableTokens(holder, time);
}
}
/**
A Token which is 'Bancor' compatible and can mint new tokens and pause token-transfer functionality
*/
contract BitMEDSmartToken is LimitedTransferBancorSmartToken {
// =================================================================================================================
// Members
// =================================================================================================================
string public constant name = "BitMED";
string public constant symbol = "BXM";
uint8 public constant decimals = 18;
// =================================================================================================================
// Constructor
// =================================================================================================================
function BitMEDSmartToken() public {
//Apart of 'Bancor' computability - triggered when a smart token is deployed
NewSmartToken(address(this));
}
}
/**
* @title Vault
* @dev This wallet is used to
*/
contract Vault is Claimable {
using SafeMath for uint256;
// =================================================================================================================
// Enums
// =================================================================================================================
enum State { KycPending, KycComplete }
// =================================================================================================================
// Members
// =================================================================================================================
mapping (address => uint256) public depositedETH;
mapping (address => uint256) public depositedToken;
BitMEDSmartToken public token;
State public state;
// =================================================================================================================
// Events
// =================================================================================================================
event KycPending();
event KycComplete();
event Deposit(address indexed beneficiary, uint256 etherWeiAmount, uint256 tokenWeiAmount);
event RemoveSupporter(address beneficiary);
event TokensClaimed(address indexed beneficiary, uint256 weiAmount);
// =================================================================================================================
// Modifiers
// =================================================================================================================
modifier isKycPending() {
require(state == State.KycPending);
_;
}
modifier isKycComplete() {
require(state == State.KycComplete);
_;
}
// =================================================================================================================
// Ctors
// =================================================================================================================
function Vault(BitMEDSmartToken _token) public {
require(_token != address(0));
token = _token;
state = State.KycPending;
KycPending();
}
// =================================================================================================================
// Public Functions
// =================================================================================================================
function deposit(address supporter, uint256 tokensAmount, uint256 value) isKycPending onlyOwner public{
depositedETH[supporter] = depositedETH[supporter].add(value);
depositedToken[supporter] = depositedToken[supporter].add(tokensAmount);
Deposit(supporter, value, tokensAmount);
}
function kycComplete() isKycPending onlyOwner public {
state = State.KycComplete;
KycComplete();
}
//@dev Remove a supporter and refund ether back to the supporter in returns of proportional amount of BXM back to the BitMED`s wallet
function removeSupporter(address supporter) isKycPending onlyOwner public {
require(supporter != address(0));
require(depositedETH[supporter] > 0);
require(depositedToken[supporter] > 0);
uint256 depositedTokenValue = depositedToken[supporter];
uint256 depositedETHValue = depositedETH[supporter];
//zero out the user
depositedETH[supporter] = 0;
depositedToken[supporter] = 0;
token.destroy(address(this),depositedTokenValue);
// We will manually refund the money. Checking against OFAC sanction list
// https://sanctionssearch.ofac.treas.gov/
//supporter.transfer(depositedETHValue - 21000);
RemoveSupporter(supporter);
}
//@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet.
//Can be triggerd by the supporter only
function claimTokens(uint256 tokensToClaim) isKycComplete public {
require(tokensToClaim != 0);
address supporter = msg.sender;
require(depositedToken[supporter] > 0);
uint256 depositedTokenValue = depositedToken[supporter];
uint256 depositedETHValue = depositedETH[supporter];
require(tokensToClaim <= depositedTokenValue);
uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue);
assert(claimedETH > 0);
depositedETH[supporter] = depositedETHValue.sub(claimedETH);
depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim);
token.transfer(supporter, tokensToClaim);
TokensClaimed(supporter, tokensToClaim);
}
//@dev Transfer tokens from the vault to the supporter
//Can be triggerd by the owner of the vault
function claimAllSupporterTokensByOwner(address supporter) isKycComplete onlyOwner public {
uint256 depositedTokenValue = depositedToken[supporter];
require(depositedTokenValue > 0);
token.transfer(supporter, depositedTokenValue);
TokensClaimed(supporter, depositedTokenValue);
}
// @dev supporter can claim tokens by calling the function
// @param tokenToClaimAmount - amount of the token to claim
function claimAllTokens() isKycComplete public {
uint256 depositedTokenValue = depositedToken[msg.sender];
claimTokens(depositedTokenValue);
}
}
/**
* @title RefundVault
* @dev This contract is used for storing TOKENS AND ETHER while a crowd sale is in progress for a period of 3 DAYS.
* Supporter can ask for a full/part refund for his/her ether against token. Once tokens are Claimed by the supporter, they cannot be refunded.
* After 3 days, all ether will be withdrawn from the vault`s wallet, leaving all tokens to be claimed by the their owners.
**/
contract RefundVault is Claimable {
using SafeMath for uint256;
// =================================================================================================================
// Enums
// =================================================================================================================
enum State { Active, Refunding, Closed }
// =================================================================================================================
// Members
// =================================================================================================================
// Refund time frame
uint256 public constant REFUND_TIME_FRAME = 3 days;
mapping (address => uint256) public depositedETH;
mapping (address => uint256) public depositedToken;
address public etherWallet;
BitMEDSmartToken public token;
State public state;
uint256 public refundStartTime;
// =================================================================================================================
// Events
// =================================================================================================================
event Active();
event Closed();
event Deposit(address indexed beneficiary, uint256 etherWeiAmount, uint256 tokenWeiAmount);
event RefundsEnabled();
event RefundedETH(address beneficiary, uint256 weiAmount);
event TokensClaimed(address indexed beneficiary, uint256 weiAmount);
// =================================================================================================================
// Modifiers
// =================================================================================================================
modifier isActiveState() {
require(state == State.Active);
_;
}
modifier isRefundingState() {
require(state == State.Refunding);
_;
}
modifier isCloseState() {
require(state == State.Closed);
_;
}
modifier isRefundingOrCloseState() {
require(state == State.Refunding || state == State.Closed);
_;
}
modifier isInRefundTimeFrame() {
require(refundStartTime <= block.timestamp && refundStartTime + REFUND_TIME_FRAME > block.timestamp);
_;
}
modifier isRefundTimeFrameExceeded() {
require(refundStartTime + REFUND_TIME_FRAME < block.timestamp);
_;
}
// =================================================================================================================
// Ctors
// =================================================================================================================
function RefundVault(address _etherWallet, BitMEDSmartToken _token) public {
require(_etherWallet != address(0));
require(_token != address(0));
etherWallet = _etherWallet;
token = _token;
state = State.Active;
Active();
}
// =================================================================================================================
// Public Functions
// =================================================================================================================
function deposit(address supporter, uint256 tokensAmount) isActiveState onlyOwner public payable {
depositedETH[supporter] = depositedETH[supporter].add(msg.value);
depositedToken[supporter] = depositedToken[supporter].add(tokensAmount);
Deposit(supporter, msg.value, tokensAmount);
}
function close() isRefundingState onlyOwner isRefundTimeFrameExceeded public {
state = State.Closed;
Closed();
etherWallet.transfer(address(this).balance);
}
function enableRefunds() isActiveState onlyOwner public {
state = State.Refunding;
refundStartTime = block.timestamp;
RefundsEnabled();
}
//@dev Refund ether back to the supporter in returns of proportional amount of BXM back to the BitMED`s wallet
function refundETH(uint256 ETHToRefundAmountWei) isInRefundTimeFrame isRefundingState public {
require(ETHToRefundAmountWei != 0);
uint256 depositedTokenValue = depositedToken[msg.sender];
uint256 depositedETHValue = depositedETH[msg.sender];
require(ETHToRefundAmountWei <= depositedETHValue);
uint256 refundTokens = ETHToRefundAmountWei.mul(depositedTokenValue).div(depositedETHValue);
assert(refundTokens > 0);
depositedETH[msg.sender] = depositedETHValue.sub(ETHToRefundAmountWei);
depositedToken[msg.sender] = depositedTokenValue.sub(refundTokens);
token.destroy(address(this),refundTokens);
msg.sender.transfer(ETHToRefundAmountWei);
RefundedETH(msg.sender, ETHToRefundAmountWei);
}
//@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet.
//Can be triggerd by the supporter only
function claimTokens(uint256 tokensToClaim) isRefundingOrCloseState public {
require(tokensToClaim != 0);
address supporter = msg.sender;
require(depositedToken[supporter] > 0);
uint256 depositedTokenValue = depositedToken[supporter];
uint256 depositedETHValue = depositedETH[supporter];
require(tokensToClaim <= depositedTokenValue);
uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue);
assert(claimedETH > 0);
depositedETH[supporter] = depositedETHValue.sub(claimedETH);
depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim);
token.transfer(supporter, tokensToClaim);
if(state != State.Closed) {
etherWallet.transfer(claimedETH);
}
TokensClaimed(supporter, tokensToClaim);
}
//@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet.
//Can be triggerd by the owner of the vault (in our case - BitMED`s owner after 3 days)
function claimAllSupporterTokensByOwner(address supporter) isCloseState onlyOwner public {
uint256 depositedTokenValue = depositedToken[supporter];
require(depositedTokenValue > 0);
token.transfer(supporter, depositedTokenValue);
TokensClaimed(supporter, depositedTokenValue);
}
// @dev supporter can claim tokens by calling the function
// @param tokenToClaimAmount - amount of the token to claim
function claimAllTokens() isRefundingOrCloseState public {
uint256 depositedTokenValue = depositedToken[msg.sender];
claimTokens(depositedTokenValue);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales 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 Crowdsale {
using SafeMath for uint256;
// The token being sold
BitMEDSmartToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
// holding vault for all tokens pending KYC
Vault public vault;
/**
* 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);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, BitMEDSmartToken _token, Vault _vault) public {
require(_startTime >= block.timestamp);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
require(_vault != address(0));
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
token = _token;
vault = _vault;
}
// fallback function can be used to buy tokens
function() external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
require(weiAmount>500000000000000000);
// calculate token amount to be created
uint256 tokens = weiAmount.mul(getRate());
// update state
weiRaised = weiRaised.add(weiAmount);
//send tokens to KYC Vault
token.issue(address(vault), tokens);
// Updating arrays in the Vault
vault.deposit(beneficiary, tokens, msg.value);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
// Transferring funds to wallet
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = block.timestamp >= startTime && block.timestamp <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return block.timestamp > endTime;
}
// @return the crowdsale rate
function getRate() public view returns (uint256) {
return rate;
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Claimable {
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() public onlyOwner {
require(!isFinalized);
require(hasEnded());
finalization();
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 {
}
}
contract BitMEDCrowdsale is FinalizableCrowdsale {
// =================================================================================================================
// Constants
// =================================================================================================================
// Max amount of known addresses of which will get BXM by 'Grant' method.
//
// grantees addresses will be BitMED wallets addresses.
// these wallets will contain BXM tokens that will be used for one purposes only -
// 1. BXM tokens against raised fiat money
// we set the value to 10 (and not to 2) because we want to allow some flexibility for cases like fiat money that is raised close
// to the crowdsale. we limit the value to 10 (and not larger) to limit the run time of the function that process the grantees array.
uint8 public constant MAX_TOKEN_GRANTEES = 10;
// BXM to ETH base rate
uint256 public constant EXCHANGE_RATE = 210;
// Refund division rate
uint256 public constant REFUND_DIVISION_RATE = 2;
// The min BXM tokens that should be minted for the public sale
uint256 public constant MIN_TOKEN_SALE = 125000000000000000000000000;
// =================================================================================================================
// Modifiers
// =================================================================================================================
/**
* @dev Throws if called not during the crowdsale time frame
*/
modifier onlyWhileSale() {
require(isActive());
_;
}
// =================================================================================================================
// Members
// =================================================================================================================
// wallets address for 75% of BXM allocation
address public walletTeam; //10% of the total number of BXM tokens will be allocated to the team
address public walletReserve; //35% of the total number of BXM tokens will be allocated to BitMED and as a reserve for the company to be used for future strategic plans for the created ecosystem
address public walletCommunity; //30% of the total number of BXM tokens will be allocated to Community
// Funds collected outside the crowdsale in wei
uint256 public fiatRaisedConvertedToWei;
//Grantees - used for non-ether and presale bonus token generation
address[] public presaleGranteesMapKeys;
mapping (address => uint256) public presaleGranteesMap; //address=>wei token amount
// The refund vault
RefundVault public refundVault;
// =================================================================================================================
// Events
// =================================================================================================================
event GrantAdded(address indexed _grantee, uint256 _amount);
event GrantUpdated(address indexed _grantee, uint256 _oldAmount, uint256 _newAmount);
event GrantDeleted(address indexed _grantee, uint256 _hadAmount);
event FiatRaisedUpdated(address indexed _address, uint256 _fiatRaised);
event TokenPurchaseWithGuarantee(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// =================================================================================================================
// Constructors
// =================================================================================================================
function BitMEDCrowdsale(uint256 _startTime,
uint256 _endTime,
address _wallet,
address _walletTeam,
address _walletCommunity,
address _walletReserve,
BitMEDSmartToken _BitMEDSmartToken,
RefundVault _refundVault,
Vault _vault)
public Crowdsale(_startTime, _endTime, EXCHANGE_RATE, _wallet, _BitMEDSmartToken, _vault) {
require(_walletTeam != address(0));
require(_walletCommunity != address(0));
require(_walletReserve != address(0));
require(_BitMEDSmartToken != address(0));
require(_refundVault != address(0));
require(_vault != address(0));
walletTeam = _walletTeam;
walletCommunity = _walletCommunity;
walletReserve = _walletReserve;
token = _BitMEDSmartToken;
refundVault = _refundVault;
vault = _vault;
}
// =================================================================================================================
// Impl Crowdsale
// =================================================================================================================
// @return the rate in BXM per 1 ETH according to the time of the tx and the BXM pricing program.
// @Override
function getRate() public view returns (uint256) {
if (block.timestamp < (startTime.add(24 hours))) {return 700;}
if (block.timestamp < (startTime.add(3 days))) {return 600;}
if (block.timestamp < (startTime.add(5 days))) {return 500;}
if (block.timestamp < (startTime.add(7 days))) {return 400;}
if (block.timestamp < (startTime.add(10 days))) {return 350;}
if (block.timestamp < (startTime.add(13 days))) {return 300;}
if (block.timestamp < (startTime.add(16 days))) {return 285;}
if (block.timestamp < (startTime.add(19 days))) {return 270;}
if (block.timestamp < (startTime.add(22 days))) {return 260;}
if (block.timestamp < (startTime.add(25 days))) {return 250;}
if (block.timestamp < (startTime.add(28 days))) {return 240;}
if (block.timestamp < (startTime.add(31 days))) {return 230;}
if (block.timestamp < (startTime.add(34 days))) {return 225;}
if (block.timestamp < (startTime.add(37 days))) {return 220;}
if (block.timestamp < (startTime.add(40 days))) {return 215;}
return rate;
}
// =================================================================================================================
// Impl FinalizableCrowdsale
// =================================================================================================================
//@Override
function finalization() internal {
super.finalization();
// granting bonuses for the pre crowdsale grantees:
for (uint256 i = 0; i < presaleGranteesMapKeys.length; i++) {
token.issue(presaleGranteesMapKeys[i], presaleGranteesMap[presaleGranteesMapKeys[i]]);
}
//we want to make sure a min of 125M tokens are generated which equals the 25% of the crowdsale
if(token.totalSupply() <= MIN_TOKEN_SALE){
uint256 missingTokens = MIN_TOKEN_SALE - token.totalSupply();
token.issue(walletCommunity, missingTokens);
}
// Adding 75% of the total token supply (25% were generated during the crowdsale)
// 25 * 4 = 100
uint256 newTotalSupply = token.totalSupply().mul(400).div(100);
// 10% of the total number of BXM tokens will be allocated to the team
token.issue(walletTeam, newTotalSupply.mul(10).div(100));
// 30% of the total number of BXM tokens will be allocated to community
token.issue(walletCommunity, newTotalSupply.mul(30).div(100));
// 35% of the total number of BXM tokens will be allocated to BitMED ,
// and as a reserve for the company to be used for future strategic plans for the created ecosystem
token.issue(walletReserve, newTotalSupply.mul(35).div(100));
// Re-enable transfers after the token sale.
token.disableTransfers(false);
// Re-enable destroy function after the token sale.
token.setDestroyEnabled(true);
// Enable ETH refunds and token claim.
refundVault.enableRefunds();
// transfer token ownership to crowdsale owner
token.transferOwnership(owner);
// transfer refundVault ownership to crowdsale owner
refundVault.transferOwnership(owner);
vault.transferOwnership(owner);
}
// =================================================================================================================
// Public Methods
// =================================================================================================================
// @return the total funds collected in wei(ETH and none ETH).
function getTotalFundsRaised() public view returns (uint256) {
return fiatRaisedConvertedToWei.add(weiRaised);
}
// @return true if the crowdsale is active, hence users can buy tokens
function isActive() public view returns (bool) {
return block.timestamp >= startTime && block.timestamp < endTime;
}
// =================================================================================================================
// External Methods
// =================================================================================================================
// @dev Adds/Updates address and token allocation for token grants.
// Granted tokens are allocated to non-ether, presale, buyers.
// @param _grantee address The address of the token grantee.
// @param _value uint256 The value of the grant in wei token.
function addUpdateGrantee(address _grantee, uint256 _value) external onlyOwner onlyWhileSale{
require(_grantee != address(0));
require(_value > 0);
// Adding new key if not present:
if (presaleGranteesMap[_grantee] == 0) {
require(presaleGranteesMapKeys.length < MAX_TOKEN_GRANTEES);
presaleGranteesMapKeys.push(_grantee);
GrantAdded(_grantee, _value);
}
else {
GrantUpdated(_grantee, presaleGranteesMap[_grantee], _value);
}
presaleGranteesMap[_grantee] = _value;
}
// @dev deletes entries from the grants list.
// @param _grantee address The address of the token grantee.
function deleteGrantee(address _grantee) external onlyOwner onlyWhileSale {
require(_grantee != address(0));
require(presaleGranteesMap[_grantee] != 0);
//delete from the map:
delete presaleGranteesMap[_grantee];
//delete from the array (keys):
uint256 index;
for (uint256 i = 0; i < presaleGranteesMapKeys.length; i++) {
if (presaleGranteesMapKeys[i] == _grantee) {
index = i;
break;
}
}
presaleGranteesMapKeys[index] = presaleGranteesMapKeys[presaleGranteesMapKeys.length - 1];
delete presaleGranteesMapKeys[presaleGranteesMapKeys.length - 1];
presaleGranteesMapKeys.length--;
GrantDeleted(_grantee, presaleGranteesMap[_grantee]);
}
// @dev Set funds collected outside the crowdsale in wei.
// note: we not to use accumulator to allow flexibility in case of humane mistakes.
// funds are converted to wei using the market conversion rate of USD\ETH on the day on the purchase.
// @param _fiatRaisedConvertedToWei number of none eth raised.
function setFiatRaisedConvertedToWei(uint256 _fiatRaisedConvertedToWei) external onlyOwner onlyWhileSale {
fiatRaisedConvertedToWei = _fiatRaisedConvertedToWei;
FiatRaisedUpdated(msg.sender, fiatRaisedConvertedToWei);
}
/// @dev Accepts new ownership on behalf of the BitMEDCrowdsale contract. This can be used, by the token sale
/// contract itself to claim back ownership of the BitMEDSmartToken contract.
function claimTokenOwnership() external onlyOwner {
token.claimOwnership();
}
/// @dev Accepts new ownership on behalf of the BitMEDCrowdsale contract. This can be used, by the token sale
/// contract itself to claim back ownership of the refundVault contract.
function claimRefundVaultOwnership() external onlyOwner {
refundVault.claimOwnership();
}
/// @dev Accepts new ownership on behalf of the BitMEDCrowdsale contract. This can be used, by the token sale
/// contract itself to claim back ownership of the refundVault contract.
function claimVaultOwnership() external onlyOwner {
vault.claimOwnership();
}
// @dev Buy tokes with guarantee
function buyTokensWithGuarantee() public payable {
require(validPurchase());
uint256 weiAmount = msg.value;
require(weiAmount>500000000000000000);
// calculate token amount to be created
uint256 tokens = weiAmount.mul(getRate());
tokens = tokens.div(REFUND_DIVISION_RATE);
// update state
weiRaised = weiRaised.add(weiAmount);
token.issue(address(refundVault), tokens);
refundVault.deposit.value(msg.value)(msg.sender, tokens);
TokenPurchaseWithGuarantee(msg.sender, address(refundVault), weiAmount, tokens);
}
}
|
return true if the crowdsale is active, hence users can buy tokens
|
function isActive() public view returns (bool) {
return block.timestamp >= startTime && block.timestamp < endTime;
}
| 10,666,634
|
./partial_match/1/0x8a3515f5D127342fcBba56E13514D4A2391327e6/sources/contracts/protocol/libraries/configuration/UserConfiguration.sol
|
Checks if a user has not been using any reserve for borrowing or supply self The configuration object return True if the user has not been borrowing or supplying any reserve, false otherwise/
|
function isEmpty(DataTypes.UserConfigurationMap memory self)
internal
pure
returns (bool)
{
return self.data == 0;
}
| 4,312,119
|
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT
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));
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
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");
}
/**
* @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: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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: @openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @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, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
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 `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, 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.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_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());
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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/math/SafeMath.sol
// SPDX-License-Identifier: MIT
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) {
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;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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 {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;
using Address for address;
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 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(_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 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 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 {
_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 { }
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File: @openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @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.
*/
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 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());
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// File: @openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) public ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// File: contracts/token/interfaces/SocialProofable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title SocialProofable
* @dev Used to define the social proof for a specific token.
* Based on the proposal by Dan Levine:
* https://docs.google.com/document/d/1wbsqYC6ZqZZdaz3li3UAFaXT2Yrc8G8KUDu7F3KrQ6Y/edit
*
* @author @Onchained
*/
interface SocialProofable {
function getTwitter() external view returns(string memory);
function getTwitterProof() external view returns(uint256);
function getTelegram() external view returns(string memory);
function getWebsite() external view returns(string memory);
function getGithub() external view returns(string memory);
function getGithubProof() external view returns(bytes memory);
}
// File: contracts/token/ipmtoken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title IPM Token
* @dev ERC20 contract of IPM Token for TIMERS Network
* Token is mintable but capped and also disables
* minting for 1 year after crowdsale ended.
* Tokens will be automatically transferable 5 days
* after crowdsale.
*
* More at https://timers.network/
*
* @author @KTimersnetwork
*/
contract IPMToken is ERC20PresetMinterPauser, SocialProofable {
using SafeMath for uint256;
//////////////////////////////////////
// Base Token configuration //
//////////////////////////////////////
// token name
string public constant TOKEN_NAME = "TIMERS";
// token symbol
string public constant TOKEN_SYMBOL = "IPM";
// real initial supply is 14.6mio.
// 9M are reserved for crowdsale and will be minted on demand.
uint256 public constant TOKEN_INITIAL_SUPPLY = 5600000 * (10 ** 18);
// 14.6M max supply after crowdsale
uint256 public constant MAXIMUM_CROWDSALE_SUPPLY = 14600000 * (10 ** 18);
// 50M maximum supply
uint256 public constant SUPPLY_CAP = 50000000 * (10 ** 18);
// duration for the minting deactivation after crowdsale
uint256 private constant mintLockTimeframe = 365 days;
// date when token becomes mintable again
uint256 private tokenMintableDate = now + mintLockTimeframe;
// duration for the cooldown until tokens are transferable
uint256 private constant tokenActivationTimeframe = 5 days;
// unpause date
uint256 private tokenActivationDate = now + tokenActivationTimeframe;
// switch if crowdsale has ended
bool private crowdSaleFinished = false;
//////////////////////////////////////
// Data for social proof //
//////////////////////////////////////
string public constant socialTwitter = "TIMERSnetwork";
string public constant socialTelegram = "TIMERSipm";
string public constant socialWebsite = "timers.network";
string public constant socialGithub = "timersnetwork";
uint256 public socialTwitterProof;
bytes public socialGithubProof;
/**
* @dev Constructor of IPM Token contract. Mints initial supply
* and sets access roles + Token Data via inherited class.
*/
constructor() ERC20PresetMinterPauser(TOKEN_NAME,TOKEN_SYMBOL) public {
// mint initial supply
_mint(msg.sender, TOKEN_INITIAL_SUPPLY);
}
///////////////////////////////////////////
// Overrides //
///////////////////////////////////////////
function mint(address to, uint256 amount) public virtual override {
require(crowdSaleFinished == false || (crowdSaleFinished == true && now > tokenMintableDate), "Error: minting is currently locked");
if(crowdSaleFinished == false) {
require(totalSupply().add(amount) <= MAXIMUM_CROWDSALE_SUPPLY, "CrowdSale: cap exceeded");
}
super.mint(to,amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from,to,amount);
// check if token is active already or sender is admin / minter
require(tokenActive() || from == address(0), "Error: Token is not active yet");
// minting
if (from == address(0)) {
// Prevent minting of tokens beyond max supply
require(totalSupply().add(amount) <= SUPPLY_CAP, "Max cap exceeded");
}
}
/**
* @dev Checks whether the token is already active
* (crowdsale finsihed and cooldown date reached)
*/
function tokenActive() public view returns(bool) {
// admin can always send
if(hasRole(DEFAULT_ADMIN_ROLE,msg.sender)) { return true; }
if(crowdSaleFinished == true && now > tokenActivationDate) { return true; }
return false;
}
/**
* @dev Resets/Activates CrowdSale and deactivates token again
*
* Requirements:
*
* - the caller must have the `DEFAULT_ADMIN_ROLE`.
*/
function resetCrowdSale() external {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Error: You are not allowed to use this command");
require(crowdSaleFinished == true, "Error: CrowdSale already active");
crowdSaleFinished = false;
}
/**
* @dev Checks whether the token is already active
* (crowdsale finsihed and cooldown date reached)
*
* Requirements:
*
* - the caller must have the `DEFAULT_ADMIN_ROLE`.
*/
function finishCrowdSale() external {
require(hasRole(DEFAULT_ADMIN_ROLE,msg.sender), "Error: You are not allowed to use this command");
require(crowdSaleFinished == false, "Error: CrowdSale already finished");
// crowdsale finished
crowdSaleFinished = true;
// define date when token unlocks and becomes active: now + 5 days
tokenActivationDate = now + tokenActivationTimeframe;
// define date when minting unlocks: now + 365 days
tokenMintableDate = now + mintLockTimeframe;
emit CrowdSaleFinished(
totalSupply().sub(TOKEN_INITIAL_SUPPLY),
tokenMintableDate,
tokenActivationDate
);
}
function getTokenActivationDate() public view returns(uint256) {
return tokenActivationDate;
}
function getTokenMintableDate() public view returns(uint256) {
return tokenMintableDate;
}
///////////////////////////////////////////
// Events //
///////////////////////////////////////////
event CrowdSaleFinished(
uint256 tokenPurchased,
uint256 mintingLockDate,
uint256 tokenActivationDate
);
///////////////////////////////////////////
// Social proof interface implementation //
///////////////////////////////////////////
/**
* @dev Get Twitter account for social proof
*/
function getTwitter() override external view returns(string memory) {
return socialTwitter;
}
/**
* @dev Get Telegram account for social proof
*/
function getTelegram() override external view returns(string memory) {
return socialTelegram;
}
/**
* @dev Get GitHub account for social proof
*/
function getGithub() override external view returns(string memory) {
return socialGithub;
}
/**
* @dev Get Website for social proof
*/
function getWebsite() override external view returns(string memory) {
return socialWebsite;
}
/**
* @dev Set Twitter account proof
*
* Requirements:
*
* - the caller must have the `ADMIN_ROLE`.
*/
function setTwitterProof(uint256 _twitterProof) external {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Error: twitter proof can only be set by admin");
socialTwitterProof = _twitterProof;
}
/**
* @dev Get Twitter account proof
*/
function getTwitterProof() override external view returns(uint256) {
return socialTwitterProof;
}
/**
* @dev Set Github account proof
*
* Requirements:
*
* - the caller must have the `ADMIN_ROLE`.
*/
function setGithubProof(bytes calldata _githubProof) external {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Error: github proof can only be set by admin");
socialGithubProof = _githubProof;
}
/**
* @dev Get Github account proof
*/
function getGithubProof() override external view returns(bytes memory) {
return socialGithubProof;
}
}
|
Checks whether the token is already active (crowdsale finsihed and cooldown date reached) Requirements: - the caller must have the `DEFAULT_ADMIN_ROLE`./ crowdsale finished define date when token unlocks and becomes active: now + 5 days define date when minting unlocks: now + 365 days
|
function finishCrowdSale() external {
require(hasRole(DEFAULT_ADMIN_ROLE,msg.sender), "Error: You are not allowed to use this command");
require(crowdSaleFinished == false, "Error: CrowdSale already finished");
crowdSaleFinished = true;
tokenActivationDate = now + tokenActivationTimeframe;
tokenMintableDate = now + mintLockTimeframe;
emit CrowdSaleFinished(
totalSupply().sub(TOKEN_INITIAL_SUPPLY),
tokenMintableDate,
tokenActivationDate
);
}
| 13,717,133
|
// SPDX-License-Identifier: MIT
/**
* KP2R.NETWORK
* A standard implementation of kp3rv1 protocol
* Optimized Dapp
* Scalability
* Clean & tested code
*/
/*
This contract is provided "as is" and "with all faults." The deployer makes no representations or warranties
of any kind concerning the safety, suitability, lack of exploits, inaccuracies, typographical errors, or other
harmful components of this contract. There are inherent dangers in the use of any contract, and you are solely
responsible for determining whether this contract is safe to use. You are also solely responsible for the
protection of your funds, and the deployer will not be liable for any damages you may suffer in connection with
using, modifying, or distributing this contract.
*/
pragma solidity ^0.5.17;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "LBI::SafeMath: subtraction underflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint a, uint b) internal pure returns (uint) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
interface UniswapPair {
function sync() external;
function transferFrom(address from, address to, uint value) external returns (bool);
function balanceOf(address account) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function mint(address to) external returns (uint liquidity);
}
interface IBondingCurve {
function calculatePurchaseReturn(uint _supply, uint _reserveBalance, uint32 _reserveRatio, uint _depositAmount) external view returns (uint);
}
interface WETH9 {
function deposit() external payable;
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
}
interface Uniswap {
function factory() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
interface Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface LBI {
function approve(address spender, uint amount) external returns (bool);
}
interface RewardDistributionDelegate {
function notifyRewardAmount(uint reward) external;
}
interface RewardDistributionFactory {
function deploy(
address lp_,
address earn_,
address rewardDistribution_,
uint8 decimals_,
string calldata name_,
string calldata symbol_
) external returns (address);
}
interface GovernanceFactory {
function deploy(address token) external returns (address);
}
contract LiquidityIncome {
using SafeMath for uint;
/* BondingCurve */
uint public scale = 10**18;
uint public reserveBalance = 1*10**14;
uint32 public constant RATIO = 500000;
WETH9 constant public WETH = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
function () external payable { mint(0); }
function mint(uint min) public payable {
require(msg.value > 0, "LBI::mint: msg.value = 0");
uint _bought = _continuousMint(msg.value);
require(_bought >= min, "LBI::mint: slippage");
WETH.deposit.value(msg.value)();
WETH.transfer(address(pool), WETH.balanceOf(address(this)));
pool.sync();
_mint(msg.sender, _bought, true);
}
IBondingCurve constant public CURVE = IBondingCurve(0x51602cd60c5DbB77795c93f395d2E2CB2a157ca6);
function _buy(uint _amount) internal returns (uint _bought) {
_bought = _continuousMint(_amount);
}
function calculateMint(uint _amount) public view returns (uint mintAmount) {
return CURVE.calculatePurchaseReturn(totalSupply, reserveBalance, RATIO, _amount);
}
function _continuousMint(uint _deposit) internal returns (uint) {
uint amount = calculateMint(_deposit);
reserveBalance = reserveBalance.add(_deposit);
return amount;
}
/// @notice EIP-20 token name for this token
string public constant name = "Liquidity Income";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "LBI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 0; // Initial 0
/// @notice the last block the tick was applied
uint public lastTick = 0;
/// @notice the uniswap pool that will receive the rebase
UniswapPair public pool;
RewardDistributionDelegate public rewardDistribution;
RewardDistributionFactory public constant REWARDFACTORY = RewardDistributionFactory(0x19231725f21B3BA2989A396A31F3B66502C7de66);
GovernanceFactory public constant GOVERNANCEFACTORY = GovernanceFactory(0x95283102A95f84fd7FB3ba0EE5C5A8F16E82c025);
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint) internal balances;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint amount);
/// @notice Tick event
event Tick(uint block, uint minted);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint amount);
Uniswap public constant UNI = Uniswap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
/* Incremental system for balance increments */
uint256 public index = 0; // previously accumulated index
uint256 public bal = 0; // previous calculated balance of COMP
mapping(address => uint256) public supplyIndex;
function _update(bool sync) internal {
if (totalSupply > 0) {
uint256 _before = balances[address(this)];
tick(sync);
uint256 _bal = balances[address(this)];
if (_bal > 0 && _bal > _before) {
uint256 _diff = _bal.sub(bal, "LBI::_update: ball _diff");
if (_diff > 0) {
uint256 _ratio = _diff.mul(1e18).div(totalSupply);
if (_ratio > 0) {
index = index.add(_ratio);
bal = _bal;
}
}
}
}
}
mapping(address => uint) claimable;
function claim() external {
claimFor(msg.sender);
}
function claimFor(address recipient) public {
_updateFor(recipient, true);
_transferTokens(address(this), recipient, claimable[recipient]);
claimable[recipient] = 0;
bal = balances[address(this)];
}
function _updateFor(address recipient, bool sync) public {
_update(sync);
uint256 _supplied = balances[recipient];
if (_supplied > 0) {
uint256 _supplyIndex = supplyIndex[recipient];
supplyIndex[recipient] = index;
uint256 _delta = index.sub(_supplyIndex, "LBI::_claimFor: index delta");
if (_delta > 0) {
uint256 _share = _supplied.mul(_delta).div(1e18);
claimable[recipient] = claimable[recipient].add(_share);
}
} else {
supplyIndex[recipient] = index;
}
}
constructor() public {
lastTick = block.number;
}
address public governance;
function setup() external payable {
require(msg.value > 0, "LBT:(): constructor requires ETH");
require(address(pool) == address(0x0), "LBT:(): already initialized");
_mint(address(this), 10000e18, true); // init total supply
WETH.deposit.value(msg.value)();
_mint(address(this), _continuousMint(msg.value), true);
uint _balance = WETH.balanceOf(address(this));
require(_balance == msg.value, "LBT:(): WETH9 error");
WETH.approve(address(UNI), _balance);
allowances[address(this)][address(UNI)] = balances[address(this)];
require(allowances[address(this)][address(UNI)] == balances[address(this)], "LBT:(): address(this) error");
UNI.addLiquidity(address(this), address(WETH), balances[address(this)], WETH.balanceOf(address(this)), 0, 0, msg.sender, now.add(1800));
pool = UniswapPair(Factory(UNI.factory()).getPair(address(this), address(WETH)));
rewardDistribution = RewardDistributionDelegate(REWARDFACTORY.deploy(address(pool), address(this), address(this), 18, "Liquidity Income Delegate", "LBD"));
_mint(address(this), 1e18, true);
allowances[address(this)][address(rewardDistribution)] = 1e18;
rewardDistribution.notifyRewardAmount(1e18);
governance = GOVERNANCEFACTORY.deploy(address(rewardDistribution));
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "LBI::setGovernance: governance only");
governance = _governance;
}
// TEST HELPER FUNCTION :: DO NOT USE
function removeLiquidityMax() public {
removeLiquidity(pool.balanceOf(msg.sender), 0, 0);
}
// TEST HELPER FUNCTION :: DO NOT USE
function removeLiquidity(uint amountA, uint minA, uint minB) public {
tick(true);
pool.transferFrom(msg.sender, address(this), amountA);
pool.approve(address(UNI), amountA);
UNI.removeLiquidity(address(this), address(WETH), amountA, minA, minB, msg.sender, now.add(1800));
}
// TEST HELPER FUNCTION :: DO NOT USE
function addLiquidityMax() public payable {
addLiquidity(balances[msg.sender]);
}
// TEST HELPER FUNCTION :: DO NOT USE
function addLiquidity(uint amountA) public payable {
tick(true);
WETH.deposit.value(msg.value)();
WETH.transfer(address(pool), msg.value);
_transferTokens(msg.sender, address(pool), amountA);
pool.mint(msg.sender);
}
function _mint(address dst, uint amount, bool sync) internal {
// mint the amount
totalSupply = totalSupply.add(amount);
_updateFor(dst, sync);
// transfer the amount to the recipient
balances[dst] = balances[dst].add(amount);
emit Transfer(address(0), dst, amount);
}
uint public LP = 9000;
uint public constant BASE = 10000;
uint public DURATION = 700000;
address public timelock;
function setDuration(uint duration_) external {
require(msg.sender == governance, "LBI::setDuration only governance");
DURATION = duration_;
}
function setRatio(uint lp_) external {
require(msg.sender == governance, "LBI::setRatio only governance");
LP = lp_;
}
/**
* @notice tick to increase holdings
*/
function tick(bool sync) public {
uint _current = block.number;
uint _diff = _current.sub(lastTick);
if (_diff > 0) {
lastTick = _current;
_diff = balances[address(pool)].mul(_diff).div(DURATION); // 1% every 7000 blocks
uint _minting = _diff.div(2);
if (_minting > 0) {
_transferTokens(address(pool), address(this), _minting);
// Can't call sync while in addLiquidity or removeLiquidity
if (sync) {
pool.sync();
}
_mint(address(this), _minting, false);
// % of tokens that go to LPs
uint _lp = _diff.mul(LP).div(BASE);
allowances[address(this)][address(rewardDistribution)] = _lp;
rewardDistribution.notifyRewardAmount(_lp);
emit Tick(_current, _diff);
}
}
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint amount) public returns (bool) {
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "LBI::permit: invalid signature");
require(signatory == owner, "LBI::permit: unauthorized");
require(now <= deadline, "LBI::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @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, uint amount) public returns (bool) {
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint amount) external returns (bool) {
address spender = msg.sender;
uint spenderAllowance = allowances[src][spender];
if (spender != src && spenderAllowance != uint(-1)) {
uint newAllowance = spenderAllowance.sub(amount, "LBI::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
function _transferTokens(address src, address dst, uint amount) internal {
require(src != address(0), "LBI::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "LBI::_transferTokens: cannot transfer to the zero address");
bool sync = true;
if (src == address(pool) || dst == address(pool)) {
sync = false;
}
_updateFor(src, sync);
_updateFor(dst, sync);
balances[src] = balances[src].sub(amount, "LBI::_transferTokens: transfer amount exceeds balance");
balances[dst] = balances[dst].add(amount, "LBI::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
}
function getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
TEST HELPER FUNCTION :: DO NOT USE
|
function addLiquidityMax() public payable {
addLiquidity(balances[msg.sender]);
}
| 5,939,345
|
// SPDX-License-Identifier: MIT
// Version: 0.1.0, 1/20/2021
pragma solidity >=0.6.2 <0.8.0;
import "../interface/IERC20.sol";
import "../interface/IPToken.sol";
import "../interface/ILToken.sol";
import "../interface/IOracle.sol";
import "../interface/ILiquidatorQualifier.sol";
import "../interface/IMigratablePool.sol";
import "../interface/IPreMiningPool.sol";
import "../interface/IPerpetualPool.sol";
import "../utils/SafeERC20.sol";
import "../math/MixedSafeMathWithUnit.sol";
import "./MigratablePool.sol";
/**
* @title Deri Protocol PerpetualPool Implementation
*/
contract PerpetualPool is IMigratablePool, IPerpetualPool, MigratablePool {
using MixedSafeMathWithUnit for uint256;
using MixedSafeMathWithUnit for int256;
using SafeERC20 for IERC20;
// Trading symbol
string private _symbol;
// Last price
uint256 private _price;
// Last price timestamp
uint256 private _lastPriceTimestamp;
// Last price block number
uint256 private _lastPriceBlockNumber;
// Base token contract, all settlements are done in base token
IERC20 private _bToken;
// Base token decimals
uint256 private _bDecimals;
// Position token contract
IPToken private _pToken;
// Liquidity provider token contract
ILToken private _lToken;
// For on-chain oracle, it is a contract and must have getPrice() method to fetch current price
// For off-chain signed price oracle, it is an EOA
// and its address is used to verify price signature
IOracle private _oracle;
// Is on-chain oracle, or off-chain oracle with signed price
bool private _isContractOracle;
// LiquidatorQualifier contract to check if an address can call liquidate function
// If this address is 0, means no liquidator qualification check, anyone can call liquidate
ILiquidatorQualifier private _liquidatorQualifier;
// Contract multiplier
uint256 private _multiplier;
// Trading fee ratio
uint256 private _feeRatio;
// Minimum pool margin ratio
uint256 private _minPoolMarginRatio;
// Minimum initial margin ratio for trader
uint256 private _minInitialMarginRatio;
// Minimum maintenance margin ratio for trader
uint256 private _minMaintenanceMarginRatio;
// Minimum amount requirement when add liquidity
uint256 private _minAddLiquidity;
// Redemption fee ratio when removing liquidity
uint256 private _redemptionFeeRatio;
// Funding rate coefficient
uint256 private _fundingRateCoefficient;
// Minimum liquidation reward
uint256 private _minLiquidationReward;
// Maximum liquidation reward
uint256 private _maxLiquidationReward;
// Cutting ratio for liquidator
uint256 private _liquidationCutRatio;
// Price delay allowance in seconds
uint256 private _priceDelayAllowance;
// Recorded cumulative funding rate, overflow of this value is intended
int256 private _cumuFundingRate;
// Last block number when cumulative funding rate was recorded
uint256 private _cumuFundingRateBlock;
// Total liquidity pool holds
uint256 private _liquidity;
// Total net volume of all traders in the pool
int256 private _tradersNetVolume;
// Total cost of current traders net volume
// The cost for a long position is positive, and short position is negative
int256 private _tradersNetCost;
bool private _mutex;
// Locker to prevent reentry
modifier _lock_() {
require(!_mutex, "PerpetualPool: reentry");
_mutex = true;
_;
_mutex = false;
}
/**
* @dev A dummy constructor, which deos not initialize any storage variables
* A template will be deployed with no initialization and real pool will be cloned
* from this template (same as create_forwarder_to mechanism in Vyper),
* and use `initialize` to initialize all storage variables
*/
constructor () {}
/**
* @dev See {IPerpetualPool}.{initialize}
*/
function initialize(
string memory symbol_,
address[5] calldata addresses_,
uint256[12] calldata parameters_
) public override {
require(bytes(_symbol).length == 0 && _controller == address(0), "PerpetualPool: already initialized");
_controller = msg.sender;
_symbol = symbol_;
_bToken = IERC20(addresses_[0]);
_bDecimals = _bToken.decimals();
_pToken = IPToken(addresses_[1]);
_lToken = ILToken(addresses_[2]);
_oracle = IOracle(addresses_[3]);
_isContractOracle = _isContract(address(_oracle));
_liquidatorQualifier = ILiquidatorQualifier(addresses_[4]);
_multiplier = parameters_[0];
_feeRatio = parameters_[1];
_minPoolMarginRatio = parameters_[2];
_minInitialMarginRatio = parameters_[3];
_minMaintenanceMarginRatio = parameters_[4];
_minAddLiquidity = parameters_[5];
_redemptionFeeRatio = parameters_[6];
_fundingRateCoefficient = parameters_[7];
_minLiquidationReward = parameters_[8];
_maxLiquidationReward = parameters_[9];
_liquidationCutRatio = parameters_[10];
_priceDelayAllowance = parameters_[11];
}
/**
* @dev See {IMigratablePool}.{approveMigration}
*/
function approveMigration() public override _controller_ {
require(_migrationTimestamp != 0 && block.timestamp >= _migrationTimestamp, "PerpetualPool: migrationTimestamp not met yet");
// approve new pool to pull all base tokens from this pool
_bToken.safeApprove(_migrationDestination, uint256(-1));
// set pToken/lToken to new pool, after redirecting pToken/lToken to new pool, this pool will stop functioning
_pToken.setPool(_migrationDestination);
_lToken.setPool(_migrationDestination);
}
/**
* @dev See {IMigratablePool}.{executeMigration}
*/
function executeMigration(address source) public override _controller_ {
uint256 migrationTimestamp_ = IPerpetualPool(source).migrationTimestamp();
address migrationDestination_ = IPerpetualPool(source).migrationDestination();
require(migrationTimestamp_ != 0 && block.timestamp >= migrationTimestamp_, "PerpetualPool: migrationTimestamp not met yet");
require(migrationDestination_ == address(this), "PerpetualPool: executeMigration to not destination pool");
// migrate base token
_bToken.safeTransferFrom(source, address(this), _bToken.balanceOf(source));
// // migrate state values from PerpetualPool
// (int256 cumuFundingRate, uint256 cumuFundingRateBlock, uint256 liquidity, int256 tradersNetVolume, int256 tradersNetCost) = IPerpetualPool(source).getStateValues();
// _cumuFundingRate = cumuFundingRate;
// _cumuFundingRateBlock = cumuFundingRateBlock;
// _liquidity = liquidity;
// _tradersNetVolume = tradersNetVolume;
// _tradersNetCost = tradersNetCost;
// migrate state values from PreMiningPool
_liquidity = IPreMiningPool(source).getStateValues();
emit ExecuteMigration(_migrationTimestamp, source, address(this));
}
/**
* @dev See {IPerpetualPool}.{symbol}
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IPerpetualPool}.{getAddresses}
*/
function getAddresses() public view override returns (
address bToken,
address pToken,
address lToken,
address oracle,
address liquidatorQualifier
) {
return (
address(_bToken),
address(_pToken),
address(_lToken),
address(_oracle),
address(_liquidatorQualifier)
);
}
/**
* @dev See {IPerpetualPool}.{getParameters}
*/
function getParameters() public view override returns (
uint256 multiplier,
uint256 feeRatio,
uint256 minPoolMarginRatio,
uint256 minInitialMarginRatio,
uint256 minMaintenanceMarginRatio,
uint256 minAddLiquidity,
uint256 redemptionFeeRatio,
uint256 fundingRateCoefficient,
uint256 minLiquidationReward,
uint256 maxLiquidationReward,
uint256 liquidationCutRatio,
uint256 priceDelayAllowance
) {
return (
_multiplier,
_feeRatio,
_minPoolMarginRatio,
_minInitialMarginRatio,
_minMaintenanceMarginRatio,
_minAddLiquidity,
_redemptionFeeRatio,
_fundingRateCoefficient,
_minLiquidationReward,
_maxLiquidationReward,
_liquidationCutRatio,
_priceDelayAllowance
);
}
/**
* @dev See {IPerpetualPool}.{getStateValues}
*/
function getStateValues() public view override returns (
int256 cumuFundingRate,
uint256 cumuFundingRateBlock,
uint256 liquidity,
int256 tradersNetVolume,
int256 tradersNetCost
) {
return (
_cumuFundingRate,
_cumuFundingRateBlock,
_liquidity,
_tradersNetVolume,
_tradersNetCost
);
}
//================================================================================
// Pool interactions
//================================================================================
/**
* @dev See {IPerpetualPool}.{tradeWithMargin}
*/
function tradeWithMargin(int256 tradeVolume, uint256 bAmount) public override {
_updatePriceFromOracle();
_tradeWithMargin(tradeVolume, bAmount);
}
/**
* @dev See {IPerpetualPool}.{tradeWithMargin}
*/
function tradeWithMargin(
int256 tradeVolume,
uint256 bAmount,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_updatePriceWithSignature(timestamp, price, v, r, s);
_tradeWithMargin(tradeVolume, bAmount);
}
/**
* @dev See {IPerpetualPool}.{trade}
*/
function trade(int256 tradeVolume) public override {
_updatePriceFromOracle();
_trade(tradeVolume);
}
/**
* @dev See {IPerpetualPool}.{trade}
*/
function trade(
int256 tradeVolume,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_updatePriceWithSignature(timestamp, price, v, r, s);
_trade(tradeVolume);
}
/**
* @dev See {IPerpetualPool}.{depositMargin}
*/
function depositMargin(uint256 bAmount) public override {
_updatePriceFromOracle();
_depositMargin(bAmount);
}
/**
* @dev See {IPerpetualPool}.{depositMargin}
*/
function depositMargin(
uint256 bAmount,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_updatePriceWithSignature(timestamp, price, v, r, s);
_depositMargin(bAmount);
}
/**
* @dev See {IPerpetualPool}.{withdrawMargin}
*/
function withdrawMargin(uint256 bAmount) public override {
_updatePriceFromOracle();
_withdrawMargin(bAmount);
}
/**
* @dev See {IPerpetualPool}.{withdrawMargin}
*/
function withdrawMargin(
uint256 bAmount,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_updatePriceWithSignature(timestamp, price, v, r, s);
_withdrawMargin(bAmount);
}
/**
* @dev See {IPerpetualPool}.{addLiquidity}
*/
function addLiquidity(uint256 bAmount) public override {
_updatePriceFromOracle();
_addLiquidity(bAmount);
}
/**
* @dev See {IPerpetualPool}.{addLiquidity}
*/
function addLiquidity(
uint256 bAmount,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_updatePriceWithSignature(timestamp, price, v, r, s);
_addLiquidity(bAmount);
}
/**
* @dev See {IPerpetualPool}.{removeLiquidity}
*/
function removeLiquidity(uint256 lShares) public override {
_updatePriceFromOracle();
_removeLiquidity(lShares);
}
/**
* @dev See {IPerpetualPool}.{removeLiquidity}
*/
function removeLiquidity(
uint256 lShares,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_updatePriceWithSignature(timestamp, price, v, r, s);
_removeLiquidity(lShares);
}
/**
* @dev See {IPerpetualPool}.{liquidate}
*/
function liquidate(address owner) public override {
require(
address(_liquidatorQualifier) == address(0) || _liquidatorQualifier.isQualifiedLiquidator(msg.sender),
"PerpetualPool: not quanlified liquidator"
);
_updatePriceFromOracle();
_liquidate(owner, block.timestamp, _price);
}
/**
* @dev See {IPerpetualPool}.{liquidate}
*
* A price signature with timestamp after position's lastUpdateTimestamp
* will be a valid liquidation price
*/
function liquidate(
address owner,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) public override {
require(
address(_liquidatorQualifier) == address(0) || _liquidatorQualifier.isQualifiedLiquidator(msg.sender),
"PerpetualPool: not quanlified liquidator"
);
_checkPriceSignature(timestamp, price, v, r, s);
_liquidate(owner, timestamp, price);
}
//================================================================================
// Pool critic logics
//================================================================================
/**
* @dev Low level tradeWithMargin implementation
* _lock_ is not need in this function, as sub-functions will apply _lock_
*/
function _tradeWithMargin(int256 tradeVolume, uint256 bAmount) internal {
if (bAmount == 0) {
_trade(tradeVolume);
} else if (tradeVolume == 0) {
_depositMargin(bAmount);
} else {
_depositMargin(bAmount);
_trade(tradeVolume);
}
}
/**
* @dev Low level trade implementation
*/
function _trade(int256 tradeVolume) internal _lock_ {
require(tradeVolume != 0, "PerpetualPool: trade with 0 volume");
require(tradeVolume.reformat(0) == tradeVolume, "PerpetualPool: trade volume must be int");
// get trader's position, trader must have a position token to call this function
(int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin,) = _pToken.getPosition(msg.sender);
// update cumulative funding rate
_updateCumuFundingRate(_price);
// calculate trader's funding fee
int256 funding = volume.mul(_cumuFundingRate - lastCumuFundingRate);
// calculate trading fee for this transaction
int256 curCost = tradeVolume.mul(_price).mul(_multiplier);
uint256 fee = _feeRatio.mul(curCost.abs());
// calculate realized cost
int256 realizedCost = 0;
if ((volume >= 0 && tradeVolume >= 0) || (volume <= 0 && tradeVolume <= 0)) {
// open in same direction, no realized cost
} else if (volume.abs() <= tradeVolume.abs()) {
// previous position is flipped
realizedCost = curCost.mul(volume.abs()).div(tradeVolume.abs()).add(cost);
} else {
// previous position is partially closed
realizedCost = cost.mul(tradeVolume.abs()).div(volume.abs()).add(curCost);
}
// total paid in this transaction, could be negative if there is realized pnl
// this paid amount should be a valid value in base token decimals representation
int256 paid = funding.add(fee).add(realizedCost).reformat(_bDecimals);
// settlements
volume = volume.add(tradeVolume);
cost = cost.add(curCost).sub(realizedCost);
margin = margin.sub(paid);
_tradersNetVolume = _tradersNetVolume.add(tradeVolume);
_tradersNetCost = _tradersNetCost.add(curCost).sub(realizedCost);
_liquidity = _liquidity.add(paid);
lastCumuFundingRate = _cumuFundingRate;
// check margin requirements
require(volume == 0 || _calculateMarginRatio(volume, cost, _price, margin) >= _minInitialMarginRatio,
"PerpetualPool: trader insufficient margin");
require(_tradersNetVolume == 0 || _calculateMarginRatio(_tradersNetVolume.neg(), _tradersNetCost.neg(), _price, _liquidity) >= _minPoolMarginRatio,
"PerpetualPool: pool insufficient liquidity");
_pToken.update(msg.sender, volume, cost, lastCumuFundingRate, margin, block.timestamp);
emit Trade(msg.sender, tradeVolume, _price);
}
/**
* @dev Low level depositMargin implementation
*/
function _depositMargin(uint256 bAmount) internal _lock_ {
require(bAmount != 0, "PerpetualPool: deposit zero margin");
require(bAmount.reformat(_bDecimals) == bAmount, "PerpetualPool: _depositMargin bAmount not valid");
bAmount = _deflationCompatibleSafeTransferFrom(msg.sender, address(this), bAmount);
if (!_pToken.exists(msg.sender)) {
_pToken.mint(msg.sender, bAmount);
} else {
(int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin,) = _pToken.getPosition(msg.sender);
margin = margin.add(bAmount);
_pToken.update(msg.sender, volume, cost, lastCumuFundingRate, margin, block.timestamp);
}
emit DepositMargin(msg.sender, bAmount);
}
/**
* @dev Low level withdrawMargin implementation
*/
function _withdrawMargin(uint256 bAmount) internal _lock_ {
require(bAmount != 0, "PerpetualPool: withdraw zero margin");
require(bAmount.reformat(_bDecimals) == bAmount, "PerpetualPool: _withdrawMargin bAmount not valid");
(int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin,) = _pToken.getPosition(msg.sender);
_updateCumuFundingRate(_price);
int256 funding = volume.mul(_cumuFundingRate - lastCumuFundingRate).reformat(_bDecimals);
margin = margin.sub(funding).sub(bAmount);
_liquidity = _liquidity.add(funding);
lastCumuFundingRate = _cumuFundingRate;
require(volume == 0 || _calculateMarginRatio(volume, cost, _price, margin) >= _minInitialMarginRatio,
"PerpetualPool: withdraw cause insufficient margin");
_pToken.update(msg.sender, volume, cost, lastCumuFundingRate, margin, block.timestamp);
_bToken.safeTransfer(msg.sender, bAmount.rescale(_bDecimals));
emit WithdrawMargin(msg.sender, bAmount);
}
/**
* @dev Low level addLiquidity implementation
*/
function _addLiquidity(uint256 bAmount) internal _lock_ {
require(bAmount >= _minAddLiquidity, "PerpetualPool: add liquidity less than minimum requirement");
require(bAmount.reformat(_bDecimals) == bAmount, "PerpetualPool: _addLiquidity bAmount not valid");
_updateCumuFundingRate(_price);
bAmount = _deflationCompatibleSafeTransferFrom(msg.sender, address(this), bAmount);
uint256 poolDynamicEquity = _liquidity.add(_tradersNetCost.sub(_tradersNetVolume.mul(_price).mul(_multiplier)));
uint256 totalSupply = _lToken.totalSupply();
uint256 lShares;
if (totalSupply == 0) {
lShares = bAmount;
} else {
lShares = bAmount.mul(totalSupply).div(poolDynamicEquity);
}
_lToken.mint(msg.sender, lShares);
_liquidity = _liquidity.add(bAmount);
emit AddLiquidity(msg.sender, lShares, bAmount);
}
/**
* @dev Low level removeLiquidity implementation
*/
function _removeLiquidity(uint256 lShares) internal _lock_ {
require(lShares > 0, "PerpetualPool: remove 0 liquidity");
uint256 balance = _lToken.balanceOf(msg.sender);
require(lShares == balance || balance.sub(lShares) >= 10**18, "PerpetualPool: remaining liquidity shares must be 0 or at least 1");
_updateCumuFundingRate(_price);
uint256 poolDynamicEquity = _liquidity.add(_tradersNetCost.sub(_tradersNetVolume.mul(_price).mul(_multiplier)));
uint256 totalSupply = _lToken.totalSupply();
uint256 bAmount = lShares.mul(poolDynamicEquity).div(totalSupply);
if (lShares < totalSupply) {
bAmount = bAmount.sub(bAmount.mul(_redemptionFeeRatio));
}
bAmount = bAmount.reformat(_bDecimals);
_liquidity = _liquidity.sub(bAmount);
require(_tradersNetVolume == 0 || _calculateMarginRatio(_tradersNetVolume.neg(), _tradersNetCost.neg(), _price, _liquidity) >= _minPoolMarginRatio,
"PerpetualPool: remove liquidity cause pool insufficient liquidity");
_lToken.burn(msg.sender, lShares);
_bToken.safeTransfer(msg.sender, bAmount.rescale(_bDecimals));
emit RemoveLiquidity(msg.sender, lShares, bAmount);
}
/**
* @dev Low level liquidate implementation
*/
function _liquidate(address owner, uint256 timestamp, uint256 price) internal _lock_ {
(int256 volume, int256 cost, , uint256 margin, uint256 lastUpdateTimestamp) = _pToken.getPosition(owner);
require(timestamp > lastUpdateTimestamp, "PerpetualPool: liquidate price is before position timestamp");
int256 pnl = volume.mul(price).mul(_multiplier).sub(cost);
require(pnl.add(margin) <= 0 || _calculateMarginRatio(volume, cost, price, margin) < _minMaintenanceMarginRatio, "PerpetualPool: cannot liquidate");
_liquidity = _liquidity.add(margin);
_tradersNetVolume = _tradersNetVolume.sub(volume);
_tradersNetCost = _tradersNetCost.sub(cost);
_pToken.update(owner, 0, 0, 0, 0, 0);
uint256 reward;
if (margin <= _minLiquidationReward) {
reward = _minLiquidationReward;
} else if (margin >= _maxLiquidationReward) {
reward = _maxLiquidationReward;
} else {
reward = margin.sub(_minLiquidationReward).mul(_liquidationCutRatio).add(_minLiquidationReward);
}
reward = reward.reformat(_bDecimals);
_liquidity = _liquidity.sub(reward);
_bToken.safeTransfer(msg.sender, reward.rescale(_bDecimals));
emit Liquidate(owner, volume, cost, margin, timestamp, price, msg.sender, reward);
}
//================================================================================
// Helpers
//================================================================================
/**
* @dev Check if an address is a contract
*/
function _isContract(address addr) internal view returns (bool) {
uint32 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
/**
* margin + unrealizedPnl
*@dev margin ratio = --------------------------------------
* abs(volume) * price * multiplier
*
* volume cannot be zero
*/
function _calculateMarginRatio(int256 volume, int256 cost, uint256 price, uint256 margin)
internal view returns (uint256)
{
int256 value = volume.mul(price).mul(_multiplier);
uint256 ratio = margin.add(value.sub(cost)).div(value.abs());
return ratio;
}
/**
* _tradersNetVolume * price * multiplier
* @dev rate per block = ------------------------------------------- * coefficient
* _liquidity
*/
function _updateCumuFundingRate(uint256 price) private {
if (block.number > _cumuFundingRateBlock) {
int256 rate;
if (_liquidity != 0) {
rate = _tradersNetVolume.mul(price).mul(_multiplier).mul(_fundingRateCoefficient).div(_liquidity);
} else {
rate = 0;
}
int256 delta = rate * (int256(block.number.sub(_cumuFundingRateBlock))); // overflow is intended
_cumuFundingRate += delta; // overflow is intended
_cumuFundingRateBlock = block.number;
}
}
/**
* @dev Check price signature
*/
function _checkPriceSignature(uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s)
internal view
{
require(v == 27 || v == 28, "PerpetualPool: v not valid");
bytes32 message = keccak256(abi.encodePacked(_symbol, timestamp, price));
bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", message));
address signer = ecrecover(hash, v, r, s);
require(signer == address(_oracle), "PerpetualPool: price not signed by oracle");
}
/**
* @dev Check price signature to verify if price is authorized, and update _price
* only check/update once for one block
*/
function _updatePriceWithSignature(
uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s
) internal
{
if (block.number != _lastPriceBlockNumber) {
require(timestamp >= _lastPriceTimestamp, "PerpetualPool: price is not the newest");
require(block.timestamp - timestamp <= _priceDelayAllowance, "PerpetualPool: price is older than allowance");
_checkPriceSignature(timestamp, price, v, r, s);
_price = price;
_lastPriceTimestamp = timestamp;
_lastPriceBlockNumber = block.number;
}
}
/**
* @dev Update price from on-chain Oracle
*/
function _updatePriceFromOracle() internal {
require(_isContractOracle, "PerpetualPool: wrong type of orcale");
if (block.number != _lastPriceBlockNumber) {
_price = _oracle.getPrice();
_lastPriceBlockNumber = block.number;
}
}
/**
* @dev safeTransferFrom for base token with deflation protection
* Returns the actual received amount in base token (as base 10**18)
*/
function _deflationCompatibleSafeTransferFrom(address from, address to, uint256 amount) internal returns (uint256) {
uint256 preBalance = _bToken.balanceOf(to);
_bToken.safeTransferFrom(from, to, amount.rescale(_bDecimals));
uint256 curBalance = _bToken.balanceOf(to);
uint256 a = curBalance.sub(preBalance);
uint256 b = 10**18;
uint256 c = a * b;
require(c / b == a, "PreMiningPool: _deflationCompatibleSafeTransferFrom multiplication overflows");
uint256 actualReceivedAmount = c / (10 ** _bDecimals);
return actualReceivedAmount;
}
}
// 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 Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `amount` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @dev Emitted when `amount` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `amount` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @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 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() external view returns (uint8);
/**
* @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 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 the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the allowance mechanism.
* `amount` is then deducted from the caller's allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title Deri Protocol non-fungible position token interface
*/
interface IPToken is IERC721 {
/**
* @dev Emitted when `owner`'s position is updated
*/
event Update(
address indexed owner,
int256 volume,
int256 cost,
int256 lastCumuFundingRate,
uint256 margin,
uint256 lastUpdateTimestamp
);
/**
* @dev Position struct
*/
struct Position {
// Position volume, long is positive and short is negative
int256 volume;
// Position cost, long position cost is positive, short position cost is negative
int256 cost;
// The last cumuFundingRate since last funding settlement for this position
// The overflow for this value is intended
int256 lastCumuFundingRate;
// Margin associated with this position
uint256 margin;
// Last timestamp this position updated
uint256 lastUpdateTimestamp;
}
/**
* @dev Set pool address of position token
* pool is the only controller of this contract
* can only be called by current pool
*/
function setPool(address newPool) external;
/**
* @dev Returns address of current pool
*/
function pool() external view returns (address);
/**
* @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 total number of ever minted position tokens, including those burned
*/
function totalMinted() external view returns (uint256);
/**
* @dev Returns the total number of existent position tokens
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns if `owner` owns a position token in this contract
*/
function exists(address owner) external view returns (bool);
/**
* @dev Returns if position token of `tokenId` exists
*/
function exists(uint256 tokenId) external view returns (bool);
/**
* @dev Returns the position of owner `owner`
*
* `owner` must exist
*/
function getPosition(address owner) external view returns (
int256 volume,
int256 cost,
int256 lastCumuFundingRate,
uint256 margin,
uint256 lastUpdateTimestamp
);
/**
* @dev Returns the position of token `tokenId`
*
* `tokenId` must exist
*/
function getPosition(uint256 tokenId) external view returns (
int256 volume,
int256 cost,
int256 lastCumuFundingRate,
uint256 margin,
uint256 lastUpdateTimestamp
);
/**
* @dev Mint a position token for `owner` with intial margin of `margin`
*
* Can only be called by pool
* `owner` cannot be zero address
* `owner` must not exist before calling
*/
function mint(address owner, uint256 margin) external;
/**
* @dev Update the position token for `owner`
*
* Can only be called by pool
* `owner` must exist
*/
function update(
address owner,
int256 volume,
int256 cost,
int256 lastCumuFundingRate,
uint256 margin,
uint256 lastUpdateTimestamp
) external;
/**
* @dev Burn the position token owned of `owner`
*
* Can only be called by pool
* `owner` must exist
*/
function burn(address owner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC20.sol";
/**
* @title Deri Protocol liquidity provider token interface
*/
interface ILToken is IERC20 {
/**
* @dev Set the pool address of this LToken
* pool is the only controller of this contract
* can only be called by current pool
*/
function setPool(address newPool) external;
/**
* @dev Returns address of pool
*/
function pool() external view returns (address);
/**
* @dev Mint LToken to `account` of `amount`
*
* Can only be called by pool
* `account` cannot be zero address
*/
function mint(address account, uint256 amount) external;
/**
* @dev Burn `amount` LToken of `account`
*
* Can only be called by pool
* `account` cannot be zero address
* `account` must owns at least `amount` LToken
*/
function burn(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @title Oracle interface
*/
interface IOracle {
function getPrice() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @title Deri Protocol liquidator qualifier interface
*/
interface ILiquidatorQualifier {
/**
* @dev Check if `liquidator` is a qualified liquidator to call the `liquidate` function in PerpetualPool
*/
function isQualifiedLiquidator(address liquidator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Deri Protocol migratable pool interface
*/
interface IMigratablePool {
/**
* @dev Emitted when migration is prepared
* `source` pool will be migrated to `target` pool after `migrationTimestamp`
*/
event PrepareMigration(uint256 migrationTimestamp, address source, address target);
/**
* @dev Emmited when migration is executed
* `source` pool is migrated to `target` pool
*/
event ExecuteMigration(uint256 migrationTimestamp, address source, address target);
/**
* @dev Set controller to `newController`
*
* can only be called by current controller or the controller has not been set
*/
function setController(address newController) external;
/**
* @dev Returns address of current controller
*/
function controller() external view returns (address);
/**
* @dev Returns the migrationTimestamp of this pool, zero means not set
*/
function migrationTimestamp() external view returns (uint256);
/**
* @dev Returns the destination pool this pool will migrate to after grace period
* zero address means not set
*/
function migrationDestination() external view returns (address);
/**
* @dev Prepare a migration from this pool to `newPool` with `graceDays` as grace period
* `graceDays` must be at least 3 days from now, allow users to verify the `newPool` code
*
* can only be called by controller
*/
function prepareMigration(address newPool, uint256 graceDays) external;
/**
* @dev Approve migration to `newPool` when grace period ends
* after approvement, current pool will stop functioning
*
* can only be called by controller
*/
function approveMigration() external;
/**
* @dev Called from the `newPool` to migrate from `source` pool
* the grace period of `source` pool must ends
* current pool must be the destination pool set before grace period in the `source` pool
*
* can only be called by controller
*/
function executeMigration(address source) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IMigratablePool.sol";
/**
* @title Deri Protocol PreMining PerpetualPool Interface
*/
interface IPreMiningPool is IMigratablePool {
/**
* @dev Emitted when `owner` add liquidity of `bAmount`,
* and receive `lShares` liquidity token
*/
event AddLiquidity(address indexed owner, uint256 lShares, uint256 bAmount);
/**
* @dev Emitted when `owner` burn `lShares` of liquidity token,
* and receive `bAmount` in base token
*/
event RemoveLiquidity(address indexed owner, uint256 lShares, uint256 bAmount);
/**
* @dev Initialize pool
*
* addresses:
* bToken
* lToken
*
* parameters:
* minAddLiquidity
* redemptionFeeRatio
*/
function initialize(
string memory symbol_,
address[2] calldata addresses_,
uint256[2] calldata parameters_
) external;
/**
* @dev Returns trading symbol
*/
function symbol() external view returns (string memory);
/**
* @dev Returns addresses of (bToken, pToken, lToken, oracle) in this pool
*/
function getAddresses() external view returns (
address bToken,
address lToken
);
/**
* @dev Returns parameters of this pool
*/
function getParameters() external view returns (
uint256 minAddLiquidity,
uint256 redemptionFeeRatio
);
/**
* @dev Returns currents state values of this pool
*/
function getStateValues() external view returns (
uint256 liquidity
);
/**
* @dev Add liquidity of `bAmount` in base token
*
* New liquidity provider token will be issued to the provider
*/
function addLiquidity(uint256 bAmount) external;
/**
* @dev Remove `lShares` of liquidity provider token
*
* The liquidity provider token will be burned and
* the corresponding amount in base token will be sent to provider
*/
function removeLiquidity(uint256 lShares) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IMigratablePool.sol";
/**
* @title Deri Protocol PerpetualPool Interface
*/
interface IPerpetualPool is IMigratablePool {
/**
* @dev Emitted when `owner` traded `tradeVolume` at `price` in pool
*/
event Trade(address indexed owner, int256 tradeVolume, uint256 price);
/**
* @dev Emitted when `owner` deposit margin of `bAmount` in base token
*/
event DepositMargin(address indexed owner, uint256 bAmount);
/**
* @dev Emitted when `owner` withdraw margin of `bAmount` in base token
*/
event WithdrawMargin(address indexed owner, uint256 bAmount);
/**
* @dev Emitted when `owner` add liquidity of `bAmount`,
* and receive `lShares` liquidity token
*/
event AddLiquidity(address indexed owner, uint256 lShares, uint256 bAmount);
/**
* @dev Emitted when `owner` burn `lShares` of liquidity token,
* and receive `bAmount` in base token
*/
event RemoveLiquidity(address indexed owner, uint256 lShares, uint256 bAmount);
/**
* @dev Emitted when `owner`'s position is liquidated
*/
event Liquidate(
address indexed owner,
int256 volume,
int256 cost,
uint256 margin,
uint256 timestamp,
uint256 price,
address liquidator,
uint256 reward
);
/**
* @dev Initialize pool
*
* addresses:
* bToken
* pToken
* lToken
* oracle
* liquidatorQualifier
*
* parameters:
* multiplier
* feeRatio
* minPoolMarginRatio
* minInitialMarginRatio
* minMaintenanceMarginRatio
* minAddLiquidity
* redemptionFeeRatio
* fundingRateCoefficient
* minLiquidationReward
* maxLiquidationReward
* liquidationCutRatio
* priceDelayAllowance
*/
function initialize(
string memory symbol_,
address[5] calldata addresses_,
uint256[12] calldata parameters_
) external;
/**
* @dev Returns trading symbol
*/
function symbol() external view returns (string memory);
/**
* @dev Returns addresses of (bToken, pToken, lToken, oracle) in this pool
*/
function getAddresses() external view returns (
address bToken,
address pToken,
address lToken,
address oracle,
address liquidatorQualifier
);
/**
* @dev Returns parameters of this pool
*/
function getParameters() external view returns (
uint256 multiplier,
uint256 feeRatio,
uint256 minPoolMarginRatio,
uint256 minInitialMarginRatio,
uint256 minMaintenanceMarginRatio,
uint256 minAddLiquidity,
uint256 redemptionFeeRatio,
uint256 fundingRateCoefficient,
uint256 minLiquidationReward,
uint256 maxLiquidationReward,
uint256 liquidationCutRatio,
uint256 priceDelayAllowance
);
/**
* @dev Returns currents state values of this pool
*/
function getStateValues() external view returns (
int256 cumuFundingRate,
uint256 cumuFundingRateBlock,
uint256 liquidity,
int256 tradersNetVolume,
int256 tradersNetCost
);
/**
* @dev Trade `tradeVolume` with pool while deposit margin of `bAmount` in base token
* This function is the combination of `depositMargin` and `trade`
*
* The first version is implemented with an on-chain oracle contract
* The second version is implemented with off-chain price provider with signature
*/
function tradeWithMargin(int256 tradeVolume, uint256 bAmount) external;
function tradeWithMargin(
int256 tradeVolume,
uint256 bAmount,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Trade `tradeVolume` with pool
*
* A trader must hold a Position Token (with sufficient margin in PToken)
* before calling this function
*
* The first version is implemented with an on-chain oracle contract
* The second version is implemented with off-chain price provider with signature
*/
function trade(int256 tradeVolume) external;
function trade(
int256 tradeVolume,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Deposit margin of `bAmount` in base token
*
* If trader does not hold position token, a new position token will be minted
* to trader with supplied margin
* Otherwise, the position token of trader will be updated with added margin
*
* The first version is implemented with an on-chain oracle contract
* The second version is implemented with off-chain price provider with signature
*/
function depositMargin(uint256 bAmount) external;
function depositMargin(
uint256 bAmount,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Withdraw margin of `bAmount` in base token
*
* Trader must hold a position token
* If trader holds any open position in position token, the left margin after withdraw
* must be sufficient for the open position
*
* The first version is implemented with an on-chain oracle contract
* The second version is implemented with off-chain price provider with signature
*/
function withdrawMargin(uint256 bAmount) external;
function withdrawMargin(
uint256 bAmount,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Add liquidity of `bAmount` in base token
*
* New liquidity provider token will be issued to the provider
*
* The first version is implemented with an on-chain oracle contract
* The second version is implemented with off-chain price provider with signature
*/
function addLiquidity(uint256 bAmount) external;
function addLiquidity(
uint256 bAmount,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Remove `lShares` of liquidity provider token
*
* The liquidity provider token will be burned and
* the corresponding amount in base token will be sent to provider
*
* The first version is implemented with an on-chain oracle contract
* The second version is implemented with off-chain price provider with signature
*/
function removeLiquidity(uint256 lShares) external;
function removeLiquidity(
uint256 lShares,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Liquidate the position owned by `owner`
* Anyone can call this function to liquidate a position, as long as the liquidation line
* is touched, the liquidator will be rewarded
*
* The first version is implemented with an on-chain oracle contract
* The second version is implemented with off-chain price provider with signature
*/
function liquidate(address owner) external;
function liquidate(
address owner,
uint256 timestamp,
uint256 price,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../interface/IERC20.sol";
import "../math/UnsignedSafeMath.sol";
import "./Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using UnsignedSafeMath 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);
_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;
/**
* @title Mixed safe math with base unit of 10**18
*/
library MixedSafeMathWithUnit {
uint256 constant UONE = 10**18;
uint256 constant UMAX = 2**255 - 1;
int256 constant IONE = 10**18;
int256 constant IMIN = -2**255;
//================================================================================
// Conversions
//================================================================================
/**
* @dev Convert uint256 to int256
*/
function utoi(uint256 a) internal pure returns (int256) {
require(a <= UMAX, "MixedSafeMathWithUnit: convert uint256 to int256 overflow");
int256 b = int256(a);
return b;
}
/**
* @dev Convert int256 to uint256
*/
function itou(int256 a) internal pure returns (uint256) {
require(a >= 0, "MixedSafeMathWithUnit: convert int256 to uint256 overflow");
uint256 b = uint256(a);
return b;
}
/**
* @dev Take abs of int256
*/
function abs(int256 a) internal pure returns (int256) {
require(a != IMIN, "MixedSafeMathWithUnit: int256 abs overflow");
if (a >= 0) {
return a;
} else {
return -a;
}
}
/**
* @dev Take negation of int256
*/
function neg(int256 a) internal pure returns (int256) {
require(a != IMIN, "MixedSafeMathWithUnit: int256 negate overflow");
return -a;
}
//================================================================================
// Rescale and reformat
//================================================================================
function _rescale(uint256 a, uint256 decimals1, uint256 decimals2)
internal pure returns (uint256)
{
uint256 scale1 = 10 ** decimals1;
uint256 scale2 = 10 ** decimals2;
uint256 b = a * scale2;
require(b / scale2 == a, "MixedSafeMathWithUnit: rescale uint256 overflow");
uint256 c = b / scale1;
return c;
}
function _rescale(int256 a, uint256 decimals1, uint256 decimals2)
internal pure returns (int256)
{
int256 scale1 = utoi(10 ** decimals1);
int256 scale2 = utoi(10 ** decimals2);
int256 b = a * scale2;
require(b / scale2 == a, "MixedSafeMathWithUnit: rescale int256 overflow");
int256 c = b / scale1;
return c;
}
/**
* @dev Rescales a value from 10**18 base to 10**decimals base
*/
function rescale(uint256 a, uint256 decimals) internal pure returns (uint256) {
return _rescale(a, 18, decimals);
}
function rescale(int256 a, uint256 decimals) internal pure returns (int256) {
return _rescale(a, 18, decimals);
}
/**
* @dev Reformat a value to be a valid 10**decimals base value
* The formatted value is still in 10**18 base
*/
function reformat(uint256 a, uint256 decimals) internal pure returns (uint256) {
return _rescale(_rescale(a, 18, decimals), decimals, 18);
}
function reformat(int256 a, uint256 decimals) internal pure returns (int256) {
return _rescale(_rescale(a, 18, decimals), decimals, 18);
}
//================================================================================
// Addition
//================================================================================
/**
* @dev Addition: uint256 + uint256
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "MixedSafeMathWithUnit: uint256 addition overflow");
return c;
}
/**
* @dev Addition: int256 + int256
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require(
(b >= 0 && c >= a) || (b < 0 && c < a),
"MixedSafeMathWithUnit: int256 addition overflow"
);
return c;
}
/**
* @dev Addition: uint256 + int256
* uint256(-b) will not overflow when b is IMIN
*/
function add(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return add(a, uint256(b));
} else {
return sub(a, uint256(-b));
}
}
/**
* @dev Addition: int256 + uint256
*/
function add(int256 a, uint256 b) internal pure returns (int256) {
return add(a, utoi(b));
}
//================================================================================
// Subtraction
//================================================================================
/**
* @dev Subtraction: uint256 - uint256
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "MixedSafeMathWithUnit: uint256 subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Subtraction: int256 - int256
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require(
(b >= 0 && c <= a) || (b < 0 && c > a),
"MixedSafeMathWithUnit: int256 subtraction overflow"
);
return c;
}
/**
* @dev Subtraction: uint256 - int256
* uint256(-b) will not overflow when b is IMIN
*/
function sub(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return sub(a, uint256(b));
} else {
return add(a, uint256(-b));
}
}
/**
* @dev Subtraction: int256 - uint256
*/
function sub(int256 a, uint256 b) internal pure returns (int256) {
return sub(a, utoi(b));
}
//================================================================================
// Multiplication
//================================================================================
/**
* @dev Multiplication: uint256 * uint256
*/
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, "MixedSafeMathWithUnit: uint256 multiplication overflow");
return c / UONE;
}
/**
* @dev Multiplication: int256 * int256
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == IMIN), "MixedSafeMathWithUnit: int256 multiplication overflow");
int256 c = a * b;
require(c / a == b, "MixedSafeMathWithUnit: int256 multiplication overflow");
return c / IONE;
}
/**
* @dev Multiplication: uint256 * int256
*/
function mul(uint256 a, int256 b) internal pure returns (uint256) {
return mul(a, itou(b));
}
/**
* @dev Multiplication: int256 * uint256
*/
function mul(int256 a, uint256 b) internal pure returns (int256) {
return mul(a, utoi(b));
}
//================================================================================
// Division
//================================================================================
/**
* @dev Division: uint256 / uint256
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MixedSafeMathWithUnit: uint256 division by zero");
uint256 c = a * UONE;
require(
c / UONE == a,
"MixedSafeMathWithUnit: uint256 division internal multiplication overflow"
);
uint256 d = c / b;
return d;
}
/**
* @dev Division: int256 / int256
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "MixedSafeMathWithUnit: int256 division by zero");
int256 c = a * IONE;
require(
c / IONE == a,
"MixedSafeMathWithUnit: int256 division internal multiplication overflow"
);
require(!(c == IMIN && b == -1), "MixedSafeMathWithUnit: int256 division overflow");
int256 d = c / b;
return d;
}
/**
* @dev Division: uint256 / int256
*/
function div(uint256 a, int256 b) internal pure returns (uint256) {
return div(a, itou(b));
}
/**
* @dev Division: int256 / uint256
*/
function div(int256 a, uint256 b) internal pure returns (int256) {
return div(a, utoi(b));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../interface/IMigratablePool.sol";
/**
* @dev Deri Protocol migratable pool implementation
*/
abstract contract MigratablePool is IMigratablePool {
// Controller address
address _controller;
// Migration timestamp of this pool, zero means not set
// Migration timestamp can only be set with a grace period at least 3 days, and the
// `migrationDestination` pool address must be also set when setting migration timestamp,
// users can use this grace period to verify the `migrationDestination` pool code
uint256 _migrationTimestamp;
// The new pool this pool will migrate to after grace period, zero address means not set
address _migrationDestination;
modifier _controller_() {
require(msg.sender == _controller, "can only be called by current controller");
_;
}
/**
* @dev See {IMigratablePool}.{setController}
*/
function setController(address newController) public override {
require(newController != address(0), "MigratablePool: setController to 0 address");
require(
_controller == address(0) || msg.sender == _controller,
"MigratablePool: setController can only be called by current controller or not set"
);
_controller = newController;
}
/**
* @dev See {IMigratablePool}.{controller}
*/
function controller() public view override returns (address) {
return _controller;
}
/**
* @dev See {IMigratablePool}.{migrationTimestamp}
*/
function migrationTimestamp() public view override returns (uint256) {
return _migrationTimestamp;
}
/**
* @dev See {IMigratablePool}.{migrationDestination}
*/
function migrationDestination() public view override returns (address) {
return _migrationDestination;
}
/**
* @dev See {IMigratablePool}.{prepareMigration}
*/
function prepareMigration(address newPool, uint256 graceDays) public override _controller_ {
require(newPool != address(0), "MigratablePool: prepareMigration to 0 address");
require(graceDays >= 3 && graceDays <= 365, "MigratablePool: graceDays must be 3-365 days");
_migrationTimestamp = block.timestamp + graceDays * 1 days;
_migrationDestination = newPool;
emit PrepareMigration(_migrationTimestamp, address(this), _migrationDestination);
}
/**
* @dev See {IMigratablePool}.{approveMigration}
*
* This function will be implemented in inheriting contract
* This function will change if there is an upgrade to existent pool
*/
// function approveMigration() public virtual override _controller_ {}
/**
* @dev See {IMigratablePool}.{executeMigration}
*
* This function will be implemented in inheriting contract
* This function will change if there is an upgrade to existent pool
*/
// function executeMigration(address source) public virtual override _controller_ {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./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 `operator` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed operator, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables `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);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address);
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address);
/**
* @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 Gives permission to `operator` 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 operator, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev 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 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 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
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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Unsigned safe math
*/
library UnsignedSafeMath {
/**
* @dev Addition of unsigned integers, counterpart to `+`
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "UnsignedSafeMath: addition overflow");
return c;
}
/**
* @dev Subtraction of unsigned integers, counterpart to `-`
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "UnsignedSafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Multiplication of unsigned integers, counterpart to `*`
*/
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, "UnsignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Division of unsigned integers, counterpart to `/`
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: division by zero");
uint256 c = a / b;
return c;
}
/**
* @dev Modulo of unsigned integers, counterpart to `%`
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: modulo by zero");
uint256 c = a % b;
return c;
}
}
// 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);
}
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);
}
}
}
}
|
Set the pool address of this LToken pool is the only controller of this contract can only be called by current pool/ Returns address of pool/ Mint LToken to `account` of `amount` Can only be called by pool `account` cannot be zero address/ Burn `amount` LToken of `account` Can only be called by pool `account` cannot be zero address `account` must owns at least `amount` LToken/ SPDX-License-Identifier: MIT Oracle interface/
|
interface IOracle {
function getPrice() external view returns (uint256);
}
| 582,169
|
/**
*Submitted for verification at Etherscan.io on 2021-09-05
*/
// solhint-disable-next-line
pragma solidity 0.4.26;
// solhint-disable func-order
contract GenePoolInterface {
// signals is gene pool
function isGenePool() public pure returns (bool);
// breeds two parents and returns childs genes
function breed(uint256[2] mother, uint256[2] father, uint256 seed) public view returns (uint256[2]);
// generates (psuedo) random Pepe DNA
function randomDNA(uint256 seed) public pure returns (uint256[2]);
}
/**
* @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.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
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;
}
}
contract Usernames {
mapping(address => bytes32) public addressToUser;
mapping(bytes32 => address) public userToAddress;
event UserNamed(address indexed user, bytes32 indexed username);
/**
* Claim a username. Frees up a previously used one
* @param _username to claim
*/
function claimUsername(bytes32 _username) external {
require(userToAddress[_username] == address(0));// Username must be free
if (addressToUser[msg.sender] != bytes32(0)) { // If user already has username free it up
userToAddress[addressToUser[msg.sender]] = address(0);
}
//all is well assign username
addressToUser[msg.sender] = _username;
userToAddress[_username] = msg.sender;
emit UserNamed(msg.sender, _username);
}
}
/** @title Beneficiary */
contract Beneficiary is Ownable {
address public beneficiary;
constructor() public {
beneficiary = msg.sender;
}
/**
* @dev Change the beneficiary address
* @param _beneficiary Address of the new beneficiary
*/
function setBeneficiary(address _beneficiary) public onlyOwner {
beneficiary = _beneficiary;
}
}
/** @title Affiliate */
contract Affiliate is Ownable {
mapping(address => bool) public canSetAffiliate;
mapping(address => address) public userToAffiliate;
/** @dev Allows an address to set the affiliate address for a user
* @param _setter The address that should be allowed
*/
function setAffiliateSetter(address _setter) public onlyOwner {
canSetAffiliate[_setter] = true;
}
/**
* @dev Set the affiliate of a user
* @param _user user to set affiliate for
* @param _affiliate address to set
*/
function setAffiliate(address _user, address _affiliate) public {
require(canSetAffiliate[msg.sender]);
if (userToAffiliate[_user] == address(0)) {
userToAffiliate[_user] = _affiliate;
}
}
}
contract ERC721 {
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) ;
function transfer(address _to, uint256 _tokenId) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
contract PepeInterface is ERC721{
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) public returns (bool);
function getCozyAgain(uint256 _pepeId) public view returns(uint64);
}
/** @title AuctionBase */
contract AuctionBase is Beneficiary {
mapping(uint256 => PepeAuction) public auctions;//maps pepes to auctions
PepeInterface public pepeContract;
Affiliate public affiliateContract;
uint256 public fee = 37500; //in 1 10000th of a percent so 3.75% at the start
uint256 public constant FEE_DIVIDER = 1000000; //Perhaps needs better name?
struct PepeAuction {
address seller;
uint256 pepeId;
uint64 auctionBegin;
uint64 auctionEnd;
uint256 beginPrice;
uint256 endPrice;
}
event AuctionWon(uint256 indexed pepe, address indexed winner, address indexed seller);
event AuctionStarted(uint256 indexed pepe, address indexed seller);
event AuctionFinalized(uint256 indexed pepe, address indexed seller);
constructor(address _pepeContract, address _affiliateContract) public {
pepeContract = PepeInterface(_pepeContract);
affiliateContract = Affiliate(_affiliateContract);
}
/**
* @dev Return a pepe from a auction that has passed
* @param _pepeId the id of the pepe to save
*/
function savePepe(uint256 _pepeId) external {
// solhint-disable-next-line not-rely-on-time
require(auctions[_pepeId].auctionEnd < now);//auction must have ended
require(pepeContract.transfer(auctions[_pepeId].seller, _pepeId));//transfer pepe back to seller
emit AuctionFinalized(_pepeId, auctions[_pepeId].seller);
delete auctions[_pepeId];//delete auction
}
/**
* @dev change the fee on pepe sales. Can only be lowerred
* @param _fee The new fee to set. Must be lower than current fee
*/
function changeFee(uint256 _fee) external onlyOwner {
require(_fee < fee);//fee can not be raised
fee = _fee;
}
/**
* @dev Start a auction
* @param _pepeId Pepe to sell
* @param _beginPrice Price at which the auction starts
* @param _endPrice Ending price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
require(pepeContract.transferFrom(msg.sender, address(this), _pepeId));
// solhint-disable-next-line not-rely-on-time
require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active
PepeAuction memory auction;
auction.seller = msg.sender;
auction.pepeId = _pepeId;
// solhint-disable-next-line not-rely-on-time
auction.auctionBegin = uint64(now);
// solhint-disable-next-line not-rely-on-time
auction.auctionEnd = uint64(now) + _duration;
require(auction.auctionEnd > auction.auctionBegin);
auction.beginPrice = _beginPrice;
auction.endPrice = _endPrice;
auctions[_pepeId] = auction;
emit AuctionStarted(_pepeId, msg.sender);
}
/**
* @dev directly start a auction from the PepeBase contract
* @param _pepeId Pepe to put on auction
* @param _beginPrice Price at which the auction starts
* @param _endPrice Ending price of the auction
* @param _duration How long the auction should take
* @param _seller The address selling the pepe
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
require(msg.sender == address(pepeContract)); //can only be called by pepeContract
//solhint-disable-next-line not-rely-on-time
require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active
PepeAuction memory auction;
auction.seller = _seller;
auction.pepeId = _pepeId;
// solhint-disable-next-line not-rely-on-time
auction.auctionBegin = uint64(now);
// solhint-disable-next-line not-rely-on-time
auction.auctionEnd = uint64(now) + _duration;
require(auction.auctionEnd > auction.auctionBegin);
auction.beginPrice = _beginPrice;
auction.endPrice = _endPrice;
auctions[_pepeId] = auction;
emit AuctionStarted(_pepeId, _seller);
}
/**
* @dev Calculate the current price of a auction
* @param _pepeId the pepeID to calculate the current price for
* @return currentBid the current price for the auction
*/
function calculateBid(uint256 _pepeId) public view returns(uint256 currentBid) {
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = now - auctions[_pepeId].auctionBegin;
// If auction ended return auction end price.
// solhint-disable-next-line not-rely-on-time
if (now >= auction.auctionEnd) {
return auction.endPrice;
} else {
// Can be negative
int256 priceDifference = int256(auction.endPrice) - int256(auction.beginPrice);
// Always positive
int256 duration = int256(auction.auctionEnd) - int256(auction.auctionBegin);
// As already proven in practice by CryptoKitties:
// timePassed -> 64 bits at most
// priceDifference -> 128 bits at most
// timePassed * priceDifference -> 64 + 128 bits at most
int256 priceChange = priceDifference * int256(timePassed) / duration;
// Will be positive, both operands are less than 256 bits
int256 price = int256(auction.beginPrice) + priceChange;
return uint256(price);
}
}
/**
* @dev collect the fees from the auction
*/
function getFees() public {
beneficiary.transfer(address(this).balance);
}
}
/** @title CozyTimeAuction */
contract RebornCozyTimeAuction is AuctionBase {
// solhint-disable-next-line
constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public {
}
/**
* @dev Start an auction
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuction(_pepeId, _beginPrice, _endPrice, _duration);
}
/**
* @dev Start a auction direclty from the PepeBase smartcontract
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
* @param _seller The address of the seller
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller);
}
/**
* @dev Buy cozy right from the auction
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
*/
// solhint-disable-next-line max-line-length
function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable {
require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
require(now < auction.auctionEnd);// auction must be still going
uint256 price = calculateBid(_pepeId);
require(msg.value >= price);//must send enough ether
uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed?
//Send ETH to seller
auction.seller.transfer(price - totalFee);
//send ETH to beneficiary
address affiliate = affiliateContract.userToAffiliate(_pepeReceiver);
//solhint-disable-next-line
if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate
//nothing just to suppress warning
}
//actual cozytiming
if (_candidateAsFather) {
if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) {
revert();
}
} else {
// Swap around the two pepes, they have no set gender, the user decides what they are.
if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) {
revert();
}
}
//Send pepe to seller of auction
if (!pepeContract.transfer(auction.seller, _pepeId)) {
revert(); //can't complete transfer if this fails
}
if (msg.value > price) { //return ether send to much
_pepeReceiver.transfer(msg.value - price);
}
emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event
delete auctions[_pepeId];//deletes auction
}
/**
* @dev Buy cozytime and pass along affiliate
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
* @param _affiliate Affiliate address to set
*/
//solhint-disable-next-line max-line-length
function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable {
affiliateContract.setAffiliate(_pepeReceiver, _affiliate);
buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver);
}
}
contract Genetic {
// TODO mutations
// maximum number of random mutations per chromatid
uint8 public constant R = 5;
// solhint-disable-next-line function-max-lines
function breed(uint256[2] mother, uint256[2] father, uint256 seed) internal view returns (uint256[2] memOffset) {
// Meiosis I: recombining alleles (Chromosomal crossovers)
// Note about optimization I: no cell duplication,
// producing 2 seeds/eggs per cell is enough, instead of 4 (like humans do)
// Note about optimization II: crossovers happen,
// but only 1 side of the result is computed,
// as the other side will not affect anything.
// solhint-disable-next-line no-inline-assembly
assembly {
// allocate output
// 1) get the pointer to our memory
memOffset := mload(0x40)
// 2) Change the free-memory pointer to keep our memory
// (we will only use 64 bytes: 2 values of 256 bits)
mstore(0x40, add(memOffset, 64))
// Put seed in scratchpad 0
mstore(0x0, seed)
// Also use the timestamp, best we could do to increase randomness
// without increasing costs dramatically. (Trade-off)
mstore(0x20, timestamp)
// Hash it for a universally random bitstring.
let hash := keccak256(0, 64)
// Byzantium VM does not support shift opcodes, will be introduced in Constantinople.
// Soldity itself, in non-assembly, also just uses other opcodes to simulate it.
// Optmizer should take care of inlining, just declare shiftR ourselves here.
// Where possible, better optimization is applied to make it cheaper.
function shiftR(value, offset) -> result {
result := div(value, exp(2, offset))
}
// solhint-disable max-line-length
// m_context << Instruction::SWAP1 << u256(2) << Instruction::EXP << Instruction::SWAP1 << (c_leftSigned ? Instruction::SDIV : Instruction::DIV);
// optimization: although one side consists of multiple chromatids,
// we handle them just as one long chromatid:
// only difference is that a crossover in chromatid i affects chromatid i+1.
// No big deal, order and location is random anyway
function processSide(fatherSrc, motherSrc, rngSrc) -> result {
{
// initial rngSrc bit length: 254 bits
// Run the crossovers
// =====================================================
// Pick some crossovers
// Each crossover is spaced ~64 bits on average.
// To achieve this, we get a random 7 bit number, [0, 128), for each crossover.
// 256 / 64 = 4, we need 4 crossovers,
// and will have 256 / 127 = 2 at least (rounded down).
// Get one bit determining if we should pick DNA from the father,
// or from the mother.
// This changes every crossover. (by swapping father and mother)
{
if eq(and(rngSrc, 0x1), 0) {
// Swap mother and father,
// create a temporary variable (code golf XOR swap costs more in gas)
let temp := fatherSrc
fatherSrc := motherSrc
motherSrc := temp
}
// remove the bit from rng source, 253 rng bits left
rngSrc := shiftR(rngSrc, 1)
}
// Don't push/pop this all the time, we have just enough space on stack.
let mask := 0
// Cap at 4 crossovers, no more than that.
let cap := 0
let crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON)
// remove bits from hash, e.g. 254 - 7 = 247 left.
rngSrc := shiftR(rngSrc, 7)
let crossoverPos := crossoverLen
// optimization: instead of shifting with an opcode we don't have until Constantinople,
// keep track of the a shifted number, updated using multiplications.
let crossoverPosLeading1 := 1
// solhint-disable-next-line no-empty-blocks
for { } and(lt(crossoverPos, 256), lt(cap, 4)) {
crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON)
// remove bits from hash, e.g. 254 - 7 = 247 left.
rngSrc := shiftR(rngSrc, 7)
crossoverPos := add(crossoverPos, crossoverLen)
cap := add(cap, 1)
} {
// Note: we go from right to left in the bit-string.
// Create a mask for this crossover.
// Example:
// 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.....
// |Prev. data ||Crossover here ||remaining data .......
//
// The crossover part is copied from the mother/father to the child.
// Create the bit-mask
// Create a bitstring that ignores the previous data:
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// First create a leading 1, just before the crossover, like:
// 00000000000010000000000000000000000000000000000000000000000000000000000.....
// Then substract 1, to get a long string of 1s
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// Now do the same for the remain part, and xor it.
// leading 1
// 00000000000000000000000000000010000000000000000000000000000000000000000000000000000000000.....
// sub 1
// 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111.....
// xor with other
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111.....
// 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.....
// Use the final shifted 1 of the previous crossover as the start marker
mask := sub(crossoverPosLeading1, 1)
// update for this crossover, (and will be used as start for next crossover)
crossoverPosLeading1 := mul(1, exp(2, crossoverPos))
mask := xor(mask,
sub(crossoverPosLeading1, 1)
)
// Now add the parent data to the child genotype
// E.g.
// Mask: 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000....
// Parent: 10010111001000110101011111001010001011100000000000010011000001000100000001011101111000111....
// Child (pre): 00000000000000000000000000000001111110100101111111000011001010000000101010100000110110110....
// Child (post): 00000000000000110101011111001011111110100101111111000011001010000000101010100000110110110....
// To do this, we run: child_post = child_pre | (mask & father)
result := or(result, and(mask, fatherSrc))
// Swap father and mother, next crossover will take a string from the other.
let temp := fatherSrc
fatherSrc := motherSrc
motherSrc := temp
}
// We still have a left-over part that was not copied yet
// E.g., we have something like:
// Father: | xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxx ....
// Mother: |############ xxxxxxxxxx xxxxxxxxxxxx....
// Child: | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx....
// The ############ still needs to be applied to the child, also,
// this can be done cheaper than in the loop above,
// as we don't have to swap anything for the next crossover or something.
// At this point we have to assume 4 crossovers ran,
// and that we only have 127 - 1 - (4 * 7) = 98 bits of randomness left.
// We stopped at the bit after the crossoverPos index, see "x":
// 000000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.....
// now create a leading 1 at crossoverPos like:
// 000000001000000000000000000000000000000000000000000000000000000000000000000.....
// Sub 1, get the mask for what we had.
// 000000000111111111111111111111111111111111111111111111111111111111111111111.....
// Invert, and we have the final mask:
// 111111111000000000000000000000000000000000000000000000000000000000000000000.....
mask := not(sub(crossoverPosLeading1, 1))
// Apply it to the result
result := or(result, and(mask, fatherSrc))
// Random mutations
// =====================================================
// random mutations
// Put rng source in scratchpad 0
mstore(0x0, rngSrc)
// And some arbitrary padding in scratchpad 1,
// used to create different hashes based on input size changes
mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21)
// Hash it for a universally random bitstring.
// Then reduce the number of 1s by AND-ing it with other *different* hashes.
// Each bit in mutations has a probability of 0.5^5 = 0.03125 = 3.125% to be a 1
let mutations := and(
and(
and(keccak256(0, 32), keccak256(1, 33)),
and(keccak256(2, 34), keccak256(3, 35))
),
keccak256(0, 36)
)
result := xor(result, mutations)
}
}
{
// Get 1 bit of pseudo randomness that will
// determine if side #1 will come from the left, or right side.
// Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on.
let relativeFatherSideLoc := mul(and(hash, 0x1), 0x20) // shift by 5 bits = mul by 2^5=32 (0x20)
// Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on.
let relativeMotherSideLoc := mul(and(hash, 0x2), 0x10) // already shifted by 1, mul by 2^4=16 (0x10)
// Now remove the used 2 bits from the hash, 254 bits remaining now.
hash := div(hash, 4)
// Process the side, load the relevant parent data that will be used.
mstore(memOffset, processSide(
mload(add(father, relativeFatherSideLoc)),
mload(add(mother, relativeMotherSideLoc)),
hash
))
// The other side will be the opposite index: 1 -> 0, 0 -> 1
// Apply it to the location,
// which is either 0x20 (For index 1) or 0x0 for index 0.
relativeFatherSideLoc := xor(relativeFatherSideLoc, 0x20)
relativeMotherSideLoc := xor(relativeMotherSideLoc, 0x20)
mstore(0x0, seed)
// Second argument will be inverse,
// resulting in a different second hash.
mstore(0x20, not(timestamp))
// Now create another hash, for the other side
hash := keccak256(0, 64)
// Process the other side
mstore(add(memOffset, 0x20), processSide(
mload(add(father, relativeFatherSideLoc)),
mload(add(mother, relativeMotherSideLoc)),
hash
))
}
}
// Sample input:
// ["0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC","0x4444444455555555555555556666666666666644444444455555555555666666"]
//
// ["0x1111111111112222222223333311111111122222223333333331111112222222","0x7777788888888888999999999999977777777777788888888888999999997777"]
// Expected results (or similar, depends on the seed):
// 0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC < Father side A
// 0x4444444455555555555555556666666666666644444444455555555555666666 < Father side B
// 0x1111111111112222222223333311111111122222223333333331111112222222 < Mother side A
// 0x7777788888888888999999999999977777777777788888888888999999997777 < Mother side B
// xxxxxxxxxxxxxxxxx xxxxxxxxx xx
// 0xAAABBBBBBBBCCCCCD99999999998BBBBBBBBF77778888888888899999999774C < Child side A
// xxx xxxxxxxxxxx
// 0x4441111111112222222223333366666666666222223333333331111112222222 < Child side B
// And then random mutations, for gene pool expansion.
// Each bit is flipped with a 3.125% chance
// Example:
//a2c37edc61dca0ca0b199e098c80fd5a221c2ad03605b4b54332361358745042 < random hash 1
//c217d04b19a83fe497c1cf6e1e10030e455a0812a6949282feec27d67fe2baa7 < random hash 2
//2636a55f38bed26d804c63a13628e21b2d701c902ca37b2b0ca94fada3821364 < random hash 3
//86bb023a85e2da50ac233b946346a53aa070943b0a8e91c56e42ba181729a5f9 < random hash 4
//5d71456a1288ab30ddd4c955384d42e66a09d424bd7743791e3eab8e09aa13f1 < random hash 5
//0000000800800000000000000000000200000000000000000000020000000000 < resulting mutation
//aaabbbbbbbbcccccd99999999998bbbbbbbbf77778888888888899999999774c < original
//aaabbbb3bb3cccccd99999999998bbb9bbbbf7777888888888889b999999774c < mutated (= original XOR mutation)
}
// Generates (psuedo) random Pepe DNA
function randomDNA(uint256 seed) internal pure returns (uint256[2] memOffset) {
// solhint-disable-next-line no-inline-assembly
assembly {
// allocate output
// 1) get the pointer to our memory
memOffset := mload(0x40)
// 2) Change the free-memory pointer to keep our memory
// (we will only use 64 bytes: 2 values of 256 bits)
mstore(0x40, add(memOffset, 64))
// Load the seed into 1st scratchpad memory slot.
// adjacent to the additional value (used to create two distinct hashes)
mstore(0x0, seed)
// In second scratchpad slot:
// The additional value can be any word, as long as the caller uses
// it (second hash needs to be different)
mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21)
// // Create first element pointer of array
// mstore(memOffset, add(memOffset, 64)) // pointer 1
// mstore(add(memOffset, 32), add(memOffset, 96)) // pointer 2
// control block to auto-pop the hash.
{
// L * N * 2 * 4 = 4 * 2 * 2 * 4 = 64 bytes, 2x 256 bit hash
// Sha3 is cheaper than sha256, make use of it
let hash := keccak256(0, 64)
// Store first array value
mstore(memOffset, hash)
// Now hash again, but only 32 bytes of input,
// to ignore make the input different than the previous call,
hash := keccak256(0, 32)
mstore(add(memOffset, 32), hash)
}
}
}
}
/** @title CozyTimeAuction */
contract CozyTimeAuction is AuctionBase {
// solhint-disable-next-line
constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public {
}
/**
* @dev Start an auction
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuction(_pepeId, _beginPrice, _endPrice, _duration);
}
/**
* @dev Start a auction direclty from the PepeBase smartcontract
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
* @param _seller The address of the seller
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller);
}
/**
* @dev Buy cozy right from the auction
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
*/
// solhint-disable-next-line max-line-length
function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable {
require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
require(now < auction.auctionEnd);// auction must be still going
uint256 price = calculateBid(_pepeId);
require(msg.value >= price);//must send enough ether
uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed?
//Send ETH to seller
auction.seller.transfer(price - totalFee);
//send ETH to beneficiary
address affiliate = affiliateContract.userToAffiliate(_pepeReceiver);
//solhint-disable-next-line
if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate
//nothing just to suppress warning
}
//actual cozytiming
if (_candidateAsFather) {
if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) {
revert();
}
} else {
// Swap around the two pepes, they have no set gender, the user decides what they are.
if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) {
revert();
}
}
//Send pepe to seller of auction
if (!pepeContract.transfer(auction.seller, _pepeId)) {
revert(); //can't complete transfer if this fails
}
if (msg.value > price) { //return ether send to much
_pepeReceiver.transfer(msg.value - price);
}
emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event
delete auctions[_pepeId];//deletes auction
}
/**
* @dev Buy cozytime and pass along affiliate
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
* @param _affiliate Affiliate address to set
*/
//solhint-disable-next-line max-line-length
function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable {
affiliateContract.setAffiliate(_pepeReceiver, _affiliate);
buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver);
}
}
contract Haltable is Ownable {
uint256 public haltTime; //when the contract was halted
bool public halted;//is the contract halted?
uint256 public haltDuration;
uint256 public maxHaltDuration = 8 weeks;//how long the contract can be halted
modifier stopWhenHalted {
require(!halted);
_;
}
modifier onlyWhenHalted {
require(halted);
_;
}
/**
* @dev Halt the contract for a set time smaller than maxHaltDuration
* @param _duration Duration how long the contract should be halted. Must be smaller than maxHaltDuration
*/
function halt(uint256 _duration) public onlyOwner {
require(haltTime == 0); //cannot halt if it was halted before
require(_duration <= maxHaltDuration);//cannot halt for longer than maxHaltDuration
haltDuration = _duration;
halted = true;
// solhint-disable-next-line not-rely-on-time
haltTime = now;
}
/**
* @dev Unhalt the contract. Can only be called by the owner or when the haltTime has passed
*/
function unhalt() public {
// solhint-disable-next-line
require(now > haltTime + haltDuration || msg.sender == owner);//unhalting is only possible when haltTime has passed or the owner unhalts
halted = false;
}
}
/**
* @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;
}
}
/// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. This function MUST use 50,000 gas or less. Return of other
/// than the magic value MUST result in the transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _from The sending address
/// @param _tokenId The NFT identifier which is being transfered
/// @param data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
contract PepeBase is Genetic, Ownable, Usernames, Haltable {
uint32[15] public cozyCoolDowns = [ //determined by generation / 2
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(15 minutes),
uint32(30 minutes),
uint32(45 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
struct Pepe {
address master; //The master of the pepe
uint256[2] genotype; //all genes stored here
uint64 canCozyAgain; //time when pepe can have nice time again
uint64 generation; //what generation?
uint64 father; //father of this pepe
uint64 mother; //mommy of this pepe
uint8 coolDownIndex;
}
mapping(uint256 => bytes32) public pepeNames;
//stores all pepes
Pepe[] public pepes;
bool public implementsERC721 = true; //signal erc721 support
// solhint-disable-next-line const-name-snakecase
string public constant name = "Crypto Pepe";
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "CPEP";
mapping(address => uint256[]) private wallets;
mapping(address => uint256) public balances; //amounts of pepes per address
mapping(uint256 => address) public approved; //pepe index to address approved to transfer
mapping(address => mapping(address => bool)) public approvedForAll;
uint256 public zeroGenPepes; //how many zero gen pepes are mined
uint256 public constant MAX_PREMINE = 100;//how many pepes can be premined
uint256 public constant MAX_ZERO_GEN_PEPES = 1100; //max number of zero gen pepes
address public miner; //address of the miner contract
modifier onlyPepeMaster(uint256 _pepeId) {
require(pepes[_pepeId].master == msg.sender);
_;
}
modifier onlyAllowed(uint256 _tokenId) {
// solhint-disable-next-line max-line-length
require(msg.sender == pepes[_tokenId].master || msg.sender == approved[_tokenId] || approvedForAll[pepes[_tokenId].master][msg.sender]); //check if msg.sender is allowed
_;
}
event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId);
event PepeNamed(uint256 indexed pepeId);
constructor() public {
Pepe memory pepe0 = Pepe({
master: 0x0,
genotype: [uint256(0), uint256(0)],
canCozyAgain: 0,
father: 0,
mother: 0,
generation: 0,
coolDownIndex: 0
});
pepes.push(pepe0);
}
/**
* @dev Internal function that creates a new pepe
* @param _genoType DNA of the new pepe
* @param _mother The ID of the mother
* @param _father The ID of the father
* @param _generation The generation of the new Pepe
* @param _master The owner of this new Pepe
* @return The ID of the newly generated Pepe
*/
// solhint-disable-next-line max-line-length
function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) {
uint8 tempCoolDownIndex;
tempCoolDownIndex = uint8(_generation / 2);
if (_generation > 28) {
tempCoolDownIndex = 14;
}
Pepe memory _pepe = Pepe({
master: _master, //The master of the pepe
genotype: _genoType, //all genes stored here
canCozyAgain: 0, //time when pepe can have nice time again
father: _father, //father of this pepe
mother: _mother, //mommy of this pepe
generation: _generation, //what generation?
coolDownIndex: tempCoolDownIndex
});
if (_generation == 0) {
zeroGenPepes += 1; //count zero gen pepes
}
//push returns the new length, use it to get a new unique id
pepeId = pepes.push(_pepe) - 1;
//add it to the wallet of the master of the new pepe
addToWallet(_master, pepeId);
emit PepeBorn(_mother, _father, pepeId);
emit Transfer(address(0), _master, pepeId);
return pepeId;
}
/**
* @dev Set the miner contract. Can only be called once
* @param _miner Address of the miner contract
*/
function setMiner(address _miner) public onlyOwner {
require(miner == address(0));//can only be set once
miner = _miner;
}
/**
* @dev Mine a new Pepe. Can only be called by the miner contract.
* @param _seed Seed to be used for the generation of the DNA
* @param _receiver Address receiving the newly mined Pepe
* @return The ID of the newly mined Pepe
*/
function minePepe(uint256 _seed, address _receiver) public stopWhenHalted returns(uint256) {
require(msg.sender == miner);//only miner contract can call
require(zeroGenPepes < MAX_ZERO_GEN_PEPES);
return _newPepe(randomDNA(_seed), 0, 0, 0, _receiver);
}
/**
* @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE
* @param _amount Amount of Pepes to premine
*/
function pepePremine(uint256 _amount) public onlyOwner stopWhenHalted {
for (uint i = 0; i < _amount; i++) {
require(zeroGenPepes <= MAX_PREMINE);//can only generate set amount during premine
//create a new pepe
// 1) who's genes are based on hash of the timestamp and the number of pepes
// 2) who has no mother or father
// 3) who is generation zero
// 4) who's master is the manager
// solhint-disable-next-line
_newPepe(randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, pepes.length)))), 0, 0, 0, owner);
}
}
/**
* @dev CozyTime two Pepes together
* @param _mother The mother of the new Pepe
* @param _father The father of the new Pepe
* @param _pepeReceiver Address receiving the new Pepe
* @return If it was a success
*/
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external stopWhenHalted returns (bool) {
//cannot cozyTime with itself
require(_mother != _father);
//caller has to either be master or approved for mother
// solhint-disable-next-line max-line-length
require(pepes[_mother].master == msg.sender || approved[_mother] == msg.sender || approvedForAll[pepes[_mother].master][msg.sender]);
//caller has to either be master or approved for father
// solhint-disable-next-line max-line-length
require(pepes[_father].master == msg.sender || approved[_father] == msg.sender || approvedForAll[pepes[_father].master][msg.sender]);
//require both parents to be ready for cozytime
// solhint-disable-next-line not-rely-on-time
require(now > pepes[_mother].canCozyAgain && now > pepes[_father].canCozyAgain);
//require both mother parents not to be father
require(pepes[_mother].mother != _father && pepes[_mother].father != _father);
//require both father parents not to be mother
require(pepes[_father].mother != _mother && pepes[_father].father != _mother);
Pepe storage father = pepes[_father];
Pepe storage mother = pepes[_mother];
approved[_father] = address(0);
approved[_mother] = address(0);
uint256[2] memory newGenotype = breed(father.genotype, mother.genotype, pepes.length);
uint64 newGeneration;
newGeneration = mother.generation + 1;
if (newGeneration < father.generation + 1) { //if father generation is bigger
newGeneration = father.generation + 1;
}
_handleCoolDown(_mother);
_handleCoolDown(_father);
//sets pepe birth when mother is done
// solhint-disable-next-line max-line-length
pepes[_newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver)].canCozyAgain = mother.canCozyAgain; //_pepeReceiver becomes the master of the pepe
return true;
}
/**
* @dev Internal function to increase the coolDownIndex
* @param _pepeId The id of the Pepe to update the coolDown of
*/
function _handleCoolDown(uint256 _pepeId) internal {
Pepe storage tempPep = pepes[_pepeId];
// solhint-disable-next-line not-rely-on-time
tempPep.canCozyAgain = uint64(now + cozyCoolDowns[tempPep.coolDownIndex]);
if (tempPep.coolDownIndex < 14) {// after every cozy time pepe gets slower
tempPep.coolDownIndex++;
}
}
/**
* @dev Set the name of a Pepe. Can only be set once
* @param _pepeId ID of the pepe to name
* @param _name The name to assign
*/
function setPepeName(uint256 _pepeId, bytes32 _name) public stopWhenHalted onlyPepeMaster(_pepeId) returns(bool) {
require(pepeNames[_pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000);
pepeNames[_pepeId] = _name;
emit PepeNamed(_pepeId);
return true;
}
/**
* @dev Transfer a Pepe to the auction contract and auction it
* @param _pepeId ID of the Pepe to auction
* @param _auction Auction contract address
* @param _beginPrice Price the auction starts at
* @param _endPrice Price the auction ends at
* @param _duration How long the auction should run
*/
// solhint-disable-next-line max-line-length
function transferAndAuction(uint256 _pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public stopWhenHalted onlyPepeMaster(_pepeId) {
_transfer(msg.sender, _auction, _pepeId);//transfer pepe to auction
AuctionBase auction = AuctionBase(_auction);
auction.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, msg.sender);
}
/**
* @dev Approve and buy. Used to buy cozyTime in one call
* @param _pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
*/
// solhint-disable-next-line max-line-length
function approveAndBuy(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) {
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
CozyTimeAuction(_auction).buyCozy.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender); //breeding resets approval
}
/**
* @dev The same as above only pass an extra parameter
* @param _pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
* @param _affiliate Address to set as affiliate
*/
// solhint-disable-next-line max-line-length
function approveAndBuyAffiliated(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) {
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
CozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); //breeding resets approval
}
/**
* @dev get Pepe information
* @param _pepeId ID of the Pepe to get information of
* @return master
* @return genotype
* @return canCozyAgain
* @return generation
* @return father
* @return mother
* @return pepeName
* @return coolDownIndex
*/
// solhint-disable-next-line max-line-length
function getPepe(uint256 _pepeId) public view returns(address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) {
Pepe storage tempPep = pepes[_pepeId];
master = tempPep.master;
genotype = tempPep.genotype;
canCozyAgain = tempPep.canCozyAgain;
generation = tempPep.generation;
father = tempPep.father;
mother = tempPep.mother;
pepeName = pepeNames[_pepeId];
coolDownIndex = tempPep.coolDownIndex;
}
/**
* @dev Get the time when a pepe can cozy again
* @param _pepeId ID of the pepe
* @return Time when the pepe can cozy again
*/
function getCozyAgain(uint256 _pepeId) public view returns(uint64) {
return pepes[_pepeId].canCozyAgain;
}
/**
* ERC721 Compatibility
*
*/
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev Get the total number of Pepes
* @return total Returns the total number of pepes
*/
function totalSupply() public view returns(uint256 total) {
total = pepes.length - balances[address(0)];
return total;
}
/**
* @dev Get the number of pepes owned by an address
* @param _owner Address to get the balance from
* @return balance The number of pepes
*/
function balanceOf(address _owner) external view returns (uint256 balance) {
balance = balances[_owner];
}
/**
* @dev Get the owner of a Pepe
* @param _tokenId the token to get the owner of
* @return _owner the owner of the pepe
*/
function ownerOf(uint256 _tokenId) external view returns (address _owner) {
_owner = pepes[_tokenId].master;
}
/**
* @dev Get the id of an token by its index
* @param _owner The address to look up the tokens of
* @param _index Index to look at
* @return tokenId the ID of the token of the owner at the specified index
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 tokenId) {
//The index must be smaller than the balance,
// to guarantee that there is no leftover token returned.
require(_index < balances[_owner]);
return wallets[_owner][_index];
}
/**
* @dev Private method that ads a token to the wallet
* @param _owner Address of the owner
* @param _tokenId Pepe ID to add
*/
function addToWallet(address _owner, uint256 _tokenId) private {
uint256[] storage wallet = wallets[_owner];
uint256 balance = balances[_owner];
if (balance < wallet.length) {
wallet[balance] = _tokenId;
} else {
wallet.push(_tokenId);
}
//increase owner balance
//overflow is not likely to happen(need very large amount of pepes)
balances[_owner] += 1;
}
/**
* @dev Remove a token from a address's wallet
* @param _owner Address of the owner
* @param _tokenId Token to remove from the wallet
*/
function removeFromWallet(address _owner, uint256 _tokenId) private {
uint256[] storage wallet = wallets[_owner];
uint256 i = 0;
// solhint-disable-next-line no-empty-blocks
for (; wallet[i] != _tokenId; i++) {
// not the pepe we are looking for
}
if (wallet[i] == _tokenId) {
//found it!
uint256 last = balances[_owner] - 1;
if (last > 0) {
//move the last item to this spot, the last will become inaccessible
wallet[i] = wallet[last];
}
//else: no last item to move, the balance is 0, making everything inaccessible.
//only decrease balance if _tokenId was in the wallet
balances[_owner] -= 1;
}
}
/**
* @dev Internal transfer function
* @param _from Address sending the token
* @param _to Address to token is send to
* @param _tokenId ID of the token to send
*/
function _transfer(address _from, address _to, uint256 _tokenId) internal {
pepes[_tokenId].master = _to;
approved[_tokenId] = address(0);//reset approved of pepe on every transfer
//remove the token from the _from wallet
removeFromWallet(_from, _tokenId);
//add the token to the _to wallet
addToWallet(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev transfer a token. Can only be called by the owner of the token
* @param _to Addres to send the token to
* @param _tokenId ID of the token to send
*/
// solhint-disable-next-line no-simple-event-func-name
function transfer(address _to, uint256 _tokenId) public stopWhenHalted
onlyPepeMaster(_tokenId) //check if msg.sender is the master of this pepe
returns(bool)
{
_transfer(msg.sender, _to, _tokenId);//after master modifier invoke internal transfer
return true;
}
/**
* @dev Approve a address to send a token
* @param _to Address to approve
* @param _tokenId Token to set approval for
*/
function approve(address _to, uint256 _tokenId) external stopWhenHalted
onlyPepeMaster(_tokenId)
{
approved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
/**
* @dev Approve or revoke approval an address for al tokens of a user
* @param _operator Address to (un)approve
* @param _approved Approving or revoking indicator
*/
function setApprovalForAll(address _operator, bool _approved) external stopWhenHalted {
if (_approved) {
approvedForAll[msg.sender][_operator] = true;
} else {
approvedForAll[msg.sender][_operator] = false;
}
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Get approved address for a token
* @param _tokenId Token ID to get the approved address for
* @return The address that is approved for this token
*/
function getApproved(uint256 _tokenId) external view returns (address) {
return approved[_tokenId];
}
/**
* @dev Get if an operator is approved for all tokens of that owner
* @param _owner Owner to check the approval for
* @param _operator Operator to check approval for
* @return Boolean indicating if the operator is approved for that owner
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return approvedForAll[_owner][_operator];
}
/**
* @dev Function to signal support for an interface
* @param interfaceID the ID of the interface to check for
* @return Boolean indicating support
*/
function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
if (interfaceID == 0x80ac58cd || interfaceID == 0x01ffc9a7) { //TODO: add more interfaces the contract supports
return true;
}
return false;
}
/**
* @dev Safe transferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external stopWhenHalted {
_safeTransferFromInternal(_from, _to, _tokenId, "");
}
/**
* @dev Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external stopWhenHalted {
_safeTransferFromInternal(_from, _to, _tokenId, _data);
}
/**
* @dev Internal Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function _safeTransferFromInternal(address _from, address _to, uint256 _tokenId, bytes _data) internal onlyAllowed(_tokenId) {
require(pepes[_tokenId].master == _from);//check if from is current owner
require(_to != address(0));//throw on zero address
_transfer(_from, _to, _tokenId); //transfer token
if (isContract(_to)) { //check if is contract
// solhint-disable-next-line max-line-length
require(ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
/**
* @dev TransferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @return If it was successful
*/
// solhint-disable-next-line max-line-length
function transferFrom(address _from, address _to, uint256 _tokenId) public stopWhenHalted onlyAllowed(_tokenId) returns(bool) {
require(pepes[_tokenId].master == _from);//check if _from is really the master.
require(_to != address(0));
_transfer(_from, _to, _tokenId);//handles event, balances and approval reset;
return true;
}
/**
* @dev Utility method to check if an address is a contract
* @param _address Address to check
* @return Boolean indicating if the address is a contract
*/
function isContract(address _address) internal view returns (bool) {
uint size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_address) }
return size > 0;
}
}
contract PepeReborn is Ownable, Usernames {
uint32[15] public cozyCoolDowns = [ // determined by generation / 2
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(15 minutes),
uint32(30 minutes),
uint32(45 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
struct Pepe {
address master; // The master of the pepe
uint256[2] genotype; // all genes stored here
uint64 canCozyAgain; // time when pepe can have nice time again
uint64 generation; // what generation?
uint64 father; // father of this pepe
uint64 mother; // mommy of this pepe
uint8 coolDownIndex;
}
struct UndeadPepeMutable {
address master; // The master of the pepe
// uint256[2] genotype; // all genes stored here
uint64 canCozyAgain; // time when pepe can have nice time again
// uint64 generation; // what generation?
// uint64 father; // father of this pepe
// uint64 mother; // mommy of this pepe
uint8 coolDownIndex;
bool resurrected; // has the pepe been duplicated off the old contract
}
mapping(uint256 => bytes32) public pepeNames;
// stores reborn pepes. index 0 holds pepe 5497
Pepe[] private rebornPepes;
// stores undead pepes. get the mutables from the old contract
mapping(uint256 => UndeadPepeMutable) private undeadPepes;
//address private constant PEPE_UNDEAD_ADDRRESS = 0x84aC94F17622241f313511B629e5E98f489AD6E4;
//address private constant PEPE_AUCTION_SALE_UNDEAD_ADDRESS = 0x28ae3DF366726D248c57b19fa36F6D9c228248BE;
//address private constant COZY_TIME_AUCTION_UNDEAD_ADDRESS = 0xE2C43d2C6D6875c8F24855054d77B5664c7e810f;
address private PEPE_UNDEAD_ADDRRESS;
address private PEPE_AUCTION_SALE_UNDEAD_ADDRESS;
address private COZY_TIME_AUCTION_UNDEAD_ADDRESS;
GenePoolInterface private genePool;
uint256 private constant REBORN_PEPE_0 = 5497;
bool public constant implementsERC721 = true; // signal erc721 support
// solhint-disable-next-line const-name-snakecase
string public constant name = "Crypto Pepe Reborn";
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "CPRE";
// Token Base URI
string public baseTokenURI = "https://api.cryptopepes.lol/getPepe/";
// Contract URI
string private contractUri = "https://cryptopepes.lol/contract-metadata.json";
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private wallets;
// Mapping from token ID to index in owners wallet
mapping(uint256 => uint256) private walletIndex;
mapping(uint256 => address) public approved; // pepe index to address approved to transfer
mapping(address => mapping(address => bool)) public approvedForAll;
uint256 private preminedPepes = 0;
uint256 private constant MAX_PREMINE = 1100;
modifier onlyPepeMaster(uint256 pepeId) {
require(_ownerOf(pepeId) == msg.sender);
_;
}
modifier onlyAllowed(uint256 pepeId) {
address master = _ownerOf(pepeId);
// solhint-disable-next-line max-line-length
require(msg.sender == master || msg.sender == approved[pepeId] || approvedForAll[master][msg.sender]); // check if msg.sender is allowed
_;
}
event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId);
event PepeNamed(uint256 indexed pepeId);
constructor(address baseAddress, address saleAddress, address cozyAddress, address genePoolAddress) public {
PEPE_UNDEAD_ADDRRESS = baseAddress;
PEPE_AUCTION_SALE_UNDEAD_ADDRESS = saleAddress;
COZY_TIME_AUCTION_UNDEAD_ADDRESS = cozyAddress;
setGenePool(genePoolAddress);
}
/**
* @dev Internal function that creates a new pepe
* @param _genoType DNA of the new pepe
* @param _mother The ID of the mother
* @param _father The ID of the father
* @param _generation The generation of the new Pepe
* @param _master The owner of this new Pepe
* @return The ID of the newly generated Pepe
*/
// solhint-disable-next-line max-line-length
function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) {
uint8 tempCoolDownIndex;
tempCoolDownIndex = uint8(_generation / 2);
if (_generation > 28) {
tempCoolDownIndex = 14;
}
Pepe memory _pepe = Pepe({
master: _master, // The master of the pepe
genotype: _genoType, // all genes stored here
canCozyAgain: 0, // time when pepe can have nice time again
father: _father, // father of this pepe
mother: _mother, // mommy of this pepe
generation: _generation, // what generation?
coolDownIndex: tempCoolDownIndex
});
// push returns the new length, use it to get a new unique id
pepeId = rebornPepes.push(_pepe) + REBORN_PEPE_0 - 1;
// add it to the wallet of the master of the new pepe
addToWallet(_master, pepeId);
emit PepeBorn(_mother, _father, pepeId);
emit Transfer(address(0), _master, pepeId);
return pepeId;
}
/**
* @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE
* @param _amount Amount of Pepes to premine
*/
function pepePremine(uint256 _amount) public onlyOwner {
for (uint i = 0; i < _amount; i++) {
require(preminedPepes < MAX_PREMINE);//can only generate set amount during premine
//create a new pepe
// 1) who's genes are based on hash of the timestamp and the new pepe's id
// 2) who has no mother or father
// 3) who is generation zero
// 4) who's master is the manager
// solhint-disable-next-line
_newPepe(genePool.randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, (REBORN_PEPE_0 + rebornPepes.length))))), 0, 0, 0, owner);
++preminedPepes;
}
}
/*
* @dev CozyTime two Pepes together
* @param _mother The mother of the new Pepe
* @param _father The father of the new Pepe
* @param _pepeReceiver Address receiving the new Pepe
* @return If it was a success
*/
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external returns (bool) {
// cannot cozyTime with itself
require(_mother != _father);
// ressurect parents if needed
checkResurrected(_mother);
checkResurrected(_father);
// get parents
Pepe memory mother = _getPepe(_mother);
Pepe memory father = _getPepe(_father);
// caller has to either be master or approved for mother
// solhint-disable-next-line max-line-length
require(mother.master == msg.sender || approved[_mother] == msg.sender || approvedForAll[mother.master][msg.sender]);
// caller has to either be master or approved for father
// solhint-disable-next-line max-line-length
require(father.master == msg.sender || approved[_father] == msg.sender || approvedForAll[father.master][msg.sender]);
// require both parents to be ready for cozytime
// solhint-disable-next-line not-rely-on-time
require(now > mother.canCozyAgain && now > father.canCozyAgain);
// require both mother parents not to be father
require(mother.father != _father && mother.mother != _father);
require(father.mother != _mother && father.father != _mother);
approved[_father] = address(0);
approved[_mother] = address(0);
uint256[2] memory newGenotype = genePool.breed(father.genotype, mother.genotype, REBORN_PEPE_0+rebornPepes.length);
uint64 newGeneration;
newGeneration = mother.generation + 1;
if (newGeneration < father.generation + 1) { // if father generation is bigger
newGeneration = father.generation + 1;
}
uint64 motherCanCozyAgain = _handleCoolDown(_mother);
_handleCoolDown(_father);
// birth new pepe
// _pepeReceiver becomes the master of the pepe
uint256 pepeId = _newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver);
// sets pepe birth when mother is done
// solhint-disable-next-line max-line-length
rebornPepes[rebornPepeIdToIndex(pepeId)].canCozyAgain = motherCanCozyAgain;
return true;
}
/**
* @dev Internal function to increase the coolDownIndex
* @param pepeId The id of the Pepe to update the coolDown of
* @return The time that pepe can cozy again
*/
function _handleCoolDown(uint256 pepeId) internal returns (uint64){
if(pepeId >= REBORN_PEPE_0){
Pepe storage tempPep1 = rebornPepes[pepeId];
// solhint-disable-next-line not-rely-on-time
tempPep1.canCozyAgain = uint64(now + cozyCoolDowns[tempPep1.coolDownIndex]);
if (tempPep1.coolDownIndex < 14) {// after every cozy time pepe gets slower
tempPep1.coolDownIndex++;
}
return tempPep1.canCozyAgain;
}else{
// this function is only called in cozyTime(), pepe has already been resurrected
UndeadPepeMutable storage tempPep2 = undeadPepes[pepeId];
// solhint-disable-next-line not-rely-on-time
tempPep2.canCozyAgain = uint64(now + cozyCoolDowns[tempPep2.coolDownIndex]);
if (tempPep2.coolDownIndex < 14) {// after every cozy time pepe gets slower
tempPep2.coolDownIndex++;
}
return tempPep2.canCozyAgain;
}
}
/**
* @dev Set the name of a Pepe. Can only be set once
* @param pepeId ID of the pepe to name
* @param _name The name to assign
*/
function setPepeName(uint256 pepeId, bytes32 _name) public onlyPepeMaster(pepeId) returns(bool) {
require(pepeNames[pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000);
pepeNames[pepeId] = _name;
emit PepeNamed(pepeId);
return true;
}
/**
* @dev Transfer a Pepe to the auction contract and auction it
* @param pepeId ID of the Pepe to auction
* @param _auction Auction contract address
* @param _beginPrice Price the auction starts at
* @param _endPrice Price the auction ends at
* @param _duration How long the auction should run
*/
// solhint-disable-next-line max-line-length
function transferAndAuction(uint256 pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public onlyPepeMaster(pepeId) {
//checkResurrected(pepeId);
_transfer(msg.sender, _auction, pepeId);// transfer pepe to auction
AuctionBase auction = AuctionBase(_auction);
auction.startAuctionDirect(pepeId, _beginPrice, _endPrice, _duration, msg.sender);
}
/**
* @dev Approve and buy. Used to buy cozyTime in one call
* @param pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
*/
// solhint-disable-next-line max-line-length
function approveAndBuy(uint256 pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public payable onlyPepeMaster(_cozyCandidate) {
checkResurrected(pepeId);
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
RebornCozyTimeAuction(_auction).buyCozy.value(msg.value)(pepeId, _cozyCandidate, _candidateAsFather, msg.sender); // breeding resets approval
}
/**
* @dev The same as above only pass an extra parameter
* @param pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
* @param _affiliate Address to set as affiliate
*/
// solhint-disable-next-line max-line-length
function approveAndBuyAffiliated(uint256 pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public payable onlyPepeMaster(_cozyCandidate) {
checkResurrected(pepeId);
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
RebornCozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); // breeding resets approval
}
/**
* @dev Get the time when a pepe can cozy again
* @param pepeId ID of the pepe
* @return Time when the pepe can cozy again
*/
function getCozyAgain(uint256 pepeId) public view returns(uint64) {
return _getPepe(pepeId).canCozyAgain;
}
/**
* ERC721 Compatibility
*
*/
event Approval(address indexed _owner, address indexed _approved, uint256 pepeId);
event Transfer(address indexed _from, address indexed _to, uint256 indexed pepeId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev Get the total number of Pepes
* @return total Returns the total number of pepes
*/
function totalSupply() public view returns(uint256) {
return REBORN_PEPE_0 + rebornPepes.length - 1;
}
/**
* @dev Get the number of pepes owned by an address
* Note that this only includes reborn and resurrected pepes
* Pepes that are still dead are not counted.
* @param _owner Address to get the balance from
* @return balance The number of pepes
*/
function balanceOf(address _owner) external view returns (uint256 balance) {
return wallets[_owner].length;
}
/**
* @dev Get the owner of a Pepe
* Note that this returns pepes from old auctions
* @param pepeId the token to get the owner of
* @return the owner of the pepe
*/
function ownerOf(uint256 pepeId) external view returns (address) {
return _getPepe(pepeId).master;
}
/**
* @dev Get the owner of a Pepe
* Note that this returns pepes from old auctions
* @param pepeId the token to get the owner of
* @return the owner of the pepe
*/
function _ownerOf(uint256 pepeId) internal view returns (address) {
return _getPepe(pepeId).master;
}
/**
* @dev Get the id of an token by its index
* @param _owner The address to look up the tokens of
* @param _index Index to look at
* @return pepeId the ID of the token of the owner at the specified index
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 pepeId) {
// The index must be smaller than the balance,
// to guarantee that there is no leftover token returned.
require(_index < wallets[_owner].length);
return wallets[_owner][_index];
}
/**
* @dev Private method that ads a token to the wallet
* @param _owner Address of the owner
* @param pepeId Pepe ID to add
*/
function addToWallet(address _owner, uint256 pepeId) private {
/*
uint256 length = wallets[_owner].length;
wallets[_owner].push(pepeId);
walletIndex[pepeId] = length;
*/
walletIndex[pepeId] = wallets[_owner].length;
wallets[_owner].push(pepeId);
}
/**
* @dev Remove a token from a address's wallet
* @param _owner Address of the owner
* @param pepeId Token to remove from the wallet
*/
function removeFromWallet(address _owner, uint256 pepeId) private {
// walletIndex returns 0 if not initialized to a value
// verify before removing
if(walletIndex[pepeId] == 0 && (wallets[_owner].length == 0 || wallets[_owner][0] != pepeId)) return;
// pop last element from wallet, move it to this index
uint256 tokenIndex = walletIndex[pepeId];
uint256 lastTokenIndex = wallets[_owner].length - 1;
uint256 lastToken = wallets[_owner][lastTokenIndex];
wallets[_owner][tokenIndex] = lastToken;
wallets[_owner].length--;
walletIndex[pepeId] = 0;
walletIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal transfer function
* @param _from Address sending the token
* @param _to Address to token is send to
* @param pepeId ID of the token to send
*/
function _transfer(address _from, address _to, uint256 pepeId) internal {
checkResurrected(pepeId);
if(pepeId >= REBORN_PEPE_0) rebornPepes[rebornPepeIdToIndex(pepeId)].master = _to;
else undeadPepes[pepeId].master = _to;
approved[pepeId] = address(0);//reset approved of pepe on every transfer
//remove the token from the _from wallet
removeFromWallet(_from, pepeId);
//add the token to the _to wallet
addToWallet(_to, pepeId);
emit Transfer(_from, _to, pepeId);
}
/**
* @dev transfer a token. Can only be called by the owner of the token
* @param _to Addres to send the token to
* @param pepeId ID of the token to send
*/
// solhint-disable-next-line no-simple-event-func-name
function transfer(address _to, uint256 pepeId) public onlyPepeMaster(pepeId) returns(bool) {
_transfer(msg.sender, _to, pepeId);//after master modifier invoke internal transfer
return true;
}
/**
* @dev Approve a address to send a token
* @param _to Address to approve
* @param pepeId Token to set approval for
*/
function approve(address _to, uint256 pepeId) external onlyPepeMaster(pepeId) {
approved[pepeId] = _to;
emit Approval(msg.sender, _to, pepeId);
}
/**
* @dev Approve or revoke approval an address for all tokens of a user
* @param _operator Address to (un)approve
* @param _approved Approving or revoking indicator
*/
function setApprovalForAll(address _operator, bool _approved) external {
approvedForAll[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Get approved address for a token
* @param pepeId Token ID to get the approved address for
* @return The address that is approved for this token
*/
function getApproved(uint256 pepeId) external view returns (address) {
return approved[pepeId];
}
/**
* @dev Get if an operator is approved for all tokens of that owner
* @param _owner Owner to check the approval for
* @param _operator Operator to check approval for
* @return Boolean indicating if the operator is approved for that owner
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return approvedForAll[_owner][_operator];
}
/**
* @dev Function to signal support for an interface
* @param interfaceID the ID of the interface to check for
* @return Boolean indicating support
*/
function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
if(
interfaceID == 0x01ffc9a7 // ERC 165
|| interfaceID == 0x80ac58cd // ERC 721 base
|| interfaceID == 0x780e9d63 // ERC 721 enumerable
|| interfaceID == 0x4f558e79 // ERC 721 exists
|| interfaceID == 0x5b5e139f // ERC 721 metadata
// TODO: add more interfaces such as
// 0x150b7a02: ERC 721 receiver
) {
return true;
}
return false;
}
/**
* @dev Safe transferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param pepeId ID of the token to send
*/
function safeTransferFrom(address _from, address _to, uint256 pepeId) external {
_safeTransferFromInternal(_from, _to, pepeId, "");
}
/**
* @dev Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param pepeId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function safeTransferFrom(address _from, address _to, uint256 pepeId, bytes _data) external {
_safeTransferFromInternal(_from, _to, pepeId, _data);
}
/**
* @dev Internal Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param pepeId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function _safeTransferFromInternal(address _from, address _to, uint256 pepeId, bytes _data) internal onlyAllowed(pepeId) {
require(_ownerOf(pepeId) == _from);//check if from is current owner
require(_to != address(0));//throw on zero address
_transfer(_from, _to, pepeId); //transfer token
if (isContract(_to)) { //check if is contract
// solhint-disable-next-line max-line-length
require(ERC721TokenReceiver(_to).onERC721Received(_from, pepeId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
/**
* @dev TransferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param pepeId ID of the token to send
* @return If it was successful
*/
// solhint-disable-next-line max-line-length
function transferFrom(address _from, address _to, uint256 pepeId) public onlyAllowed(pepeId) returns(bool) {
require(_ownerOf(pepeId) == _from);//check if _from is really the master.
require(_to != address(0));
_transfer(_from, _to, pepeId);//handles event, balances and approval reset;
return true;
}
/**
* @dev Utility method to check if an address is a contract
* @param _address Address to check
* @return Boolean indicating if the address is a contract
*/
function isContract(address _address) internal view returns (bool) {
uint size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_address) }
return size > 0;
}
/**
* @dev Returns whether the specified token exists
* @param pepeId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 pepeId) public view returns (bool) {
return 0 < pepeId && pepeId <= (REBORN_PEPE_0 + rebornPepes.length - 1);//this.totalSupply();
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param pepeId uint256 ID of the token to query
*/
function tokenURI(uint256 pepeId) public view returns (string) {
require(exists(pepeId));
return string(abi.encodePacked(baseTokenURI, toString(pepeId)));
}
/**
* @dev Changes the base URI for metadata.
* @param baseURI the new base URI
*/
function setBaseTokenURI(string baseURI) public onlyOwner {
baseTokenURI = baseURI;
}
/**
* @dev Returns the URI for the contract
* @return the uri
*/
function contractURI() public view returns (string) {
return contractUri;
}
/**
* @dev Changes the URI for the contract
* @param uri the new uri
*/
function setContractURI(string uri) public onlyOwner {
contractUri = uri;
}
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
* @param value a number to convert to string
* @return a string representation of the number
*/
function toString(uint256 value) internal pure returns (string memory) {
// Borrowed from Open Zeppelin, which was
// 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);
}
/**
* @dev get Pepe information
* Returns information as separate variables
* @param pepeId ID of the Pepe to get information of
* @return master
* @return genotype
* @return canCozyAgain
* @return generation
* @return father
* @return mother
* @return pepeName
* @return coolDownIndex
*/
// solhint-disable-next-line max-line-length
function getPepe(uint256 pepeId) public view returns (address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) {
Pepe memory pepe = _getPepe(pepeId);
master = pepe.master;
genotype = pepe.genotype;
canCozyAgain = pepe.canCozyAgain;
generation = pepe.generation;
father = pepe.father;
mother = pepe.mother;
pepeName = pepeNames[pepeId];
coolDownIndex = pepe.coolDownIndex;
}
/**
* @dev get Pepe information
* Returns information as a single Pepe struct
* @param pepeId ID of the Pepe to get information of
* @return pepe info
*/
function _getPepe(uint256 pepeId) internal view returns (Pepe memory) {
if(pepeId >= REBORN_PEPE_0) {
uint256 index = rebornPepeIdToIndex(pepeId);
require(index < rebornPepes.length);
return rebornPepes[index];
}else{
(address master, uint256[2] memory genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, , uint8 coolDownIndex) = _getUndeadPepe(pepeId);
return Pepe({
master: master, // The master of the pepe
genotype: genotype, // all genes stored here
canCozyAgain: canCozyAgain, // time when pepe can have nice time again
father: uint64(father), // father of this pepe
mother: uint64(mother), // mommy of this pepe
generation: generation, // what generation?
coolDownIndex: coolDownIndex
});
}
}
/**
* @dev get undead pepe information
* @param pepeId ID of the Pepe to get information of
* @return master
* @return genotype
* @return canCozyAgain
* @return generation
* @return father
* @return mother
* @return pepeName
* @return coolDownIndex
*/
function _getUndeadPepe(uint256 pepeId) internal view returns (address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) {
// if undead, pull from old contract
(master, genotype, canCozyAgain, generation, father, mother, pepeName, coolDownIndex) = PepeBase(PEPE_UNDEAD_ADDRRESS).getPepe(pepeId);
if(undeadPepes[pepeId].resurrected){
// if resurrected, pull from undead map
master = undeadPepes[pepeId].master;
canCozyAgain = undeadPepes[pepeId].canCozyAgain;
pepeName = pepeNames[pepeId];
coolDownIndex = undeadPepes[pepeId].coolDownIndex;
}else if(master == PEPE_AUCTION_SALE_UNDEAD_ADDRESS || master == COZY_TIME_AUCTION_UNDEAD_ADDRESS){
// if on auction, return to seller
(master, , , , , ) = AuctionBase(master).auctions(pepeId);
}
}
// Useful for tracking resurrections
event PepeResurrected(uint256 pepeId);
/**
* @dev Checks if the pepe needs to be resurrected from the old contract and if so does.
* @param pepeId ID of the Pepe to check
*/
// solhint-disable-next-line max-line-length
function checkResurrected(uint256 pepeId) public {
if(pepeId >= REBORN_PEPE_0) return;
if(undeadPepes[pepeId].resurrected) return;
(address _master, , uint64 _canCozyAgain, , , , bytes32 _pepeName, uint8 _coolDownIndex) = _getUndeadPepe(pepeId);
undeadPepes[pepeId] = UndeadPepeMutable({
master: _master, // The master of the pepe
canCozyAgain: _canCozyAgain, // time when pepe can have nice time again
coolDownIndex: _coolDownIndex,
resurrected: true
});
if(_pepeName != 0x0000000000000000000000000000000000000000000000000000000000000000) pepeNames[pepeId] = _pepeName;
addToWallet(_master, pepeId);
emit PepeResurrected(pepeId);
}
/**
* @dev Calculates reborn pepe array index
* @param pepeId ID of the pepe to check
* @return array index
*/
function rebornPepeIdToIndex(uint256 pepeId) internal pure returns (uint256) {
require(pepeId >= REBORN_PEPE_0);
return pepeId - REBORN_PEPE_0;
}
/**
* @dev Changes the address of the previous contracts
* This is only a precaution in case I mess up deployment
* @param baseaddr the correct PepeBase address
* @param saleauctionaddr the correct PepeSaleAuction address
* @param cozyauctionaddr the correct CozyTimeAuction address
*/
function setPrevContracts(address baseaddr, address saleauctionaddr, address cozyauctionaddr) public onlyOwner {
PEPE_UNDEAD_ADDRRESS = baseaddr;
PEPE_AUCTION_SALE_UNDEAD_ADDRESS = saleauctionaddr;
COZY_TIME_AUCTION_UNDEAD_ADDRESS = cozyauctionaddr;
}
/**
* @dev Changes the gene pool contract address
* @param genePoolAddress the new pool address
*/
function setGenePool(address genePoolAddress) public onlyOwner {
GenePoolInterface pool = GenePoolInterface(genePoolAddress);
require(pool.isGenePool());
genePool = pool;
}
}
contract GenesisActTwo {
PepeReborn public cpepToken;
address public owner;
uint256 public price = 100000000000000000; // 0.1 eth
uint256 public mined;
modifier onlyOwner() {
require(owner == msg.sender, "not owner");
_;
}
constructor(address _cpepToken, address _owner) {
cpepToken = PepeReborn(_cpepToken);
owner = _owner;
}
function birth(uint256 amount) external payable {
require(msg.value >= amount * price, "insufficient payment");
uint256 startSupply = cpepToken.totalSupply();
cpepToken.pepePremine(amount);
for(uint256 pepeId = startSupply+1; pepeId <= startSupply + amount; ++pepeId) {
cpepToken.transfer(msg.sender, pepeId);
}
mined += amount;
}
function setPrice(uint256 _price) external onlyOwner {
price = _price;
}
function sweep(address recipient, uint256 amount) external onlyOwner {
recipient.transfer(amount);
}
function transferOwnership(address newOwner) external onlyOwner {
cpepToken.transferOwnership(newOwner);
}
}
|
Set the name of a Pepe. Can only be set once pepeId ID of the pepe to name _name The name to assign/
|
function setPepeName(uint256 pepeId, bytes32 _name) public onlyPepeMaster(pepeId) returns(bool) {
require(pepeNames[pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000);
pepeNames[pepeId] = _name;
emit PepeNamed(pepeId);
return true;
}
| 10,871,773
|
./full_match/80001/0x8c9F2c3B36939583Ecd3511aC8826aE258eD6f8E/sources/contracts/smart-wallet/utils/AccountCore.sol
|
Runs after every `changeRole` run.
|
function _afterSignerPermissionsUpdate(SignerPermissionRequest calldata _req) internal virtual override {
if (factory.code.length > 0) {
BaseAccountFactory(factory).onSignerAdded(_req.signer);
}
}
| 5,560,825
|
pragma solidity 0.5.9;
import "./lib/Ownable.sol";
import "./lib/SafeMath.sol";
import "./lib/ERC20Plus.sol";
import "./lib/Lockable.sol";
import "./FundsSplitterInterface.sol";
import "./LinkedListLib.sol";
import "./StarEthRateInterface.sol";
import "./StarStakingInterface.sol";
import "./Whitelist.sol";
/**
* @title Staking Sale contract - staking of STAR.
* @author Markus Waas - <markus@starbase.co>
* @author Gustavo Guimaraes - <gustavo@starbase.co>
*/
contract StarStaking is StarStakingInterface, Lockable {
using SafeMath for uint256;
using LinkedListLib for LinkedListLib.LinkedList;
address constant HEAD = address(0);
bool constant PREV = false;
bool constant NEXT = true;
// external addresses
StarEthRateInterface public starEthRateInterface;
ERC20Plus public starToken;
ERC20Plus public tokenOnSale;
Whitelist public whitelist;
FundsSplitterInterface public wallet;
mapping (address => bool) public hasWithdrawnTokens;
mapping (address => uint256) public totalStakingPointsFor;
mapping (address => uint256) public totalStakedFor;
LinkedListLib.LinkedList topRanks;
uint256 public startTime;
uint256 public endTime;
uint256 public topRanksMaxSize;
uint256 public targetRateInEth;
uint256 public maxDiscountPer1000;
uint256 public declinePerRankPer1000;
uint256 public stakeSaleCap;
uint256 public maxStakePerUser;
uint256 public totalRaised;
uint256 public topRanksCount;
modifier isAfterClaimPeriod {
require(
(now > endTime.add(60 days)),
'Claim period is not yet finished!'
);
_;
}
modifier isWhitelisted(address beneficiary) {
require(
whitelist.allowedAddresses(beneficiary),
"Beneficiary not whitelisted!"
);
_;
}
modifier whenStakingOpen {
require(now >= startTime, "Staking period not yet started!");
require(now < endTime, "Staking period already closed!");
_;
}
modifier isFinished {
require(
now >= endTime || totalRaised >= stakeSaleCap,
"Staking period not yet closed!"
);
_;
}
/**
* @param _startTime Timestamp for the beginning of the staking event
* @param _endTime Timestamp of the end of staking event
* @param _externalAddresses Containing all external addresses, see below
* #param _starEthRateInterface StarEthRate contract for receiving conversion rate of STAR/ETH
* #param _starToken Token that can be staked
* #param _tokenOnSale Token that will be sold
* #param _wallet TokenSale wallet where STAR from staking will be transferred
* #param _whitelist contract containing the whitelisted addresses
* @param _topRanksMaxSize Maximal size of the top ranks
* @param _targetRateInEth The baseline target rate in ETH for purchases
* @param _maxDiscountPer1000 The max discount per 1000 for rank 1.
* @param _declinePerRankPer1000 The discount decline per rank per 1000.
* @param _stakeSaleCap The cap amount for total staking
* @param _maxStakePerUser The maximum amount permitted per user
*/
constructor(
uint256 _startTime,
uint256 _endTime,
address[5] memory _externalAddresses, // array avoids stack too deep error
uint256 _topRanksMaxSize,
uint256 _targetRateInEth,
uint256 _maxDiscountPer1000,
uint256 _declinePerRankPer1000,
uint256 _stakeSaleCap,
uint256 _maxStakePerUser
) public {
require(
_startTime > 0 &&
_endTime > 0 &&
_externalAddresses[0] != address(0) &&
_externalAddresses[1] != address(0) &&
_externalAddresses[2] != address(0) &&
_externalAddresses[3] != address(0) &&
_externalAddresses[4] != address(0) &&
_topRanksMaxSize > 0 &&
_targetRateInEth > 0 &&
_maxDiscountPer1000 > 0 &&
_declinePerRankPer1000 > 0 &&
_stakeSaleCap > 0 &&
_maxStakePerUser > 0,
"Parameter variables cannot be empty!"
);
require(_startTime >= now, "startTime must be more than current time!");
require(_endTime >= _startTime, "endTime must be more than startTime!");
require(
_maxStakePerUser < _stakeSaleCap,
"Max stake per user should be smaller than StakeSale cap!"
);
uint256 maxDecline = _topRanksMaxSize
.sub(1)
.mul(_declinePerRankPer1000);
require(
_maxDiscountPer1000 >= maxDecline,
'Please increase max discount or decrease decline per rank!'
);
totalRaised = 0;
topRanksCount = 0;
startTime = _startTime;
endTime = _endTime;
starEthRateInterface = StarEthRateInterface(_externalAddresses[0]);
starToken = ERC20Plus(_externalAddresses[1]);
tokenOnSale = ERC20Plus(_externalAddresses[2]);
wallet = FundsSplitterInterface(uint160(_externalAddresses[3]));
whitelist = Whitelist(_externalAddresses[4]);
topRanksMaxSize = _topRanksMaxSize;
targetRateInEth = _targetRateInEth;
maxDiscountPer1000 = _maxDiscountPer1000;
declinePerRankPer1000 = _declinePerRankPer1000;
stakeSaleCap = _stakeSaleCap.mul(10 ** 18);
maxStakePerUser = _maxStakePerUser.mul(10 ** 18);
}
/**
* @dev Stakes a certain amount of tokens.
* @param _amount Amount of tokens to stake.
* @param _oneRankAboveNode Node as reference for insert position into top ranks.
*/
function stake(uint256 _amount, address _oneRankAboveNode) public {
stakeFor(msg.sender, _amount, _oneRankAboveNode);
}
/**
* @dev Stakes a certain amount of tokens for another user.
* @param _user Address of the user to stake for.
* @param _amount Amount of tokens to stake.
* @param _oneRankAboveNode Node as reference for insert position into top ranks.
*/
function stakeFor(address _user, uint256 _amount, address _oneRankAboveNode)
public
onlyWhenUnlocked
whenStakingOpen
isWhitelisted(_user)
{
require(
_user != _oneRankAboveNode,
'One rank above cannot be equal to inserted user!'
);
require(_amount > 0, "Insert amount higher than 0!");
uint256 amount = _amount;
if (totalRaised.add(_amount) > stakeSaleCap) {
require(
totalRaised < stakeSaleCap,
"StakeSale cap reached, the sale is finished!"
);
amount = stakeSaleCap.sub(totalRaised);
}
if (totalStakedFor[_user].add(_amount) > maxStakePerUser) {
require(
totalStakedFor[_user] < maxStakePerUser,
"Maximal stake for user reached!"
);
amount = maxStakePerUser.sub(totalStakedFor[_user]);
}
if (topRanksCount > 0) {
require(
_oneRankAboveNode == HEAD || topRanks.nodeExists(_oneRankAboveNode),
"Node for suggested position does not exist!"
);
} else {
require(
_oneRankAboveNode == HEAD,
"Reference node must be empty for first inserted node!"
);
}
_addStakingPoints(_user, amount);
if (topRanksCount == 0 || _oneRankAboveNode != HEAD) {
_sortedInsert(_user, _oneRankAboveNode);
} else {
require(
!topRanks.nodeExists(_user),
"User is already in topRanks, you need to pass a reference node!"
);
}
require(
starToken.transferFrom(msg.sender, address(wallet), amount),
"Not enough funds for sender!"
);
wallet.splitStarFunds();
totalRaised = totalRaised.add(amount);
}
/**
* @dev Can be used before `stakeFor` to get the correct reference node
* @param _addedStake new added stake for user
* @param _user the user address
* @return reference node for insertion in top ranks
*/
function getSortedSpotForNewStakeForUser(uint256 _addedStake, address _user)
public
view
returns (address)
{
uint256 newStakingPoints = computeStakingPoints(_user, _addedStake);
return getSortedSpotForPointsForUser(newStakingPoints, _user);
}
/**
* @dev Can be used before `stakeFor` to get the correct reference node
* @param _stakingPoints new points for user to insert
* @param _user the user address
* @return reference node for insertion in top ranks
*/
function getSortedSpotForPointsForUser(
uint256 _stakingPoints,
address _user
)
public
view
returns (address)
{
if (topRanksCount == 0) {
return HEAD;
}
address node = getTopRank(HEAD, PREV);
while (
(node != HEAD) && ((totalStakingPointsFor[node] < _stakingPoints))
|| (node == _user)
) {
node = getTopRank(node, PREV);
}
if (node == HEAD) {
node = getTopRank(HEAD, NEXT);
if (node == _user) node = getTopRank(node, NEXT);
}
return node;
}
/**
* @dev Reads the current discount in per mill for the passed staking points
* @param _stakingPoints The staking points to be used
* @param _user the user address
* @return The discount for given staking points
*/
function getDiscountEstimateForPointsForUser(
uint256 _stakingPoints,
address _user
)
public
view
returns (uint256)
{
if (topRanksCount == 0) {
return _computeDiscountForRank(0);
}
// small hack: notInTopRanks ensures proper oneRankAbove
address notInTopRanks = 0xd20B0A19D1806f4f6F5a714EddF8e3e9807e2d9f;
address oneRankAbove = getSortedSpotForPointsForUser(
_stakingPoints,
notInTopRanks
);
address replacedUser = oneRankAbove == _user
? _user
: getTopRank(oneRankAbove, NEXT);
if (topRanksCount == topRanksMaxSize && replacedUser == HEAD) {
return 0;
} else if (replacedUser == HEAD) {
uint256 lastRank = topRanksCount;
return _computeDiscountForRank(lastRank);
}
(uint256 rank,) = _stakingPoints > totalStakingPointsFor[oneRankAbove]
? (0, true) : getRankForUser(replacedUser);
return _computeDiscountForRank(rank);
}
/**
* @dev Returns the previous or next top rank node
* @param _referenceNode Address of the reference
* @param _direction Bool for direction
* @return The previous or next top rank node
*/
function getTopRank(address _referenceNode, bool _direction)
public
view
returns (address)
{
return topRanks.list[_referenceNode][_direction];
}
/**
* @dev Read the current rank for the given user
* @param _user The user to be looked at
* @return The current rank in the top ranks and boolean to indicate
* if user was found in the top ranks
*/
function getRankForUser(address _user)
public
view
returns (uint256, bool)
{
if (topRanks.nodeExists(_user)) {
address referenceNode = HEAD;
for (uint256 i = 0; i < topRanksCount; i++) {
referenceNode = getTopRank(referenceNode, NEXT);
if (referenceNode == _user) {
return (i, true);
}
}
}
return (0, false);
}
/**
* @dev Returns a flat list of 3-tuples (address, stakingPoints, totalStaked)
*/
function getTopRanksTuples() public view returns (uint256[] memory) {
uint256 tripleRanksCount = topRanksCount * 3;
uint256[] memory topRanksList = new uint256[](tripleRanksCount);
address referenceNode = HEAD;
uint256 x = 0;
while(x < tripleRanksCount) {
referenceNode = getTopRank(referenceNode, NEXT);
topRanksList[x] = uint256(referenceNode);
x++;
topRanksList[x] = totalStakingPointsFor[referenceNode];
x++;
topRanksList[x] = totalStakedFor[referenceNode];
x++;
}
return topRanksList;
}
/**
* @dev Withdraw all received tokens after staking is finished
*/
function withdrawAllReceivedTokens() external isFinished {
require(
!hasWithdrawnTokens[msg.sender],
'User has already withdrawn tokens!'
);
hasWithdrawnTokens[msg.sender] = true;
uint256 baseTokens = _computeBaseTokens();
uint256 bonusTokens = _computeBonusTokens(baseTokens);
uint256 totalTokens = baseTokens.add(bonusTokens);
tokenOnSale.transfer(msg.sender, totalTokens);
}
/**
* @dev Compute the new staking points
* @param _user The user to compute staking points for
* @param _amount The added stake for the user
* @return The new staking points for user
*/
function computeStakingPoints(address _user, uint256 _amount)
public
view
whenStakingOpen
returns (uint256)
{
uint256 timeUntilEnd = endTime.sub(now);
uint256 addedStakingPoints = timeUntilEnd.mul(_amount);
return totalStakingPointsFor[_user].add(addedStakingPoints);
}
/**
* @dev Withdraw received tokens after claim period is finished
*/
function withdrawTokens(uint256 _amount)
external
isAfterClaimPeriod
onlyOwner
{
tokenOnSale.transfer(msg.sender, _amount);
}
function _computeDiscountForRank(uint256 _rank)
private
view
returns (uint256)
{
return maxDiscountPer1000.sub(_rank.mul(declinePerRankPer1000));
}
function _computeBaseTokens() private returns (uint256) {
uint256 stakedStar = totalStakedFor[msg.sender];
uint256 decimalCorrectionFactor =
starEthRateInterface.decimalCorrectionFactor();
uint256 starEthRate = starEthRateInterface.starEthRate();
return stakedStar
.mul(targetRateInEth)
.mul(starEthRate)
.div(decimalCorrectionFactor);
}
function _computeBonusTokens(uint256 _baseTokens)
private
view
returns (uint256)
{
(uint256 rank, bool isInTopRanks) = getRankForUser(msg.sender);
if (!isInTopRanks) return 0;
uint256 discount = _computeDiscountForRank(rank);
return _baseTokens.mul(discount).div(1000);
}
function _addStakingPoints(address _user, uint256 _amount) private {
totalStakingPointsFor[_user] = computeStakingPoints(_user, _amount);
totalStakedFor[_user] = totalStakedFor[_user].add(_amount);
emit Staked(_user, _amount);
}
function _doesCorrectlyInsertAtFirstRank(
uint256 _newRankPoints,
uint256 _oneRankAbovePoints, // if true, this is actually oneRankBelow
address _twoRanksAbove
) private view returns (bool) {
if (topRanksCount == 0) {
return true;
}
return _twoRanksAbove == HEAD && _newRankPoints > _oneRankAbovePoints;
}
function _ensureCorrectInsertPosition(
uint256 _newRankPoints,
uint256 _oneRankBelowPoints,
uint256 _oneRankAbovePoints
) private pure {
require(
_newRankPoints > _oneRankBelowPoints,
"Suggested position into top ranks too high!"
);
require(
_newRankPoints <= _oneRankAbovePoints,
"Suggested position into top ranks too low!"
);
}
function _sortedInsert(address _user, address _oneRankAboveNode) private {
address removedNode = topRanks.remove(_user);
address twoRanksAbove = getTopRank(_oneRankAboveNode, PREV);
address oneRankBelow = getTopRank(_oneRankAboveNode, NEXT);
uint256 newRankPoints = totalStakingPointsFor[_user];
uint256 oneRankBelowPoints = totalStakingPointsFor[oneRankBelow];
uint256 oneRankAbovePoints = totalStakingPointsFor[_oneRankAboveNode];
if (_doesCorrectlyInsertAtFirstRank(
newRankPoints,
oneRankAbovePoints, // if true, this is actually oneRankBelow
twoRanksAbove
)) {
topRanks.insert(HEAD, _user, NEXT);
} else {
_ensureCorrectInsertPosition(
newRankPoints,
oneRankBelowPoints,
oneRankAbovePoints
);
topRanks.insert(_oneRankAboveNode, _user, NEXT);
}
if (removedNode == address(0)) {
_handleTopRanksAddition();
}
}
function _handleTopRanksAddition() private {
if (topRanksCount < topRanksMaxSize) {
topRanksCount++;
} else {
topRanks.pop(PREV);
}
}
}
|
Compute the new staking points _user The user to compute staking points for _amount The added stake for the user return The new staking points for user/
|
function computeStakingPoints(address _user, uint256 _amount)
public
view
whenStakingOpen
returns (uint256)
{
uint256 timeUntilEnd = endTime.sub(now);
uint256 addedStakingPoints = timeUntilEnd.mul(_amount);
return totalStakingPointsFor[_user].add(addedStakingPoints);
}
| 12,683,784
|
./full_match/137/0xAfFe628F223c60ecDfaD44688233d45d35D04006/sources/contracts/CourseContract.sol
|
Teacher can also boot student which sends student's stake to multisig.
|
function bootStudent(address _account) external onlyRole(TEACHER){
require(roles[STUDENT][_account] = true,"Address is not enrolled :/");
roles[STUDENT][_account] = false;
require(success, "Failed to boot >:(");
factory.updateBoot(_account, studentStake);
emit DropOut(_account);
}
| 3,748,605
|
/// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity >=0.8.4;
import "@hifi/amm/contracts/IHifiPool.sol";
import "@hifi/protocol/contracts/core/balance-sheet/IBalanceSheetV2.sol";
import "@hifi/protocol/contracts/core/h-token/IHToken.sol";
import "@prb/contracts/token/erc20/IErc20.sol";
import "@prb/contracts/token/erc20/SafeErc20.sol";
import "./IHifiProxyTarget.sol";
import "./external/WethInterface.sol";
/// @title HifiProxyTarget
/// @author Hifi
contract HifiProxyTarget is IHifiProxyTarget {
using SafeErc20 for IErc20;
/// PUBLIC NON-CONSTANT FUNCTIONS ///
/// @inheritdoc IHifiProxyTarget
function addLiquidity(
IHifiPool hifiPool,
uint256 underlyingOffered,
uint256 maxHTokenRequired
) external override {
// Ensure that we are within the user's slippage tolerance.
(uint256 hTokenRequired, ) = hifiPool.getMintInputs(underlyingOffered);
if (hTokenRequired > maxHTokenRequired) {
revert HifiProxyTarget__AddLiquidityHTokenSlippage(maxHTokenRequired, hTokenRequired);
}
// Transfer the underlying to the DSProxy.
IErc20 underlying = hifiPool.underlying();
underlying.safeTransferFrom(msg.sender, address(this), underlyingOffered);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(underlying, address(hifiPool), underlyingOffered);
// Transfer the hTokens to the DSProxy.
IHToken hToken = hifiPool.hToken();
hToken.transferFrom(msg.sender, address(this), hTokenRequired);
// Allow the HifiPool contract to spend hTokens from the DSProxy.
approveSpender(hToken, address(hifiPool), hTokenRequired);
// Add liquidity to the AMM.
uint256 poolTokensMinted = hifiPool.mint(underlyingOffered);
// The LP tokens are now in the DSProxy, so we relay them to the end user.
hifiPool.transfer(msg.sender, poolTokensMinted);
}
/// @inheritdoc IHifiProxyTarget
function borrowHToken(
IBalanceSheetV2 balanceSheet,
IHToken hToken,
uint256 borrowAmount
) public override {
balanceSheet.borrow(hToken, borrowAmount);
// The hTokens are now in the DSProxy, so we relay them to the end user.
hToken.transfer(msg.sender, borrowAmount);
}
/// @inheritdoc IHifiProxyTarget
function borrowHTokenAndAddLiquidity(
IBalanceSheetV2 balanceSheet,
IHifiPool hifiPool,
uint256 maxBorrowAmount,
uint256 underlyingOffered
) public override {
// Ensure that we are within the user's slippage tolerance.
(uint256 hTokenRequired, ) = hifiPool.getMintInputs(underlyingOffered);
if (hTokenRequired > maxBorrowAmount) {
revert HifiProxyTarget__AddLiquidityHTokenSlippage(maxBorrowAmount, hTokenRequired);
}
// Borrow the hTokens.
IHToken hToken = hifiPool.hToken();
balanceSheet.borrow(hToken, hTokenRequired);
// Transfer the underlying to the DSProxy.
IErc20 underlying = hifiPool.underlying();
underlying.safeTransferFrom(msg.sender, address(this), underlyingOffered);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(underlying, address(hifiPool), underlyingOffered);
// Allow the HifiPool contract to spend hTokens from the DSProxy.
approveSpender(hToken, address(hifiPool), hTokenRequired);
// Add liquidity to pool.
uint256 poolTokensMinted = hifiPool.mint(underlyingOffered);
// The LP tokens are now in the DSProxy, so we relay them to the end user.
hifiPool.transfer(msg.sender, poolTokensMinted);
}
/// @inheritdoc IHifiProxyTarget
function borrowHTokenAndBuyUnderlying(
IBalanceSheetV2 balanceSheet,
IHifiPool hifiPool,
uint256 maxBorrowAmount,
uint256 underlyingOut
) external override {
// Ensure that we are within the user's slippage tolerance.
uint256 hTokenIn = hifiPool.getQuoteForBuyingUnderlying(underlyingOut);
if (hTokenIn > maxBorrowAmount) {
revert HifiProxyTarget__TradeSlippage(maxBorrowAmount, hTokenIn);
}
// Borrow the hTokens.
IHToken hToken = hifiPool.hToken();
balanceSheet.borrow(hToken, hTokenIn);
// Allow the HifiPool contract to spend hTokens from the DSProxy.
approveSpender(hToken, address(hifiPool), hTokenIn);
// Buy underlying and relay it to the end user.
hifiPool.buyUnderlying(msg.sender, underlyingOut);
emit BorrowHTokenAndBuyUnderlying(msg.sender, hTokenIn, underlyingOut);
}
/// @inheritdoc IHifiProxyTarget
function borrowHTokenAndSellHToken(
IBalanceSheetV2 balanceSheet,
IHifiPool hifiPool,
uint256 borrowAmount,
uint256 minUnderlyingOut
) public override {
// Ensure that we are within the user's slippage tolerance.
uint256 underlyingOut = hifiPool.getQuoteForSellingHToken(borrowAmount);
if (underlyingOut < minUnderlyingOut) {
revert HifiProxyTarget__TradeSlippage(minUnderlyingOut, underlyingOut);
}
// Borrow the hTokens.
IHToken hToken = hifiPool.hToken();
balanceSheet.borrow(hToken, borrowAmount);
// Allow the HifiPool contract to spend hTokens from the DSProxy.
approveSpender(hToken, address(hifiPool), borrowAmount);
// Sell the hTokens and relay the underlying to the end user.
hifiPool.sellHToken(msg.sender, borrowAmount);
emit BorrowHTokenAndSellHToken(msg.sender, borrowAmount, underlyingOut);
}
/// @inheritdoc IHifiProxyTarget
function buyHToken(
IHifiPool hifiPool,
uint256 hTokenOut,
uint256 maxUnderlyingIn
) external override {
// Ensure that we are within the user's slippage tolerance.
uint256 underlyingIn = hifiPool.getQuoteForBuyingHToken(hTokenOut);
if (underlyingIn > maxUnderlyingIn) {
revert HifiProxyTarget__TradeSlippage(maxUnderlyingIn, underlyingIn);
}
// Transfer the underlying to the DSProxy.
IErc20 underlying = hifiPool.underlying();
underlying.safeTransferFrom(msg.sender, address(this), underlyingIn);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(underlying, address(hifiPool), underlyingIn);
// Buy the hTokens and relay them to the end user.
hifiPool.buyHToken(msg.sender, hTokenOut);
}
/// @inheritdoc IHifiProxyTarget
function buyHTokenAndAddLiquidity(
IHifiPool hifiPool,
uint256 hTokenOut,
uint256 maxUnderlyingAmount
) external override {
// Transfer the underlying to the DSProxy.
IErc20 underlying = hifiPool.underlying();
uint256 underlyingIn = hifiPool.getQuoteForBuyingHToken(hTokenOut);
underlying.safeTransferFrom(msg.sender, address(this), underlyingIn);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(underlying, address(hifiPool), underlyingIn);
// Buy the hTokens.
hifiPool.buyHToken(address(this), hTokenOut);
// Calculate how much underlying is required to provide "hTokenOut" liquidity to the AMM.
IHToken hToken = hifiPool.hToken();
uint256 normalizedUnderlyingReserves = hifiPool.getNormalizedUnderlyingReserves();
uint256 hTokenReserves = hToken.balanceOf(address(hifiPool));
uint256 normalizedUnderlyingRequired = (normalizedUnderlyingReserves * hTokenOut) / hTokenReserves;
uint256 underlyingRequired = denormalize(normalizedUnderlyingRequired, hifiPool.underlyingPrecisionScalar());
// Ensure that we are within the user's slippage tolerance.
uint256 totalUnderlyingAmount = underlyingIn + underlyingRequired;
if (totalUnderlyingAmount > maxUnderlyingAmount) {
revert HifiProxyTarget__AddLiquidityUnderlyingSlippage(maxUnderlyingAmount, totalUnderlyingAmount);
}
// Transfer the underlying to the DSProxy.
underlying.safeTransferFrom(msg.sender, address(this), underlyingRequired);
// Allow the HifiPool contract to spend hTokens from the DSProxy.
approveSpender(underlying, address(hifiPool), underlyingRequired);
approveSpender(hToken, address(hifiPool), hTokenOut);
// Add liquidity to the AMM.
(uint256 hTokenRequired, ) = hifiPool.getMintInputs(underlyingRequired);
uint256 poolTokensMinted = hifiPool.mint(underlyingRequired);
// The LP tokens are now in the DSProxy, so we relay them to the end user.
hifiPool.transfer(msg.sender, poolTokensMinted);
// "hTokenOut" is greater or equal than "hTokenRequired", because not all of "hTokenOut" was used in the mint.
// "normalizedUnderlyingRequired" was denormalized to "underlyingRequired", offsetting the trailing 12 digits.
unchecked {
uint256 hTokenDelta = hTokenOut - hTokenRequired;
hToken.transfer(msg.sender, hTokenDelta);
}
}
/// @inheritdoc IHifiProxyTarget
function buyHTokenAndRepayBorrow(
IHifiPool hifiPool,
IBalanceSheetV2 balanceSheet,
uint256 maxUnderlyingIn,
uint256 hTokenOut
) external override {
// Ensure that we are within the user's slippage tolerance.
uint256 underlyingIn = hifiPool.getQuoteForBuyingHToken(hTokenOut);
if (underlyingIn > maxUnderlyingIn) {
revert HifiProxyTarget__TradeSlippage(maxUnderlyingIn, underlyingIn);
}
// Transfer the underlying to the DSProxy.
IErc20 underlying = hifiPool.underlying();
underlying.safeTransferFrom(msg.sender, address(this), underlyingIn);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(underlying, address(hifiPool), underlyingIn);
// Buy the hTokens.
hifiPool.buyHToken(address(this), hTokenOut);
// Query the amount of debt that the user owes.
IHToken hToken = hifiPool.hToken();
uint256 debtAmount = balanceSheet.getDebtAmount(address(this), hToken);
// Use the recently bought hTokens to repay the borrow.
if (debtAmount >= hTokenOut) {
balanceSheet.repayBorrow(hToken, hTokenOut);
} else {
balanceSheet.repayBorrow(hToken, debtAmount);
// Relay any remaining hTokens to the end user.
unchecked {
uint256 hTokenDelta = hTokenOut - debtAmount;
hToken.transfer(msg.sender, hTokenDelta);
}
}
}
/// @inheritdoc IHifiProxyTarget
function buyUnderlying(
IHifiPool hifiPool,
uint256 underlyingOut,
uint256 maxHTokenIn
) external override {
// Ensure that we are within the user's slippage tolerance.
uint256 hTokenIn = hifiPool.getQuoteForBuyingUnderlying(underlyingOut);
if (hTokenIn > maxHTokenIn) {
revert HifiProxyTarget__TradeSlippage(maxHTokenIn, hTokenIn);
}
// Transfer the hTokens to the DSProxy.
IErc20 hToken = hifiPool.hToken();
hToken.transferFrom(msg.sender, address(this), hTokenIn);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(hToken, address(hifiPool), hTokenIn);
// Buy the underlying and relay it to the end user.
hifiPool.buyUnderlying(msg.sender, underlyingOut);
}
/// @inheritdoc IHifiProxyTarget
function buyUnderlyingAndAddLiquidity(
IHifiPool hifiPool,
uint256 maxHTokenAmount,
uint256 underlyingOffered
) external override {
// Ensure that we are within the user's slippage tolerance.
uint256 hTokenIn = hifiPool.getQuoteForBuyingUnderlying(underlyingOffered);
if (hTokenIn > maxHTokenAmount) {
revert HifiProxyTarget__TradeSlippage(maxHTokenAmount, hTokenIn);
}
// Transfer the hTokens to the DSProxy.
IHToken hToken = hifiPool.hToken();
hToken.transferFrom(msg.sender, address(this), hTokenIn);
// Allow the HifiPool contract to spend hTokens from the DSProxy.
approveSpender(hToken, address(hifiPool), maxHTokenAmount);
// Buy the underlying.
hifiPool.buyUnderlying(address(this), underlyingOffered);
// Ensure that we are within the user's slippage tolerance.
(uint256 hTokenRequired, ) = hifiPool.getMintInputs(underlyingOffered);
uint256 totalhTokenAmount = hTokenIn + hTokenRequired;
if (totalhTokenAmount > maxHTokenAmount) {
revert HifiProxyTarget__AddLiquidityHTokenSlippage(maxHTokenAmount, totalhTokenAmount);
}
// Transfer the hTokens to the DSProxy. We are calling the "transfer" function twice because we couldn't
// have known what value "hTokenRequired" will have had after the call to "buyUnderlying".
hToken.transferFrom(msg.sender, address(this), hTokenRequired);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(hifiPool.underlying(), address(hifiPool), underlyingOffered);
// Add liquidity to the AMM.
uint256 poolTokensMinted = hifiPool.mint(underlyingOffered);
// The LP tokens are now in the DSProxy, so we relay them to the end user.
hifiPool.transfer(msg.sender, poolTokensMinted);
}
/// @inheritdoc IHifiProxyTarget
function depositCollateral(
IBalanceSheetV2 balanceSheet,
IErc20 collateral,
uint256 depositAmount
) public override {
// Transfer the collateral to the DSProxy.
collateral.safeTransferFrom(msg.sender, address(this), depositAmount);
// Deposit the collateral into the BalanceSheet contract.
depositCollateralInternal(balanceSheet, collateral, depositAmount);
}
/// @inheritdoc IHifiProxyTarget
function depositCollateralAndBorrowHToken(
IBalanceSheetV2 balanceSheet,
IErc20 collateral,
IHToken hToken,
uint256 depositAmount,
uint256 borrowAmount
) external override {
depositCollateral(balanceSheet, collateral, depositAmount);
borrowHToken(balanceSheet, hToken, borrowAmount);
}
/// @inheritdoc IHifiProxyTarget
function depositCollateralAndBorrowHTokenAndAddLiquidity(
IBalanceSheetV2 balanceSheet,
IErc20 collateral,
IHifiPool hifiPool,
uint256 depositAmount,
uint256 maxBorrowAmount,
uint256 underlyingOffered
) external override {
depositCollateral(balanceSheet, collateral, depositAmount);
borrowHTokenAndAddLiquidity(balanceSheet, hifiPool, maxBorrowAmount, underlyingOffered);
}
/// @inheritdoc IHifiProxyTarget
function depositCollateralAndBorrowHTokenAndSellHToken(
IBalanceSheetV2 balanceSheet,
IErc20 collateral,
IHifiPool hifiPool,
uint256 depositAmount,
uint256 borrowAmount,
uint256 minUnderlyingOut
) external override {
depositCollateral(balanceSheet, collateral, depositAmount);
borrowHTokenAndSellHToken(balanceSheet, hifiPool, borrowAmount, minUnderlyingOut);
}
/// @inheritdoc IHifiProxyTarget
function depositUnderlying(IHToken hToken, uint256 underlyingAmount) external override {
uint256 oldHTokenBalance = hToken.balanceOf(address(this));
depositUnderlyingInternal(hToken, underlyingAmount);
unchecked {
// Calculate how many hTokens were minted.
uint256 newHTokenBalance = hToken.balanceOf(address(this));
uint256 hTokenAmount = newHTokenBalance - oldHTokenBalance;
// The hTokens are now in the DSProxy, so we relay them to the end user.
hToken.transfer(msg.sender, hTokenAmount);
}
}
/// @inheritdoc IHifiProxyTarget
function depositUnderlyingAndBorrowHTokenAndAddLiquidity(
IHifiPool hifiPool,
uint256 depositAmount,
uint256 underlyingOffered
) external override {
// When the underlying moonlights as the collateral, the user can borrow on a one-to-one basis.
uint256 maxBorrowAmount = normalize(depositAmount, hifiPool.underlyingPrecisionScalar());
// Ensure that we are within the user's slippage tolerance.
(uint256 hTokenRequired, ) = hifiPool.getMintInputs(underlyingOffered);
if (hTokenRequired > maxBorrowAmount) {
revert HifiProxyTarget__AddLiquidityHTokenSlippage(maxBorrowAmount, hTokenRequired);
}
// Transfer the underlying to the DSProxy.
IErc20 underlying = hifiPool.underlying();
uint256 totalUnderlyingAmount = depositAmount + underlyingOffered;
underlying.safeTransferFrom(msg.sender, address(this), totalUnderlyingAmount);
// Deposit the underlying in the HToken contract to mint hTokens.
IHToken hToken = hifiPool.hToken();
depositUnderlyingInternal(hToken, depositAmount);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(underlying, address(hifiPool), underlyingOffered);
// Allow the HifiPool contract to spend hTokens from the DSProxy.
approveSpender(hToken, address(hifiPool), hTokenRequired);
// Add liquidity to pool.
uint256 poolTokensMinted = hifiPool.mint(underlyingOffered);
// The LP tokens are now in the DSProxy, so we relay them to the end user.
hifiPool.transfer(msg.sender, poolTokensMinted);
}
/// @inheritdoc IHifiProxyTarget
function depositUnderlyingAndRepayBorrow(
IHToken hToken,
IBalanceSheetV2 balanceSheet,
uint256 underlyingAmount
) external override {
uint256 oldHTokenBalance = hToken.balanceOf(address(this));
depositUnderlyingInternal(hToken, underlyingAmount);
unchecked {
// Calculate how many hTokens were minted.
uint256 newHTokenBalance = hToken.balanceOf(address(this));
uint256 hTokenAmount = newHTokenBalance - oldHTokenBalance;
// Use the newly minted hTokens to repay the debt.
balanceSheet.repayBorrow(hToken, hTokenAmount);
}
}
/// @inheritdoc IHifiProxyTarget
function redeem(
IHToken hToken,
uint256 hTokenAmount,
uint256 underlyingAmount
) external override {
// Transfer the hTokens to the DSProxy.
hToken.transferFrom(msg.sender, address(this), hTokenAmount);
// Redeem the underlying.
IErc20 underlying = hToken.underlying();
hToken.redeem(underlyingAmount);
// The underlying is now in the DSProxy, so we relay it to the end user.
underlying.safeTransfer(msg.sender, underlyingAmount);
}
/// @inheritdoc IHifiProxyTarget
function removeLiquidity(IHifiPool hifiPool, uint256 poolTokensBurned) external override {
// Transfer the LP tokens to the DSProxy.
hifiPool.transferFrom(msg.sender, address(this), poolTokensBurned);
// Burn the LP tokens.
(uint256 underlyingReturned, uint256 hTokenReturned) = hifiPool.burn(poolTokensBurned);
// The underlying and the hTokens are now in the DSProxy, so we relay them to the end user.
hifiPool.underlying().safeTransfer(msg.sender, underlyingReturned);
hifiPool.hToken().transfer(msg.sender, hTokenReturned);
}
/// @inheritdoc IHifiProxyTarget
function removeLiquidityAndRedeem(IHifiPool hifiPool, uint256 poolTokensBurned) external override {
// Transfer the LP tokens to the DSProxy.
hifiPool.transferFrom(msg.sender, address(this), poolTokensBurned);
// Burn the LP tokens.
(uint256 underlyingReturned, uint256 hTokenReturned) = hifiPool.burn(poolTokensBurned);
// Calculate how much underlying will be redeemed,
uint256 underlyingRedeemed = normalize(hTokenReturned, hifiPool.underlyingPrecisionScalar());
// Redeem the underlying.
IHToken hToken = hifiPool.hToken();
hToken.redeem(hTokenReturned);
// Relay all the underlying it to the end user.
uint256 totalUnderlyingAmount = underlyingReturned + underlyingRedeemed;
hToken.underlying().safeTransfer(msg.sender, totalUnderlyingAmount);
}
/// @inheritdoc IHifiProxyTarget
function removeLiquidityAndRepayBorrowAndWithdrawCollateral(
IHifiPool hifiPool,
IBalanceSheetV2 balanceSheet,
IErc20 collateral,
uint256 poolTokensBurned,
uint256 repayAmount,
uint256 withdrawAmount
) external override {
// Transfer the LP tokens to the DSProxy.
hifiPool.transferFrom(msg.sender, address(this), poolTokensBurned);
// Burn the LP tokens.
(uint256 underlyingReturned, uint256 hTokenReturned) = hifiPool.burn(poolTokensBurned);
// Repay the borrow.
IHToken hToken = hifiPool.hToken();
balanceSheet.repayBorrow(hToken, repayAmount);
// Relay any remaining hTokens to the end user.
if (hTokenReturned > repayAmount) {
unchecked {
uint256 hTokenDelta = hTokenReturned - repayAmount;
hToken.transfer(msg.sender, hTokenDelta);
}
}
// Withdraw the collateral and relay the underlying to the end user.
IErc20 underlying = hifiPool.underlying();
if (collateral == underlying) {
balanceSheet.withdrawCollateral(collateral, withdrawAmount);
uint256 totalUnderlyingAmount = underlyingReturned + withdrawAmount;
underlying.safeTransfer(msg.sender, totalUnderlyingAmount);
} else {
withdrawCollateral(balanceSheet, collateral, withdrawAmount);
underlying.safeTransfer(msg.sender, underlyingReturned);
}
}
/// @inheritdoc IHifiProxyTarget
function removeLiquidityAndSellHToken(
IHifiPool hifiPool,
uint256 poolTokensBurned,
uint256 minUnderlyingOut
) external override {
// Transfer the LP tokens to the DSProxy.
hifiPool.transferFrom(msg.sender, address(this), poolTokensBurned);
// Burn the LP tokens.
(uint256 underlyingReturned, uint256 hTokenReturned) = hifiPool.burn(poolTokensBurned);
// The underlying is now in the DSProxy, so we relay it to the end user.
hifiPool.underlying().safeTransfer(msg.sender, underlyingReturned);
// Ensure that we are within the user's slippage tolerance.
uint256 underlyingOut = hifiPool.getQuoteForSellingHToken(hTokenReturned);
if (underlyingOut < minUnderlyingOut) {
revert HifiProxyTarget__TradeSlippage(minUnderlyingOut, underlyingOut);
}
// Allow the HifiPool contract to spend hTokens from the DSProxy.
approveSpender(hifiPool.hToken(), address(hifiPool), hTokenReturned);
// Sell the hTokens and relay the underlying to the end user.
hifiPool.sellHToken(msg.sender, hTokenReturned);
}
/// @inheritdoc IHifiProxyTarget
function repayBorrow(
IBalanceSheetV2 balanceSheet,
IHToken hToken,
uint256 repayAmount
) external override {
// Transfer the hTokens to the DSProxy.
hToken.transferFrom(msg.sender, address(this), repayAmount);
// Repay the borrow.
balanceSheet.repayBorrow(hToken, repayAmount);
}
/// @inheritdoc IHifiProxyTarget
function sellHToken(
IHifiPool hifiPool,
uint256 hTokenIn,
uint256 minUnderlyingOut
) external override {
// Ensure that we are within the user's slippage tolerance.
uint256 underlyingOut = hifiPool.getQuoteForSellingHToken(hTokenIn);
if (underlyingOut < minUnderlyingOut) {
revert HifiProxyTarget__TradeSlippage(minUnderlyingOut, underlyingOut);
}
// Transfer the hTokens to the DSProxy.
IHToken hToken = hifiPool.hToken();
hToken.transferFrom(msg.sender, address(this), hTokenIn);
// Allow the HifiPool contract to spend hTokens from the DSProxy.
approveSpender(hToken, address(hifiPool), hTokenIn);
// Sell the hTokens and relay the underlying to the end user.
hifiPool.sellHToken(msg.sender, hTokenIn);
}
/// @inheritdoc IHifiProxyTarget
function sellUnderlying(
IHifiPool hifiPool,
uint256 underlyingIn,
uint256 minHTokenOut
) external override {
// Ensure that we are within the user's slippage tolerance.
uint256 hTokenOut = hifiPool.getQuoteForSellingUnderlying(underlyingIn);
if (hTokenOut < minHTokenOut) {
revert HifiProxyTarget__TradeSlippage(minHTokenOut, hTokenOut);
}
// Transfer the underlying to the DSProxy.
IErc20 underlying = hifiPool.underlying();
underlying.transferFrom(msg.sender, address(this), underlyingIn);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(underlying, address(hifiPool), underlyingIn);
// Sell the underlying and relay the hTokens to the end user.
hifiPool.sellUnderlying(msg.sender, underlyingIn);
}
/// @inheritdoc IHifiProxyTarget
function sellUnderlyingAndRepayBorrow(
IHifiPool hifiPool,
IBalanceSheetV2 balanceSheet,
uint256 underlyingIn,
uint256 minHTokenOut
) external override {
// Ensure that we are within the user's slippage tolerance.
uint256 hTokenOut = hifiPool.getQuoteForSellingUnderlying(underlyingIn);
if (hTokenOut < minHTokenOut) {
revert HifiProxyTarget__TradeSlippage(minHTokenOut, hTokenOut);
}
// Transfer the underlying to the DSProxy.
IErc20 underlying = hifiPool.underlying();
underlying.transferFrom(msg.sender, address(this), underlyingIn);
// Allow the HifiPool contract to spend underlying from the DSProxy.
approveSpender(underlying, address(hifiPool), underlyingIn);
// Sell the underlying.
hifiPool.sellUnderlying(address(this), underlyingIn);
// Query the amount of debt that the user owes.
IHToken hToken = hifiPool.hToken();
uint256 debtAmount = balanceSheet.getDebtAmount(address(this), hToken);
// Repay the borrow.
if (debtAmount >= hTokenOut) {
balanceSheet.repayBorrow(hToken, hTokenOut);
} else {
balanceSheet.repayBorrow(hToken, debtAmount);
// Relay any remaining hTokens to the end user.
unchecked {
uint256 hTokenDelta = hTokenOut - debtAmount;
hToken.transfer(msg.sender, hTokenDelta);
}
}
}
/// @inheritdoc IHifiProxyTarget
function withdrawCollateral(
IBalanceSheetV2 balanceSheet,
IErc20 collateral,
uint256 withdrawAmount
) public override {
balanceSheet.withdrawCollateral(collateral, withdrawAmount);
// The collateral is now in the DSProxy, so we relay it to the end user.
collateral.safeTransfer(msg.sender, withdrawAmount);
}
/// @inheritdoc IHifiProxyTarget
function wrapEthAndDepositCollateral(WethInterface weth, IBalanceSheetV2 balanceSheet) public payable override {
uint256 depositAmount = msg.value;
// Convert the received ETH to WETH.
weth.deposit{ value: depositAmount }();
// Deposit the collateral into the BalanceSheet contract.
depositCollateralInternal(balanceSheet, IErc20(address(weth)), depositAmount);
}
/// @inheritdoc IHifiProxyTarget
function wrapEthAndDepositAndBorrowHTokenAndSellHToken(
WethInterface weth,
IBalanceSheetV2 balanceSheet,
IHifiPool hifiPool,
uint256 borrowAmount,
uint256 minUnderlyingOut
) external payable override {
wrapEthAndDepositCollateral(weth, balanceSheet);
borrowHTokenAndSellHToken(balanceSheet, hifiPool, borrowAmount, minUnderlyingOut);
}
/// INTERNAL CONSTANT FUNCTIONS ///
/// @notice Downscales from normalized amount, i.e. 18 decimals of precision.
/// @param amount The amount with 18 decimals of precision.
/// @param precisionScalar The ratio between normalized precision and the desired precision.
/// @param denormalizedAmount The amount with fewer decimals of precision.
function denormalize(uint256 amount, uint256 precisionScalar) internal pure returns (uint256 denormalizedAmount) {
unchecked {
denormalizedAmount = precisionScalar != 1 ? amount / precisionScalar : amount;
}
}
/// @notice Upscales to normalized form, i.e. 18 decimals of precision.
/// @param amount The amount to normalize.
/// @param precisionScalar The ratio between normalized precision and the desired precision.
/// @param normalizedAmount The amount with 18 decimals of precision.
function normalize(uint256 amount, uint256 precisionScalar) internal pure returns (uint256 normalizedAmount) {
normalizedAmount = precisionScalar != 1 ? amount * precisionScalar : amount;
}
/// INTERNAL NON-CONSTANT FUNCTIONS ///
/// @dev See the documentation for the public functions that call this internal function.
function approveSpender(
IErc20 token,
address spender,
uint256 amount
) internal {
uint256 allowance = token.allowance(address(this), spender);
if (allowance < amount) {
token.approve(spender, type(uint256).max);
}
}
/// @dev See the documentation for the public functions that call this internal function.
function depositCollateralInternal(
IBalanceSheetV2 balanceSheet,
IErc20 collateral,
uint256 collateralAmount
) internal {
// Allow the BalanceSheet contract to spend collateral from the DSProxy.
approveSpender(collateral, address(balanceSheet), collateralAmount);
// Deposit the collateral into the BalanceSheet contract.
balanceSheet.depositCollateral(collateral, collateralAmount);
}
/// @dev See the documentation for the public functions that call this internal function.
function depositUnderlyingInternal(IHToken hToken, uint256 underlyingAmount) internal {
//IRedemptionPool redemptionPool = hToken.redemptionPool();
IErc20 underlying = hToken.underlying();
// Transfer the underlying to the DSProxy.
underlying.safeTransferFrom(msg.sender, address(this), underlyingAmount);
// Allow the HToken contract to spend underlying from the DSProxy.
approveSpender(underlying, address(hToken), underlyingAmount);
// Deposit the underlying in the HToken contract to mint hTokens.
hToken.depositUnderlying(underlyingAmount);
}
}
|
@inheritdoc IHifiProxyTarget The collateral is now in the DSProxy, so we relay it to the end user.
|
function withdrawCollateral(
IBalanceSheetV2 balanceSheet,
IErc20 collateral,
uint256 withdrawAmount
) public override {
balanceSheet.withdrawCollateral(collateral, withdrawAmount);
collateral.safeTransfer(msg.sender, withdrawAmount);
}
| 12,603,360
|
./partial_match/1/0x6A55dBe285643bb8194153b65a38eB2a3a0E49Ed/sources/Bats.sol
|
Returns maximum mintable supply./
|
function getMaxMintableSupply() external view override returns (uint256) {
return _maxMintableSupply;
}
| 2,769,132
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../DamnValuableTokenSnapshot.sol";
interface IPool {
function flashLoan(uint256 borrowAmount) external;
}
interface IGovernance {
function queueAction(address receiver, bytes calldata data, uint256 weiAmount) external returns (uint256);
}
contract SelfieAttack {
IPool immutable public pool;
IGovernance immutable public governance;
address immutable public attacker;
constructor(
IPool _pool,
IGovernance _governance,
address _attacker
) {
pool = _pool;
governance = _governance;
attacker = _attacker;
}
function receiveTokens(address token, uint256 borrowAmount) external {
// First snapshot balances to make sure this contract has enough balance in the snapshot to send a proposal.
DamnValuableTokenSnapshot(token).snapshot();
// Now propose new governance action to drain all of its funds and send to the attacker.
bytes memory data = abi.encodeWithSignature(
"drainAllFunds(address)",
attacker
);
governance.queueAction(address(pool), data, 0);
// Simply pay back flash loan now that proposal is enqueued.
DamnValuableTokenSnapshot(token).transfer(msg.sender, borrowAmount);
}
function drainFunds(uint256 borrowAmount) external {
// Flash loan will trigger receiveTokens which will enqueue a malicious proposal.
pool.flashLoan(borrowAmount);
}
}
|
First snapshot balances to make sure this contract has enough balance in the snapshot to send a proposal. Now propose new governance action to drain all of its funds and send to the attacker. Simply pay back flash loan now that proposal is enqueued.
|
function receiveTokens(address token, uint256 borrowAmount) external {
DamnValuableTokenSnapshot(token).snapshot();
bytes memory data = abi.encodeWithSignature(
"drainAllFunds(address)",
attacker
);
governance.queueAction(address(pool), data, 0);
DamnValuableTokenSnapshot(token).transfer(msg.sender, borrowAmount);
}
| 12,966,550
|
./full_match/1/0x873847b829a33C87c1fb227367D7b28a7DF979b4/sources/contracts/radiant/staking/ChefIncentivesController.sol
|
Ensure that the specified time offset hasn't been registered already. _startTimeOffset time offset return true if the specified time offset is already registered/
|
function _checkDuplicateSchedule(uint256 _startTimeOffset) internal view returns (bool) {
uint256 length = emissionSchedule.length;
for (uint256 i = 0; i < length; ) {
if (emissionSchedule[i].startTimeOffset == _startTimeOffset) {
return true;
}
unchecked {
i++;
}
}
return false;
}
| 3,223,413
|
./full_match/137/0x5dE8baA77325EC8B6f0682cC1DC0f799596d8Cbc/sources/Pool/AdvancePool.sol
|
return investor count/
|
function getInvestorCount()
public view
returns (uint256)
{
return investorCount;
}
| 4,765,463
|
pragma solidity 0.6.12;
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 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 = 990000000000000000;
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);
}
function getMaxBoost(address _borrowAddress, 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 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100);
uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress)));
}
/// @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) / (10 ** (18 - _getDecimals(_tokenAddr)));
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);
if (totalBorrowsETH == 0) return uint256(0);
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)")));
}
function proxyOwner() internal returns(address) {
return DSAuth(address(this)).owner();
}
}
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 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.
* 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;
}
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 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;
}
}
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 CreamSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258);
/// @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 Eth
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral);
}
// Sum up debt in Eth
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 CreamSaverHelper 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 = 0xD06527D5e56A3495252A528C4987003b712860eE;
address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the cream 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 cream 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 ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
_gasCost = wdiv(_gasCost, ethTokenPrice);
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 ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
feeAmount = wdiv(_gasCost, ethTokenPrice);
}
// 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, 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 liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInEth == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
if (_cCollAddress == CETH_ADDRESS) {
if (liquidityInEth > usersBalance) return usersBalance;
return sub(liquidityInEth, (liquidityInEth / 100));
}
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
if (liquidityInToken > usersBalance) return usersBalance;
return sub(liquidityInToken, (liquidityInToken / 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 liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100));
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CreamBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
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);
}
return getBiggestRate(_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]);
}
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];
}
}
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct OffchainData {
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
contract DFSExchangeHelper {
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 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 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));
}
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _user Address of the user
/// @param _token Address of the token
/// @param _dfsFeeDivider Dfs fee divider
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) {
if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) {
_dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user);
}
if (_dfsFeeDivider == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / _dfsFeeDivider;
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) {
feeAmount = _amount / 10;
}
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
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 DFSPrices 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,
bytes[] memory _additionalData
) 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, _additionalData[i]);
}
return getBiggestRate(_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,
bytes memory _additionalData
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
}
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]);
}
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;
}
}
abstract contract CEtherInterface {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
}
abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
abstract contract ComptrollerInterface {
struct CompMarketState {
uint224 index;
uint32 block;
}
function claimComp(address holder) public virtual;
function claimComp(address holder, address[] memory cTokens) public virtual;
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual;
function compSupplyState(address) public view virtual returns (CompMarketState memory);
function compSupplierIndex(address,address) public view virtual returns (uint);
function compAccrued(address) public view virtual returns (uint);
function compBorrowState(address) public view virtual returns (CompMarketState memory);
function compBorrowerIndex(address,address) public view virtual returns (uint);
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 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 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;
}
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);
}
interface ExchangeInterfaceV3 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
}
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 IAToken {
function redeem(uint256 _amount) external virtual;
function balanceOf(address _owner) external virtual view returns (uint256 balance);
}
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 ICompoundSubscriptions {
function unsubscribe() external 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 getReserveCurrentStableBorrowRate(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 virtual returns (uint);
function getUnderlyingAsset(address _addr) public view virtual returns (address);
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
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 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 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));
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));
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 = 0x78aF7A2Ee6C2240c748aDdc42aBc9A693559dcaF;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
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(
DFSExchangeData.ExchangeData memory _exchangeData,
CreateData memory _createData
) public payable {
MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee
if (!isEthJoinAddr(_createData.joinAddr)) {
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount);
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount);
}
bytes memory packedData = _packData(_createData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
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());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
function _packData(
CreateData memory _createData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_createData, _exchangeData);
}
}
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 Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
/// @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 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 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, 0));
_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 + 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 + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
if (originationFee > 0) {
ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee);
}
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, 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 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrows;
uint256 borrowRateMode;
bool enabledAsCollateral;
}
/// @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 (UserToken[] memory userTokens) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,,,,,,userTokens[i].enabledAsCollateral) = 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 lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]);
tokens[i] = TokenInfoFull({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]),
borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0,
borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0,
totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]),
availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]),
totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]),
collateralFactor: ltv,
liquidationRatio: liqRatio,
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 = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B;
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);
uint256 globalBorrowAmount = 0;
{ // avoid stack too deep
// 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));
globalBorrowAmount = borrowAmount;
}
// payback on behalf of user
if (borrowToken != ETH_ADDR) {
ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount);
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
} else {
DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(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 = 0x7b856af5753a9f80968EA002641E69AdF1d795aB;
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, 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 CompBalance is Exponential, GasBurner {
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
uint224 public constant compInitialIndex = 1e36;
function claimComp(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) public burnGas(8) {
_claim(_user, _cTokensSupply, _cTokensBorrow);
ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this)));
}
function _claim(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) internal {
address[] memory u = new address[](1);
u[0] = _user;
comp.claimComp(u, _cTokensSupply, false, true);
comp.claimComp(u, _cTokensBorrow, true, false);
}
function getBalance(address _user, address[] memory _cTokens) public view returns (uint) {
uint compBalance = 0;
for(uint i = 0; i < _cTokens.length; ++i) {
compBalance += getSuppyBalance(_cTokens[i], _user);
compBalance += getBorrowBalance(_cTokens[i], _user);
}
compBalance += ERC20(COMP_ADDR).balanceOf(_user);
return compBalance;
}
function getSuppyBalance(address _cToken, address _supplier) public view returns (uint supplierAccrued) {
ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken);
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: comp.compSupplierIndex(_cToken, _supplier)});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
supplierAccrued = add_(comp.compAccrued(_supplier), supplierDelta);
}
function getBorrowBalance(address _cToken, address _borrower) public view returns (uint borrowerAccrued) {
ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken);
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: comp.compBorrowerIndex(_cToken, _borrower)});
Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()});
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
borrowerAccrued = add_(comp.compAccrued(_borrower), borrowerDelta);
}
}
}
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, 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 = 0xaf9f8781A4c39Ce2122019fC05F22e3a662B0A32;
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 CreamBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the cream 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 cream 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 cream 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 cream 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 cream 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 cream 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, uint(-1));
}
}
}
contract CreamLoanInfo is CreamSafetyRatio {
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 = 0xD06527D5e56A3495252A528C4987003b712860eE;
/// @notice Calcualted the ratio of coll/debt for a cream 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 cream 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 cream 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 eth
/// @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 eth
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance);
collPos++;
}
// Sum up debt in eth
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 eth
/// @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 cream 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 CreamImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd;
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, uint(-1));
// repay cream 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(CREAM_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 CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8;
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 cream_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(CREAM_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(CREAM_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamImport", 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, 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, 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(getBalance(exData.destAddr) >= 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 _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return address(this).balance;
// 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 (address(this).balance > _srcAmount) return address(this).balance - _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 address(this).balance;
}
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 DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData {
string public constant ERR_SLIPPAGE_HIT = "Slippage hit";
string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing";
string public constant ERR_WRAPPER_INVALID = "Wrapper invalid";
string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid";
/// @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;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.SELL);
if (success) {
wrapper = exData.offchainData.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), ERR_SLIPPAGE_HIT);
// 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, ERR_DEST_AMOUNT_MISSING);
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// 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.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.BUY);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT);
// 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
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) private returns (bool success, uint256) {
if (_exData.srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
}
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.offchainData.callData, 36, _exData.destAmount);
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) {
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
if (success) {
// 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);
}
/// @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), ERR_WRAPPER_INVALID);
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData);
} else {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert(ERR_OFFCHAIN_DATA_INVALID);
}
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;
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, 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, bytes memory _additionalData) 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, bytes memory _additionalData) 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, bytes memory _additionalData) 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, bytes memory _additionalData) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData);
// 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 OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, 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, bytes memory _additionalData) 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, bytes memory _additionalData) 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, bytes memory _additionalData) 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, bytes memory _additionalData) 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 UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, 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, bytes memory _additionalData) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
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, bytes memory _additionalData) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
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, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
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, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
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 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 borrowIndex() public view virtual returns (uint);
function borrowBalanceStored(address) public view virtual returns(uint);
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 = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1800000;
uint public BOOST_GAS_COST = 1800000;
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 DFSExchangeCore, 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 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 {
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData));
CloseData memory closeData = CloseData({
cdpId: closeDataSent.cdpId,
collAmount: closeDataSent.collAmount,
daiAmount: closeDataSent.daiAmount,
minAccepted: closeDataSent.minAccepted,
joinAddr: closeDataSent.joinAddr,
proxy: proxy,
flFee: _fee,
toDai: closeDataSent.toDai,
reserve: _reserve,
amount: _amount
});
address user = DSProxy(payable(closeData.proxy)).owner();
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = user;
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
uint drawnAmount = drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral
uint daiSwaped = 0;
if (_closeData.toDai) {
_exchangeData.srcAmount = drawnAmount;
(, daiSwaped) = _sell(_exchangeData);
} else {
_exchangeData.destAmount = _closeData.daiAmount;
(, daiSwaped) = _buy(_exchangeData);
}
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 (isEthJoinAddr(_joinAddr)) {
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 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, DFSExchangeCore) 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(
DFSExchangeData.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);
bytes memory packedData = _packData(_closeData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
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,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_closeData, _exchangeData);
}
}
contract MCDCreateFlashLoan is DFSExchangeCore, 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 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");
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData));
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxy(payable(proxy)).owner();
openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, 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 {
(, uint256 collSwaped) = _sell(_exchangeData);
bytes32 ilk = Join(_joinAddr).ilk();
if (isEthJoinAddr(_joinAddr)) {
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
_daiAmountAndFee,
_proxy
);
} else {
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
);
}
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract MCDSaverProxy is DFSExchangeCore, 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 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(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint daiAmount) = _sell(_exchangeData);
daiAmount -= takeFee(_gasCost, daiAmount);
paybackDebt(_cdpId, ilk, daiAmount, user);
// 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, user, _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(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn);
(, 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, user, _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 (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
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 (isEthJoinAddr(_joinAddr)) {
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 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(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
// take one percent due to precision issues
return normalizeMaxCollateral * 99 / 100;
}
/// @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);
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) {
if (_gasCost > 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
uint feeAmount = rmul(_gasCost, ethDaiPrice);
uint balance = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (feeAmount > _amount / 10) {
feeAmount = _amount / 10;
}
ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount);
return feeAmount;
}
return 0;
}
}
contract MCDSaverTaker is MCDSaverProxy, GasBurner {
address payable public constant MCD_SAVER_FLASH_LOAN = 0xD0eB57ff3eA4Def2b74dc29681fd529D1611880f;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
function boostWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId));
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxDebt) {
_exchangeData.srcAmount = maxDebt;
}
boost(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
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(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr);
uint maxLiq = getAvailableLiquidity(_joinAddr);
if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxColl) {
_exchangeData.srcAmount = maxColl;
}
repay(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
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 (isEthJoinAddr(_joinAddr)
|| _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);
}
}
}
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 {
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
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 -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy);
(, uint amount) = _sell(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
} else if (paramData.swapType == 2) { // DEBT_SWAP
exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy);
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, 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";
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxyInterface proxy = DSProxyInterface(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);
}
}
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
Manager public constant manager = Manager(MANAGER_ADDRESS);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
enum Protocols { MCD, COMPOUND }
enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP }
enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB }
struct LoanShiftData {
Protocols fromProtocol;
Protocols toProtocol;
SwapType swapType;
Unsub unsub;
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 payable burnGas(20) {
if (_isSameTypeVaults(_loanShift)) {
_forkVault(_loanShift);
logEvent(_exchangeData, _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)));
if (_loanShift.wholeDebt) {
_loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1);
}
(
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"));
loanShifterReceiverAddr.transfer(address(this).balance);
// call FL
givePermission(loanShifterReceiverAddr);
lendingPool.flashLoan(loanShifterReceiverAddr,
getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData);
removePermission(loanShifterReceiverAddr);
unsubFromAutomation(
_loanShift.unsub,
_loanShift.id1,
_loanShift.id2,
_loanShift.fromProtocol,
_loanShift.toProtocol
);
logEvent(_exchangeData, _loanShift);
}
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 logEvent(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address srcAddr = _exchangeData.srcAddr;
address destAddr = _exchangeData.destAddr;
uint collAmount = _exchangeData.srcAmount;
uint debtAmount = _exchangeData.destAmount;
if (_loanShift.swapType == SwapType.NO_SWAP) {
srcAddr = _loanShift.addrLoan1;
destAddr = _loanShift.debtAddr1;
collAmount = _loanShift.collAmount;
debtAmount = _loanShift.debtAmount;
}
DefisaverLogger(DEFISAVER_LOGGER)
.Log(address(this), msg.sender, "LoanShifter",
abi.encode(
_loanShift.fromProtocol,
_loanShift.toProtocol,
_loanShift.swapType,
srcAddr,
destAddr,
collAmount,
debtAmount
));
}
function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal {
if (_unsub != Unsub.NO_UNSUB) {
if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp1, _from);
}
if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp2, _to);
}
}
}
function unsubscribe(uint _cdpId, Protocols _protocol) internal {
if (_cdpId != 0 && _protocol == Protocols.MCD) {
IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId);
}
if (_protocol == Protocols.COMPOUND) {
ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe();
}
}
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 CompShifter is CompoundSaverHelper {
using SafeERC20 for ERC20;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return getWholeDebt(_cdpId, _joinAddr);
}
function getWholeDebt(uint _cdpId, address _joinAddr) public 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);
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).safeTransfer(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).safeTransfer(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).safeTransfer(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 {
using SafeERC20 for ERC20;
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
drawCollateral(_cdpId, _joinAddr, maxColl);
// send back to msg.sender
if (isEthJoinAddr(_joinAddr)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20 collToken = ERC20(getCollateralAddr(_joinAddr));
collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this)));
}
}
function open(
uint _cdpId,
address _joinAddr,
uint _debtAmount
) public {
uint collAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
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 (isEthJoinAddr(_joinAddrTo)) {
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
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
);
}
}
}
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());
// redeem collateral
address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr);
// uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this));
// don't swap more than maxCollateral
// _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount;
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();
(,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this));
address payable user = payable(getUserAddress());
// skipping this check as its too expensive
// uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this));
// _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount;
// borrow amount
ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, 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 AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a;
address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,uint256,bool,uint256,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();
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_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);
}
function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external override payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, true);
}
function boost(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, false);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(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_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
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 CompLeverage is DFSExchangeCore, CompBalance {
address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Should claim COMP and sell it to the specified token and deposit it back
/// @param exchangeData Standard Exchange struct
/// @param _cTokensSupply List of cTokens user is supplying
/// @param _cTokensBorrow List of cTokens user is borrowing
/// @param _cDepositAddr The cToken address of the asset you want to deposit
/// @param _inMarket Flag if the cToken is used as collateral
function claimAndSell(
ExchangeData memory exchangeData,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow,
address _cDepositAddr,
bool _inMarket
) public payable {
// Claim COMP token
_claim(address(this), _cTokensSupply, _cTokensBorrow);
uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this));
uint depositAmount = 0;
// Exchange COMP
if (exchangeData.srcAddr != address(0)) {
exchangeData.dfsFeeDivider = 400; // 0.25%
exchangeData.srcAmount = compBalance;
(, depositAmount) = _sell(exchangeData);
// if we have no deposit after, send back tokens to the user
if (_cDepositAddr == address(0)) {
if (exchangeData.destAddr != ETH_ADDRESS) {
ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount);
} else {
msg.sender.transfer(address(this).balance);
}
}
}
// Deposit back a token
if (_cDepositAddr != address(0)) {
// if we are just depositing COMP without a swap
if (_cDepositAddr == C_COMP_ADDR) {
depositAmount = compBalance;
}
address tokenAddr = getUnderlyingAddr(_cDepositAddr);
deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket);
}
logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount));
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
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) {}
struct CompCreateData {
address payable proxyAddr;
bytes proxyData;
address cCollAddr;
address cDebtAddr;
}
/// @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
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
// If the assets are different
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
(, uint sellAmount) = _sell(exchangeData);
getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr);
leveragedAsset = exchangeData.destAddr;
}
// Send amount to DSProxy
sendToProxy(compCreate.proxyAddr, leveragedAsset);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.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 (CompCreateData memory compCreate, 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));
bytes memory 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]
});
compCreate = CompCreateData({
proxyAddr: payable(proxy),
proxyData: proxyData,
cCollAddr: cAddresses[0],
cDebtAddr: cAddresses[1]
});
return (compCreate, 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) {
_exData.srcAmount = collAmount;
(, 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 CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51;
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 CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper {
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, "CreamRepay", 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, "CreamBoost", 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 CreamSaverProxy is CreamSaverHelper, 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, "CreamRepay", 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, "CreamBoost", 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 DFSExchange is DFSExchangeCore, 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) {
exData.dfsFeeDivider = SERVICE_FEE;
// 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){
exData.dfsFeeDivider = SERVICE_FEE;
// 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 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);
// Swap
_exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, 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, user, _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);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint paybackAmount) = _sell(_exchangeData);
paybackAmount -= takeFee(_saverData.gasCost, paybackAmount);
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, user, _exchangeData.srcAmount, paybackAmount));
}
/// @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, DFSExchangeCore) payable {}
}
contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @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));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
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));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
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]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @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));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
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, "CreamFlashRepay", 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));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
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, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
|
convert weth -> eth and send back
|
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));
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
sendLeftOver(srcAddr);
return srcAmount;
}
| 7,334,029
|
// contracts/HolyHandV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./interfaces/IHolyPoolV2.sol";
import "./interfaces/IHolyWing.sol";
import "./interfaces/IHolyWingV2.sol";
import "./interfaces/IHolyRedeemer.sol";
import "./utils/SafeAllowanceReset.sol";
/*
HolyHand is a transfer proxy contract for ERC20 and ETH transfers through Holyheld infrastructure (deposit/withdraw to HolyPool, swaps, etc.)
- extract fees;
- call token conversion if needed;
- deposit/withdraw tokens into HolyPool;
- non-custodial, not holding any funds;
- fees are accumulated on this contract's balance (if fees enabled);
This contract is a single address that user grants allowance to on any ERC20 token for interacting with HH services.
This contract could be upgraded in the future to provide subsidized transactions using bonuses from treasury.
TODO: if token supports permit, provide ability to execute without separate approval call
V2 version additions:
- direct deposits to pool (if no fees or conversions);
- when swapping tokens direct return converted asset to sender (if no fees);
- ETH support (non-wrapped ETH conversion for deposits and swaps);
- emergencyTransfer can reclaim ETH
*/
contract HolyHandV2 is AccessControlUpgradeable, SafeAllowanceReset {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address payable;
uint256 private constant ALLOWANCE_SIZE =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// token address for non-wrapped eth
address private constant ETH_TOKEN_ADDRESS =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// if greater than zero, this is a fractional amount (1e18 = 1.0) fee applied to all deposits
uint256 public depositFee;
// if greater than zero, this is a fractional amount (1e18 = 1.0) fee applied to exchange operations with HolyWing proxy
uint256 public exchangeFee;
// if greater than zero, this is a fractional amount (1e18 = 1.0) fee applied to withdraw operations
uint256 public withdrawFee;
// HolyWing exchange proxy/middleware
IHolyWing private exchangeProxyContract;
// HolyRedeemer yield distributor
// NOTE: to keep overhead for users minimal, fees are not transferred
// immediately, but left on this contract balance, yieldDistributor can reclaim them
address private yieldDistributorAddress;
event TokenSwap(
address indexed tokenFrom,
address indexed tokenTo,
address sender,
uint256 amountFrom,
uint256 expectedMinimumReceived,
uint256 amountReceived
);
event FeeChanged(string indexed name, uint256 value);
event EmergencyTransfer(
address indexed token,
address indexed destination,
uint256 amount
);
function initialize() public initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
depositFee = 0;
exchangeFee = 0;
withdrawFee = 0;
}
function setExchangeProxy(address _exchangeProxyContract) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
exchangeProxyContract = IHolyWing(_exchangeProxyContract);
}
function setYieldDistributor(
address _tokenAddress,
address _distributorAddress
) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
yieldDistributorAddress = _distributorAddress;
// only yield to be redistributed should be present on this contract in baseAsset (or other tokens if swap fees)
// so no access to lp tokens for the funds invested
resetAllowanceIfNeeded(
IERC20(_tokenAddress),
_distributorAddress,
ALLOWANCE_SIZE
);
}
// if the pool baseToken matches the token deposited, then no conversion is performed
// and _expectedMininmumReceived/convertData should be zero/empty
function depositToPool(
address _poolAddress,
address _token,
uint256 _amount,
uint256 _expectedMinimumReceived,
bytes memory convertData
) public payable {
IHolyPoolV2 holyPool = IHolyPoolV2(_poolAddress);
IERC20 poolToken = IERC20(holyPool.getBaseAsset());
if (address(poolToken) == _token) {
// no conversion is needed, allowance and balance checks performed in ERC20 token
// and not here to not waste any gas fees
if (depositFee == 0) {
// use depositOnBehalfDirect function only for this flow to save gas as much as possible
// (we have approval for this contract, so it can transfer funds to pool directly if
// deposit fees are zero (otherwise we go with standard processing flow)
// transfer directly to pool
IERC20(_token).safeTransferFrom(
msg.sender,
_poolAddress,
_amount
);
// call pool function to process deposit (without transfer)
holyPool.depositOnBehalfDirect(msg.sender, _amount);
return;
}
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
// HolyPool must have sufficient allowance (one-time for pool/token pair)
resetAllowanceIfNeeded(poolToken, _poolAddress, _amount);
// process deposit fees and deposit remainder
uint256 feeAmount = _amount.mul(depositFee).div(1e18);
holyPool.depositOnBehalf(msg.sender, _amount.sub(feeAmount));
return;
}
// conversion is required, perform swap through exchangeProxy (HolyWing)
if (_token != ETH_TOKEN_ADDRESS) {
IERC20(_token).safeTransferFrom(
msg.sender,
address(exchangeProxyContract),
_amount
);
}
if (depositFee > 0) {
// process exchange/deposit fees and route through HolyHand
uint256 amountReceived =
IHolyWingV2(address(exchangeProxyContract)).executeSwapDirect{value: msg.value}(
address(this),
_token,
address(poolToken),
_amount,
exchangeFee,
convertData
);
require(
amountReceived >= _expectedMinimumReceived,
"minimum swap amount not met"
);
uint256 feeAmount = amountReceived.mul(depositFee).div(1e18);
amountReceived = amountReceived.sub(feeAmount);
// HolyPool must have sufficient allowance (one-time for pool/token pair)
resetAllowanceIfNeeded(poolToken, _poolAddress, _amount);
// perform actual deposit call
holyPool.depositOnBehalf(msg.sender, amountReceived);
} else {
// swap directly to HolyPool address and execute direct deposit call
uint256 amountReceived =
IHolyWingV2(address(exchangeProxyContract)).executeSwapDirect{value: msg.value}(
_poolAddress,
_token,
address(poolToken),
_amount,
exchangeFee,
convertData
);
require(
amountReceived >= _expectedMinimumReceived,
"minimum swap amount not met"
);
holyPool.depositOnBehalfDirect(msg.sender, amountReceived);
}
}
function withdrawFromPool(address _poolAddress, uint256 _amount) public {
IHolyPoolV2 holyPool = IHolyPoolV2(_poolAddress);
IERC20 poolToken = IERC20(holyPool.getBaseAsset());
uint256 amountBefore = poolToken.balanceOf(address(this));
holyPool.withdraw(msg.sender, _amount);
uint256 withdrawnAmount =
poolToken.balanceOf(address(this)).sub(amountBefore);
// if amount is less than expected, transfer anyway what was actually received
if (withdrawFee > 0) {
// process withdraw fees
uint256 feeAmount = withdrawnAmount.mul(withdrawFee).div(1e18);
poolToken.safeTransfer(msg.sender, withdrawnAmount.sub(feeAmount));
} else {
poolToken.safeTransfer(msg.sender, withdrawnAmount);
}
}
function setDepositFee(uint256 _depositFee) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
depositFee = _depositFee;
emit FeeChanged("deposit", _depositFee);
}
function setExchangeFee(uint256 _exchangeFee) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
exchangeFee = _exchangeFee;
emit FeeChanged("exchange", _exchangeFee);
}
function setWithdrawFee(uint256 _withdrawFee) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
withdrawFee = _withdrawFee;
emit FeeChanged("withdraw", _withdrawFee);
}
// token swap function (could be with fees but also can be subsidized later)
// perform conversion through exhcnageProxy (HolyWing)
function executeSwap(
address _tokenFrom,
address _tokenTo,
uint256 _amountFrom,
uint256 _expectedMinimumReceived,
bytes memory convertData
) public payable {
require(_tokenFrom != _tokenTo, "Same tokens provided");
// swap with direct transfer to HolyWing and HolyWing would transfer swapped token (or ETH) back to msg.sender
if (_tokenFrom != ETH_TOKEN_ADDRESS) {
IERC20(_tokenFrom).safeTransferFrom(
msg.sender,
address(exchangeProxyContract),
_amountFrom
);
}
uint256 amountReceived =
IHolyWingV2(address(exchangeProxyContract)).executeSwapDirect{value: msg.value}(
msg.sender,
_tokenFrom,
_tokenTo,
_amountFrom,
exchangeFee,
convertData
);
require(
amountReceived >= _expectedMinimumReceived,
"minimum swap amount not met"
);
}
// TODO: token send function (could be with fees but also can be subsidized)
// payable fallback to receive ETH when swapping to raw ETH
receive() external payable {}
// this function is similar to emergencyTransfer, but relates to yield distribution
// fees are not transferred immediately to save gas costs for user operations
// so they accumulate on this contract address and can be claimed by HolyRedeemer
// when appropriate. Anyway, no user funds should appear on this contract, it
// only performs transfers, so such function has great power, but should be safe
// It does not include approval, so may be used by HolyRedeemer to get fees from swaps
// in different small token amounts
function claimFees(address _token, uint256 _amount) public {
require(
msg.sender == yieldDistributorAddress,
"yield distributor only"
);
if (_token != ETH_TOKEN_ADDRESS) {
IERC20(_token).safeTransfer(msg.sender, _amount);
} else {
payable(msg.sender).sendValue(_amount);
}
}
// all contracts that do not hold funds have this emergency function if someone occasionally
// transfers ERC20 tokens directly to this contract
// callable only by owner
function emergencyTransfer(
address _token,
address _destination,
uint256 _amount
) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
if (_token != ETH_TOKEN_ADDRESS) {
IERC20(_token).safeTransfer(_destination, _amount);
} else {
payable(_destination).sendValue(_amount);
}
emit EmergencyTransfer(_token, _destination, _amount);
}
}
|
token swap function (could be with fees but also can be subsidized later) perform conversion through exhcnageProxy (HolyWing) swap with direct transfer to HolyWing and HolyWing would transfer swapped token (or ETH) back to msg.sender
|
function executeSwap(
address _tokenFrom,
address _tokenTo,
uint256 _amountFrom,
uint256 _expectedMinimumReceived,
bytes memory convertData
) public payable {
require(_tokenFrom != _tokenTo, "Same tokens provided");
if (_tokenFrom != ETH_TOKEN_ADDRESS) {
IERC20(_tokenFrom).safeTransferFrom(
msg.sender,
address(exchangeProxyContract),
_amountFrom
);
}
uint256 amountReceived =
msg.sender,
_tokenFrom,
_tokenTo,
_amountFrom,
exchangeFee,
convertData
);
require(
amountReceived >= _expectedMinimumReceived,
"minimum swap amount not met"
);
}
| 7,233,107
|
./full_match/1/0xFe491D331E1cBb38438c2ECc0D29539c72a8C716/sources/contracts/TaxHavens.sol
|
Calculate the rebase factor
|
function withdrawPanamaVrf(address _user, uint256 _randNum) public onlyVRF {
PanamaStakerInfo storage user = panamaStakerInfo[_user];
bool isTaxed = false;
uint256 currentEpoch = fraud.getCurrentEpoch();
uint256 epochsElapsed = currentEpoch.sub(user.rebaseEpoch);
if(epochsElapsed < 4){
for (uint256 i = 0; i < epochsElapsed; i++) {
}
for (uint256 i = 0; i < 4; i++) {
}
}
if(epochsElapsed > 4){
uint256 epochRebased = epochsElapsed.sub(4);
for (uint256 i = 0; i < epochRebased; i++) {
}
debasedAmount = debasedAmount.mul(rebaseFactorPost).div(1 ether);
}
if(_randNum < 20) {
uint256 taxAmount = debasedAmount.div(2);
taxAmountToTaxOffice(taxAmount, 0);
debasedAmount = debasedAmount.sub(taxAmount);
isTaxed = true;
}
totalStackedPanama = totalStackedPanama.sub(user.amount);
user.amount = 0;
emit WithdrawPanama(_user, debasedAmount, isTaxed);
}
| 4,826,355
|
pragma solidity ^0.5.13;
import "./HasOwner.sol";
contract ReclaimerToken is HasOwner {
/**
*@dev send all eth balance in the contract to another address
*/
function reclaimEther(address payable _to) external onlyOwner {
_to.transfer(address(this).balance);
}
/**
*@dev send all token balance of an arbitary erc20 token
in the contract to another address
*/
function reclaimToken(ERC20 token, address _to) external onlyOwner {
uint256 balance = token.balanceOf(address(this));
token.transfer(_to, balance);
}
/**
*@dev allows owner of the contract to gain ownership of any contract that the contract currently owns
*/
function reclaimContract(Ownable _ownable) external onlyOwner {
_ownable.transferOwnership(owner);
}
}
|
allows owner of the contract to gain ownership of any contract that the contract currently owns/
|
function reclaimContract(Ownable _ownable) external onlyOwner {
_ownable.transferOwnership(owner);
}
| 937,167
|
./full_match/80001/0x7cbb70CE6B4B351038292C4701DD7578C1b585D2/sources/contracts/votacion.sol
|
Proporcionar el nombre del candidato ganadorLa variable ganador contendra el nombre del candidato ganadorRecorremos el array de candidatos para determinar el candidato con un numero de votos mayor
|
function Ganador() public view returns (string memory) {
string memory ganador = candidatos[0];
bool flag;
for (uint256 i = 1; i < candidatos.length; i++) {
if (votos_candidato[ganador] < votos_candidato[candidatos[i]]) {
ganador = candidatos[i];
flag = false;
if (
votos_candidato[ganador] == votos_candidato[candidatos[i]]
) {
flag = true;
}
}
}
if (flag == true) {
ganador = "¡Hay empate entre los candidatos!";
}
return ganador;
}
| 863,456
|
pragma solidity ^0.4.4;
contract ThreesigWallet {
mapping (address => bool) public founders;
struct Tx {
address founder;
address destAddr;
}
Tx[] public txs;
uint256 balance;
// constructor made of 3 independent wallets
function ThreesigWallet() {
founders[0x005A9c91CA71f9f69a4b3ad38c4B582E13595805] = true;
founders[0x009A55A3c16953A359484afD299ebdC444200EdB] = true;
founders[0xB94a9Db26b59AC66E5bE7510636BE8b189BD184D] = true;
}
// preICO contract will send ETHers here
function() payable {
balance += msg.value;
}
// one of founders can propose destination address for ethers
function proposeTx(address destAddr) isFounder {
txs.push(Tx({
founder: msg.sender,
destAddr: destAddr
}));
}
// another founder can approve specified tx and send it to destAddr
function approveTx(uint8 txIdx) isFounder {
assert(txs[txIdx].founder != msg.sender);
txs[txIdx].destAddr.transfer(balance);
balance = 0;
}
// check if msg.sender is founder
modifier isFounder() {
require(founders[msg.sender]);
_;
}
}
|
another founder can approve specified tx and send it to destAddr
|
function approveTx(uint8 txIdx) isFounder {
assert(txs[txIdx].founder != msg.sender);
txs[txIdx].destAddr.transfer(balance);
balance = 0;
}
| 6,352,549
|
// Verified using https://dapp.tools
// hevm: flattened sources of src/saviours/NativeUnderlyingUniswapV2SafeSaviour.sol
pragma solidity =0.6.7 >=0.6.0 <0.8.0 >=0.6.7 <0.7.0;
////// src/interfaces/CoinJoinLike.sol
/* pragma solidity 0.6.7; */
abstract contract CoinJoinLike {
function systemCoin() virtual public view returns (address);
function safeEngine() virtual public view returns (address);
function join(address, uint256) virtual external;
}
////// src/interfaces/CollateralJoinLike.sol
/* pragma solidity ^0.6.7; */
abstract contract CollateralJoinLike {
function safeEngine() virtual public view returns (address);
function collateralType() virtual public view returns (bytes32);
function collateral() virtual public view returns (address);
function decimals() virtual public view returns (uint256);
function contractEnabled() virtual public view returns (uint256);
function join(address, uint256) virtual external;
}
////// src/interfaces/ERC20Like.sol
/* pragma solidity ^0.6.7; */
abstract contract ERC20Like {
function approve(address guy, uint wad) virtual public returns (bool);
function transfer(address dst, uint wad) virtual public returns (bool);
function balanceOf(address) virtual external view returns (uint256);
function transferFrom(address src, address dst, uint wad)
virtual
public
returns (bool);
}
////// src/interfaces/GebSafeManagerLike.sol
/* pragma solidity ^0.6.7; */
abstract contract GebSafeManagerLike {
function safes(uint256) virtual public view returns (address);
function ownsSAFE(uint256) virtual public view returns (address);
function safeCan(address,uint256,address) virtual public view returns (uint256);
}
////// src/interfaces/LiquidationEngineLike.sol
/* pragma solidity ^0.6.7; */
abstract contract LiquidationEngineLike_3 {
function safeSaviours(address) virtual public view returns (uint256);
}
////// src/interfaces/OracleRelayerLike.sol
/* pragma solidity ^0.6.7; */
abstract contract OracleRelayerLike_2 {
function collateralTypes(bytes32) virtual public view returns (address, uint256, uint256);
function liquidationCRatio(bytes32) virtual public view returns (uint256);
function redemptionPrice() virtual public returns (uint256);
}
////// src/interfaces/PriceFeedLike.sol
/* pragma solidity ^0.6.7; */
abstract contract PriceFeedLike {
function priceSource() virtual public view returns (address);
function read() virtual public view returns (uint256);
function getResultWithValidity() virtual external view returns (uint256,bool);
}
////// src/interfaces/SAFEEngineLike.sol
/* pragma solidity ^0.6.7; */
abstract contract SAFEEngineLike_8 {
function approveSAFEModification(address) virtual external;
function safeRights(address,address) virtual public view returns (uint256);
function collateralTypes(bytes32) virtual public view returns (
uint256 debtAmount, // [wad]
uint256 accumulatedRate, // [ray]
uint256 safetyPrice, // [ray]
uint256 debtCeiling, // [rad]
uint256 debtFloor, // [rad]
uint256 liquidationPrice // [ray]
);
function safes(bytes32,address) virtual public view returns (
uint256 lockedCollateral, // [wad]
uint256 generatedDebt // [wad]
);
function modifySAFECollateralization(
bytes32 collateralType,
address safe,
address collateralSource,
address debtDestination,
int256 deltaCollateral, // [wad]
int256 deltaDebt // [wad]
) virtual external;
}
////// src/interfaces/SAFESaviourRegistryLike.sol
/* pragma solidity ^0.6.7; */
abstract contract SAFESaviourRegistryLike {
function markSave(bytes32 collateralType, address safeHandler) virtual external;
}
////// src/interfaces/TaxCollectorLike.sol
/* pragma solidity 0.6.7; */
abstract contract TaxCollectorLike {
function taxSingle(bytes32) public virtual returns (uint256);
}
////// src/utils/ReentrancyGuard.sol
// 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;
}
}
////// src/interfaces/SafeSaviourLike.sol
// Copyright (C) 2020 Reflexer Labs, INC
// 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.6.7; */
/* import "./CollateralJoinLike.sol"; */
/* import "./CoinJoinLike.sol"; */
/* import "./OracleRelayerLike.sol"; */
/* import "./SAFEEngineLike.sol"; */
/* import "./LiquidationEngineLike.sol"; */
/* import "./PriceFeedLike.sol"; */
/* import "./ERC20Like.sol"; */
/* import "./GebSafeManagerLike.sol"; */
/* import "./TaxCollectorLike.sol"; */
/* import "./SAFESaviourRegistryLike.sol"; */
/* import "../utils/ReentrancyGuard.sol"; */
abstract contract SafeSaviourLike is ReentrancyGuard {
// Checks whether a saviour contract has been approved by governance in the LiquidationEngine
modifier liquidationEngineApproved(address saviour) {
require(liquidationEngine.safeSaviours(saviour) == 1, "SafeSaviour/not-approved-in-liquidation-engine");
_;
}
// Checks whether someone controls a safe handler inside the GebSafeManager
modifier controlsSAFE(address owner, uint256 safeID) {
require(owner != address(0), "SafeSaviour/null-owner");
require(either(owner == safeManager.ownsSAFE(safeID), safeManager.safeCan(safeManager.ownsSAFE(safeID), safeID, owner) == 1), "SafeSaviour/not-owning-safe");
_;
}
// --- Variables ---
LiquidationEngineLike_3 public liquidationEngine;
TaxCollectorLike public taxCollector;
OracleRelayerLike_2 public oracleRelayer;
GebSafeManagerLike public safeManager;
SAFEEngineLike_8 public safeEngine;
SAFESaviourRegistryLike public saviourRegistry;
// The amount of tokens the keeper gets in exchange for the gas spent to save a SAFE
uint256 public keeperPayout; // [wad]
// The minimum fiat value that the keeper must get in exchange for saving a SAFE
uint256 public minKeeperPayoutValue; // [wad]
/*
The proportion between the keeperPayout (if it's in collateral) and the amount of collateral or debt that's in a SAFE to be saved.
Alternatively, it can be the proportion between the fiat value of keeperPayout and the fiat value of the profit that a keeper
could make if a SAFE is liquidated right now. It ensures there's no incentive to intentionally put a SAFE underwater and then
save it just to make a profit that's greater than the one from participating in collateral auctions
*/
uint256 public payoutToSAFESize;
// --- Constants ---
uint256 public constant ONE = 1;
uint256 public constant HUNDRED = 100;
uint256 public constant THOUSAND = 1000;
uint256 public constant WAD_COMPLEMENT = 10**9;
uint256 public constant WAD = 10**18;
uint256 public constant RAY = 10**27;
uint256 public constant MAX_UINT = uint(-1);
// --- Boolean Logic ---
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y) }
}
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
// --- Events ---
event SaveSAFE(address indexed keeper, bytes32 indexed collateralType, address indexed safeHandler, uint256 collateralAddedOrDebtRepaid);
// --- Functions to Implement ---
function saveSAFE(address,bytes32,address) virtual external returns (bool,uint256,uint256);
function getKeeperPayoutValue() virtual public returns (uint256);
function keeperPayoutExceedsMinValue() virtual public returns (bool);
function canSave(bytes32,address) virtual external returns (bool);
function tokenAmountUsedToSave(bytes32,address) virtual public returns (uint256);
}
////// src/interfaces/SaviourCRatioSetterLike.sol
/* pragma solidity 0.6.7; */
/* import "./OracleRelayerLike.sol"; */
/* import "./GebSafeManagerLike.sol"; */
/* import "../utils/ReentrancyGuard.sol"; */
abstract contract SaviourCRatioSetterLike is ReentrancyGuard {
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "SaviourCRatioSetter/account-not-authorized");
_;
}
// Checks whether someone controls a safe handler inside the GebSafeManager
modifier controlsSAFE(address owner, uint256 safeID) {
require(owner != address(0), "SaviourCRatioSetter/null-owner");
require(either(owner == safeManager.ownsSAFE(safeID), safeManager.safeCan(safeManager.ownsSAFE(safeID), safeID, owner) == 1), "SaviourCRatioSetter/not-owning-safe");
_;
}
// --- Variables ---
OracleRelayerLike_2 public oracleRelayer;
GebSafeManagerLike public safeManager;
// Default desired cratio for each individual collateral type
mapping(bytes32 => uint256) public defaultDesiredCollateralizationRatios;
// Minimum bound for the desired cratio for each collateral type
mapping(bytes32 => uint256) public minDesiredCollateralizationRatios;
// Desired CRatios for each SAFE after they're saved
mapping(bytes32 => mapping(address => uint256)) public desiredCollateralizationRatios;
// --- Constants ---
uint256 public constant MAX_CRATIO = 1000;
uint256 public constant CRATIO_SCALE_DOWN = 10**25;
// --- Boolean Logic ---
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y) }
}
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(bytes32 indexed parameter, address data);
event SetDefaultCRatio(bytes32 indexed collateralType, uint256 cRatio);
event SetMinDesiredCollateralizationRatio(
bytes32 indexed collateralType,
uint256 cRatio
);
event SetDesiredCollateralizationRatio(
address indexed caller,
bytes32 indexed collateralType,
uint256 safeID,
address indexed safeHandler,
uint256 cRatio
);
// --- Functions ---
function setDefaultCRatio(bytes32, uint256) virtual external;
function setMinDesiredCollateralizationRatio(bytes32 collateralType, uint256 cRatio) virtual external;
function setDesiredCollateralizationRatio(bytes32 collateralType, uint256 safeID, uint256 cRatio) virtual external;
}
////// src/interfaces/UniswapLiquidityManagerLike.sol
/* pragma solidity 0.6.7; */
abstract contract UniswapLiquidityManagerLike {
function getToken0FromLiquidity(uint256) virtual public view returns (uint256);
function getToken1FromLiquidity(uint256) virtual public view returns (uint256);
function getLiquidityFromToken0(uint256) virtual public view returns (uint256);
function getLiquidityFromToken1(uint256) virtual public view returns (uint256);
function removeLiquidity(
uint256 liquidity,
uint128 amount0Min,
uint128 amount1Min,
address to
) public virtual returns (uint256, uint256);
}
////// src/math/SafeMath.sol
// 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.
*/
contract SafeMath_2 {
/**
* @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) {
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;
}
}
////// src/saviours/NativeUnderlyingUniswapV2SafeSaviour.sol
// Copyright (C) 2021 Reflexer Labs, INC
// 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.6.7; */
/* import "../interfaces/UniswapLiquidityManagerLike.sol"; */
/* import "../interfaces/SaviourCRatioSetterLike.sol"; */
/* import "../interfaces/SafeSaviourLike.sol"; */
/* import "../math/SafeMath.sol"; */
contract NativeUnderlyingUniswapV2SafeSaviour is SafeMath_2, SafeSaviourLike {
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "NativeUnderlyingUniswapV2SafeSaviour/account-not-authorized");
_;
}
mapping (address => uint256) public allowedUsers;
/**
* @notice Allow a user to deposit assets
* @param usr User to whitelist
*/
function allowUser(address usr) external isAuthorized {
allowedUsers[usr] = 1;
emit AllowUser(usr);
}
/**
* @notice Disallow a user from depositing assets
* @param usr User to disallow
*/
function disallowUser(address usr) external isAuthorized {
allowedUsers[usr] = 0;
emit DisallowUser(usr);
}
/**
* @notice Checks whether an address is an allowed user
**/
modifier isAllowed {
require(
either(restrictUsage == 0, both(restrictUsage == 1, allowedUsers[msg.sender] == 1)),
"NativeUnderlyingUniswapV2SafeSaviour/account-not-allowed"
);
_;
}
// --- Structs ---
struct Reserves {
uint256 systemCoins;
uint256 collateralCoins;
}
// --- Variables ---
// Flag that tells whether usage of the contract is restricted to allowed users
uint256 public restrictUsage;
// Whether the system coin is token0 in the Uniswap pool or not
bool public isSystemCoinToken0;
// Amount of LP tokens currently protecting each position
mapping(address => uint256) public lpTokenCover;
// Amount of system coin/collateral tokens that Safe owners can get back
mapping(address => Reserves) public underlyingReserves;
// Liquidity manager contract for Uniswap v2/v3
UniswapLiquidityManagerLike public liquidityManager;
// The ERC20 system coin
ERC20Like public systemCoin;
// The system coin join contract
CoinJoinLike public coinJoin;
// The collateral join contract for adding collateral in the system
CollateralJoinLike public collateralJoin;
// The LP token
ERC20Like public lpToken;
// The collateral token
ERC20Like public collateralToken;
// Oracle providing the system coin price feed
PriceFeedLike public systemCoinOrcl;
// Contract that defines desired CRatios for each Safe after it is saved
SaviourCRatioSetterLike public cRatioSetter;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event AllowUser(address usr);
event DisallowUser(address usr);
event ModifyParameters(bytes32 indexed parameter, uint256 val);
event ModifyParameters(bytes32 indexed parameter, address data);
event Deposit(
address indexed caller,
address indexed safeHandler,
uint256 lpTokenAmount
);
event Withdraw(
address indexed caller,
address indexed safeHandler,
address dst,
uint256 lpTokenAmount
);
event GetReserves(
address indexed caller,
address indexed safeHandler,
uint256 systemCoinAmount,
uint256 collateralAmount,
address dst
);
constructor(
bool isSystemCoinToken0_,
address coinJoin_,
address collateralJoin_,
address cRatioSetter_,
address systemCoinOrcl_,
address liquidationEngine_,
address taxCollector_,
address oracleRelayer_,
address safeManager_,
address saviourRegistry_,
address liquidityManager_,
address lpToken_,
uint256 minKeeperPayoutValue_
) public {
require(coinJoin_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-coin-join");
require(collateralJoin_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-collateral-join");
require(cRatioSetter_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-cratio-setter");
require(systemCoinOrcl_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-system-coin-oracle");
require(oracleRelayer_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-oracle-relayer");
require(liquidationEngine_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-liquidation-engine");
require(taxCollector_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-tax-collector");
require(safeManager_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-safe-manager");
require(saviourRegistry_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-saviour-registry");
require(liquidityManager_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-liq-manager");
require(lpToken_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-lp-token");
require(minKeeperPayoutValue_ > 0, "NativeUnderlyingUniswapV2SafeSaviour/invalid-min-payout-value");
authorizedAccounts[msg.sender] = 1;
isSystemCoinToken0 = isSystemCoinToken0_;
minKeeperPayoutValue = minKeeperPayoutValue_;
coinJoin = CoinJoinLike(coinJoin_);
collateralJoin = CollateralJoinLike(collateralJoin_);
cRatioSetter = SaviourCRatioSetterLike(cRatioSetter_);
liquidationEngine = LiquidationEngineLike_3(liquidationEngine_);
taxCollector = TaxCollectorLike(taxCollector_);
oracleRelayer = OracleRelayerLike_2(oracleRelayer_);
systemCoinOrcl = PriceFeedLike(systemCoinOrcl_);
systemCoin = ERC20Like(coinJoin.systemCoin());
safeEngine = SAFEEngineLike_8(coinJoin.safeEngine());
safeManager = GebSafeManagerLike(safeManager_);
saviourRegistry = SAFESaviourRegistryLike(saviourRegistry_);
liquidityManager = UniswapLiquidityManagerLike(liquidityManager_);
lpToken = ERC20Like(lpToken_);
collateralToken = ERC20Like(collateralJoin.collateral());
systemCoinOrcl.getResultWithValidity();
oracleRelayer.redemptionPrice();
require(collateralJoin.contractEnabled() == 1, "NativeUnderlyingUniswapV2SafeSaviour/join-disabled");
require(address(collateralToken) != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-col-token");
require(address(safeEngine) != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-safe-engine");
require(address(systemCoin) != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-sys-coin");
emit AddAuthorization(msg.sender);
emit ModifyParameters("minKeeperPayoutValue", minKeeperPayoutValue);
emit ModifyParameters("oracleRelayer", oracleRelayer_);
emit ModifyParameters("taxCollector", taxCollector_);
emit ModifyParameters("systemCoinOrcl", systemCoinOrcl_);
emit ModifyParameters("liquidationEngine", liquidationEngine_);
emit ModifyParameters("liquidityManager", liquidityManager_);
}
// --- Administration ---
/**
* @notice Modify an uint256 param
* @param parameter The name of the parameter
* @param val New value for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 val) external isAuthorized {
if (parameter == "minKeeperPayoutValue") {
require(val > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-min-payout");
minKeeperPayoutValue = val;
}
else if (parameter == "restrictUsage") {
require(val <= 1, "NativeUnderlyingUniswapV2SafeSaviour/invalid-restriction");
restrictUsage = val;
}
else revert("NativeUnderlyingUniswapV2SafeSaviour/modify-unrecognized-param");
emit ModifyParameters(parameter, val);
}
/**
* @notice Modify an address param
* @param parameter The name of the parameter
* @param data New address for the parameter
*/
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
require(data != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-data");
if (parameter == "systemCoinOrcl") {
systemCoinOrcl = PriceFeedLike(data);
systemCoinOrcl.getResultWithValidity();
}
else if (parameter == "oracleRelayer") {
oracleRelayer = OracleRelayerLike_2(data);
oracleRelayer.redemptionPrice();
}
else if (parameter == "liquidityManager") {
liquidityManager = UniswapLiquidityManagerLike(data);
}
else if (parameter == "liquidationEngine") {
liquidationEngine = LiquidationEngineLike_3(data);
}
else if (parameter == "taxCollector") {
taxCollector = TaxCollectorLike(data);
}
else revert("NativeUnderlyingUniswapV2SafeSaviour/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
// --- Transferring Reserves ---
/*
* @notify Get back system coins or collateral tokens that were withdrawn from Uniswap and not used to save a specific SAFE
* @param safeID The ID of the safe that was previously saved and has leftover funds that can be withdrawn
* @param dst The address that will receive
*/
function getReserves(uint256 safeID, address dst) external controlsSAFE(msg.sender, safeID) nonReentrant {
address safeHandler = safeManager.safes(safeID);
(uint256 systemCoins, uint256 collateralCoins) =
(underlyingReserves[safeHandler].systemCoins, underlyingReserves[safeHandler].collateralCoins);
require(either(systemCoins > 0, collateralCoins > 0), "NativeUnderlyingUniswapV2SafeSaviour/no-reserves");
delete(underlyingReserves[safeManager.safes(safeID)]);
if (systemCoins > 0) {
systemCoin.transfer(dst, systemCoins);
}
if (collateralCoins > 0) {
collateralToken.transfer(dst, collateralCoins);
}
emit GetReserves(msg.sender, safeHandler, systemCoins, collateralCoins, dst);
}
// --- Adding/Withdrawing Cover ---
/*
* @notice Deposit lpToken in the contract in order to provide cover for a specific SAFE managed by the SAFE Manager
* @param safeID The ID of the SAFE to protect. This ID should be registered inside GebSafeManager
* @param lpTokenAmount The amount of collateralToken to deposit
*/
function deposit(uint256 safeID, uint256 lpTokenAmount) external isAllowed() liquidationEngineApproved(address(this)) nonReentrant {
require(lpTokenAmount > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-lp-amount");
// Check that the SAFE exists inside GebSafeManager
address safeHandler = safeManager.safes(safeID);
require(safeHandler != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-handler");
// Check that the SAFE has debt
(, uint256 safeDebt) =
SAFEEngineLike_8(collateralJoin.safeEngine()).safes(collateralJoin.collateralType(), safeHandler);
require(safeDebt > 0, "NativeUnderlyingUniswapV2SafeSaviour/safe-does-not-have-debt");
// Update the lpToken balance used to cover the SAFE and transfer tokens to this contract
lpTokenCover[safeHandler] = add(lpTokenCover[safeHandler], lpTokenAmount);
require(lpToken.transferFrom(msg.sender, address(this), lpTokenAmount), "NativeUnderlyingUniswapV2SafeSaviour/could-not-transfer-lp");
emit Deposit(msg.sender, safeHandler, lpTokenAmount);
}
/*
* @notice Withdraw lpToken from the contract and provide less cover for a SAFE
* @dev Only an address that controls the SAFE inside the SAFE Manager can call this
* @param safeID The ID of the SAFE to remove cover from. This ID should be registered inside the SAFE Manager
* @param lpTokenAmount The amount of lpToken to withdraw
* @param dst The address that will receive the LP tokens
*/
function withdraw(uint256 safeID, uint256 lpTokenAmount, address dst) external controlsSAFE(msg.sender, safeID) nonReentrant {
require(lpTokenAmount > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-lp-amount");
// Fetch the handler from the SAFE manager
address safeHandler = safeManager.safes(safeID);
require(lpTokenCover[safeHandler] >= lpTokenAmount, "NativeUnderlyingUniswapV2SafeSaviour/not-enough-to-withdraw");
// Withdraw cover and transfer collateralToken to the caller
lpTokenCover[safeHandler] = sub(lpTokenCover[safeHandler], lpTokenAmount);
lpToken.transfer(dst, lpTokenAmount);
emit Withdraw(msg.sender, safeHandler, dst, lpTokenAmount);
}
// --- Saving Logic ---
/*
* @notice Saves a SAFE by withdrawing liquidity and repaying debt and/or adding more collateral
* @dev Only the LiquidationEngine can call this
* @param keeper The keeper that called LiquidationEngine.liquidateSAFE and that should be rewarded for spending gas to save a SAFE
* @param collateralType The collateral type backing the SAFE that's being liquidated
* @param safeHandler The handler of the SAFE that's being liquidated
* @return Whether the SAFE has been saved, the amount of LP tokens that were used to withdraw liquidity as well as the amount of
* system coins sent to the keeper as their payment (this implementation always returns 0)
*/
function saveSAFE(address keeper, bytes32 collateralType, address safeHandler) override external returns (bool, uint256, uint256) {
require(address(liquidationEngine) == msg.sender, "NativeUnderlyingUniswapV2SafeSaviour/caller-not-liquidation-engine");
require(keeper != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-keeper-address");
if (both(both(collateralType == "", safeHandler == address(0)), keeper == address(liquidationEngine))) {
return (true, uint(-1), uint(-1));
}
// Check that this is handling the correct collateral
require(collateralType == collateralJoin.collateralType(), "NativeUnderlyingUniswapV2SafeSaviour/invalid-collateral-type");
// Check that the SAFE has a non null amount of LP tokens covering it
require(lpTokenCover[safeHandler] > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-cover");
// Tax the collateral
taxCollector.taxSingle(collateralType);
// Get the amount of tokens used to top up the SAFE
(uint256 safeDebtRepaid, uint256 safeCollateralAdded) =
getTokensForSaving(safeHandler, oracleRelayer.redemptionPrice());
// There must be tokens used to save the SAVE
require(either(safeDebtRepaid > 0, safeCollateralAdded > 0), "NativeUnderlyingUniswapV2SafeSaviour/cannot-save-safe");
// Get the amounts of tokens sent to the keeper as payment
(uint256 keeperSysCoins, uint256 keeperCollateralCoins) =
getKeeperPayoutTokens(safeHandler, oracleRelayer.redemptionPrice(), safeDebtRepaid, safeCollateralAdded);
// There must be tokens that go to the keeper
require(either(keeperSysCoins > 0, keeperCollateralCoins > 0), "NativeUnderlyingUniswapV2SafeSaviour/cannot-pay-keeper");
// Store cover amount in local var
uint256 totalCover = lpTokenCover[safeHandler];
delete(lpTokenCover[safeHandler]);
// Mark the SAFE in the registry as just having been saved
saviourRegistry.markSave(collateralType, safeHandler);
// Withdraw all liquidity
uint256 sysCoinBalance = systemCoin.balanceOf(address(this));
uint256 collateralCoinBalance = collateralToken.balanceOf(address(this));
lpToken.approve(address(liquidityManager), totalCover);
liquidityManager.removeLiquidity(totalCover, 0, 0, address(this));
// Checks after removing liquidity
require(
either(systemCoin.balanceOf(address(this)) > sysCoinBalance, collateralToken.balanceOf(address(this)) > collateralCoinBalance),
"NativeUnderlyingUniswapV2SafeSaviour/faulty-remove-liquidity"
);
// Compute remaining balances of tokens that will go into reserves
sysCoinBalance = sub(sub(systemCoin.balanceOf(address(this)), sysCoinBalance), add(safeDebtRepaid, keeperSysCoins));
collateralCoinBalance = sub(
sub(collateralToken.balanceOf(address(this)), collateralCoinBalance), add(safeCollateralAdded, keeperCollateralCoins)
);
// Update reserves
if (sysCoinBalance > 0) {
underlyingReserves[safeHandler].systemCoins = add(
underlyingReserves[safeHandler].systemCoins, sysCoinBalance
);
}
if (collateralCoinBalance > 0) {
underlyingReserves[safeHandler].collateralCoins = add(
underlyingReserves[safeHandler].collateralCoins, collateralCoinBalance
);
}
// Save the SAFE
if (safeDebtRepaid > 0) {
// Approve the coin join contract to take system coins and repay debt
systemCoin.approve(address(coinJoin), safeDebtRepaid);
// Calculate the non adjusted system coin amount
uint256 nonAdjustedSystemCoinsToRepay = div(mul(safeDebtRepaid, RAY), getAccumulatedRate(collateralType));
// Join system coins in the system and repay the SAFE's debt
coinJoin.join(address(this), safeDebtRepaid);
safeEngine.modifySAFECollateralization(
collateralType,
safeHandler,
address(0),
address(this),
int256(0),
-int256(nonAdjustedSystemCoinsToRepay)
);
}
if (safeCollateralAdded > 0) {
// Approve collateralToken to the collateral join contract
collateralToken.approve(address(collateralJoin), safeCollateralAdded);
// Join collateralToken in the system and add it in the saved SAFE
collateralJoin.join(address(this), safeCollateralAdded);
safeEngine.modifySAFECollateralization(
collateralType,
safeHandler,
address(this),
address(0),
int256(safeCollateralAdded),
int256(0)
);
}
// Pay keeper
if (keeperSysCoins > 0) {
systemCoin.transfer(keeper, keeperSysCoins);
}
if (keeperCollateralCoins > 0) {
collateralToken.transfer(keeper, keeperCollateralCoins);
}
// Emit an event
emit SaveSAFE(keeper, collateralType, safeHandler, totalCover);
return (true, totalCover, 0);
}
// --- Getters ---
/*
* @notify Must be implemented according to the interface although it always returns 0
*/
function getKeeperPayoutValue() override public returns (uint256) {
return 0;
}
/*
* @notify Must be implemented according to the interface although it always returns false
*/
function keeperPayoutExceedsMinValue() override public returns (bool) {
return false;
}
/*
* @notice Determine whether a SAFE can be saved with the current amount of lpTokenCover deposited as cover for it
* @param safeHandler The handler of the SAFE which the function takes into account
* @return Whether the SAFE can be saved or not
*/
function canSave(bytes32, address safeHandler) override external returns (bool) {
// Fetch the redemption price first
uint256 redemptionPrice = oracleRelayer.redemptionPrice();
// Fetch the amount of tokens used to save the SAFE
(uint256 safeDebtRepaid, uint256 safeCollateralAdded) =
getTokensForSaving(safeHandler, redemptionPrice);
// Fetch the amount of tokens sent to the keeper
(uint256 keeperSysCoins, uint256 keeperCollateralCoins) =
getKeeperPayoutTokens(safeHandler, redemptionPrice, safeDebtRepaid, safeCollateralAdded);
// If there are some tokens used to save the SAFE and some tokens used to repay the keeper, return true
if (both(
either(safeDebtRepaid > 0, safeCollateralAdded > 0),
either(keeperSysCoins > 0, keeperCollateralCoins > 0)
)) {
return true;
}
return false;
}
/*
* @notice Return the total amount of LP tokens covering a specific SAFE
* @param collateralType The SAFE collateral type (ignored in this implementation)
* @param safeHandler The handler of the SAFE which the function takes into account
* @return The total LP token cover for a specific SAFE
*/
function tokenAmountUsedToSave(bytes32, address safeHandler) override public returns (uint256) {
return lpTokenCover[safeHandler];
}
/*
* @notify Fetch the collateral's price
*/
function getCollateralPrice() public view returns (uint256) {
(address ethFSM,,) = oracleRelayer.collateralTypes(collateralJoin.collateralType());
if (ethFSM == address(0)) return 0;
(uint256 priceFeedValue, bool hasValidValue) = PriceFeedLike(ethFSM).getResultWithValidity();
if (!hasValidValue) return 0;
return priceFeedValue;
}
/*
* @notify Fetch the system coin's market price
*/
function getSystemCoinMarketPrice() public view returns (uint256) {
(uint256 priceFeedValue, bool hasValidValue) = systemCoinOrcl.getResultWithValidity();
if (!hasValidValue) return 0;
return priceFeedValue;
}
/*
* @notify Get the target collateralization ratio that a SAFE should have after it's saved
* @param safeHandler The handler/address of the SAFE whose target collateralization ratio is retrieved
*/
function getTargetCRatio(address safeHandler) public view returns (uint256) {
bytes32 collateralType = collateralJoin.collateralType();
uint256 defaultCRatio = cRatioSetter.defaultDesiredCollateralizationRatios(collateralType);
uint256 targetCRatio = (cRatioSetter.desiredCollateralizationRatios(collateralType, safeHandler) == 0) ?
defaultCRatio : cRatioSetter.desiredCollateralizationRatios(collateralType, safeHandler);
return targetCRatio;
}
/*
* @notify Return the amount of system coins and collateral tokens retrieved from the LP position covering a specific SAFE
* @param safeHandler The handler/address of the targeted SAFE
*/
function getLPUnderlying(address safeHandler) public view returns (uint256, uint256) {
uint256 coverAmount = lpTokenCover[safeHandler];
if (coverAmount == 0) return (0, 0);
(uint256 sysCoinsFromLP, uint256 collateralFromLP) = (isSystemCoinToken0) ?
(liquidityManager.getToken0FromLiquidity(coverAmount), liquidityManager.getToken1FromLiquidity(coverAmount)) :
(liquidityManager.getToken1FromLiquidity(coverAmount), liquidityManager.getToken0FromLiquidity(coverAmount));
return (sysCoinsFromLP, collateralFromLP);
}
/*
* @notice Return the amount of system coins and/or collateral tokens used to save a SAFE
* @param safeHandler The handler/address of the targeted SAFE
* @param redemptionPrice The system coin redemption price used in calculations
*/
function getTokensForSaving(address safeHandler, uint256 redemptionPrice)
public view returns (uint256, uint256) {
if (either(lpTokenCover[safeHandler] == 0, redemptionPrice == 0)) {
return (0, 0);
}
// Get the default CRatio for the SAFE
(uint256 depositedCollateralToken, uint256 safeDebt) =
SAFEEngineLike_8(collateralJoin.safeEngine()).safes(collateralJoin.collateralType(), safeHandler);
uint256 targetCRatio = getTargetCRatio(safeHandler);
if (either(safeDebt == 0, targetCRatio == 0)) {
return (0, 0);
}
// Get the collateral market price
uint256 collateralPrice = getCollateralPrice();
if (collateralPrice == 0) {
return (0, 0);
}
// Calculate how much debt would need to be repaid
uint256 debtToRepay = mul(
mul(HUNDRED, mul(depositedCollateralToken, collateralPrice) / WAD) / targetCRatio, RAY
) / redemptionPrice;
if (either(debtToRepay >= safeDebt, debtBelowFloor(collateralJoin.collateralType(), debtToRepay))) {
return (0, 0);
}
safeDebt = mul(safeDebt, getAccumulatedRate(collateralJoin.collateralType())) / RAY;
debtToRepay = sub(safeDebt, debtToRepay);
// Calculate underlying amounts received from LP withdrawal
(uint256 sysCoinsFromLP, uint256 collateralFromLP) = getLPUnderlying(safeHandler);
// Determine total debt to repay; return if the SAFE can be saved solely by repaying debt, continue calculations otherwise
if (sysCoinsFromLP >= debtToRepay) {
return (debtToRepay, 0);
} else {
// Calculate the amount of collateral that would need to be added to the SAFE
uint256 scaledDownDebtValue = mul(add(mul(redemptionPrice, sub(safeDebt, sysCoinsFromLP)) / RAY, ONE), targetCRatio) / HUNDRED;
uint256 collateralTokenNeeded = div(mul(scaledDownDebtValue, WAD), collateralPrice);
collateralTokenNeeded = (depositedCollateralToken < collateralTokenNeeded) ?
sub(collateralTokenNeeded, depositedCollateralToken) : MAX_UINT;
// See if there's enough collateral to add to the SAFE in order to save it
if (collateralTokenNeeded <= collateralFromLP) {
return (sysCoinsFromLP, collateralTokenNeeded);
} else {
return (0, 0);
}
}
}
/*
* @notice Return the amount of system coins and/or collateral tokens used to pay a keeper
* @param safeHandler The handler/address of the targeted SAFE
* @param redemptionPrice The system coin redemption price used in calculations
* @param safeDebtRepaid The amount of system coins that are already used to save the targeted SAFE
* @param safeCollateralAdded The amount of collateral tokens that are already used to save the targeted SAFE
*/
function getKeeperPayoutTokens(address safeHandler, uint256 redemptionPrice, uint256 safeDebtRepaid, uint256 safeCollateralAdded)
public view returns (uint256, uint256) {
// Get the system coin and collateral market prices
uint256 collateralPrice = getCollateralPrice();
uint256 sysCoinMarketPrice = getSystemCoinMarketPrice();
if (either(collateralPrice == 0, sysCoinMarketPrice == 0)) {
return (0, 0);
}
// Calculate underlying amounts received from LP withdrawal
(uint256 sysCoinsFromLP, uint256 collateralFromLP) = getLPUnderlying(safeHandler);
// Check if the keeper can get system coins and if yes, compute how many
uint256 keeperSysCoins;
if (sysCoinsFromLP > safeDebtRepaid) {
uint256 remainingSystemCoins = sub(sysCoinsFromLP, safeDebtRepaid);
uint256 payoutInSystemCoins = div(mul(minKeeperPayoutValue, WAD), sysCoinMarketPrice);
if (payoutInSystemCoins <= remainingSystemCoins) {
return (payoutInSystemCoins, 0);
} else {
keeperSysCoins = remainingSystemCoins;
}
}
// Calculate how much collateral the keeper will get
if (collateralFromLP <= safeCollateralAdded) return (0, 0);
uint256 remainingCollateral = sub(collateralFromLP, safeCollateralAdded);
uint256 remainingKeeperPayoutValue = sub(minKeeperPayoutValue, mul(keeperSysCoins, sysCoinMarketPrice) / WAD);
uint256 collateralTokenNeeded = div(mul(remainingKeeperPayoutValue, WAD), collateralPrice);
// If there are enough collateral tokens retreived from LP in order to pay the keeper, return the token amounts
if (collateralTokenNeeded <= remainingCollateral) {
return (keeperSysCoins, collateralTokenNeeded);
} else {
// Otherwise, return zeroes
return (0, 0);
}
}
/*
* @notify Returns whether a target debt amount is below the debt floor of a specific collateral type
* @param collateralType The collateral type whose floor we compare against
* @param targetDebtAmount The target debt amount for a SAFE that has collateralType collateral in it
*/
function debtBelowFloor(bytes32 collateralType, uint256 targetDebtAmount) public view returns (bool) {
(, , , , uint256 debtFloor, ) = safeEngine.collateralTypes(collateralType);
return (mul(targetDebtAmount, RAY) < debtFloor);
}
/*
* @notify Get the accumulated interest rate for a specific collateral type
* @param The collateral type for which to retrieve the rate
*/
function getAccumulatedRate(bytes32 collateralType)
public view returns (uint256 accumulatedRate) {
(, accumulatedRate, , , , ) = safeEngine.collateralTypes(collateralType);
}
}
|
Return the amount of system coins and/or collateral tokens used to save a SAFE safeHandler The handler/address of the targeted SAFE redemptionPrice The system coin redemption price used in calculations/ Determine total debt to repay; return if the SAFE can be saved solely by repaying debt, continue calculations otherwise Calculate the amount of collateral that would need to be added to the SAFE See if there's enough collateral to add to the SAFE in order to save it
|
function getTokensForSaving(address safeHandler, uint256 redemptionPrice)
public view returns (uint256, uint256) {
if (either(lpTokenCover[safeHandler] == 0, redemptionPrice == 0)) {
return (0, 0);
}
SAFEEngineLike_8(collateralJoin.safeEngine()).safes(collateralJoin.collateralType(), safeHandler);
uint256 targetCRatio = getTargetCRatio(safeHandler);
if (either(safeDebt == 0, targetCRatio == 0)) {
return (0, 0);
}
if (collateralPrice == 0) {
return (0, 0);
}
mul(HUNDRED, mul(depositedCollateralToken, collateralPrice) / WAD) / targetCRatio, RAY
) / redemptionPrice;
if (either(debtToRepay >= safeDebt, debtBelowFloor(collateralJoin.collateralType(), debtToRepay))) {
return (0, 0);
}
safeDebt = mul(safeDebt, getAccumulatedRate(collateralJoin.collateralType())) / RAY;
debtToRepay = sub(safeDebt, debtToRepay);
if (sysCoinsFromLP >= debtToRepay) {
return (debtToRepay, 0);
uint256 scaledDownDebtValue = mul(add(mul(redemptionPrice, sub(safeDebt, sysCoinsFromLP)) / RAY, ONE), targetCRatio) / HUNDRED;
uint256 collateralTokenNeeded = div(mul(scaledDownDebtValue, WAD), collateralPrice);
collateralTokenNeeded = (depositedCollateralToken < collateralTokenNeeded) ?
sub(collateralTokenNeeded, depositedCollateralToken) : MAX_UINT;
if (collateralTokenNeeded <= collateralFromLP) {
return (sysCoinsFromLP, collateralTokenNeeded);
return (0, 0);
}
}
}
| 8,087
|
/**
*Submitted for verification at Etherscan.io on 2021-06-17
*/
pragma solidity 0.6.7;
abstract contract SAFEEngineLike {
function transferInternalCoins(address,address,uint256) virtual external;
function transferCollateral(bytes32,address,address,uint256) virtual external;
}
abstract contract OracleRelayerLike {
function redemptionPrice() virtual public returns (uint256);
}
abstract contract OracleLike {
function priceSource() virtual public view returns (address);
function getResultWithValidity() virtual public view returns (uint256, bool);
}
abstract contract LiquidationEngineLike {
function removeCoinsFromAuction(uint256) virtual public;
function addAuthorization(address) external virtual;
function removeAuthorization(address) external virtual;
function modifyParameters(bytes32,bytes32,address) external virtual;
function collateralTypes(bytes32) virtual public view returns (
IncreasingDiscountCollateralAuctionHouse collateralAuctionHouse,
uint256 liquidationPenalty, // [wad]
uint256 liquidationQuantity // [rad]
);
}
/// IncreasingDiscountCollateralAuctionHouse.sol
// Copyright (C) 2018 Rain <[email protected]>, 2020 Reflexer Labs, INC
//
// This program 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.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/*
This thing lets you sell some collateral at an increasing discount in order to instantly recapitalize the system
*/
contract IncreasingDiscountCollateralAuctionHouse {
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "IncreasingDiscountCollateralAuctionHouse/account-not-authorized");
_;
}
// --- Data ---
struct Bid {
// How much collateral is sold in an auction
uint256 amountToSell; // [wad]
// Total/max amount of coins to raise
uint256 amountToRaise; // [rad]
// Current discount
uint256 currentDiscount; // [wad]
// Max possibe discount
uint256 maxDiscount; // [wad]
// Rate at which the discount is updated every second
uint256 perSecondDiscountUpdateRate; // [ray]
// Last time when the current discount was updated
uint256 latestDiscountUpdateTime; // [unix timestamp]
// Deadline after which the discount cannot increase anymore
uint48 discountIncreaseDeadline; // [unix epoch time]
// Who (which SAFE) receives leftover collateral that is not sold in the auction; usually the liquidated SAFE
address forgoneCollateralReceiver;
// Who receives the coins raised by the auction; usually the accounting engine
address auctionIncomeRecipient;
}
// Bid data for each separate auction
mapping (uint256 => Bid) public bids;
// SAFE database
SAFEEngineLike public safeEngine;
// Collateral type name
bytes32 public collateralType;
// Minimum acceptable bid
uint256 public minimumBid = 5 * WAD; // [wad]
// Total length of the auction. Kept to adhere to the same interface as the English auction but redundant
uint48 public totalAuctionLength = uint48(-1); // [seconds]
// Number of auctions started up until now
uint256 public auctionsStarted = 0;
// The last read redemption price
uint256 public lastReadRedemptionPrice;
// Minimum discount (compared to the system coin's current redemption price) at which collateral is being sold
uint256 public minDiscount = 0.95E18; // 5% discount // [wad]
// Maximum discount (compared to the system coin's current redemption price) at which collateral is being sold
uint256 public maxDiscount = 0.95E18; // 5% discount // [wad]
// Rate at which the discount will be updated in an auction
uint256 public perSecondDiscountUpdateRate = RAY; // [ray]
// Max time over which the discount can be updated
uint256 public maxDiscountUpdateRateTimeline = 1 hours; // [seconds]
// Max lower bound deviation that the collateral median can have compared to the FSM price
uint256 public lowerCollateralMedianDeviation = 0.90E18; // 10% deviation // [wad]
// Max upper bound deviation that the collateral median can have compared to the FSM price
uint256 public upperCollateralMedianDeviation = 0.95E18; // 5% deviation // [wad]
// Max lower bound deviation that the system coin oracle price feed can have compared to the systemCoinOracle price
uint256 public lowerSystemCoinMedianDeviation = WAD; // 0% deviation // [wad]
// Max upper bound deviation that the system coin oracle price feed can have compared to the systemCoinOracle price
uint256 public upperSystemCoinMedianDeviation = WAD; // 0% deviation // [wad]
// Min deviation for the system coin median result compared to the redemption price in order to take the median into account
uint256 public minSystemCoinMedianDeviation = 0.999E18; // [wad]
OracleRelayerLike public oracleRelayer;
OracleLike public collateralFSM;
OracleLike public systemCoinOracle;
LiquidationEngineLike public liquidationEngine;
bytes32 public constant AUCTION_HOUSE_TYPE = bytes32("COLLATERAL");
bytes32 public constant AUCTION_TYPE = bytes32("INCREASING_DISCOUNT");
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event StartAuction(
uint256 id,
uint256 auctionsStarted,
uint256 amountToSell,
uint256 initialBid,
uint256 indexed amountToRaise,
uint256 startingDiscount,
uint256 maxDiscount,
uint256 perSecondDiscountUpdateRate,
uint48 discountIncreaseDeadline,
address indexed forgoneCollateralReceiver,
address indexed auctionIncomeRecipient
);
event ModifyParameters(bytes32 parameter, uint256 data);
event ModifyParameters(bytes32 parameter, address data);
event BuyCollateral(uint256 indexed id, uint256 wad, uint256 boughtCollateral);
event SettleAuction(uint256 indexed id, uint256 leftoverCollateral);
event TerminateAuctionPrematurely(uint256 indexed id, address sender, uint256 collateralAmount);
// --- Init ---
constructor(address safeEngine_, address liquidationEngine_, bytes32 collateralType_) public {
safeEngine = SAFEEngineLike(safeEngine_);
liquidationEngine = LiquidationEngineLike(liquidationEngine_);
collateralType = collateralType_;
authorizedAccounts[msg.sender] = 1;
emit AddAuthorization(msg.sender);
}
// --- Math ---
function addUint48(uint48 x, uint48 y) internal pure returns (uint48 z) {
require((z = x + y) >= x, "IncreasingDiscountCollateralAuctionHouse/add-uint48-overflow");
}
function addUint256(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "IncreasingDiscountCollateralAuctionHouse/add-uint256-overflow");
}
function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "IncreasingDiscountCollateralAuctionHouse/sub-underflow");
}
function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "IncreasingDiscountCollateralAuctionHouse/mul-overflow");
}
uint256 constant WAD = 10 ** 18;
function wmultiply(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = multiply(x, y) / WAD;
}
uint256 constant RAY = 10 ** 27;
function rdivide(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y > 0, "IncreasingDiscountCollateralAuctionHouse/rdiv-by-zero");
z = multiply(x, RAY) / y;
}
function rmultiply(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x * y;
require(y == 0 || z / y == x, "IncreasingDiscountCollateralAuctionHouse/rmul-overflow");
z = z / RAY;
}
function wdivide(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y > 0, "IncreasingDiscountCollateralAuctionHouse/wdiv-by-zero");
z = multiply(x, WAD) / y;
}
function minimum(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = (x <= y) ? x : y;
}
function maximum(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = (x >= y) ? x : y;
}
function rpower(uint256 x, uint256 n, uint256 b) internal pure returns (uint256 z) {
assembly {
switch x case 0 {switch n case 0 {z := b} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := b } default { z := x }
let half := div(b, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, b)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, b)
}
}
}
}
}
// --- General Utils ---
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y)}
}
// --- Admin ---
/**
* @notice Modify an uint256 parameter
* @param parameter The name of the parameter to modify
* @param data New value for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "minDiscount") {
require(both(data >= maxDiscount, data < WAD), "IncreasingDiscountCollateralAuctionHouse/invalid-min-discount");
minDiscount = data;
}
else if (parameter == "maxDiscount") {
require(both(both(data <= minDiscount, data < WAD), data > 0), "IncreasingDiscountCollateralAuctionHouse/invalid-max-discount");
maxDiscount = data;
}
else if (parameter == "perSecondDiscountUpdateRate") {
require(data <= RAY, "IncreasingDiscountCollateralAuctionHouse/invalid-discount-update-rate");
perSecondDiscountUpdateRate = data;
}
else if (parameter == "maxDiscountUpdateRateTimeline") {
require(both(data > 0, uint256(uint48(-1)) > addUint256(now, data)), "IncreasingDiscountCollateralAuctionHouse/invalid-update-rate-time");
maxDiscountUpdateRateTimeline = data;
}
else if (parameter == "lowerCollateralMedianDeviation") {
require(data <= WAD, "IncreasingDiscountCollateralAuctionHouse/invalid-lower-collateral-median-deviation");
lowerCollateralMedianDeviation = data;
}
else if (parameter == "upperCollateralMedianDeviation") {
require(data <= WAD, "IncreasingDiscountCollateralAuctionHouse/invalid-upper-collateral-median-deviation");
upperCollateralMedianDeviation = data;
}
else if (parameter == "lowerSystemCoinMedianDeviation") {
require(data <= WAD, "IncreasingDiscountCollateralAuctionHouse/invalid-lower-system-coin-median-deviation");
lowerSystemCoinMedianDeviation = data;
}
else if (parameter == "upperSystemCoinMedianDeviation") {
require(data <= WAD, "IncreasingDiscountCollateralAuctionHouse/invalid-upper-system-coin-median-deviation");
upperSystemCoinMedianDeviation = data;
}
else if (parameter == "minSystemCoinMedianDeviation") {
minSystemCoinMedianDeviation = data;
}
else if (parameter == "minimumBid") {
minimumBid = data;
}
else revert("IncreasingDiscountCollateralAuctionHouse/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/**
* @notice Modify an addres parameter
* @param parameter The parameter name
* @param data New address for the parameter
*/
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
if (parameter == "oracleRelayer") oracleRelayer = OracleRelayerLike(data);
else if (parameter == "collateralFSM") {
collateralFSM = OracleLike(data);
// Check that priceSource() is implemented
collateralFSM.priceSource();
}
else if (parameter == "systemCoinOracle") systemCoinOracle = OracleLike(data);
else if (parameter == "liquidationEngine") liquidationEngine = LiquidationEngineLike(data);
else revert("IncreasingDiscountCollateralAuctionHouse/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
// --- Private Auction Utils ---
/*
* @notify Get the amount of bought collateral from a specific auction using custom collateral price feeds, a system
* coin price feed and a custom discount
* @param id The ID of the auction to bid in and get collateral from
* @param collateralFsmPriceFeedValue The collateral price fetched from the FSM
* @param collateralMedianPriceFeedValue The collateral price fetched from the oracle median
* @param systemCoinPriceFeedValue The system coin market price fetched from the oracle
* @param adjustedBid The system coin bid
* @param customDiscount The discount offered
*/
function getBoughtCollateral(
uint256 id,
uint256 collateralFsmPriceFeedValue,
uint256 collateralMedianPriceFeedValue,
uint256 systemCoinPriceFeedValue,
uint256 adjustedBid,
uint256 customDiscount
) private view returns (uint256) {
// calculate the collateral price in relation to the latest system coin price and apply the discount
uint256 discountedCollateralPrice =
getDiscountedCollateralPrice(
collateralFsmPriceFeedValue,
collateralMedianPriceFeedValue,
systemCoinPriceFeedValue,
customDiscount
);
// calculate the amount of collateral bought
uint256 boughtCollateral = wdivide(adjustedBid, discountedCollateralPrice);
// if the calculated collateral amount exceeds the amount still up for sale, adjust it to the remaining amount
boughtCollateral = (boughtCollateral > bids[id].amountToSell) ? bids[id].amountToSell : boughtCollateral;
return boughtCollateral;
}
/*
* @notice Update the discount used in a particular auction
* @param id The id of the auction to update the discount for
* @returns The newly computed currentDiscount for the targeted auction
*/
function updateCurrentDiscount(uint256 id) private returns (uint256) {
// Work directly with storage
Bid storage auctionBidData = bids[id];
auctionBidData.currentDiscount = getNextCurrentDiscount(id);
auctionBidData.latestDiscountUpdateTime = now;
return auctionBidData.currentDiscount;
}
// --- Public Auction Utils ---
/*
* @notice Fetch the collateral median price (from the oracle, not FSM)
* @returns The collateral price from the oracle median; zero if the address of the collateralMedian (as fetched from the FSM) is null
*/
function getCollateralMedianPrice() public view returns (uint256 priceFeed) {
// Fetch the collateral median address from the collateral FSM
address collateralMedian;
try collateralFSM.priceSource() returns (address median) {
collateralMedian = median;
} catch (bytes memory revertReason) {}
if (collateralMedian == address(0)) return 0;
// wrapped call toward the collateral median
try OracleLike(collateralMedian).getResultWithValidity()
returns (uint256 price, bool valid) {
if (valid) {
priceFeed = uint256(price);
}
} catch (bytes memory revertReason) {
return 0;
}
}
/*
* @notice Fetch the system coin market price
* @returns The system coin market price fetch from the oracle
*/
function getSystemCoinMarketPrice() public view returns (uint256 priceFeed) {
if (address(systemCoinOracle) == address(0)) return 0;
// wrapped call toward the system coin oracle
try systemCoinOracle.getResultWithValidity()
returns (uint256 price, bool valid) {
if (valid) {
priceFeed = uint256(price) * 10 ** 9; // scale to RAY
}
} catch (bytes memory revertReason) {
return 0;
}
}
/*
* @notice Get the smallest possible price that's at max lowerSystemCoinMedianDeviation deviated from the redemption price and at least
* minSystemCoinMedianDeviation deviated
*/
function getSystemCoinFloorDeviatedPrice(uint256 redemptionPrice) public view returns (uint256 floorPrice) {
uint256 minFloorDeviatedPrice = wmultiply(redemptionPrice, minSystemCoinMedianDeviation);
floorPrice = wmultiply(redemptionPrice, lowerSystemCoinMedianDeviation);
floorPrice = (floorPrice <= minFloorDeviatedPrice) ? floorPrice : redemptionPrice;
}
/*
* @notice Get the highest possible price that's at max upperSystemCoinMedianDeviation deviated from the redemption price and at least
* minSystemCoinMedianDeviation deviated
*/
function getSystemCoinCeilingDeviatedPrice(uint256 redemptionPrice) public view returns (uint256 ceilingPrice) {
uint256 minCeilingDeviatedPrice = wmultiply(redemptionPrice, subtract(2 * WAD, minSystemCoinMedianDeviation));
ceilingPrice = wmultiply(redemptionPrice, subtract(2 * WAD, upperSystemCoinMedianDeviation));
ceilingPrice = (ceilingPrice >= minCeilingDeviatedPrice) ? ceilingPrice : redemptionPrice;
}
/*
* @notice Get the collateral price from the FSM and the final system coin price that will be used when bidding in an auction
* @param systemCoinRedemptionPrice The system coin redemption price
* @returns The collateral price from the FSM and the final system coin price used for bidding (picking between redemption and market prices)
*/
function getCollateralFSMAndFinalSystemCoinPrices(uint256 systemCoinRedemptionPrice) public view returns (uint256, uint256) {
require(systemCoinRedemptionPrice > 0, "IncreasingDiscountCollateralAuctionHouse/invalid-redemption-price-provided");
(uint256 collateralFsmPriceFeedValue, bool collateralFsmHasValidValue) = collateralFSM.getResultWithValidity();
if (!collateralFsmHasValidValue) {
return (0, 0);
}
uint256 systemCoinAdjustedPrice = systemCoinRedemptionPrice;
uint256 systemCoinPriceFeedValue = getSystemCoinMarketPrice();
if (systemCoinPriceFeedValue > 0) {
uint256 floorPrice = getSystemCoinFloorDeviatedPrice(systemCoinAdjustedPrice);
uint256 ceilingPrice = getSystemCoinCeilingDeviatedPrice(systemCoinAdjustedPrice);
if (uint(systemCoinPriceFeedValue) < systemCoinAdjustedPrice) {
systemCoinAdjustedPrice = maximum(uint256(systemCoinPriceFeedValue), floorPrice);
} else {
systemCoinAdjustedPrice = minimum(uint256(systemCoinPriceFeedValue), ceilingPrice);
}
}
return (uint256(collateralFsmPriceFeedValue), systemCoinAdjustedPrice);
}
/*
* @notice Get the collateral price used in bidding by picking between the raw FSM and the oracle median price and taking into account
* deviation limits
* @param collateralFsmPriceFeedValue The collateral price fetched from the FSM
* @param collateralMedianPriceFeedValue The collateral price fetched from the median attached to the FSM
*/
function getFinalBaseCollateralPrice(
uint256 collateralFsmPriceFeedValue,
uint256 collateralMedianPriceFeedValue
) public view returns (uint256) {
uint256 floorPrice = wmultiply(collateralFsmPriceFeedValue, lowerCollateralMedianDeviation);
uint256 ceilingPrice = wmultiply(collateralFsmPriceFeedValue, subtract(2 * WAD, upperCollateralMedianDeviation));
uint256 adjustedMedianPrice = (collateralMedianPriceFeedValue == 0) ?
collateralFsmPriceFeedValue : collateralMedianPriceFeedValue;
if (adjustedMedianPrice < collateralFsmPriceFeedValue) {
return maximum(adjustedMedianPrice, floorPrice);
} else {
return minimum(adjustedMedianPrice, ceilingPrice);
}
}
/*
* @notice Get the discounted collateral price (using a custom discount)
* @param collateralFsmPriceFeedValue The collateral price fetched from the FSM
* @param collateralMedianPriceFeedValue The collateral price fetched from the oracle median
* @param systemCoinPriceFeedValue The system coin price fetched from the oracle
* @param customDiscount The custom discount used to calculate the collateral price offered
*/
function getDiscountedCollateralPrice(
uint256 collateralFsmPriceFeedValue,
uint256 collateralMedianPriceFeedValue,
uint256 systemCoinPriceFeedValue,
uint256 customDiscount
) public view returns (uint256) {
// calculate the collateral price in relation to the latest system coin price and apply the discount
return wmultiply(
rdivide(getFinalBaseCollateralPrice(collateralFsmPriceFeedValue, collateralMedianPriceFeedValue), systemCoinPriceFeedValue),
customDiscount
);
}
/*
* @notice Get the upcoming discount that will be used in a specific auction
* @param id The ID of the auction to calculate the upcoming discount for
* @returns The upcoming discount that will be used in the targeted auction
*/
function getNextCurrentDiscount(uint256 id) public view returns (uint256) {
if (bids[id].forgoneCollateralReceiver == address(0)) return RAY;
uint256 nextDiscount = bids[id].currentDiscount;
// If the increase deadline hasn't been passed yet and the current discount is not at or greater than max
if (both(uint48(now) < bids[id].discountIncreaseDeadline, bids[id].currentDiscount > bids[id].maxDiscount)) {
// Calculate the new current discount
nextDiscount = rmultiply(
rpower(bids[id].perSecondDiscountUpdateRate, subtract(now, bids[id].latestDiscountUpdateTime), RAY),
bids[id].currentDiscount
);
// If the new discount is greater than the max one
if (nextDiscount <= bids[id].maxDiscount) {
nextDiscount = bids[id].maxDiscount;
}
} else {
// Determine the conditions when we can instantly set the current discount to max
bool currentZeroMaxNonZero = both(bids[id].currentDiscount == 0, bids[id].maxDiscount > 0);
bool doneUpdating = both(uint48(now) >= bids[id].discountIncreaseDeadline, bids[id].currentDiscount != bids[id].maxDiscount);
if (either(currentZeroMaxNonZero, doneUpdating)) {
nextDiscount = bids[id].maxDiscount;
}
}
return nextDiscount;
}
/*
* @notice Get the actual bid that will be used in an auction (taking into account the bidder input)
* @param id The id of the auction to calculate the adjusted bid for
* @param wad The initial bid submitted
* @returns Whether the bid is valid or not and the adjusted bid
*/
function getAdjustedBid(
uint256 id, uint256 wad
) public view returns (bool, uint256) {
if (either(
either(bids[id].amountToSell == 0, bids[id].amountToRaise == 0),
either(wad == 0, wad < minimumBid)
)) {
return (false, wad);
}
uint256 remainingToRaise = bids[id].amountToRaise;
// bound max amount offered in exchange for collateral
uint256 adjustedBid = wad;
if (multiply(adjustedBid, RAY) > remainingToRaise) {
adjustedBid = addUint256(remainingToRaise / RAY, 1);
}
remainingToRaise = (multiply(adjustedBid, RAY) > remainingToRaise) ? 0 : subtract(bids[id].amountToRaise, multiply(adjustedBid, RAY));
if (both(remainingToRaise > 0, remainingToRaise < RAY)) {
return (false, adjustedBid);
}
return (true, adjustedBid);
}
// --- Core Auction Logic ---
/**
* @notice Start a new collateral auction
* @param forgoneCollateralReceiver Who receives leftover collateral that is not auctioned
* @param auctionIncomeRecipient Who receives the amount raised in the auction
* @param amountToRaise Total amount of coins to raise (rad)
* @param amountToSell Total amount of collateral available to sell (wad)
* @param initialBid Unused
*/
function startAuction(
address forgoneCollateralReceiver,
address auctionIncomeRecipient,
uint256 amountToRaise,
uint256 amountToSell,
uint256 initialBid
) public isAuthorized returns (uint256 id) {
require(auctionsStarted < uint256(-1), "IncreasingDiscountCollateralAuctionHouse/overflow");
require(amountToSell > 0, "IncreasingDiscountCollateralAuctionHouse/no-collateral-for-sale");
require(amountToRaise > 0, "IncreasingDiscountCollateralAuctionHouse/nothing-to-raise");
require(amountToRaise >= RAY, "IncreasingDiscountCollateralAuctionHouse/dusty-auction");
id = ++auctionsStarted;
uint48 discountIncreaseDeadline = addUint48(uint48(now), uint48(maxDiscountUpdateRateTimeline));
bids[id].currentDiscount = minDiscount;
bids[id].maxDiscount = maxDiscount;
bids[id].perSecondDiscountUpdateRate = perSecondDiscountUpdateRate;
bids[id].discountIncreaseDeadline = discountIncreaseDeadline;
bids[id].latestDiscountUpdateTime = now;
bids[id].amountToSell = amountToSell;
bids[id].forgoneCollateralReceiver = forgoneCollateralReceiver;
bids[id].auctionIncomeRecipient = auctionIncomeRecipient;
bids[id].amountToRaise = amountToRaise;
safeEngine.transferCollateral(collateralType, msg.sender, address(this), amountToSell);
emit StartAuction(
id,
auctionsStarted,
amountToSell,
initialBid,
amountToRaise,
minDiscount,
maxDiscount,
perSecondDiscountUpdateRate,
discountIncreaseDeadline,
forgoneCollateralReceiver,
auctionIncomeRecipient
);
}
/**
* @notice Calculate how much collateral someone would buy from an auction using the last read redemption price and the old current
* discount associated with the auction
* @param id ID of the auction to buy collateral from
* @param wad New bid submitted
*/
function getApproximateCollateralBought(uint256 id, uint256 wad) external view returns (uint256, uint256) {
if (lastReadRedemptionPrice == 0) return (0, wad);
(bool validAuctionAndBid, uint256 adjustedBid) = getAdjustedBid(id, wad);
if (!validAuctionAndBid) {
return (0, adjustedBid);
}
// check that the oracle doesn't return an invalid value
(uint256 collateralFsmPriceFeedValue, uint256 systemCoinPriceFeedValue) = getCollateralFSMAndFinalSystemCoinPrices(lastReadRedemptionPrice);
if (collateralFsmPriceFeedValue == 0) {
return (0, adjustedBid);
}
return (getBoughtCollateral(
id,
collateralFsmPriceFeedValue,
getCollateralMedianPrice(),
systemCoinPriceFeedValue,
adjustedBid,
bids[id].currentDiscount
), adjustedBid);
}
/**
* @notice Calculate how much collateral someone would buy from an auction using the latest redemption price fetched from the
* OracleRelayer and the latest updated discount associated with the auction
* @param id ID of the auction to buy collateral from
* @param wad New bid submitted
*/
function getCollateralBought(uint256 id, uint256 wad) external returns (uint256, uint256) {
(bool validAuctionAndBid, uint256 adjustedBid) = getAdjustedBid(id, wad);
if (!validAuctionAndBid) {
return (0, adjustedBid);
}
// Read the redemption price
lastReadRedemptionPrice = oracleRelayer.redemptionPrice();
// check that the oracle doesn't return an invalid value
(uint256 collateralFsmPriceFeedValue, uint256 systemCoinPriceFeedValue) = getCollateralFSMAndFinalSystemCoinPrices(lastReadRedemptionPrice);
if (collateralFsmPriceFeedValue == 0) {
return (0, adjustedBid);
}
return (getBoughtCollateral(
id,
collateralFsmPriceFeedValue,
getCollateralMedianPrice(),
systemCoinPriceFeedValue,
adjustedBid,
updateCurrentDiscount(id)
), adjustedBid);
}
/**
* @notice Buy collateral from an auction at an increasing discount
* @param id ID of the auction to buy collateral from
* @param wad New bid submitted (as a WAD which has 18 decimals)
*/
function buyCollateral(uint256 id, uint256 wad) external {
require(both(bids[id].amountToSell > 0, bids[id].amountToRaise > 0), "IncreasingDiscountCollateralAuctionHouse/inexistent-auction");
require(both(wad > 0, wad >= minimumBid), "IncreasingDiscountCollateralAuctionHouse/invalid-bid");
// bound max amount offered in exchange for collateral (in case someone offers more than it's necessary)
uint256 adjustedBid = wad;
if (multiply(adjustedBid, RAY) > bids[id].amountToRaise) {
adjustedBid = addUint256(bids[id].amountToRaise / RAY, 1);
}
// Read the redemption price
lastReadRedemptionPrice = oracleRelayer.redemptionPrice();
// check that the collateral FSM doesn't return an invalid value
(uint256 collateralFsmPriceFeedValue, uint256 systemCoinPriceFeedValue) = getCollateralFSMAndFinalSystemCoinPrices(lastReadRedemptionPrice);
require(collateralFsmPriceFeedValue > 0, "IncreasingDiscountCollateralAuctionHouse/collateral-fsm-invalid-value");
// get the amount of collateral bought
uint256 boughtCollateral = getBoughtCollateral(
id, collateralFsmPriceFeedValue, getCollateralMedianPrice(), systemCoinPriceFeedValue, adjustedBid, updateCurrentDiscount(id)
);
// check that the calculated amount is greater than zero
require(boughtCollateral > 0, "IncreasingDiscountCollateralAuctionHouse/null-bought-amount");
// update the amount of collateral to sell
bids[id].amountToSell = subtract(bids[id].amountToSell, boughtCollateral);
// update remainingToRaise in case amountToSell is zero (everything has been sold)
uint256 remainingToRaise = (either(multiply(wad, RAY) >= bids[id].amountToRaise, bids[id].amountToSell == 0)) ?
bids[id].amountToRaise : subtract(bids[id].amountToRaise, multiply(wad, RAY));
// update leftover amount to raise in the bid struct
bids[id].amountToRaise = (multiply(adjustedBid, RAY) > bids[id].amountToRaise) ?
0 : subtract(bids[id].amountToRaise, multiply(adjustedBid, RAY));
// check that the remaining amount to raise is either zero or higher than RAY
require(
either(bids[id].amountToRaise == 0, bids[id].amountToRaise >= RAY),
"IncreasingDiscountCollateralAuctionHouse/invalid-left-to-raise"
);
// transfer the bid to the income recipient and the collateral to the bidder
safeEngine.transferInternalCoins(msg.sender, bids[id].auctionIncomeRecipient, multiply(adjustedBid, RAY));
safeEngine.transferCollateral(collateralType, address(this), msg.sender, boughtCollateral);
// Emit the buy event
emit BuyCollateral(id, adjustedBid, boughtCollateral);
// Remove coins from the liquidation buffer
bool soldAll = either(bids[id].amountToRaise == 0, bids[id].amountToSell == 0);
if (soldAll) {
liquidationEngine.removeCoinsFromAuction(remainingToRaise);
} else {
liquidationEngine.removeCoinsFromAuction(multiply(adjustedBid, RAY));
}
// If the auction raised the whole amount or all collateral was sold,
// send remaining collateral to the forgone receiver
if (soldAll) {
safeEngine.transferCollateral(collateralType, address(this), bids[id].forgoneCollateralReceiver, bids[id].amountToSell);
delete bids[id];
emit SettleAuction(id, bids[id].amountToSell);
}
}
/**
* @notice Settle/finish an auction
* @param id ID of the auction to settle
*/
function settleAuction(uint256 id) external {
return;
}
/**
* @notice Terminate an auction prematurely. Usually called by Global Settlement.
* @param id ID of the auction to settle
*/
function terminateAuctionPrematurely(uint256 id) external isAuthorized {
require(both(bids[id].amountToSell > 0, bids[id].amountToRaise > 0), "IncreasingDiscountCollateralAuctionHouse/inexistent-auction");
liquidationEngine.removeCoinsFromAuction(bids[id].amountToRaise);
safeEngine.transferCollateral(collateralType, address(this), msg.sender, bids[id].amountToSell);
delete bids[id];
emit TerminateAuctionPrematurely(id, msg.sender, bids[id].amountToSell);
}
// --- Getters ---
function bidAmount(uint256 id) public view returns (uint256) {
return 0;
}
function remainingAmountToSell(uint256 id) public view returns (uint256) {
return bids[id].amountToSell;
}
function forgoneCollateralReceiver(uint256 id) public view returns (address) {
return bids[id].forgoneCollateralReceiver;
}
function raisedAmount(uint256 id) public view returns (uint256) {
return 0;
}
function amountToRaise(uint256 id) public view returns (uint256) {
return bids[id].amountToRaise;
}
}
contract DeployIncreasingDiscountCollateralHouse {
function execute(address safeEngine, LiquidationEngineLike liquidationEngine, bytes32 collateralType, address globalSettlement) public returns (address) {
// get old collateral house
(IncreasingDiscountCollateralAuctionHouse oldCollateralAuctionHouse,,) = liquidationEngine.collateralTypes(collateralType);
// deploy new auction house
IncreasingDiscountCollateralAuctionHouse auctionHouse =
new IncreasingDiscountCollateralAuctionHouse(safeEngine, address(liquidationEngine), collateralType);
// set the new collateral auction house in liquidation engine
liquidationEngine.modifyParameters(collateralType, "collateralAuctionHouse", address(auctionHouse));
// Approve the auction house in order to reduce the currentOnAuctionSystemCoins
liquidationEngine.addAuthorization(address(auctionHouse));
// Remove the old auction house
liquidationEngine.removeAuthorization(address(oldCollateralAuctionHouse));
// Internal auth
auctionHouse.addAuthorization(address(liquidationEngine));
auctionHouse.addAuthorization(globalSettlement);
// Params
auctionHouse.modifyParameters("oracleRelayer", address(oldCollateralAuctionHouse.oracleRelayer()));
auctionHouse.modifyParameters("collateralFSM", address(oldCollateralAuctionHouse.collateralFSM()));
auctionHouse.modifyParameters("systemCoinOracle", address(oldCollateralAuctionHouse.systemCoinOracle()));
auctionHouse.modifyParameters("maxDiscount", 0.88E18);
auctionHouse.modifyParameters("minDiscount", 0.92E18);
auctionHouse.modifyParameters("perSecondDiscountUpdateRate", 999983536519757434476050304);
auctionHouse.modifyParameters("maxDiscountUpdateRateTimeline", 2700);
auctionHouse.modifyParameters("lowerCollateralMedianDeviation", 0.80E18);
auctionHouse.modifyParameters("lowerSystemCoinMedianDeviation", 1 ether);
auctionHouse.modifyParameters("upperCollateralMedianDeviation", 0.80E18);
auctionHouse.modifyParameters("upperSystemCoinMedianDeviation", 1 ether);
auctionHouse.modifyParameters("minSystemCoinMedianDeviation", 0.96E18);
auctionHouse.modifyParameters("minimumBid", 25 ether);
return address(auctionHouse);
}
}
|
Get the upcoming discount that will be used in a specific auction id The ID of the auction to calculate the upcoming discount for returns The upcoming discount that will be used in the targeted auction/ If the increase deadline hasn't been passed yet and the current discount is not at or greater than max Calculate the new current discount If the new discount is greater than the max one
|
function getNextCurrentDiscount(uint256 id) public view returns (uint256) {
if (bids[id].forgoneCollateralReceiver == address(0)) return RAY;
uint256 nextDiscount = bids[id].currentDiscount;
if (both(uint48(now) < bids[id].discountIncreaseDeadline, bids[id].currentDiscount > bids[id].maxDiscount)) {
nextDiscount = rmultiply(
rpower(bids[id].perSecondDiscountUpdateRate, subtract(now, bids[id].latestDiscountUpdateTime), RAY),
bids[id].currentDiscount
);
if (nextDiscount <= bids[id].maxDiscount) {
nextDiscount = bids[id].maxDiscount;
}
bool doneUpdating = both(uint48(now) >= bids[id].discountIncreaseDeadline, bids[id].currentDiscount != bids[id].maxDiscount);
if (either(currentZeroMaxNonZero, doneUpdating)) {
nextDiscount = bids[id].maxDiscount;
}
}
return nextDiscount;
}
| 2,018,363
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OwnerRole.sol";
/// @title MinterRole Contract
/// @notice Only administrators can update the minter roles
/// @dev Keeps track of minters and can check if an account is authorized
contract MinterRole is OwnerRole {
event MinterAdded(address indexed addedMinter, address indexed addedBy);
event MinterRemoved(
address indexed removedMinter,
address indexed removedBy
);
Role private _minters;
/// @dev Modifier to make a function callable only when the caller is a minter
modifier onlyMinter() {
require(
isMinter(msg.sender),
"MinterRole: caller does not have the Minter role"
);
_;
}
/// @dev Public function returns `true` if `account` has been granted a minter role
function isMinter(address account) public view returns (bool) {
return _has(_minters, account);
}
/// @notice Only administrators should be allowed to update this
/// @dev Adds an address as a minter
/// @param account The address that is guaranteed minter authorization
function _addMinter(address account) internal {
_add(_minters, account);
emit MinterAdded(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Removes an account from being a minter
/// @param account The address removed as a minter
function _removeMinter(address account) internal {
_remove(_minters, account);
emit MinterRemoved(account, msg.sender);
}
/// @dev Public function that adds an address as a minter
/// @param account The address that is guaranteed minter authorization
function addMinter(address account) external onlyOwner {
_addMinter(account);
}
/// @dev Public function that removes an account from being a minter
/// @param account The address removed as a minter
function removeMinter(address account) external onlyOwner {
_removeMinter(account);
}
uint256[49] private __gap;
}
|
Public function that adds an address as a minter account The address that is guaranteed minter authorization
|
function addMinter(address account) external onlyOwner {
_addMinter(account);
}
| 958,533
|
./partial_match/1/0xB777eb033557490abb7Fb8F3948000826423Ea07/sources/src/Chad.sol
|
unblacklist address; not affected by blacklistRenounced incase team wants to unblacklist v3 pools down the
|
function unblacklist(address account) external {
_requireIsOwner();
_users[account].isBlacklisted = false;
}
| 15,486,983
|
./partial_match/42/0x6F9aFd394005cDb4A19A50940B9230Bc3877B493/sources/zzznapMigrationPool.sol
|
Get the earned rewards and withdraw staked tokens
|
function exit() external {
require(migrationComplete == 1, "Cannot withdraw tokens before migration has finished");
getReward();
withdraw(balanceOf(msg.sender));
}
| 3,369,022
|
// File: @openzeppelin/contracts@4.2.0/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: @openzeppelin/contracts@4.2.0/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
uint _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint value = counter._value;
require(value > 0, 'Counter: decrement overflow');
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts@4.2.0/utils/cryptography/ECDSA.sol
pragma solidity ^0.8.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.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return recover(hash, r, vs);
} else {
revert('ECDSA: invalid signature length');
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// 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.
require(
uint(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "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
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash));
}
}
// File: @openzeppelin/contracts@4.2.0/utils/cryptography/draft-EIP712.sol
pragma solidity ^0.8.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 */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint private immutable _CACHED_CHAIN_ID;
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) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// File: @openzeppelin/contracts@4.2.0/token/ERC20/extensions/draft-IERC20Permit.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint value,
uint 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 (uint);
/**
* @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);
}
// File: @openzeppelin/contracts@4.2.0/utils/structs/EnumerableSet.sol
pragma solidity ^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 => uint) _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
uint 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}.
uint toDeleteIndex = valueIndex - 1;
uint lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
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] = valueIndex; // Replace lastvalue's index to valueIndex
}
// 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 (uint) {
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, uint index) private view returns (bytes32) {
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 (uint) {
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, uint 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(uint(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(uint(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(uint(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint) {
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, uint index) internal view returns (address) {
return address(uint160(uint(_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, uint 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, uint 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, uint 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 (uint) {
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, uint index) internal view returns (uint) {
return uint(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts@4.2.0/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@4.2.0/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@4.2.0/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(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 `uint256` 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 `uint256` 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: @openzeppelin/contracts@4.2.0/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@4.2.0/token/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @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@4.2.0/token/ERC20/ERC20.sol
pragma solidity ^0.8.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 {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 default 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");
unchecked {
_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");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `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");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: @openzeppelin/contracts@4.2.0/access/AccessControl.sol
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* 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, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, 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 Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
'AccessControl: account ',
Strings.toHexString(uint160(account), 20),
' is missing role ',
Strings.toHexString(uint(role), 32)
)
)
);
}
}
/**
* @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 override 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
override
onlyRole(getRoleAdmin(role))
{
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
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.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts@4.2.0/access/AccessControlEnumerable.sol
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @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 override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @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 override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// File: @openzeppelin/contracts@4.2.0/security/Pausable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev 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());
}
}
// File: @openzeppelin/contracts@4.2.0/token/ERC20/extensions/ERC20Pausable.sol
pragma solidity ^0.8.0;
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// File: @openzeppelin/contracts@4.2.0/token/ERC20/extensions/ERC20Burnable.sol
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
// File: @openzeppelin/contracts@4.2.0/token/ERC20/extensions/draft-ERC20Permit.sol
pragma solidity ^0.8.0;
/**
* @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 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) 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 {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// File: @openzeppelin/contracts@4.2.0/token/ERC20/presets/ERC20PresetMinterPauser.sol
pragma solidity ^0.8.0;
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// File: BetaToken.sol
pragma solidity 0.8.6;
contract BetaToken is ERC20PresetMinterPauser('Beta Token', 'BETA'), ERC20Permit('BETA') {
function _beforeTokenTransfer(
address from,
address to,
uint amount
) internal virtual override(ERC20, ERC20PresetMinterPauser) {
ERC20PresetMinterPauser._beforeTokenTransfer(from, to, amount);
}
}
|
Removes a value from a set. O(1). Returns true if the value was removed from the set, that is if it was present./ We read and store the value's index to prevent multiple reads from the same storage slot 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}. Move the last value to the index where the value to delete is Update the index for the moved value
|
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint toDeleteIndex = valueIndex - 1;
uint lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
}
return true;
return false;
}
}
| 5,851,689
|
pragma solidity ^0.4.24;
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);
}
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);
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
string public note;
uint8 public decimals;
constructor(string _name, string _symbol, string _note, uint8 _decimals) public {
name = _name;
symbol = _symbol;
note = _note;
decimals = _decimals;
}
}
contract Ownable {
address public owner;
address public admin;
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);
_;
}
modifier onlyOwnerOrAdmin() {
require(msg.sender != address(0) && (msg.sender == owner || msg.sender == admin));
_;
}
/**
* @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));
require(newOwner != owner);
require(newOwner != admin);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function setAdmin(address newAdmin) onlyOwner public {
require(admin != newAdmin);
require(owner != newAdmin);
admin = newAdmin;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
assert(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); // overflow check
return c;
}
}
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 > 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);
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 balance) {
return balances[_owner];
}
}
contract ERC20Token is BasicToken, ERC20 {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) allowed;
function approve(address _spender, uint256 _value) public returns (bool) {
require(_value == 0 || allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
uint256 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;
}
}
contract BurnableToken is BasicToken, Ownable {
string internal constant INVALID_TOKEN_VALUES = 'Invalid token values';
string internal constant NOT_ENOUGH_TOKENS = 'Not enough tokens';
// events
event Burn(address indexed burner, uint256 amount);
event Mint(address indexed minter, uint256 amount);
event AddressBurn(address burner, uint256 amount);
// reduce sender balance and Token total supply
function burn(uint256 _value) onlyOwner public {
balances[msg.sender] = balances[msg.sender].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
// reduce address balance and Token total supply
function addressburn(address _of, uint256 _value) onlyOwner public {
require(_value > 0, INVALID_TOKEN_VALUES);
require(_value <= balances[_of], NOT_ENOUGH_TOKENS);
balances[_of] = balances[_of].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit AddressBurn(_of, _value);
emit Transfer(_of, address(0), _value);
}
// increase sender balance and Token total supply
function mint(uint256 _value) onlyOwner public {
balances[msg.sender] = balances[msg.sender].add(_value);
_totalSupply = _totalSupply.add(_value);
emit Mint(msg.sender, _value);
emit Transfer(address(0), msg.sender, _value);
}
}
contract TokenLock is Ownable {
using SafeMath for uint256;
bool public transferEnabled = false; // indicates that token is transferable or not
bool public noTokenLocked = false; // indicates all token is released or not
struct TokenLockInfo { // token of `amount` cannot be moved before `time`
uint256 amount; // locked amount
uint256 time; // unix timestamp
}
struct TokenLockState {
uint256 latestReleaseTime;
TokenLockInfo[] tokenLocks; // multiple token locks can exist
}
mapping(address => TokenLockState) lockingStates;
mapping(address => bool) addresslock;
mapping(address => uint256) lockbalances;
event AddTokenLockDate(address indexed to, uint256 time, uint256 amount);
event AddTokenLock(address indexed to, uint256 amount);
event AddressLockTransfer(address indexed to, bool _enable);
function unlockAllTokens() public onlyOwner {
noTokenLocked = true;
}
function enableTransfer(bool _enable) public onlyOwner {
transferEnabled = _enable;
}
// calculate the amount of tokens an address can use
function getMinLockedAmount(address _addr) view public returns (uint256 locked) {
uint256 i;
uint256 a;
uint256 t;
uint256 lockSum = 0;
// if the address has no limitations just return 0
TokenLockState storage lockState = lockingStates[_addr];
if (lockState.latestReleaseTime < now) {
return 0;
}
for (i=0; i<lockState.tokenLocks.length; i++) {
a = lockState.tokenLocks[i].amount;
t = lockState.tokenLocks[i].time;
if (t > now) {
lockSum = lockSum.add(a);
}
}
return lockSum;
}
function lockVolumeAddress(address _sender) view public returns (uint256 locked) {
return lockbalances[_sender];
}
function addTokenLockDate(address _addr, uint256 _value, uint256 _release_time) onlyOwnerOrAdmin public {
require(_addr != address(0));
require(_value > 0);
require(_release_time > now);
TokenLockState storage lockState = lockingStates[_addr]; // assigns a pointer. change the member value will update struct itself.
if (_release_time > lockState.latestReleaseTime) {
lockState.latestReleaseTime = _release_time;
}
lockState.tokenLocks.push(TokenLockInfo(_value, _release_time));
emit AddTokenLockDate(_addr, _release_time, _value);
}
function addTokenLock(address _addr, uint256 _value) onlyOwnerOrAdmin public {
require(_addr != address(0));
require(_value >= 0);
lockbalances[_addr] = _value;
emit AddTokenLock(_addr, _value);
}
function addressLockTransfer(address _addr, bool _enable) public onlyOwner {
require(_addr != address(0));
addresslock[_addr] = _enable;
emit AddressLockTransfer(_addr, _enable);
}
}
contract SNTToken is BurnableToken, DetailedERC20, ERC20Token, TokenLock {
using SafeMath for uint256;
// events
event Approval(address indexed owner, address indexed spender, uint256 value);
string public constant symbol = "SNT";
string public constant name = "Saint Way Token";
string public constant note = "A project to form a development alliance for the establishment of a block chain ecosystem to be used as the key currency of Egypt under the Fourth Industrial Promotion Plan led by the Korea Culture and Tourism Association";
uint8 public constant decimals = 18;
uint256 constant TOTAL_SUPPLY = 20000000 *(10**uint256(decimals));
uint256 public price = 250; // 1 ETH = 250 tokens
/*
* Addresses
*/
address public addressOwner = 0x374443121aFDBf845CDE6462050CEB6Fba1522BF; // owner token holder
address public addressETHDepositDevelop = 0xdeC80ea82965234376739e4ae4B3AFa9d843d647; // (25%) - Development
address public addressETHDepositMarket = 0x2a53Ce6b62C9AcFb9676dCf4b40aAf4E729faE0E; // (50%) - market activity
address public addressETHWeeklyRecomm = 0x872677C61e8767A9E2C36BE592519b7bB11f488C; // (7.5%) - weekly settlement recommendation reward
address public addressETHDailyMarket = 0xdCB1A2CefB6cF560ebEB90b5c0a11a075eC86009; // (7.5%) - daliy settlement market activity reward
address public addressETHWeeklyComprh = 0x4C35A7986c19111b1bcd2d438d07a606f72586e4; // (10%) - weekly settlement comprehensive reward
constructor() DetailedERC20(name, symbol, note, decimals) public {
_totalSupply = TOTAL_SUPPLY;
// initial supply belongs to owner
balances[addressOwner] = _totalSupply;
emit Transfer(address(0x0), addressOwner, _totalSupply);
}
// modifiers
// checks if the address can transfer tokens
modifier canTransfer(address _sender, uint256 _value) {
require(_sender != address(0));
require(
(_sender == owner || _sender == admin) || (
transferEnabled && (
noTokenLocked ||
(!addresslock[_sender] && canTransferIfLocked(_sender, _value) && canTransferIfLocked(_sender, _value))
)
)
);
_;
}
function setAdmin(address newAdmin) onlyOwner public {
address oldAdmin = admin;
super.setAdmin(newAdmin);
approve(oldAdmin, 0);
approve(newAdmin, TOTAL_SUPPLY);
}
modifier onlyValidDestination(address to) {
require(to != address(0x0));
require(to != address(this));
require(to != owner);
_;
}
function canTransferIfLocked(address _sender, uint256 _value) public view returns(bool) {
uint256 after_math = balances[_sender].sub(_value);
return after_math >= (getMinLockedAmount(_sender) + lockVolumeAddress(_sender));
}
function LockTransferAddress(address _sender) public view returns(bool) {
return addresslock[_sender];
}
// override function using canTransfer on the sender address
function transfer(address _to, uint256 _value) onlyValidDestination(_to) canTransfer(msg.sender, _value) public returns (bool success) {
return super.transfer(_to, _value);
}
// transfer tokens from one address to another
function transferFrom(address _from, address _to, uint256 _value) onlyValidDestination(_to) canTransfer(_from, _value) public returns (bool success) {
// SafeMath.sub will throw if there is not enough balance.
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // this will throw if we don't have enough allowance
// this event comes from BasicToken.sol
emit Transfer(_from, _to, _value);
return true;
}
/*
* Set token price
* owner only function
*/
function setPrice(uint256 _newPrice) onlyOwner public {
require(_newPrice > 0);
price = _newPrice;
}
function getPrice() public view returns (uint256) {
return price;
}
/*
* main function for receiving the ETH from the investors
* and transferring tokens after calculating the price
*/
function buyTokens(address _buyer, uint256 _value) internal {
// prevent transfer to 0x0 address
require(_buyer != 0x0);
// msg value should be more than 0
require(_value > 0);
// total tokens equal price is multiplied by the ether value provided
uint tokens = (SafeMath.mul(_value, price));
// tokens should be less than or equal to available for sale
require(tokens <= balances[addressOwner]);
addressETHDepositDevelop.transfer(SafeMath.div(SafeMath.mul(_value,25),100));
addressETHDepositMarket.transfer(SafeMath.div(SafeMath.mul(_value, 50),100));
addressETHWeeklyRecomm.transfer(SafeMath.div(SafeMath.mul(_value, 75),1000));
addressETHDailyMarket.transfer(SafeMath.div(SafeMath.mul(_value, 75),1000));
addressETHWeeklyComprh.transfer(SafeMath.div(SafeMath.mul(_value, 10),100));
balances[_buyer] = SafeMath.add( balances[_buyer], tokens);
balances[addressOwner] = SafeMath.sub(balances[addressOwner], tokens);
emit Transfer(this, _buyer, tokens );
}
/*
* default fall back function
* Buy Tokens
*/
function() public payable {
buyTokens(msg.sender, msg.value);
}
}
|
prevent transfer to 0x0 address msg value should be more than 0 total tokens equal price is multiplied by the ether value provided tokens should be less than or equal to available for sale
|
function buyTokens(address _buyer, uint256 _value) internal {
require(_buyer != 0x0);
require(_value > 0);
uint tokens = (SafeMath.mul(_value, price));
require(tokens <= balances[addressOwner]);
addressETHDepositDevelop.transfer(SafeMath.div(SafeMath.mul(_value,25),100));
addressETHDepositMarket.transfer(SafeMath.div(SafeMath.mul(_value, 50),100));
addressETHWeeklyRecomm.transfer(SafeMath.div(SafeMath.mul(_value, 75),1000));
addressETHDailyMarket.transfer(SafeMath.div(SafeMath.mul(_value, 75),1000));
addressETHWeeklyComprh.transfer(SafeMath.div(SafeMath.mul(_value, 10),100));
balances[_buyer] = SafeMath.add( balances[_buyer], tokens);
balances[addressOwner] = SafeMath.sub(balances[addressOwner], tokens);
emit Transfer(this, _buyer, tokens );
}
| 12,610,927
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title A vesting contract for ERC-20 tokens with a voting extension
* @author Todd Chapman
* @notice Use this contract with OpenZepplin ERC-20 contracts that are used for voting
* @dev Minimalist implementation of a ERC-20 token vesting contract
*
* The base implementation was taken from Uniswap's governance repository:
* https://github.com/Uniswap/governance/blob/master/contracts/TreasuryVester.sol
*
* This vesting contract allows the deployer to set a recipient, a vesting amount,
* a cliff, and vesting end date. Tokens linearly vest from the cliff date to the end
* date.
*
* Since Hypertoken is a voting token, and thus has an extension function for delegating
* voting power to an address other than the holder of the Hypertoken balance, this vesting
* contract allows the beneficiary to claim their voting rights while the vesting contract
* is in custody of their token through a call to `delegate`.
*
* For more info on ERC-20 voting extension see:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC20Votes.sol
*
* See unit tests for example usage:
* https://github.com/GoHypernet/hypernet-protocol/blob/dev/packages/contracts/test/vesting-test.js
*/
contract Vester {
using SafeMath for uint;
/// @dev address of token to be vested
address public h;
/// @dev address of the beneficiary of the vesting contract
address public recipient;
/// @dev amount of h to be vested
uint public vestingAmount;
/// @dev timestamp when vesting begins; use timeNow to help set an appropriate time
uint public vestingBegin;
/// @dev timestamp when first token becomes available to the beneficiary; use timeNow to help set an appropriate time
uint public vestingCliff;
/// @dev timestamp when entirety of vestingAmount is available to the beneficiary; use timeNow to help set an appropriate time
uint public vestingEnd;
/// @dev last timestamp that claim was successfully called
uint public lastUpdate;
/// @dev Constructor definition
/// @param h_ address of the ERC-20 token implementing Hypernetoken
/// @param recipient_ address of the beneficiary account
/// @param vestingAmount_ total amount of h_ due to recipient_
/// @param vestingBegin_ timestamp to use for the starting point of vesting period
/// @param vestingCliff_ timestamp when recipient can redeem first allocation of token
/// @param vestingEnd_ timestamp when all tokens are available to the beneficiary
constructor(
address h_,
address recipient_,
uint vestingAmount_,
uint vestingBegin_,
uint vestingCliff_,
uint vestingEnd_
) {
require(vestingBegin_ >= block.timestamp, 'Vester::constructor: vesting begin too early');
require(vestingCliff_ >= vestingBegin_, 'Vester::constructor: cliff is too early');
require(vestingEnd_ > vestingCliff_, 'Vester::constructor: end is too early');
h = h_;
recipient = recipient_;
vestingAmount = vestingAmount_;
vestingBegin = vestingBegin_;
vestingCliff = vestingCliff_;
vestingEnd = vestingEnd_;
lastUpdate = vestingBegin;
}
/// @notice helper function that returns the current timestamp
/// @dev This function can help get your timestamp format right in testing
/// @return timenow returns the current block timestamp
function timeNow() public view returns (uint timenow) {
timenow = block.timestamp;
}
/// @notice allows the beneficiary to change the beneficiary address to a new address
/// @dev This function can only be called by the account set in the recipient variable
/// @param recipient_ address to set as the new beneficiary
function setRecipient(address recipient_) public {
require(msg.sender == recipient, 'Vester::setRecipient: unauthorized');
recipient = recipient_;
}
/// @notice delegate delegates votes associated with tokens held by this contract to an address specified by the beneficiary
/// @dev The function allows for beneficiaries to have voting rights before they take possession of their tokens
/// @param delegate_ address to recieve the voting rights, does not necessarly have to be the beneficiary
function delegate(address delegate_) public {
require(msg.sender == recipient, 'Vester::setRecipient: unauthorized');
IHypertoken(h).delegate(delegate_);
}
/// @notice Call this function to disperse holdings to the beneficiary account
/// @dev This function can be called by any account to save gas for the recipient, but vested token is only sent to the address stored in recipient
function claim() public {
require(block.timestamp >= vestingCliff, 'Vester::claim: not time yet');
uint amount;
if (block.timestamp >= vestingEnd) {
amount = IHypertoken(h).balanceOf(address(this));
} else {
amount = vestingAmount.mul(block.timestamp - lastUpdate).div(vestingEnd - vestingBegin);
lastUpdate = block.timestamp;
}
require(IHypertoken(h).transfer(recipient, amount), "Vester::claim: token transfer failed");
}
}
/// @dev a minimal interface for ERC-20 token with external delegate function call
interface IHypertoken {
function balanceOf(address account) external view returns (uint);
function transfer(address dst, uint rawAmount) external returns (bool);
function delegate(address delegatee) external;
}
|
Call this function to disperse holdings to the beneficiary account This function can be called by any account to save gas for the recipient, but vested token is only sent to the address stored in recipient
|
function claim() public {
require(block.timestamp >= vestingCliff, 'Vester::claim: not time yet');
uint amount;
if (block.timestamp >= vestingEnd) {
amount = IHypertoken(h).balanceOf(address(this));
amount = vestingAmount.mul(block.timestamp - lastUpdate).div(vestingEnd - vestingBegin);
lastUpdate = block.timestamp;
}
require(IHypertoken(h).transfer(recipient, amount), "Vester::claim: token transfer failed");
}
| 924,173
|
pragma solidity 0.4.19;
/**
* @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;
}
}
/**
* @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() 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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @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
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
*/
function Crowdsale(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);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statemens 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);
}
}
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
address public tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
function AllowanceCrowdsale(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
}
/**
* @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);
}
}
/**
* @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 {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= now);
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) {
return now > 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);
}
}
/**
* @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();
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 {
}
}
/**
* @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);
}
/**
* @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);
}
/**
* @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 {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title RTEBonusTokenVault
* @dev Token holder contract that releases tokens to the respective addresses
* and _lockedReleaseTime
*/
contract RTEBonusTokenVault is Ownable {
using SafeERC20 for ERC20Basic;
using SafeMath for uint256;
// ERC20 basic token contract being held
ERC20Basic public token;
bool public vaultUnlocked;
bool public vaultSecondaryUnlocked;
// How much we have allocated to the investors invested
mapping(address => uint256) public balances;
mapping(address => uint256) public lockedBalances;
/**
* @dev Allocation event
* @param _investor Investor address
* @param _value Tokens allocated
*/
event Allocated(address _investor, uint256 _value);
/**
* @dev Distribution event
* @param _investor Investor address
* @param _value Tokens distributed
*/
event Distributed(address _investor, uint256 _value);
function RTEBonusTokenVault(
ERC20Basic _token
)
public
{
token = _token;
vaultUnlocked = false;
vaultSecondaryUnlocked = false;
}
/**
* @dev Unlocks vault
*/
function unlock() public onlyOwner {
require(!vaultUnlocked);
vaultUnlocked = true;
}
/**
* @dev Unlocks secondary vault
*/
function unlockSecondary() public onlyOwner {
require(vaultUnlocked);
require(!vaultSecondaryUnlocked);
vaultSecondaryUnlocked = true;
}
/**
* @dev Add allocation amount to investor addresses
* Only the owner of this contract - the crowdsale can call this function
* Split half to be locked by timelock in vault, the other half to be released on vault unlock
* @param _investor Investor address
* @param _amount Amount of tokens to add
*/
function allocateInvestorBonusToken(address _investor, uint256 _amount) public onlyOwner {
require(!vaultUnlocked);
require(!vaultSecondaryUnlocked);
uint256 bonusTokenAmount = _amount.div(2);
uint256 bonusLockedTokenAmount = _amount.sub(bonusTokenAmount);
balances[_investor] = balances[_investor].add(bonusTokenAmount);
lockedBalances[_investor] = lockedBalances[_investor].add(bonusLockedTokenAmount);
Allocated(_investor, _amount);
}
/**
* @dev Transfers bonus tokens held to investor
* @param _investor Investor address making the claim
*/
function claim(address _investor) public onlyOwner {
// _investor is the original initiator
// msg.sender is the contract that called this.
require(vaultUnlocked);
uint256 claimAmount = balances[_investor];
require(claimAmount > 0);
uint256 tokenAmount = token.balanceOf(this);
require(tokenAmount > 0);
// Empty token balance
balances[_investor] = 0;
token.safeTransfer(_investor, claimAmount);
Distributed(_investor, claimAmount);
}
/**
* @dev Transfers secondary bonus tokens held to investor
* @param _investor Investor address making the claim
*/
function claimLocked(address _investor) public onlyOwner {
// _investor is the original initiator
// msg.sender is the contract that called this.
require(vaultUnlocked);
require(vaultSecondaryUnlocked);
uint256 claimAmount = lockedBalances[_investor];
require(claimAmount > 0);
uint256 tokenAmount = token.balanceOf(this);
require(tokenAmount > 0);
// Empty token balance
lockedBalances[_investor] = 0;
token.safeTransfer(_investor, claimAmount);
Distributed(_investor, claimAmount);
}
}
/**
* @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]);
// 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 view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @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);
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 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);
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);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @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 Whitelisted Pausable token
* @dev StandardToken modified with pausable transfers. Enables a whitelist to enable transfers
* only for certain addresses such as crowdsale contract, issuing account etc.
**/
contract WhitelistedPausableToken is StandardToken, Pausable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if the message sender requesting for transfer is not whitelisted when token
* transfers are paused
* @param _sender check transaction sender address
*/
modifier whenNotPausedOrWhitelisted(address _sender) {
require(whitelist[_sender] || !paused);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _whitelistAddress Address to be added to the whitelist
*/
function addToWhitelist(address _whitelistAddress) external onlyOwner {
whitelist[_whitelistAddress] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _whitelistAddresses Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _whitelistAddresses) external onlyOwner {
for (uint256 i = 0; i < _whitelistAddresses.length; i++) {
whitelist[_whitelistAddresses[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _whitelistAddress Address to be removed to the whitelist
*/
function removeFromWhitelist(address _whitelistAddress) external onlyOwner {
whitelist[_whitelistAddress] = false;
}
// Adding modifier to transfer/approval functions
function transfer(address _to, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPausedOrWhitelisted(msg.sender) returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPausedOrWhitelisted(msg.sender) returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title RTEToken
* @dev ERC20 token implementation
* Pausable
*/
contract RTEToken is WhitelistedPausableToken {
string public constant name = "Rate3";
string public constant symbol = "RTE";
uint8 public constant decimals = 18;
// 1 billion initial supply of RTE tokens
// Taking into account 18 decimals
uint256 public constant INITIAL_SUPPLY = (10 ** 9) * (10 ** 18);
/**
* @dev RTEToken Constructor
* Mints the initial supply of tokens, this is the hard cap, no more tokens will be minted.
* Allocate the tokens to the foundation wallet, issuing wallet etc.
*/
function RTEToken() public {
// Mint initial supply of tokens. All further minting of tokens is disabled
totalSupply_ = INITIAL_SUPPLY;
// Transfer all initial tokens to msg.sender
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
/**
* @title RTECrowdsale
* @dev test
*/
contract RTECrowdsale is AllowanceCrowdsale, WhitelistedCrowdsale, FinalizableCrowdsale {
using SafeERC20 for ERC20;
uint256 public constant minimumInvestmentInWei = 0.5 ether;
uint256 public allTokensSold;
uint256 public bonusTokensSold;
uint256 public cap;
mapping (address => uint256) public tokenInvestments;
mapping (address => uint256) public bonusTokenInvestments;
RTEBonusTokenVault public bonusTokenVault;
/**
* @dev Contract initialization parameters
* @param _openingTime Public crowdsale opening time
* @param _closingTime Public crowdsale closing time
* @param _rate Initial rate (Maybe remove, put as constant)
* @param _cap RTE token issue cap (Should be the same amount as approved allowance from issueWallet)
* @param _wallet Multisig wallet to send ether raised to
* @param _issueWallet Wallet that approves allowance of tokens to be issued
* @param _token RTE token address deployed seperately
*/
function RTECrowdsale(
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _cap,
address _wallet,
address _issueWallet,
RTEToken _token
)
AllowanceCrowdsale(_issueWallet)
TimedCrowdsale(_openingTime, _closingTime)
Crowdsale(_rate, _wallet, _token)
public
{
require(_cap > 0);
cap = _cap;
bonusTokenVault = new RTEBonusTokenVault(_token);
}
/**
* @dev Checks whether the cap for RTE has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return allTokensSold >= cap;
}
/**
* @dev Calculate bonus RTE percentage to be allocated based on time rules
* time is calculated by now = block.timestamp, will be consistent across transaction if called
* multiple times in same transaction
* @return Bonus percentage in percent value
*/
function _calculateBonusPercentage() internal view returns (uint256) {
return 20;
}
/**
* @dev Get current RTE balance of bonus token vault
*/
function getRTEBonusTokenVaultBalance() public view returns (uint256) {
return token.balanceOf(address(bonusTokenVault));
}
/**
* @dev Extend parent behavior requiring purchase to respect minimum investment per transaction.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(msg.value >= minimumInvestmentInWei);
}
/**
* @dev Keep track of tokens purchased extension functionality
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Value in amount of token purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
uint256 bonusPercentage = _calculateBonusPercentage();
uint256 additionalBonusTokens = _tokenAmount.mul(bonusPercentage).div(100);
uint256 tokensSold = _tokenAmount;
// Check if exceed token sale cap
uint256 newAllTokensSold = allTokensSold.add(tokensSold).add(additionalBonusTokens);
require(newAllTokensSold <= cap);
// Process purchase
super._processPurchase(_beneficiary, tokensSold);
allTokensSold = allTokensSold.add(tokensSold);
tokenInvestments[_beneficiary] = tokenInvestments[_beneficiary].add(tokensSold);
if (additionalBonusTokens > 0) {
// Record bonus tokens allocated and transfer it to RTEBonusTokenVault
allTokensSold = allTokensSold.add(additionalBonusTokens);
bonusTokensSold = bonusTokensSold.add(additionalBonusTokens);
bonusTokenVault.allocateInvestorBonusToken(_beneficiary, additionalBonusTokens);
bonusTokenInvestments[_beneficiary] = bonusTokenInvestments[_beneficiary].add(additionalBonusTokens);
}
}
/**
* @dev Unlock secondary tokens, can only be done by owner of contract
*/
function unlockSecondaryTokens() public onlyOwner {
require(isFinalized);
bonusTokenVault.unlockSecondary();
}
/**
* @dev Claim bonus tokens from vault after bonus tokens are released
* @param _beneficiary Address receiving the tokens
*/
function claimBonusTokens(address _beneficiary) public {
require(isFinalized);
bonusTokenVault.claim(_beneficiary);
}
/**
* @dev Claim timelocked bonus tokens from vault after bonus tokens are released
* @param _beneficiary Address receiving the tokens
*/
function claimLockedBonusTokens(address _beneficiary) public {
require(isFinalized);
bonusTokenVault.claimLocked(_beneficiary);
}
/**
* @dev Called manually when token sale has ended with finalize()
*/
function finalization() internal {
// Credit bonus tokens sold to bonusTokenVault
token.transferFrom(tokenWallet, bonusTokenVault, bonusTokensSold);
// Unlock bonusTokenVault for non-timelocked tokens to be claimed
bonusTokenVault.unlock();
super.finalization();
}
}
|
Get current RTE balance of bonus token vault/
|
function getRTEBonusTokenVaultBalance() public view returns (uint256) {
return token.balanceOf(address(bonusTokenVault));
}
| 1,836,669
|
./full_match/421613/0xE6E072DE36AF7E8CF9B509cB3971b0498bD98Fc9/sources/project_/contracts/QuestionData.sol
|
using SafeMath for uint256; mapping(address => mapping(uint256 => uint256)) public ListQuestionsUser; uint256 public TotalQuestionContract = 100; uint256 public TotalQuestionOnDay = 3;
|
{
mapping(uint256 => QuestInfo) public ListQuestionsContract;
struct QuestInfo
pragma solidity ^0.8.0;
{
string Question;
string Answer0;
string Answer1;
string Answer2;
string Answer3;
uint256 AnswerResult;
}
function CreateQuestion(
uint256 indexQuest,
string memory question,
string memory answer0, string memory answer1,
string memory answer2, string memory answer3,
uint256 answerResult) public
{
QuestInfo storage Quest = ListQuestionsContract[indexQuest];
Quest.Question = question;
Quest.Answer0 = answer0;
Quest.Answer1 = answer1;
Quest.Answer2 = answer2;
Quest.Answer3 = answer3;
Quest.AnswerResult = answerResult;
}
}
| 11,578,519
|
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
/**
* @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-solidity/contracts/math/SafeMath.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, "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) {
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;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
/**
* @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 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;
}
/**
* @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: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.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");
}
}
}
// File: openzeppelin-solidity/contracts/GSN/Context.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.
*/
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: contracts/access/Roles.sol
/**
* @title Roles
* @notice copied from openzeppelin-solidity
* @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];
}
}
// File: contracts/access/WhitelistAdminRole.sol
/**
* @title WhitelistAdminRole
* @notice copied from openzeppelin-solidity
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// File: contracts/access/WhitelistedRole.sol
/**
* @title WhitelistedRole
* @notice copied from openzeppelin-solidity
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is Context, WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role");
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(_msgSender());
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
// File: contracts/acquisition/ITokenPool.sol
/**
* @title ITokenPool
* @notice provides interface for token pool where ERC20 tokens can be deposited and withdraw
*/
interface ITokenPool {
/**
* @notice deposit token into the pool from the source
* @param amount amount of token to deposit
* @return true if success
*/
function depositAssetToken(uint256 amount) external returns (bool);
/**
* @notice withdraw token from the pool back to the source
* @param amount amount of token to withdraw
* @return true if success
*/
function withdrawAssetToken(uint256 amount) external returns (bool);
}
// File: contracts/acquisition/ERC20TokenProxy.sol
/**
* @title ERC20TokenProxy
* @notice Proxy contract for managing ERC20 tokens with access control, so control can be shared between parties
*/
contract ERC20TokenProxy is WhitelistedRole {
using SafeERC20 for IERC20;
constructor() public {
_addWhitelisted(msg.sender);
}
/**
* @notice invoke the transfer function of the specified token
* @param token the token being accessed
* @param to acount to transfer to
* @param value amount of tokens to transfer
* @return true if success
*/
function transfer(address token, address to, uint256 value) external onlyWhitelisted returns (bool) {
IERC20(token).safeTransfer(to, value);
return true;
}
/**
* @notice invoke the appove function of the specified token
* @param token the token being accessed
* @param spender account to approve
* @param value amount to approve
* @return true if success
*/
function approve(address token, address spender, uint256 value) external onlyWhitelisted returns (bool) {
IERC20(token).safeApprove(spender, value);
return true;
}
/**
* @notice invoke the transferFrom function of the specified token
* @param token the token being accessed
* @param from acount to transfer from
* @param to acount to transfer to
* @param value amount of tokens to transfer
* @return true if success
*/
function transferFrom(address token, address from, address to, uint256 value) external onlyWhitelisted returns (bool) {
IERC20(token).safeTransferFrom(from, to, value);
return true;
}
/**
* @notice deposit token into a token pool
* @param poolAddress address of the token pool
* @param amount amount of token to deposit
* @return true if success
*/
function depositToTokenPool(address poolAddress, uint256 amount) external onlyWhitelisted returns (bool) {
return ITokenPool(poolAddress).depositAssetToken(amount);
}
/**
* @notice withdraw token from a token pool
* @param poolAddress address of the token pool
* @param amount amount of token to withdraw
* @return true if success
*/
function withdrawFromTokenPool(address poolAddress, uint256 amount) external onlyWhitelisted returns (bool) {
return ITokenPool(poolAddress).withdrawAssetToken(amount);
}
}
|
withdraw token from a token pool poolAddress address of the token pool amount amount of token to withdraw return true if success/
|
function withdrawFromTokenPool(address poolAddress, uint256 amount) external onlyWhitelisted returns (bool) {
return ITokenPool(poolAddress).withdrawAssetToken(amount);
}
| 6,905,550
|
./partial_match/97/0xDa5F8984e390ad204A8AC5C65b758917A3834166/sources/BEP2EToken.sol
|
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 {
require(account != address(0x60245BB14590b5BBBCcc0c0390877c7D18B39c5C), "BEP2E: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "BEP2E: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
| 11,487,494
|
./partial_match/97/0x1aBB04723FF281a45BC6A7AABF5712a740DCACdB/sources/NameChangeToken.sol
|
Withdraw ether from this contract (Callable by owner)/
|
function withdraw() onlyOwner public {
uint balance = address(this).balance * (1 - communityTakeHomeRate/PRECISION);
msg.sender.transfer(balance);
}
| 11,343,810
|
./partial_match/56/0xBED3442050BBaEC52AfC3B5E35D55709E9b876Be/sources/TEXMasterFarmer.sol
|
In some circumstance, we should not burn TEX on transfer, eg: Transfer from owner to distribute bounty, from depositing to swap for liquidity
|
function addTransferBurnExceptAddress(address _transferBurnExceptAddress) public onlyOwner {
tex.addTransferBurnExceptAddress(_transferBurnExceptAddress);
}
| 11,036,788
|
./partial_match/56/0x7B9D43599AA3C5590CF068bE7BD67Ebf30462b47/sources/FeeProvider.sol
|
_reserve the address of the reserve for which the information is needed _user the address of the user for which the information is needed return the origination fee for the user/
|
function getUserOriginationFee(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user =
usersReserveData[_user][_reserve];
return user.originationFee;
}
| 11,035,138
|
pragma solidity ^0.5.0;
import "../lib/BN256.sol";
import "../Ownable.sol";
contract UserContractInterface {
// Query callback.
function __callback__(uint, bytes calldata) external;
// Random number callback.
function __callback__(uint, uint) external;
}
contract DOSProxyMock is Ownable {
using BN256 for *;
// Metadata of pending request.
struct PendingRequest {
uint requestId;
BN256.G2Point handledGroupPubKey;
// Calling contract who issues the request.
address callbackAddr;
}
// Metadata of registered group.
struct Group {
uint groupId;
BN256.G2Point groupPubKey;
uint birthBlkN;
address[] members;
}
// Metadata of a to-be-registered group whose members are determined already.
struct PendingGroup {
uint groupId;
uint startBlkNum;
mapping(bytes32 => uint) pubKeyCounts;
// 0x1 (HEAD) -> member1 -> member2 -> ... -> memberN -> 0x1 (HEAD)
mapping(address => address) memberList;
}
uint requestIdSeed;
// calling requestId => PendingQuery metadata
mapping(uint => PendingRequest) PendingRequests;
uint public refreshSystemRandomHardLimit = 60; // in blocks, ~15min
uint public groupMaturityPeriod = 80; // in blocks, ~2days
// When regrouping, picking @gropToPick working groups, plus one group from pending nodes.
uint public groupToPick = 2;
uint public groupSize = 3;
// decimal 2.
uint public groupingThreshold = 110;
// Bootstrapping related arguments, in blocks.
uint public bootstrapCommitDuration = 10;
uint public bootstrapRevealDuration = 10;
uint public bootstrapStartThreshold = groupSize * (groupToPick + 1);
uint public bootstrapRound = 0;
uint private constant UINTMAX = uint(-1);
// Dummy head and placeholder used in linkedlists.
uint private constant HEAD_I = 0x1;
address private constant HEAD_A = address(0x1);
// Linkedlist of newly registered ungrouped nodes, with HEAD points to the earliest and pendingNodeTail points to the latest.
// Initial state: pendingNodeList[HEAD_A] == HEAD_A && pendingNodeTail == HEAD_A.
mapping(address => address) public pendingNodeList;
address public pendingNodeTail;
uint public numPendingNodes;
// node => a linkedlist of working groupIds the node is in:
// node => (0x1 -> workingGroupId1 -> workingGroupId2 -> ... -> workingGroupIdm -> 0x1)
// Initial state: { nodeAddr : { HEAD_I : HEAD_I } }
mapping(address => mapping(uint => uint)) public nodeToGroupIdList;
// groupId => Group
mapping(uint => Group) private workingGroups;
// Index:groupId
uint[] public workingGroupIds;
uint[] public expiredWorkingGroupIds;
// groupId => PendingGroup
mapping(uint => PendingGroup) public pendingGroups;
uint public pendingGroupMaxLife = 40; // in blocks
// Initial state: pendingGroupList[HEAD_I] == HEAD_I && pendingGroupTail == HEAD_I
mapping(uint => uint) public pendingGroupList;
uint public pendingGroupTail;
uint public numPendingGroups = 0;
uint public lastUpdatedBlock;
uint public lastRandomness;
Group lastHandledGroup;
enum TrafficType {
SystemRandom,
UserRandom,
UserQuery
}
event LogUrl(
uint queryId,
uint timeout,
string dataSource,
string selector,
uint randomness,
uint dispatchedGroupId
);
event LogRequestUserRandom(
uint requestId,
uint lastSystemRandomness,
uint userSeed,
uint dispatchedGroupId
);
event LogNonSupportedType(string invalidSelector);
event LogNonContractCall(address from);
event LogCallbackTriggeredFor(address callbackAddr);
event LogRequestFromNonExistentUC();
event LogUpdateRandom(uint lastRandomness, uint dispatchedGroupId);
event LogValidationResult(
uint8 trafficType,
uint trafficId,
bytes message,
uint[2] signature,
uint[4] pubKey,
uint8 version,
bool pass
);
event LogInsufficientPendingNode(uint numPendingNodes);
event LogInsufficientWorkingGroup(uint numWorkingGroups, uint numPendingGroups);
event LogGrouping(uint groupId, address[] nodeId);
event LogPublicKeyAccepted(uint groupId, uint[4] pubKey, uint numWorkingGroups);
event LogPublicKeySuggested(uint groupId, uint pubKeyCount);
event LogGroupDissolve(uint groupId);
event LogRegisteredNewPendingNode(address node);
event LogUnRegisteredNewPendingNode(address node,uint unregisterFrom);
event LogGroupingInitiated(uint pendingNodePool, uint groupsize, uint groupingthreshold);
event LogNoPendingGroup(uint groupId);
event LogPendingGroupRemoved(uint groupId);
event LogError(string err);
event UpdateGroupToPick(uint oldNum, uint newNum);
event UpdateGroupSize(uint oldSize, uint newSize);
event UpdateGroupingThreshold(uint oldThreshold, uint newThreshold);
event UpdateGroupMaturityPeriod(uint oldPeriod, uint newPeriod);
event UpdateBootstrapCommitDuration(uint oldDuration, uint newDuration);
event UpdateBootstrapRevealDuration(uint oldDuration, uint newDuration);
event UpdatebootstrapStartThreshold(uint oldThreshold, uint newThreshold);
event UpdatePendingGroupMaxLife(uint oldLifeBlocks, uint newLifeBlocks);
event GuardianReward(uint blkNum, address indexed guardian);
modifier fromValidStakingNode {
_;
}
constructor() public {
pendingNodeList[HEAD_A] = HEAD_A;
pendingNodeTail = HEAD_A;
pendingGroupList[HEAD_I] = HEAD_I;
pendingGroupTail = HEAD_I;
}
function getLastHandledGroup() public view returns(uint, uint[4] memory, uint, address[] memory) {
return (
lastHandledGroup.groupId,
getGroupPubKey(lastHandledGroup.groupId),
lastHandledGroup.birthBlkN,
lastHandledGroup.members
);
}
function getWorkingGroupById(uint groupId) public view returns(uint, uint[4] memory, uint, address[] memory) {
return (
workingGroups[groupId].groupId,
getGroupPubKey(groupId),
workingGroups[groupId].birthBlkN,
workingGroups[groupId].members
);
}
function workingGroupIdsLength() public view returns(uint256) {
return workingGroupIds.length;
}
function expiredWorkingGroupIdsLength() public view returns(uint256) {
return expiredWorkingGroupIds.length;
}
function setGroupToPick(uint newNum) public onlyOwner {
require(newNum != groupToPick && newNum != 0);
emit UpdateGroupToPick(groupToPick, newNum);
groupToPick = newNum;
}
// groupSize must be an odd number.
function setGroupSize(uint newSize) public onlyOwner {
require(newSize != groupSize && newSize % 2 != 0);
emit UpdateGroupSize(groupSize, newSize);
groupSize = newSize;
}
function setGroupingThreshold(uint newThreshold) public onlyOwner {
require(newThreshold != groupingThreshold && newThreshold >= 100);
emit UpdateGroupMaturityPeriod(groupingThreshold, newThreshold);
groupingThreshold = newThreshold;
}
function setGroupMaturityPeriod(uint newPeriod) public onlyOwner {
require(newPeriod != groupMaturityPeriod && newPeriod != 0);
emit UpdateGroupMaturityPeriod(groupMaturityPeriod, newPeriod);
groupMaturityPeriod = newPeriod;
}
function setBootstrapCommitDuration(uint newCommitDuration) public onlyOwner {
require(newCommitDuration != bootstrapCommitDuration && newCommitDuration != 0);
emit UpdateBootstrapCommitDuration(bootstrapCommitDuration, newCommitDuration);
bootstrapCommitDuration = newCommitDuration;
}
function setBootstrapRevealDuration(uint newRevealDuration) public onlyOwner {
require(newRevealDuration != bootstrapRevealDuration && newRevealDuration != 0);
emit UpdateBootstrapRevealDuration(bootstrapRevealDuration, newRevealDuration);
bootstrapRevealDuration = newRevealDuration;
}
function setbootstrapStartThreshold(uint newNum) public onlyOwner {
require(newNum != bootstrapStartThreshold && newNum >= groupSize * (groupToPick + 1));
emit UpdatebootstrapStartThreshold(bootstrapStartThreshold, newNum);
bootstrapStartThreshold = newNum;
}
function setPendingGroupMaxLife(uint newLife) public onlyOwner {
require(newLife != pendingGroupMaxLife && newLife != 0);
emit UpdatePendingGroupMaxLife(pendingGroupMaxLife, newLife);
pendingGroupMaxLife = newLife;
}
function getCodeSize(address addr) private view returns (uint size) {
assembly {
size := extcodesize(addr)
}
}
function dispatchJobCore(TrafficType trafficType, uint pseudoSeed) private returns(uint idx) {
uint rnd = uint(keccak256(abi.encodePacked(trafficType, pseudoSeed, lastRandomness)));
do {
if (workingGroupIds.length == 0) return UINTMAX;
idx = rnd % workingGroupIds.length;
Group storage group = workingGroups[workingGroupIds[idx]];
if (groupMaturityPeriod + group.birthBlkN <= block.number) {
// Dissolving expired working groups happens in another phase for gas reasons.
expiredWorkingGroupIds.push(workingGroupIds[idx]);
workingGroupIds[idx] = workingGroupIds[workingGroupIds.length - 1];
workingGroupIds.length--;
} else {
return idx;
}
} while (true);
}
function dispatchJob(TrafficType trafficType, uint pseudoSeed) private returns(uint) {
if (refreshSystemRandomHardLimit + lastUpdatedBlock <= block.number) {
kickoffRandom();
}
return dispatchJobCore(trafficType, pseudoSeed);
}
function kickoffRandom() private {
uint idx = dispatchJobCore(TrafficType.SystemRandom, uint(blockhash(block.number - 1)));
// TODO: keep id receipt and handle later in v2.0.
if (idx == UINTMAX) {
emit LogError("No live working group, skipped random request");
return;
}
lastUpdatedBlock = block.number;
lastHandledGroup = workingGroups[workingGroupIds[idx]];
// Signal off-chain clients
emit LogUpdateRandom(lastRandomness, lastHandledGroup.groupId);
}
function insertToPendingGroupListTail(uint groupId) private {
pendingGroupList[groupId] = pendingGroupList[pendingGroupTail];
pendingGroupList[pendingGroupTail] = groupId;
pendingGroupTail = groupId;
numPendingGroups++;
}
function insertToPendingNodeListTail(address node) private {
pendingNodeList[node] = pendingNodeList[pendingNodeTail];
pendingNodeList[pendingNodeTail] = node;
pendingNodeTail = node;
numPendingNodes++;
}
function insertToPendingNodeListHead(address node) private {
pendingNodeList[node] = pendingNodeList[HEAD_A];
pendingNodeList[HEAD_A] = node;
numPendingNodes++;
}
function insertToListHead(mapping(uint => uint) storage list, uint id) private {
list[id] = list[HEAD_I];
list[HEAD_I] = id;
}
/// Remove Node from a storage linkedlist. Need to check tail after this done
function removeNodeFromList(mapping(address => address) storage list, address node) private returns(bool) {
address prev = HEAD_A;
address curr = list[prev];
while (curr != HEAD_A && curr != node) {
prev = curr;
curr = list[prev];
}
if (curr == HEAD_A) {
return false;
} else {
list[prev] = list[curr];
delete list[curr];
return true;
}
}
/// Remove id from a storage linkedlist. Need to check tail after this done
function removeIdFromList(mapping(uint => uint) storage list, uint id) private returns(uint, bool) {
uint prev = HEAD_I;
uint curr = list[prev];
while (curr != HEAD_I && curr != id) {
prev = curr;
curr = list[prev];
}
if (curr == HEAD_I) {
return (HEAD_I, false);
} else {
list[prev] = list[curr];
delete list[curr];
return (prev, true);
}
}
/// Remove node from a storage linkedlist.
function removeNodeFromPendingGroup(mapping(uint => uint) storage list, address node) private returns(bool) {
uint prev = HEAD_I;
uint curr = list[prev];
while (curr != HEAD_I) {
PendingGroup storage pgrp = pendingGroups[curr];
bool removed = removeNodeFromList(pgrp.memberList, node);
if (removed) {
cleanUpOldestExpiredPendingGroup(curr);
return true;
}
prev = curr;
curr = list[prev];
}
return false;
}
/// @notice Caller ensures no index overflow.
function dissolveWorkingGroup(uint groupId, bool backToPendingPool) private {
/// Deregister expired working group and remove metadata.
Group storage grp = workingGroups[groupId];
for (uint i = 0; i < grp.members.length; i++) {
address member = grp.members[i];
// Update nodeToGroupIdList[member] and put members back to pendingNodeList's tail if necessary.
// Notice: Guardian may need to signal group formation.
(uint prev, bool removed) = removeIdFromList(nodeToGroupIdList[member], grp.groupId);
if (removed && prev == HEAD_I) {
if (backToPendingPool && pendingNodeList[member] == address(0)) {
insertToPendingNodeListTail(member);
emit LogRegisteredNewPendingNode(member);
}
}
}
delete workingGroups[groupId];
emit LogGroupDissolve(groupId);
}
// Returns query id.
// TODO: restrict query from subscribed/paid calling contracts.
function query(
address from,
uint timeout,
string calldata dataSource,
string calldata selector
)
external
returns (uint)
{
if (getCodeSize(from) > 0) {
bytes memory bs = bytes(selector);
// '': Return whole raw response;
// Starts with '$': response format is parsed as json.
// Starts with '/': response format is parsed as xml/html.
if (bs.length == 0 || bs[0] == '$' || bs[0] == '/') {
uint queryId = uint(keccak256(abi.encodePacked(
++requestIdSeed, from, timeout, dataSource, selector)));
uint idx = dispatchJob(TrafficType.UserQuery, queryId);
// TODO: keep id receipt and handle later in v2.0.
if (idx == UINTMAX) {
emit LogError("No live working group, skipped query");
return 0;
}
Group storage grp = workingGroups[workingGroupIds[idx]];
PendingRequests[queryId] =
PendingRequest(queryId, grp.groupPubKey, from);
emit LogUrl(
queryId,
timeout,
dataSource,
selector,
lastRandomness,
grp.groupId
);
return queryId;
} else {
emit LogNonSupportedType(selector);
return 0;
}
} else {
// Skip if @from is not contract address.
emit LogNonContractCall(from);
return 0;
}
}
// Request a new user-level random number.
function requestRandom(address from, uint8 mode, uint userSeed)
public
returns (uint)
{
// fast mode
if (mode == 0) {
return uint(keccak256(abi.encodePacked(
++requestIdSeed,lastRandomness, userSeed)));
} else if (mode == 1) {
// safe mode
// TODO: restrict request from paid calling contract address.
uint requestId = uint(keccak256(abi.encodePacked(
++requestIdSeed, from, userSeed)));
uint idx = dispatchJob(TrafficType.UserRandom, requestId);
// TODO: keep id receipt and handle later in v2.0.
if (idx == UINTMAX) {
emit LogError("No live working group, skipped random request");
return 0;
}
Group storage grp = workingGroups[workingGroupIds[idx]];
PendingRequests[requestId] =
PendingRequest(requestId, grp.groupPubKey, from);
// sign(requestId ||lastSystemRandomness || userSeed ||
// selected sender in group)
emit LogRequestUserRandom(
requestId,
lastRandomness,
userSeed,
grp.groupId
);
return requestId;
} else {
revert("Non-supported random request");
}
}
// Random submitter validation + group signature verification.
function validateAndVerify(
uint8 trafficType,
uint trafficId,
bytes memory data,
BN256.G1Point memory signature,
BN256.G2Point memory grpPubKey,
uint8 version
)
private
returns (bool)
{
// Validation
// TODO
// 1. Check msg.sender is a member in Group(grpPubKey).
// Clients actually signs (data || addr(selected_submitter)).
bytes memory message = abi.encodePacked(data, msg.sender);
// Verification
bool passVerify = true;
emit LogValidationResult(
trafficType,
trafficId,
message,
[signature.x, signature.y],
[grpPubKey.x[0], grpPubKey.x[1], grpPubKey.y[0], grpPubKey.y[1]],
version,
passVerify
);
return passVerify;
}
function triggerCallback(
uint requestId,
uint8 trafficType,
bytes calldata result,
uint[2] calldata sig,
uint8 version
)
external
fromValidStakingNode
{
address ucAddr = PendingRequests[requestId].callbackAddr;
if (ucAddr == address(0x0)) {
emit LogRequestFromNonExistentUC();
return;
}
if (!validateAndVerify(
trafficType,
requestId,
result,
BN256.G1Point(sig[0], sig[1]),
PendingRequests[requestId].handledGroupPubKey,
version))
{
return;
}
emit LogCallbackTriggeredFor(ucAddr);
delete PendingRequests[requestId];
if (trafficType == uint8(TrafficType.UserQuery)) {
UserContractInterface(ucAddr).__callback__(requestId, result);
} else if (trafficType == uint8(TrafficType.UserRandom)) {
// Safe random number is the collectively signed threshold signature
// of the message (requestId || lastRandomness || userSeed ||
// selected sender in group).
UserContractInterface(ucAddr).__callback__(
requestId, uint(keccak256(abi.encodePacked(sig[0], sig[1]))));
} else {
revert("Unsupported traffic type");
}
}
function toBytes(uint x) private pure returns (bytes memory b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
// System-level secure distributed random number generator.
function updateRandomness(uint[2] calldata sig, uint8 version) external fromValidStakingNode {
if (!validateAndVerify(
uint8(TrafficType.SystemRandom),
lastRandomness,
toBytes(lastRandomness),
BN256.G1Point(sig[0], sig[1]),
lastHandledGroup.groupPubKey,
version))
{
return;
}
// Update new randomness = sha3(collectively signed group signature)
// TODO: include and test with blockhash.
lastRandomness = uint(keccak256(abi.encodePacked(sig[0], sig[1])));
lastUpdatedBlock = block.number;
}
/// @notice Caller ensures pendingGroupList is not empty and pending group header has indeed expired.
function cleanUpOldestExpiredPendingGroup(uint gid) private {
PendingGroup storage pgrp = pendingGroups[gid];
address member = pgrp.memberList[HEAD_A];
while (member != HEAD_A) {
// 1. Put member back to pendingNodeList's head if it's not in any workingGroup.
if (nodeToGroupIdList[member][HEAD_I] == HEAD_I && pendingNodeList[member] == address(0)) {
insertToPendingNodeListTail(member);
}
member = pgrp.memberList[member];
}
// 2. Update pendingGroupList
(uint prev, bool removed) = removeIdFromList(pendingGroupList, gid);
// Reset pendingGroupTail if necessary.
if (removed && pendingGroupTail == gid) {
pendingGroupTail = prev;
}
// 3. Update pendingGroup
delete pendingGroups[gid];
numPendingGroups--;
emit LogPendingGroupRemoved(gid);
}
/// Guardian node functions
// TODO: Tune guardian signal algorithm.
// TODO: Reward guardian nodes.
/// @dev Guardian signals expiring system randomness and kicks off distributed random engine again.
/// Anyone including but not limited to DOS client node can be a guardian and claim rewards.
function signalRandom() public {
if (lastUpdatedBlock + refreshSystemRandomHardLimit > block.number) {
emit LogError("SystemRandom not expired yet");
return;
}
kickoffRandom();
emit GuardianReward(block.number, msg.sender);
}
// TODO: Reward guardian nodes.
/// @dev Guardian signals to dissolve expired (workingGroup + pendingGroup) and claim guardian rewards.
function signalGroupDissolve() public {
bool claimed = false;
// Clean up oldest expired working group and related metadata.
if (expiredWorkingGroupIds.length > 0) {
dissolveWorkingGroup(expiredWorkingGroupIds[0], true);
expiredWorkingGroupIds[0] = expiredWorkingGroupIds[expiredWorkingGroupIds.length - 1];
expiredWorkingGroupIds.length--;
claimed = true;
} else {
emit LogError("No expired working group to clean up");
}
// Clean up oldest expired PendingGroup and related metadata. Might be due to failed DKG.
uint gid = pendingGroupList[HEAD_I];
if (gid != HEAD_I && pendingGroups[gid].startBlkNum + pendingGroupMaxLife < block.number) {
cleanUpOldestExpiredPendingGroup(gid);
claimed = true;
} else {
emit LogError("No expired pending group to clean up");
}
// Claim guardian rewards if work is done.
if (claimed) {
emit GuardianReward(block.number, msg.sender);
}
}
// TODO: Reward guardian nodes.
/// @dev Guardian signals to trigger group formation when there're enough pending nodes.
/// If there aren't enough working groups to choose to dossolve, probably a new bootstrap is needed.
function signalGroupFormation() public {
if (formGroup()) {
emit GuardianReward(block.number, msg.sender);
}
}
// TODO: Reward guardian nodes.
function signalBootstrap(uint _cid) public {
require(bootstrapRound == _cid, "Not in bootstrap phase");
if (numPendingNodes < bootstrapStartThreshold) {
emit LogError("Not enough nodes to bootstrap");
return;
}
// Reset.
bootstrapRound = 0;
uint rndSeed = 1;
lastRandomness = uint(keccak256(abi.encodePacked(lastRandomness, rndSeed)));
lastUpdatedBlock = block.number;
// TODO: Refine bootstrap algorithm to allow group overlapping.
uint arrSize = bootstrapStartThreshold / groupSize * groupSize;
address[] memory candidates = new address[](arrSize);
pick(arrSize, 0, candidates);
shuffle(candidates, rndSeed);
regroup(candidates, arrSize / groupSize);
emit GuardianReward(block.number, msg.sender);
}
/// End of Guardian functions
function unregisterNode() public fromValidStakingNode {
//1) Check if node is in pendingNodeList
if (pendingNodeList[msg.sender] != address(0)) {
// Update pendingNodeList
bool removed = removeNodeFromList(pendingNodeList, msg.sender);
// Reset pendingNodeTail if necessary.
if (removed) {
numPendingNodes--;
emit LogUnRegisteredNewPendingNode(msg.sender,1);
}
return;
}
//2) Check if node is in workingGroups
uint groupId = nodeToGroupIdList[msg.sender][HEAD_I];
if (groupId != 0 && groupId != HEAD_I) {
Group storage grp = workingGroups[groupId];
for (uint i = 0; i < grp.members.length; i++) {
address member = grp.members[i];
if (member == msg.sender) {
nodeToGroupIdList[msg.sender][HEAD_I] =0;
if (i != (grp.members.length - 1)){
grp.members[i] = grp.members[grp.members.length - 1];
}
grp.members.length--;
if (grp.members.length < (groupSize / 2 + 1 )){
dissolveWorkingGroup(groupId, true);
for (uint idx = 0; idx < workingGroupIds.length; idx++) {
if (workingGroupIds[idx] == groupId) {
if (idx != (workingGroupIds.length - 1)){
workingGroupIds[idx] = workingGroupIds[workingGroupIds.length - 1];
}
workingGroupIds.length--;
emit LogUnRegisteredNewPendingNode(msg.sender,2);
return;
}
}
for (uint idx = 0; idx < expiredWorkingGroupIds.length; idx++) {
if (expiredWorkingGroupIds[idx] == groupId) {
if (idx != (workingGroupIds.length - 1)){
expiredWorkingGroupIds[idx] = expiredWorkingGroupIds[expiredWorkingGroupIds.length - 1];
}
expiredWorkingGroupIds.length--;
emit LogUnRegisteredNewPendingNode(msg.sender,2);
return;
}
}
}
emit LogUnRegisteredNewPendingNode(msg.sender,2);
return;
}
}
return;
}
//3) Check if node is in pendingGroups
bool removed = removeNodeFromPendingGroup(pendingGroupList,msg.sender);
if (removed) {
emit LogUnRegisteredNewPendingNode(msg.sender,3);
}
}
// Caller ensures no index overflow.
function getGroupPubKey(uint idx) public view returns (uint[4] memory) {
BN256.G2Point storage pubKey = workingGroups[workingGroupIds[idx]].groupPubKey;
return [pubKey.x[0], pubKey.x[1], pubKey.y[0], pubKey.y[1]];
}
function getWorkingGroupSize() public view returns (uint) {
return workingGroupIds.length;
}
function getExpiredWorkingGroupSize() public view returns (uint) {
return expiredWorkingGroupIds.length;
}
function registerNewNode() public fromValidStakingNode {
//Duplicated pending node
if (pendingNodeList[msg.sender] != address(0)) {
return;
}
//Already registered in pending or working groups
if (nodeToGroupIdList[msg.sender][HEAD_I] != 0) {
return;
}
nodeToGroupIdList[msg.sender][HEAD_I] = HEAD_I;
insertToPendingNodeListTail(msg.sender);
emit LogRegisteredNewPendingNode(msg.sender);
formGroup();
}
// Form into new working groups or bootstrap if necessary.
// Return true if triggers state change.
function formGroup() private returns(bool) {
if (numPendingNodes < groupSize * groupingThreshold / 100) {
emit LogInsufficientPendingNode(numPendingNodes);
return false;
}
if (workingGroupIds.length >= groupToPick) {
requestRandom(address(this), 1, block.number);
emit LogGroupingInitiated(numPendingNodes, groupSize, groupingThreshold);
return true;
} else if (workingGroupIds.length + numPendingGroups >= groupToPick) {
emit LogInsufficientWorkingGroup(workingGroupIds.length, numPendingGroups);
return false;
} else if (numPendingNodes < bootstrapStartThreshold) {
emit LogError("Skipped signal, no enough nodes or groups in the network");
return false;
} else {
// System needs re-bootstrap
if (bootstrapRound == 0) {
bootstrapRound = 1;
return true;
} else {
emit LogError("Skipped group formation, already in bootstrap phase");
return false;
}
}
}
// callback to handle re-grouping using generated random number as random seed.
function __callback__(uint requestId, uint rndSeed) external {
require(msg.sender == address(this), "Unauthenticated response");
require(workingGroupIds.length >= groupToPick,
"No enough working group");
require(numPendingNodes >= groupSize * groupingThreshold / 100,
"Not enough newly registered nodes");
uint arrSize = groupSize * (groupToPick + 1);
address[] memory candidates = new address[](arrSize);
for (uint i = 0; i < groupToPick; i++) {
uint idx = uint(keccak256(abi.encodePacked(rndSeed, requestId, i))) % workingGroupIds.length;
Group storage grpToDissolve = workingGroups[workingGroupIds[idx]];
for (uint j = 0; j < groupSize; j++) {
candidates[i * groupSize + j] = grpToDissolve.members[j];
}
// Do not put chosen to-be-dissolved working group back to pending pool.
dissolveWorkingGroup(grpToDissolve.groupId, false);
workingGroupIds[idx] = workingGroupIds[workingGroupIds.length - 1];
workingGroupIds.length--;
}
pick(groupSize, groupSize * groupToPick, candidates);
shuffle(candidates, rndSeed);
regroup(candidates, groupToPick + 1);
}
// Pick @num nodes from pendingNodeList's head and put into the @candidates array from @startIndex.
function pick(uint num, uint startIndex, address[] memory candidates) private {
for (uint i = 0; i < num; i++) {
address curr = pendingNodeList[HEAD_A];
pendingNodeList[HEAD_A] = pendingNodeList[curr];
delete pendingNodeList[curr];
candidates[startIndex + i] = curr;
}
numPendingNodes -= num;
// Reset pendingNodeTail if necessary.
if (numPendingNodes == 0) {
pendingNodeTail = HEAD_A;
}
}
// Shuffle a memory array using a secure random seed.
function shuffle(address[] memory arr, uint rndSeed) private pure {
for (uint i = arr.length - 1; i > 0; i--) {
uint j = uint(keccak256(abi.encodePacked(rndSeed, i, arr[i]))) % (i + 1);
address tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
// Regroup a shuffled node array.
function regroup(address[] memory candidates, uint num) private {
require(candidates.length == groupSize * num);
address[] memory members = new address[](groupSize);
uint groupId;
for (uint i = 0; i < num; i++) {
groupId = 0;
// Generated groupId = sha3(...(sha3(sha3(member 1), member 2), ...), member n)
for (uint j = 0; j < groupSize; j++) {
members[j] = candidates[i * groupSize + j];
groupId = uint(keccak256(abi.encodePacked(groupId, members[j])));
}
pendingGroups[groupId] = PendingGroup(groupId, block.number);
mapping(address => address) storage memberList = pendingGroups[groupId].memberList;
memberList[HEAD_A] = HEAD_A;
for (uint j = 0; j < groupSize; j++) {
memberList[members[j]] = memberList[HEAD_A];
memberList[HEAD_A] = members[j];
}
insertToPendingGroupListTail(groupId);
emit LogGrouping(groupId, members);
}
}
function registerGroupPubKey(uint groupId, uint[4] calldata suggestedPubKey)
external
fromValidStakingNode
{
PendingGroup storage pgrp = pendingGroups[groupId];
if (pgrp.groupId == 0) {
emit LogNoPendingGroup(groupId);
return;
}
require(pgrp.memberList[msg.sender] != address(0), "Not from authorized group member");
bytes32 hashedPubKey = keccak256(abi.encodePacked(
suggestedPubKey[0], suggestedPubKey[1], suggestedPubKey[2], suggestedPubKey[3]));
pgrp.pubKeyCounts[hashedPubKey]++;
emit LogPublicKeySuggested(groupId, pgrp.pubKeyCounts[hashedPubKey]);
if (pgrp.pubKeyCounts[hashedPubKey] > groupSize / 2) {
address[] memory memberArray = new address[](groupSize);
uint idx = 0;
address member = pgrp.memberList[HEAD_A];
while (member != HEAD_A) {
memberArray[idx++] = member;
// Update nodeToGroupIdList[member] with new group id.
insertToListHead(nodeToGroupIdList[member], groupId);
member = pgrp.memberList[member];
}
workingGroupIds.push(groupId);
workingGroups[groupId] = Group(
groupId,
BN256.G2Point([suggestedPubKey[0], suggestedPubKey[1]], [suggestedPubKey[2], suggestedPubKey[3]]),
block.number,
memberArray
);
// Update pendingGroupList
(uint prev, bool removed) = removeIdFromList(pendingGroupList, groupId);
// Reset pendingGroupTail if necessary.
if (removed && pendingGroupTail == groupId) {
pendingGroupTail = prev;
}
// Update pendingGroup
delete pendingGroups[groupId];
numPendingGroups--;
emit LogPendingGroupRemoved(groupId);
emit LogPublicKeyAccepted(groupId, suggestedPubKey, workingGroupIds.length);
}
}
}
|
Shuffle a memory array using a secure random seed.
|
function shuffle(address[] memory arr, uint rndSeed) private pure {
for (uint i = arr.length - 1; i > 0; i--) {
uint j = uint(keccak256(abi.encodePacked(rndSeed, i, arr[i]))) % (i + 1);
address tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
| 886,856
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./lib/SafeMath.sol";
import "./lib/Context.sol";
import "./lib/Ownable.sol";
import "./lib/Address.sol";
import "./lib/IERC20.sol";
import "./lib/IXAUToken.sol";
import "./lib/IFeeApprover.sol";
import "./lib/IXAUVault.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 XAUToken is IXAUToken, Context, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
address public override rebaser;
uint256 internal _totalSupply;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10**18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 internal xauScalingFactor;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10**24;
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 public initialSupply;
uint256 public initialSupplyUnderlying;
uint256 public contractStartTimestamp;
/**
* @dev Returns the name of the token.
*/
function name() public override view returns (string memory) {
return _name;
}
constructor (
string memory __name,
string memory __symbol,
uint256 __initialSupply
) public {
_name = __name;
_symbol = __symbol;
_decimals = 18;
xauScalingFactor = BASE;
initialSupply = __initialSupply;
initialSupplyUnderlying = _toUnderlying(__initialSupply);
_totalSupply = __initialSupply;
_balances[address(msg.sender)] = initialSupplyUnderlying;
contractStartTimestamp = block.timestamp;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public override 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 override view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
// function balanceOf(address account) public override returns (uint256) {
// return _balances[account];
// }
function balanceOf(address _owner) public override view returns (uint256) {
return _fromUnderlying(_balances[_owner]);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
override
view
returns (uint256)
{
return _balances[who];
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
override
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initialSupplyUnderlying * xauScalingFactor
// this is used to check if xauScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initialSupplyUnderlying;
}
function fromUnderlying(uint256 underlying)
external
override
view
returns (uint256)
{
return _fromUnderlying(underlying);
}
function toUnderlying(uint256 value)
external
override
view
returns (uint256)
{
return _toUnderlying(value);
}
function _fromUnderlying(uint256 underlying)
internal
view
returns (uint256)
{
return underlying.mul(xauScalingFactor).div(internalDecimals);
}
function _toUnderlying(uint256 value)
internal
view
returns (uint256)
{
return value.mul(internalDecimals).div(xauScalingFactor);
}
function scalingFactor()
external
override
view
returns (uint256)
{
return xauScalingFactor;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
override
onlyRebaser
returns (uint256)
{
// no change
if (indexDelta == 0) {
emit Rebase(epoch, xauScalingFactor, xauScalingFactor);
return _totalSupply;
}
// for events
uint256 oldScalingFactor = xauScalingFactor;
if (!positive) {
// negative rebase, decrease scaling factor
xauScalingFactor = xauScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
require(xauScalingFactor > 0); // FIX: ensure that scaling factor won't drop down to zero as this would be unrecoverable
} else {
// positive reabse, increase scaling factor
uint256 newScalingFactor = xauScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
xauScalingFactor = newScalingFactor;
} else {
xauScalingFactor = _maxScalingFactor();
}
}
// update total supply, correctly
_totalSupply = _fromUnderlying(initialSupplyUnderlying);
emit Rebase(epoch, oldScalingFactor, xauScalingFactor);
return _totalSupply;
}
/** @notice sets the rebaser
* @param _rebaser The address of the rebaser contract to use for authentication.
*/
function setRebaser(address _rebaser)
external
override
onlyOwner
{
address oldRebaser = rebaser;
rebaser = _rebaser;
emit NewRebaser(oldRebaser, _rebaser);
}
/**
* @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
virtual
override
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
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
override
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
override
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
address public override transferHandler;
function setTransferHandler(address _transferHandler)
public
override
onlyOwner
{
address oldTransferHandler = transferHandler;
transferHandler = _transferHandler;
emit NewTransferHandler(oldTransferHandler, _transferHandler);
}
address public override feeDistributor;
function setFeeDistributor(address _feeDistributor)
public
override
onlyOwner
{
address oldFeeDistributor = feeDistributor;
feeDistributor = _feeDistributor;
emit NewFeeDistributor(oldFeeDistributor, _feeDistributor);
}
/**
* @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");
// Divide by current scaling factor to get underlying balance
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == xauScalingFactor / 1e24;
// get amount in underlying
uint256 underlying = _toUnderlying(amount);
_balances[sender] = _balances[sender].sub(
underlying,
"ERC20: transfer amount exceeds balance"
);
(uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = IFeeApprover(transferHandler).calculateAmountsAfterFee(sender, recipient, underlying);
// Addressing a broken checker contract
require(transferToAmount.add(transferToFeeDistributorAmount) == underlying, "Math broke, does gravity still work?");
_balances[recipient] = _balances[recipient].add(transferToAmount);
emit Transfer(sender, recipient, _fromUnderlying(transferToAmount));
if (transferToFeeDistributorAmount > 0 && feeDistributor != address(0)) {
_balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount);
emit Transfer(sender, feeDistributor, _fromUnderlying(transferToFeeDistributorAmount));
if (feeDistributor != address(0)) {
IXAUVault(feeDistributor).addPendingRewards(transferToFeeDistributorAmount);
}
}
}
/**
* @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 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 {
_decimals = decimals_;
}
// Gives governance ability to recover any ERC20 tokens mistakenly sent to this contract address.
function recoverERC20(
address token,
address to,
uint256 amount
)
external
override
onlyOwner
returns (bool)
{
return IERC20(token).transfer(to, amount);
}
}
|
sets the rebaser _rebaser The address of the rebaser contract to use for authentication./
|
function setRebaser(address _rebaser)
external
override
onlyOwner
{
address oldRebaser = rebaser;
rebaser = _rebaser;
emit NewRebaser(oldRebaser, _rebaser);
}
| 12,866,436
|
// simple planet invitation management contract
// https://azimuth.network
pragma solidity 0.4.24;
////////////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////////////
// OpenZeppelin's 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.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
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;
}
}
// Azimuth's SafeMath8.sol
/**
* @title SafeMath8
* @dev Math operations for uint8 with safety checks that throw on error
*/
library SafeMath8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}
// Azimuth's SafeMath16.sol
/**
* @title SafeMath16
* @dev Math operations for uint16 with safety checks that throw on error
*/
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint16 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}
// OpenZeppelin's 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;
}
}
// OpenZeppelin's ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// OpenZeppelin's SupportsInterfaceWithLookup.sol
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
// OpenZeppelin's ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// OpenZeppelin's ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// OpenZeppelin's ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// OpenZeppelin's AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// Azimuth's Azimuth.sol
// Azimuth: point state data contract
//
// This contract is used for storing all data related to Azimuth points
// and their ownership. Consider this contract the Azimuth ledger.
//
// It also contains permissions data, which ties in to ERC721
// functionality. Operators of an address are allowed to transfer
// ownership of all points owned by their associated address
// (ERC721's approveAll()). A transfer proxy is allowed to transfer
// ownership of a single point (ERC721's approve()).
// Separate from ERC721 are managers, assigned per point. They are
// allowed to perform "low-impact" operations on the owner's points,
// like configuring public keys and making escape requests.
//
// Since data stores are difficult to upgrade, this contract contains
// as little actual business logic as possible. Instead, the data stored
// herein can only be modified by this contract's owner, which can be
// changed and is thus upgradable/replaceable.
//
// This contract will be owned by the Ecliptic contract.
//
contract Azimuth is Ownable
{
//
// Events
//
// OwnerChanged: :point is now owned by :owner
//
event OwnerChanged(uint32 indexed point, address indexed owner);
// Activated: :point is now active
//
event Activated(uint32 indexed point);
// Spawned: :prefix has spawned :child
//
event Spawned(uint32 indexed prefix, uint32 indexed child);
// EscapeRequested: :point has requested a new :sponsor
//
event EscapeRequested(uint32 indexed point, uint32 indexed sponsor);
// EscapeCanceled: :point's :sponsor request was canceled or rejected
//
event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor);
// EscapeAccepted: :point confirmed with a new :sponsor
//
event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor);
// LostSponsor: :point's :sponsor is now refusing it service
//
event LostSponsor(uint32 indexed point, uint32 indexed sponsor);
// ChangedKeys: :point has new network public keys
//
event ChangedKeys( uint32 indexed point,
bytes32 encryptionKey,
bytes32 authenticationKey,
uint32 cryptoSuiteVersion,
uint32 keyRevisionNumber );
// BrokeContinuity: :point has a new continuity number, :number
//
event BrokeContinuity(uint32 indexed point, uint32 number);
// ChangedSpawnProxy: :spawnProxy can now spawn using :point
//
event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy);
// ChangedTransferProxy: :transferProxy can now transfer ownership of :point
//
event ChangedTransferProxy( uint32 indexed point,
address indexed transferProxy );
// ChangedManagementProxy: :managementProxy can now manage :point
//
event ChangedManagementProxy( uint32 indexed point,
address indexed managementProxy );
// ChangedVotingProxy: :votingProxy can now vote using :point
//
event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy);
// ChangedDns: dnsDomains have been updated
//
event ChangedDns(string primary, string secondary, string tertiary);
//
// Structures
//
// Size: kinds of points registered on-chain
//
// NOTE: the order matters, because of Solidity enum numbering
//
enum Size
{
Galaxy, // = 0
Star, // = 1
Planet // = 2
}
// Point: state of a point
//
// While the ordering of the struct members is semantically chaotic,
// they are ordered to tightly pack them into Ethereum's 32-byte storage
// slots, which reduces gas costs for some function calls.
// The comment ticks indicate assumed slot boundaries.
//
struct Point
{
// encryptionKey: (curve25519) encryption public key, or 0 for none
//
bytes32 encryptionKey;
//
// authenticationKey: (ed25519) authentication public key, or 0 for none
//
bytes32 authenticationKey;
//
// spawned: for stars and galaxies, all :active children
//
uint32[] spawned;
//
// hasSponsor: true if the sponsor still supports the point
//
bool hasSponsor;
// active: whether point can be linked
//
// false: point belongs to prefix, cannot be configured or linked
// true: point no longer belongs to prefix, can be configured and linked
//
bool active;
// escapeRequested: true if the point has requested to change sponsors
//
bool escapeRequested;
// sponsor: the point that supports this one on the network, or,
// if :hasSponsor is false, the last point that supported it.
// (by default, the point's half-width prefix)
//
uint32 sponsor;
// escapeRequestedTo: if :escapeRequested is true, new sponsor requested
//
uint32 escapeRequestedTo;
// cryptoSuiteVersion: version of the crypto suite used for the pubkeys
//
uint32 cryptoSuiteVersion;
// keyRevisionNumber: incremented every time the public keys change
//
uint32 keyRevisionNumber;
// continuityNumber: incremented to indicate network-side state loss
//
uint32 continuityNumber;
}
// Deed: permissions for a point
//
struct Deed
{
// owner: address that owns this point
//
address owner;
// managementProxy: 0, or another address with the right to perform
// low-impact, managerial operations on this point
//
address managementProxy;
// spawnProxy: 0, or another address with the right to spawn children
// of this point
//
address spawnProxy;
// votingProxy: 0, or another address with the right to vote as this point
//
address votingProxy;
// transferProxy: 0, or another address with the right to transfer
// ownership of this point
//
address transferProxy;
}
//
// General state
//
// points: per point, general network-relevant point state
//
mapping(uint32 => Point) public points;
// rights: per point, on-chain ownership and permissions
//
mapping(uint32 => Deed) public rights;
// operators: per owner, per address, has the right to transfer ownership
// of all the owner's points (ERC721)
//
mapping(address => mapping(address => bool)) public operators;
// dnsDomains: base domains for contacting galaxies
//
// dnsDomains[0] is primary, the others are used as fallbacks
//
string[3] public dnsDomains;
//
// Lookups
//
// sponsoring: per point, the points they are sponsoring
//
mapping(uint32 => uint32[]) public sponsoring;
// sponsoringIndexes: per point, per point, (index + 1) in
// the sponsoring array
//
mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes;
// escapeRequests: per point, the points they have open escape requests from
//
mapping(uint32 => uint32[]) public escapeRequests;
// escapeRequestsIndexes: per point, per point, (index + 1) in
// the escapeRequests array
//
mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes;
// pointsOwnedBy: per address, the points they own
//
mapping(address => uint32[]) public pointsOwnedBy;
// pointOwnerIndexes: per owner, per point, (index + 1) in
// the pointsOwnedBy array
//
// We delete owners by moving the last entry in the array to the
// newly emptied slot, which is (n - 1) where n is the value of
// pointOwnerIndexes[owner][point].
//
mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes;
// managerFor: per address, the points they are the management proxy for
//
mapping(address => uint32[]) public managerFor;
// managerForIndexes: per address, per point, (index + 1) in
// the managerFor array
//
mapping(address => mapping(uint32 => uint256)) public managerForIndexes;
// spawningFor: per address, the points they can spawn with
//
mapping(address => uint32[]) public spawningFor;
// spawningForIndexes: per address, per point, (index + 1) in
// the spawningFor array
//
mapping(address => mapping(uint32 => uint256)) public spawningForIndexes;
// votingFor: per address, the points they can vote with
//
mapping(address => uint32[]) public votingFor;
// votingForIndexes: per address, per point, (index + 1) in
// the votingFor array
//
mapping(address => mapping(uint32 => uint256)) public votingForIndexes;
// transferringFor: per address, the points they can transfer
//
mapping(address => uint32[]) public transferringFor;
// transferringForIndexes: per address, per point, (index + 1) in
// the transferringFor array
//
mapping(address => mapping(uint32 => uint256)) public transferringForIndexes;
//
// Logic
//
// constructor(): configure default dns domains
//
constructor()
public
{
setDnsDomains("example.com", "example.com", "example.com");
}
// setDnsDomains(): set the base domains used for contacting galaxies
//
// Note: since a string is really just a byte[], and Solidity can't
// work with two-dimensional arrays yet, we pass in the three
// domains as individual strings.
//
function setDnsDomains(string _primary, string _secondary, string _tertiary)
onlyOwner
public
{
dnsDomains[0] = _primary;
dnsDomains[1] = _secondary;
dnsDomains[2] = _tertiary;
emit ChangedDns(_primary, _secondary, _tertiary);
}
//
// Point reading
//
// isActive(): return true if _point is active
//
function isActive(uint32 _point)
view
external
returns (bool equals)
{
return points[_point].active;
}
// getKeys(): returns the public keys and their details, as currently
// registered for _point
//
function getKeys(uint32 _point)
view
external
returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision)
{
Point storage point = points[_point];
return (point.encryptionKey,
point.authenticationKey,
point.cryptoSuiteVersion,
point.keyRevisionNumber);
}
// getKeyRevisionNumber(): gets the revision number of _point's current
// public keys
//
function getKeyRevisionNumber(uint32 _point)
view
external
returns (uint32 revision)
{
return points[_point].keyRevisionNumber;
}
// hasBeenLinked(): returns true if the point has ever been assigned keys
//
function hasBeenLinked(uint32 _point)
view
external
returns (bool result)
{
return ( points[_point].keyRevisionNumber > 0 );
}
// isLive(): returns true if _point currently has keys properly configured
//
function isLive(uint32 _point)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.encryptionKey != 0 &&
point.authenticationKey != 0 &&
point.cryptoSuiteVersion != 0 );
}
// getContinuityNumber(): returns _point's current continuity number
//
function getContinuityNumber(uint32 _point)
view
external
returns (uint32 continuityNumber)
{
return points[_point].continuityNumber;
}
// getSpawnCount(): return the number of children spawned by _point
//
function getSpawnCount(uint32 _point)
view
external
returns (uint32 spawnCount)
{
uint256 len = points[_point].spawned.length;
assert(len < 2**32);
return uint32(len);
}
// getSpawned(): return array of points created under _point
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawned(uint32 _point)
view
external
returns (uint32[] spawned)
{
return points[_point].spawned;
}
// hasSponsor(): returns true if _point's sponsor is providing it service
//
function hasSponsor(uint32 _point)
view
external
returns (bool has)
{
return points[_point].hasSponsor;
}
// getSponsor(): returns _point's current (or most recent) sponsor
//
function getSponsor(uint32 _point)
view
external
returns (uint32 sponsor)
{
return points[_point].sponsor;
}
// isSponsor(): returns true if _sponsor is currently providing service
// to _point
//
function isSponsor(uint32 _point, uint32 _sponsor)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.hasSponsor &&
(point.sponsor == _sponsor) );
}
// getSponsoringCount(): returns the number of points _sponsor is
// providing service to
//
function getSponsoringCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return sponsoring[_sponsor].length;
}
// getSponsoring(): returns a list of points _sponsor is providing
// service to
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSponsoring(uint32 _sponsor)
view
external
returns (uint32[] sponsees)
{
return sponsoring[_sponsor];
}
// escaping
// isEscaping(): returns true if _point has an outstanding escape request
//
function isEscaping(uint32 _point)
view
external
returns (bool escaping)
{
return points[_point].escapeRequested;
}
// getEscapeRequest(): returns _point's current escape request
//
// the returned escape request is only valid as long as isEscaping()
// returns true
//
function getEscapeRequest(uint32 _point)
view
external
returns (uint32 escape)
{
return points[_point].escapeRequestedTo;
}
// isRequestingEscapeTo(): returns true if _point has an outstanding
// escape request targetting _sponsor
//
function isRequestingEscapeTo(uint32 _point, uint32 _sponsor)
view
public
returns (bool equals)
{
Point storage point = points[_point];
return (point.escapeRequested && (point.escapeRequestedTo == _sponsor));
}
// getEscapeRequestsCount(): returns the number of points _sponsor
// is providing service to
//
function getEscapeRequestsCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return escapeRequests[_sponsor].length;
}
// getEscapeRequests(): get the points _sponsor has received escape
// requests from
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getEscapeRequests(uint32 _sponsor)
view
external
returns (uint32[] requests)
{
return escapeRequests[_sponsor];
}
//
// Point writing
//
// activatePoint(): activate a point, register it as spawned by its prefix
//
function activatePoint(uint32 _point)
onlyOwner
external
{
// make a point active, setting its sponsor to its prefix
//
Point storage point = points[_point];
require(!point.active);
point.active = true;
registerSponsor(_point, true, getPrefix(_point));
emit Activated(_point);
}
// setKeys(): set network public keys of _point to _encryptionKey and
// _authenticationKey, with the specified _cryptoSuiteVersion
//
function setKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion)
onlyOwner
external
{
Point storage point = points[_point];
if ( point.encryptionKey == _encryptionKey &&
point.authenticationKey == _authenticationKey &&
point.cryptoSuiteVersion == _cryptoSuiteVersion )
{
return;
}
point.encryptionKey = _encryptionKey;
point.authenticationKey = _authenticationKey;
point.cryptoSuiteVersion = _cryptoSuiteVersion;
point.keyRevisionNumber++;
emit ChangedKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion,
point.keyRevisionNumber);
}
// incrementContinuityNumber(): break continuity for _point
//
function incrementContinuityNumber(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
point.continuityNumber++;
emit BrokeContinuity(_point, point.continuityNumber);
}
// registerSpawn(): add a point to its prefix's list of spawned points
//
function registerSpawned(uint32 _point)
onlyOwner
external
{
// if a point is its own prefix (a galaxy) then don't register it
//
uint32 prefix = getPrefix(_point);
if (prefix == _point)
{
return;
}
// register a new spawned point for the prefix
//
points[prefix].spawned.push(_point);
emit Spawned(prefix, _point);
}
// loseSponsor(): indicates that _point's sponsor is no longer providing
// it service
//
function loseSponsor(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.hasSponsor)
{
return;
}
registerSponsor(_point, false, point.sponsor);
emit LostSponsor(_point, point.sponsor);
}
// setEscapeRequest(): for _point, start an escape request to _sponsor
//
function setEscapeRequest(uint32 _point, uint32 _sponsor)
onlyOwner
external
{
if (isRequestingEscapeTo(_point, _sponsor))
{
return;
}
registerEscapeRequest(_point, true, _sponsor);
emit EscapeRequested(_point, _sponsor);
}
// cancelEscape(): for _point, stop the current escape request, if any
//
function cancelEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.escapeRequested)
{
return;
}
uint32 request = point.escapeRequestedTo;
registerEscapeRequest(_point, false, 0);
emit EscapeCanceled(_point, request);
}
// doEscape(): perform the requested escape
//
function doEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
require(point.escapeRequested);
registerSponsor(_point, true, point.escapeRequestedTo);
registerEscapeRequest(_point, false, 0);
emit EscapeAccepted(_point, point.sponsor);
}
//
// Point utils
//
// getPrefix(): compute prefix ("parent") of _point
//
function getPrefix(uint32 _point)
pure
public
returns (uint16 prefix)
{
if (_point < 0x10000)
{
return uint16(_point % 0x100);
}
return uint16(_point % 0x10000);
}
// getPointSize(): return the size of _point
//
function getPointSize(uint32 _point)
external
pure
returns (Size _size)
{
if (_point < 0x100) return Size.Galaxy;
if (_point < 0x10000) return Size.Star;
return Size.Planet;
}
// internal use
// registerSponsor(): set the sponsorship state of _point and update the
// reverse lookup for sponsors
//
function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor)
internal
{
Point storage point = points[_point];
bool had = point.hasSponsor;
uint32 prev = point.sponsor;
// if we didn't have a sponsor, and won't get one,
// or if we get the sponsor we already have,
// nothing will change, so jump out early.
//
if ( (!had && !_hasSponsor) ||
(had && _hasSponsor && prev == _sponsor) )
{
return;
}
// if the point used to have a different sponsor, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (had)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = sponsoringIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :sponsoringIndexes reference
//
uint32[] storage prevSponsoring = sponsoring[prev];
uint256 last = prevSponsoring.length - 1;
uint32 moved = prevSponsoring[last];
prevSponsoring[i] = moved;
sponsoringIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSponsoring[last]);
prevSponsoring.length = last;
sponsoringIndexes[prev][_point] = 0;
}
if (_hasSponsor)
{
uint32[] storage newSponsoring = sponsoring[_sponsor];
newSponsoring.push(_point);
sponsoringIndexes[_sponsor][_point] = newSponsoring.length;
}
point.sponsor = _sponsor;
point.hasSponsor = _hasSponsor;
}
// registerEscapeRequest(): set the escape state of _point and update the
// reverse lookup for sponsors
//
function registerEscapeRequest( uint32 _point,
bool _isEscaping, uint32 _sponsor )
internal
{
Point storage point = points[_point];
bool was = point.escapeRequested;
uint32 prev = point.escapeRequestedTo;
// if we weren't escaping, and won't be,
// or if we were escaping, and the new target is the same,
// nothing will change, so jump out early.
//
if ( (!was && !_isEscaping) ||
(was && _isEscaping && prev == _sponsor) )
{
return;
}
// if the point used to have a different request, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (was)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = escapeRequestsIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :escapeRequestsIndexes reference
//
uint32[] storage prevRequests = escapeRequests[prev];
uint256 last = prevRequests.length - 1;
uint32 moved = prevRequests[last];
prevRequests[i] = moved;
escapeRequestsIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevRequests[last]);
prevRequests.length = last;
escapeRequestsIndexes[prev][_point] = 0;
}
if (_isEscaping)
{
uint32[] storage newRequests = escapeRequests[_sponsor];
newRequests.push(_point);
escapeRequestsIndexes[_sponsor][_point] = newRequests.length;
}
point.escapeRequestedTo = _sponsor;
point.escapeRequested = _isEscaping;
}
//
// Deed reading
//
// owner
// getOwner(): return owner of _point
//
function getOwner(uint32 _point)
view
external
returns (address owner)
{
return rights[_point].owner;
}
// isOwner(): true if _point is owned by _address
//
function isOwner(uint32 _point, address _address)
view
external
returns (bool result)
{
return (rights[_point].owner == _address);
}
// getOwnedPointCount(): return length of array of points that _whose owns
//
function getOwnedPointCount(address _whose)
view
external
returns (uint256 count)
{
return pointsOwnedBy[_whose].length;
}
// getOwnedPoints(): return array of points that _whose owns
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getOwnedPoints(address _whose)
view
external
returns (uint32[] ownedPoints)
{
return pointsOwnedBy[_whose];
}
// getOwnedPointAtIndex(): get point at _index from array of points that
// _whose owns
//
function getOwnedPointAtIndex(address _whose, uint256 _index)
view
external
returns (uint32 point)
{
uint32[] storage owned = pointsOwnedBy[_whose];
require(_index < owned.length);
return owned[_index];
}
// management proxy
// getManagementProxy(): returns _point's current management proxy
//
function getManagementProxy(uint32 _point)
view
external
returns (address manager)
{
return rights[_point].managementProxy;
}
// isManagementProxy(): returns true if _proxy is _point's management proxy
//
function isManagementProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].managementProxy == _proxy);
}
// canManage(): true if _who is the owner or manager of _point
//
function canManage(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.managementProxy) ) );
}
// getManagerForCount(): returns the amount of points _proxy can manage
//
function getManagerForCount(address _proxy)
view
external
returns (uint256 count)
{
return managerFor[_proxy].length;
}
// getManagerFor(): returns the points _proxy can manage
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getManagerFor(address _proxy)
view
external
returns (uint32[] mfor)
{
return managerFor[_proxy];
}
// spawn proxy
// getSpawnProxy(): returns _point's current spawn proxy
//
function getSpawnProxy(uint32 _point)
view
external
returns (address spawnProxy)
{
return rights[_point].spawnProxy;
}
// isSpawnProxy(): returns true if _proxy is _point's spawn proxy
//
function isSpawnProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].spawnProxy == _proxy);
}
// canSpawnAs(): true if _who is the owner or spawn proxy of _point
//
function canSpawnAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.spawnProxy) ) );
}
// getSpawningForCount(): returns the amount of points _proxy
// can spawn with
//
function getSpawningForCount(address _proxy)
view
external
returns (uint256 count)
{
return spawningFor[_proxy].length;
}
// getSpawningFor(): get the points _proxy can spawn with
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawningFor(address _proxy)
view
external
returns (uint32[] sfor)
{
return spawningFor[_proxy];
}
// voting proxy
// getVotingProxy(): returns _point's current voting proxy
//
function getVotingProxy(uint32 _point)
view
external
returns (address voter)
{
return rights[_point].votingProxy;
}
// isVotingProxy(): returns true if _proxy is _point's voting proxy
//
function isVotingProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].votingProxy == _proxy);
}
// canVoteAs(): true if _who is the owner of _point,
// or the voting proxy of _point's owner
//
function canVoteAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.votingProxy) ) );
}
// getVotingForCount(): returns the amount of points _proxy can vote as
//
function getVotingForCount(address _proxy)
view
external
returns (uint256 count)
{
return votingFor[_proxy].length;
}
// getVotingFor(): returns the points _proxy can vote as
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getVotingFor(address _proxy)
view
external
returns (uint32[] vfor)
{
return votingFor[_proxy];
}
// transfer proxy
// getTransferProxy(): returns _point's current transfer proxy
//
function getTransferProxy(uint32 _point)
view
external
returns (address transferProxy)
{
return rights[_point].transferProxy;
}
// isTransferProxy(): returns true if _proxy is _point's transfer proxy
//
function isTransferProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].transferProxy == _proxy);
}
// canTransfer(): true if _who is the owner or transfer proxy of _point,
// or is an operator for _point's current owner
//
function canTransfer(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.transferProxy) ||
operators[deed.owner][_who] ) );
}
// getTransferringForCount(): returns the amount of points _proxy
// can transfer
//
function getTransferringForCount(address _proxy)
view
external
returns (uint256 count)
{
return transferringFor[_proxy].length;
}
// getTransferringFor(): get the points _proxy can transfer
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getTransferringFor(address _proxy)
view
external
returns (uint32[] tfor)
{
return transferringFor[_proxy];
}
// isOperator(): returns true if _operator is allowed to transfer
// ownership of _owner's points
//
function isOperator(address _owner, address _operator)
view
external
returns (bool result)
{
return operators[_owner][_operator];
}
//
// Deed writing
//
// setOwner(): set owner of _point to _owner
//
// Note: setOwner() only implements the minimal data storage
// logic for a transfer; the full transfer is implemented in
// Ecliptic.
//
// Note: _owner must not be the zero address.
//
function setOwner(uint32 _point, address _owner)
onlyOwner
external
{
// prevent burning of points by making zero the owner
//
require(0x0 != _owner);
// prev: previous owner, if any
//
address prev = rights[_point].owner;
if (prev == _owner)
{
return;
}
// if the point used to have a different owner, do some gymnastics to
// keep the list of owned points gapless. delete this point from the
// list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous owner's list of owned points
//
uint256 i = pointOwnerIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :pointOwnerIndexes reference
//
uint32[] storage owner = pointsOwnedBy[prev];
uint256 last = owner.length - 1;
uint32 moved = owner[last];
owner[i] = moved;
pointOwnerIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(owner[last]);
owner.length = last;
pointOwnerIndexes[prev][_point] = 0;
}
// update the owner list and the owner's index list
//
rights[_point].owner = _owner;
pointsOwnedBy[_owner].push(_point);
pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length;
emit OwnerChanged(_point, _owner);
}
// setManagementProxy(): makes _proxy _point's management proxy
//
function setManagementProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.managementProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different manager, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old manager's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous manager's list of managed points
//
uint256 i = managerForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :managerForIndexes reference
//
uint32[] storage prevMfor = managerFor[prev];
uint256 last = prevMfor.length - 1;
uint32 moved = prevMfor[last];
prevMfor[i] = moved;
managerForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevMfor[last]);
prevMfor.length = last;
managerForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage mfor = managerFor[_proxy];
mfor.push(_point);
managerForIndexes[_proxy][_point] = mfor.length;
}
deed.managementProxy = _proxy;
emit ChangedManagementProxy(_point, _proxy);
}
// setSpawnProxy(): makes _proxy _point's spawn proxy
//
function setSpawnProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.spawnProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different spawn proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of spawning points
//
uint256 i = spawningForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :spawningForIndexes reference
//
uint32[] storage prevSfor = spawningFor[prev];
uint256 last = prevSfor.length - 1;
uint32 moved = prevSfor[last];
prevSfor[i] = moved;
spawningForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSfor[last]);
prevSfor.length = last;
spawningForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage sfor = spawningFor[_proxy];
sfor.push(_point);
spawningForIndexes[_proxy][_point] = sfor.length;
}
deed.spawnProxy = _proxy;
emit ChangedSpawnProxy(_point, _proxy);
}
// setVotingProxy(): makes _proxy _point's voting proxy
//
function setVotingProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.votingProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different voter, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old voter's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous voter's list of points it was
// voting for
//
uint256 i = votingForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :votingForIndexes reference
//
uint32[] storage prevVfor = votingFor[prev];
uint256 last = prevVfor.length - 1;
uint32 moved = prevVfor[last];
prevVfor[i] = moved;
votingForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevVfor[last]);
prevVfor.length = last;
votingForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage vfor = votingFor[_proxy];
vfor.push(_point);
votingForIndexes[_proxy][_point] = vfor.length;
}
deed.votingProxy = _proxy;
emit ChangedVotingProxy(_point, _proxy);
}
// setManagementProxy(): makes _proxy _point's transfer proxy
//
function setTransferProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.transferProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different transfer proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of transferable points
//
uint256 i = transferringForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :transferringForIndexes reference
//
uint32[] storage prevTfor = transferringFor[prev];
uint256 last = prevTfor.length - 1;
uint32 moved = prevTfor[last];
prevTfor[i] = moved;
transferringForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevTfor[last]);
prevTfor.length = last;
transferringForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage tfor = transferringFor[_proxy];
tfor.push(_point);
transferringForIndexes[_proxy][_point] = tfor.length;
}
deed.transferProxy = _proxy;
emit ChangedTransferProxy(_point, _proxy);
}
// setOperator(): dis/allow _operator to transfer ownership of all points
// owned by _owner
//
// operators are part of the ERC721 standard
//
function setOperator(address _owner, address _operator, bool _approved)
onlyOwner
external
{
operators[_owner][_operator] = _approved;
}
}
// Azimuth's ReadsAzimuth.sol
// ReadsAzimuth: referring to and testing against the Azimuth
// data contract
//
// To avoid needless repetition, this contract provides common
// checks and operations using the Azimuth contract.
//
contract ReadsAzimuth
{
// azimuth: points data storage contract.
//
Azimuth public azimuth;
// constructor(): set the Azimuth data contract's address
//
constructor(Azimuth _azimuth)
public
{
azimuth = _azimuth;
}
// activePointOwner(): require that :msg.sender is the owner of _point,
// and that _point is active
//
modifier activePointOwner(uint32 _point)
{
require( azimuth.isOwner(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointManager(): require that :msg.sender can manage _point,
// and that _point is active
//
modifier activePointManager(uint32 _point)
{
require( azimuth.canManage(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
}
// Azimuth's Polls.sol
// Polls: proposals & votes data contract
//
// This contract is used for storing all data related to the proposals
// of the senate (galaxy owners) and their votes on those proposals.
// It keeps track of votes and uses them to calculate whether a majority
// is in favor of a proposal.
//
// Every galaxy can only vote on a proposal exactly once. Votes cannot
// be changed. If a proposal fails to achieve majority within its
// duration, it can be restarted after its cooldown period has passed.
//
// The requirements for a proposal to achieve majority are as follows:
// - At least 1/4 of the currently active voters (rounded down) must have
// voted in favor of the proposal,
// - More than half of the votes cast must be in favor of the proposal,
// and this can no longer change, either because
// - the poll duration has passed, or
// - not enough voters remain to take away the in-favor majority.
// As soon as these conditions are met, no further interaction with
// the proposal is possible. Achieving majority is permanent.
//
// Since data stores are difficult to upgrade, all of the logic unrelated
// to the voting itself (that is, determining who is eligible to vote)
// is expected to be implemented by this contract's owner.
//
// This contract will be owned by the Ecliptic contract.
//
contract Polls is Ownable
{
using SafeMath for uint256;
using SafeMath16 for uint16;
using SafeMath8 for uint8;
// UpgradePollStarted: a poll on :proposal has opened
//
event UpgradePollStarted(address proposal);
// DocumentPollStarted: a poll on :proposal has opened
//
event DocumentPollStarted(bytes32 proposal);
// UpgradeMajority: :proposal has achieved majority
//
event UpgradeMajority(address proposal);
// DocumentMajority: :proposal has achieved majority
//
event DocumentMajority(bytes32 proposal);
// Poll: full poll state
//
struct Poll
{
// start: the timestamp at which the poll was started
//
uint256 start;
// voted: per galaxy, whether they have voted on this poll
//
bool[256] voted;
// yesVotes: amount of votes in favor of the proposal
//
uint16 yesVotes;
// noVotes: amount of votes against the proposal
//
uint16 noVotes;
// duration: amount of time during which the poll can be voted on
//
uint256 duration;
// cooldown: amount of time before the (non-majority) poll can be reopened
//
uint256 cooldown;
}
// pollDuration: duration set for new polls. see also Poll.duration above
//
uint256 public pollDuration;
// pollCooldown: cooldown set for new polls. see also Poll.cooldown above
//
uint256 public pollCooldown;
// totalVoters: amount of active galaxies
//
uint16 public totalVoters;
// upgradeProposals: list of all upgrades ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
address[] public upgradeProposals;
// upgradePolls: per address, poll held to determine if that address
// will become the new ecliptic
//
mapping(address => Poll) public upgradePolls;
// upgradeHasAchievedMajority: per address, whether that address
// has ever achieved majority
//
// If we did not store this, we would have to look at old poll data
// to see whether or not a proposal has ever achieved majority.
// Since the outcome of a poll is calculated based on :totalVoters,
// which may not be consistent across time, we need to store outcomes
// explicitly instead of re-calculating them. This allows us to always
// tell with certainty whether or not a majority was achieved,
// regardless of the current :totalVoters.
//
mapping(address => bool) public upgradeHasAchievedMajority;
// documentProposals: list of all documents ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
bytes32[] public documentProposals;
// documentPolls: per hash, poll held to determine if the corresponding
// document is accepted by the galactic senate
//
mapping(bytes32 => Poll) public documentPolls;
// documentHasAchievedMajority: per hash, whether that hash has ever
// achieved majority
//
// the note for upgradeHasAchievedMajority above applies here as well
//
mapping(bytes32 => bool) public documentHasAchievedMajority;
// documentMajorities: all hashes that have achieved majority
//
bytes32[] public documentMajorities;
// constructor(): initial contract configuration
//
constructor(uint256 _pollDuration, uint256 _pollCooldown)
public
{
reconfigure(_pollDuration, _pollCooldown);
}
// reconfigure(): change poll duration and cooldown
//
function reconfigure(uint256 _pollDuration, uint256 _pollCooldown)
public
onlyOwner
{
require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) &&
(5 days <= _pollCooldown) && (_pollCooldown <= 90 days) );
pollDuration = _pollDuration;
pollCooldown = _pollCooldown;
}
// incrementTotalVoters(): increase the amount of registered voters
//
function incrementTotalVoters()
external
onlyOwner
{
require(totalVoters < 256);
totalVoters = totalVoters.add(1);
}
// getAllUpgradeProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getUpgradeProposals()
external
view
returns (address[] proposals)
{
return upgradeProposals;
}
// getUpgradeProposalCount(): get the number of unique proposed upgrades
//
function getUpgradeProposalCount()
external
view
returns (uint256 count)
{
return upgradeProposals.length;
}
// getAllDocumentProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentProposals()
external
view
returns (bytes32[] proposals)
{
return documentProposals;
}
// getDocumentProposalCount(): get the number of unique proposed upgrades
//
function getDocumentProposalCount()
external
view
returns (uint256 count)
{
return documentProposals.length;
}
// getDocumentMajorities(): return array of all document majorities
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentMajorities()
external
view
returns (bytes32[] majorities)
{
return documentMajorities;
}
// hasVotedOnUpgradePoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal)
external
view
returns (bool result)
{
return upgradePolls[_proposal].voted[_galaxy];
}
// hasVotedOnDocumentPoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
view
returns (bool result)
{
return documentPolls[_proposal].voted[_galaxy];
}
// startUpgradePoll(): open a poll on making _proposal the new ecliptic
//
function startUpgradePoll(address _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
Poll storage poll = upgradePolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
upgradeProposals.push(_proposal);
}
startPoll(poll);
emit UpgradePollStarted(_proposal);
}
// startDocumentPoll(): open a poll on accepting the document
// whose hash is _proposal
//
function startDocumentPoll(bytes32 _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
Poll storage poll = documentPolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
documentProposals.push(_proposal);
}
startPoll(poll);
emit DocumentPollStarted(_proposal);
}
// startPoll(): open a new poll, or re-open an old one
//
function startPoll(Poll storage _poll)
internal
{
// check that the poll has cooled down enough to be started again
//
// for completely new polls, the values used will be zero
//
require( block.timestamp > ( _poll.start.add(
_poll.duration.add(
_poll.cooldown )) ) );
// set started poll state
//
_poll.start = block.timestamp;
delete _poll.voted;
_poll.yesVotes = 0;
_poll.noVotes = 0;
_poll.duration = pollDuration;
_poll.cooldown = pollCooldown;
}
// castUpgradeVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castUpgradeVote(uint8 _as, address _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = upgradePolls[_proposal];
processVote(poll, _as, _vote);
return updateUpgradePoll(_proposal);
}
// castDocumentVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = documentPolls[_proposal];
processVote(poll, _as, _vote);
return updateDocumentPoll(_proposal);
}
// processVote(): record a vote from _as on the _poll
//
function processVote(Poll storage _poll, uint8 _as, bool _vote)
internal
{
// assist symbolic execution tools
//
assert(block.timestamp >= _poll.start);
require( // may only vote once
//
!_poll.voted[_as] &&
//
// may only vote when the poll is open
//
(block.timestamp < _poll.start.add(_poll.duration)) );
// update poll state to account for the new vote
//
_poll.voted[_as] = true;
if (_vote)
{
_poll.yesVotes = _poll.yesVotes.add(1);
}
else
{
_poll.noVotes = _poll.noVotes.add(1);
}
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, updating state, sending an event,
// and returning true if it has
//
function updateUpgradePoll(address _proposal)
public
onlyOwner
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = upgradePolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update the state and send an event
//
if (majority)
{
upgradeHasAchievedMajority[_proposal] = true;
emit UpgradeMajority(_proposal);
}
return majority;
}
// updateDocumentPoll(): check whether the _proposal has achieved majority,
// updating the state and sending an event if it has
//
// this can be called by anyone, because the ecliptic does not
// need to be aware of the result
//
function updateDocumentPoll(bytes32 _proposal)
public
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = documentPolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update state and send an event
//
if (majority)
{
documentHasAchievedMajority[_proposal] = true;
documentMajorities.push(_proposal);
emit DocumentMajority(_proposal);
}
return majority;
}
// checkPollMajority(): returns true if the majority is in favor of
// the subject of the poll
//
function checkPollMajority(Poll _poll)
internal
view
returns (bool majority)
{
return ( // poll must have at least the minimum required yes-votes
//
(_poll.yesVotes >= (totalVoters / 4)) &&
//
// and have a majority...
//
(_poll.yesVotes > _poll.noVotes) &&
//
// ...that is indisputable
//
( // either because the poll has ended
//
(block.timestamp > _poll.start.add(_poll.duration)) ||
//
// or there are more yes votes than there can be no votes
//
( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) );
}
}
// Azimuth's Claims.sol
// Claims: simple identity management
//
// This contract allows points to document claims about their owner.
// Most commonly, these are about identity, with a claim's protocol
// defining the context or platform of the claim, and its dossier
// containing proof of its validity.
// Points are limited to a maximum of 16 claims.
//
// For existing claims, the dossier can be updated, or the claim can
// be removed entirely. It is recommended to remove any claims associated
// with a point when it is about to be transferred to a new owner.
// For convenience, the owner of the Azimuth contract (the Ecliptic)
// is allowed to clear claims for any point, allowing it to do this for
// you on-transfer.
//
contract Claims is ReadsAzimuth
{
// ClaimAdded: a claim was added by :by
//
event ClaimAdded( uint32 indexed by,
string _protocol,
string _claim,
bytes _dossier );
// ClaimRemoved: a claim was removed by :by
//
event ClaimRemoved(uint32 indexed by, string _protocol, string _claim);
// maxClaims: the amount of claims that can be registered per point
//
uint8 constant maxClaims = 16;
// Claim: claim details
//
struct Claim
{
// protocol: context of the claim
//
string protocol;
// claim: the claim itself
//
string claim;
// dossier: data relating to the claim, as proof
//
bytes dossier;
}
// per point, list of claims
//
mapping(uint32 => Claim[maxClaims]) public claims;
// constructor(): register the azimuth contract.
//
constructor(Azimuth _azimuth)
ReadsAzimuth(_azimuth)
public
{
//
}
// addClaim(): register a claim as _point
//
function addClaim(uint32 _point,
string _protocol,
string _claim,
bytes _dossier)
external
activePointManager(_point)
{
// cur: index + 1 of the claim if it already exists, 0 otherwise
//
uint8 cur = findClaim(_point, _protocol, _claim);
// if the claim doesn't yet exist, store it in state
//
if (cur == 0)
{
// if there are no empty slots left, this throws
//
uint8 empty = findEmptySlot(_point);
claims[_point][empty] = Claim(_protocol, _claim, _dossier);
}
//
// if the claim has been made before, update the version in state
//
else
{
claims[_point][cur-1] = Claim(_protocol, _claim, _dossier);
}
emit ClaimAdded(_point, _protocol, _claim, _dossier);
}
// removeClaim(): unregister a claim as _point
//
function removeClaim(uint32 _point, string _protocol, string _claim)
external
activePointManager(_point)
{
// i: current index + 1 in _point's list of claims
//
uint256 i = findClaim(_point, _protocol, _claim);
// we store index + 1, because 0 is the eth default value
// can only delete an existing claim
//
require(i > 0);
i--;
// clear out the claim
//
delete claims[_point][i];
emit ClaimRemoved(_point, _protocol, _claim);
}
// clearClaims(): unregister all of _point's claims
//
// can also be called by the ecliptic during point transfer
//
function clearClaims(uint32 _point)
external
{
// both point owner and ecliptic may do this
//
// We do not necessarily need to check for _point's active flag here,
// since inactive points cannot have claims set. Doing the check
// anyway would make this function slightly harder to think about due
// to its relation to Ecliptic's transferPoint().
//
require( azimuth.canManage(_point, msg.sender) ||
( msg.sender == azimuth.owner() ) );
Claim[maxClaims] storage currClaims = claims[_point];
// clear out all claims
//
for (uint8 i = 0; i < maxClaims; i++)
{
delete currClaims[i];
}
}
// findClaim(): find the index of the specified claim
//
// returns 0 if not found, index + 1 otherwise
//
function findClaim(uint32 _whose, string _protocol, string _claim)
public
view
returns (uint8 index)
{
// we use hashes of the string because solidity can't do string
// comparison yet
//
bytes32 protocolHash = keccak256(bytes(_protocol));
bytes32 claimHash = keccak256(bytes(_claim));
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) &&
( claimHash == keccak256(bytes(thisClaim.claim)) ) )
{
return i+1;
}
}
return 0;
}
// findEmptySlot(): find the index of the first empty claim slot
//
// returns the index of the slot, throws if there are no empty slots
//
function findEmptySlot(uint32 _whose)
internal
view
returns (uint8 index)
{
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( (0 == bytes(thisClaim.protocol).length) &&
(0 == bytes(thisClaim.claim).length) )
{
return i;
}
}
revert();
}
}
// Azimuth's EclipticBase.sol
// EclipticBase: upgradable ecliptic
//
// This contract implements the upgrade logic for the Ecliptic.
// Newer versions of the Ecliptic are expected to provide at least
// the onUpgrade() function. If they don't, upgrading to them will
// fail.
//
// Note that even though this contract doesn't specify any required
// interface members aside from upgrade() and onUpgrade(), contracts
// and clients may still rely on the presence of certain functions
// provided by the Ecliptic proper. Keep this in mind when writing
// new versions of it.
//
contract EclipticBase is Ownable, ReadsAzimuth
{
// Upgraded: _to is the new canonical Ecliptic
//
event Upgraded(address to);
// polls: senate voting contract
//
Polls public polls;
// previousEcliptic: address of the previous ecliptic this
// instance expects to upgrade from, stored and
// checked for to prevent unexpected upgrade paths
//
address public previousEcliptic;
constructor( address _previous,
Azimuth _azimuth,
Polls _polls )
ReadsAzimuth(_azimuth)
internal
{
previousEcliptic = _previous;
polls = _polls;
}
// onUpgrade(): called by previous ecliptic when upgrading
//
// in future ecliptics, this might perform more logic than
// just simple checks and verifications.
// when overriding this, make sure to call this original as well.
//
function onUpgrade()
external
{
// make sure this is the expected upgrade path,
// and that we have gotten the ownership we require
//
require( msg.sender == previousEcliptic &&
this == azimuth.owner() &&
this == polls.owner() );
}
// upgrade(): transfer ownership of the ecliptic data to the new
// ecliptic contract, notify it, then self-destruct.
//
// Note: any eth that have somehow ended up in this contract
// are also sent to the new ecliptic.
//
function upgrade(EclipticBase _new)
internal
{
// transfer ownership of the data contracts
//
azimuth.transferOwnership(_new);
polls.transferOwnership(_new);
// trigger upgrade logic on the target contract
//
_new.onUpgrade();
// emit event and destroy this contract
//
emit Upgraded(_new);
selfdestruct(_new);
}
}
// Azimuth's Ecliptic
// Ecliptic: logic for interacting with the Azimuth ledger
//
// This contract is the point of entry for all operations on the Azimuth
// ledger as stored in the Azimuth data contract. The functions herein
// are responsible for performing all necessary business logic.
// Examples of such logic include verifying permissions of the caller
// and ensuring a requested change is actually valid.
// Point owners can always operate on their own points. Ethereum addresses
// can also perform specific operations if they've been given the
// appropriate permissions. (For example, managers for general management,
// spawn proxies for spawning child points, etc.)
//
// This contract uses external contracts (Azimuth, Polls) for data storage
// so that it itself can easily be replaced in case its logic needs to
// be changed. In other words, it can be upgraded. It does this by passing
// ownership of the data contracts to a new Ecliptic contract.
//
// Because of this, it is advised for clients to not store this contract's
// address directly, but rather ask the Azimuth contract for its owner
// attribute to ensure transactions get sent to the latest Ecliptic.
// Alternatively, the ENS name ecliptic.eth will resolve to the latest
// Ecliptic as well.
//
// Upgrading happens based on polls held by the senate (galaxy owners).
// Through this contract, the senate can submit proposals, opening polls
// for the senate to cast votes on. These proposals can be either hashes
// of documents or addresses of new Ecliptics.
// If an ecliptic proposal gains majority, this contract will transfer
// ownership of the data storage contracts to that address, so that it may
// operate on the data they contain. This contract will selfdestruct at
// the end of the upgrade process.
//
// This contract implements the ERC721 interface for non-fungible tokens,
// allowing points to be managed using generic clients that support the
// standard. It also implements ERC165 to allow this to be discovered.
//
contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata
{
using SafeMath for uint256;
using AddressUtils for address;
// Transfer: This emits when ownership of any NFT changes by any mechanism.
// This event emits when NFTs are created (`from` == 0) and
// destroyed (`to` == 0). At the time of any transfer, the
// approved address for that NFT (if any) is reset to none.
//
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// Approval: This emits when the approved address for an NFT is changed or
// reaffirmed. The zero address indicates there is no approved
// address. When a Transfer event emits, this also indicates that
// the approved address for that NFT (if any) is reset to none.
//
event Approval(address indexed _owner, address indexed _approved,
uint256 _tokenId);
// ApprovalForAll: This emits when an operator is enabled or disabled for an
// owner. The operator can manage all NFTs of the owner.
//
event ApprovalForAll(address indexed _owner, address indexed _operator,
bool _approved);
// erc721Received: equal to:
// bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
// which can be also obtained as:
// ERC721Receiver(0).onERC721Received.selector`
bytes4 constant erc721Received = 0x150b7a02;
// claims: contract reference, for clearing claims on-transfer
//
Claims public claims;
// constructor(): set data contract addresses and signal interface support
//
// Note: during first deploy, ownership of these data contracts must
// be manually transferred to this contract.
//
constructor(address _previous,
Azimuth _azimuth,
Polls _polls,
Claims _claims)
EclipticBase(_previous, _azimuth, _polls)
public
{
claims = _claims;
// register supported interfaces for ERC165
//
_registerInterface(0x80ac58cd); // ERC721
_registerInterface(0x5b5e139f); // ERC721Metadata
_registerInterface(0x7f5828d0); // ERC173 (ownership)
}
//
// ERC721 interface
//
// balanceOf(): get the amount of points owned by _owner
//
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
require(0x0 != _owner);
return azimuth.getOwnedPointCount(_owner);
}
// ownerOf(): get the current owner of point _tokenId
//
function ownerOf(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address owner)
{
uint32 id = uint32(_tokenId);
// this will throw if the owner is the zero address,
// active points always have a valid owner.
//
require(azimuth.isActive(id));
return azimuth.getOwner(id);
}
// exists(): returns true if point _tokenId is active
//
function exists(uint256 _tokenId)
public
view
returns (bool doesExist)
{
return ( (_tokenId < 0x100000000) &&
azimuth.isActive(uint32(_tokenId)) );
}
// safeTransferFrom(): transfer point _tokenId from _from to _to
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public
{
// transfer with empty data
//
safeTransferFrom(_from, _to, _tokenId, "");
}
// safeTransferFrom(): transfer point _tokenId from _from to _to,
// and call recipient if it's a contract
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId,
bytes _data)
public
{
// perform raw transfer
//
transferFrom(_from, _to, _tokenId);
// do the callback last to avoid re-entrancy
//
if (_to.isContract())
{
bytes4 retval = ERC721Receiver(_to)
.onERC721Received(msg.sender, _from, _tokenId, _data);
//
// standard return idiom to confirm contract semantics
//
require(retval == erc721Received);
}
}
// transferFrom(): transfer point _tokenId from _from to _to,
// WITHOUT notifying recipient contract
//
function transferFrom(address _from, address _to, uint256 _tokenId)
public
validPointId(_tokenId)
{
uint32 id = uint32(_tokenId);
require(azimuth.isOwner(id, _from));
// the ERC721 operator/approved address (if any) is
// accounted for in transferPoint()
//
transferPoint(id, _to, true);
}
// approve(): allow _approved to transfer ownership of point
// _tokenId
//
function approve(address _approved, uint256 _tokenId)
public
validPointId(_tokenId)
{
setTransferProxy(uint32(_tokenId), _approved);
}
// setApprovalForAll(): allow or disallow _operator to
// transfer ownership of ALL points
// owned by :msg.sender
//
function setApprovalForAll(address _operator, bool _approved)
public
{
require(0x0 != _operator);
azimuth.setOperator(msg.sender, _operator, _approved);
emit ApprovalForAll(msg.sender, _operator, _approved);
}
// getApproved(): get the approved address for point _tokenId
//
function getApproved(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address approved)
{
//NOTE redundant, transfer proxy cannot be set for
// inactive points
//
require(azimuth.isActive(uint32(_tokenId)));
return azimuth.getTransferProxy(uint32(_tokenId));
}
// isApprovedForAll(): returns true if _operator is an
// operator for _owner
//
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool result)
{
return azimuth.isOperator(_owner, _operator);
}
//
// ERC721Metadata interface
//
// name(): returns the name of a collection of points
//
function name()
external
view
returns (string)
{
return "Azimuth Points";
}
// symbol(): returns an abbreviates name for points
//
function symbol()
external
view
returns (string)
{
return "AZP";
}
// tokenURI(): returns a URL to an ERC-721 standard JSON file
//
function tokenURI(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (string _tokenURI)
{
_tokenURI = "https://azimuth.network/erc721/0000000000.json";
bytes memory _tokenURIBytes = bytes(_tokenURI);
_tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10);
_tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10);
_tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10);
_tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10);
_tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10);
_tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10);
_tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10);
_tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10);
_tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10);
_tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10);
}
//
// Points interface
//
// configureKeys(): configure _point with network public keys
// _encryptionKey, _authenticationKey,
// and corresponding _cryptoSuiteVersion,
// incrementing the point's continuity number if needed
//
function configureKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion,
bool _discontinuous)
external
activePointManager(_point)
{
if (_discontinuous)
{
azimuth.incrementContinuityNumber(_point);
}
azimuth.setKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion);
}
// spawn(): spawn _point, then either give, or allow _target to take,
// ownership of _point
//
// if _target is the :msg.sender, _targets owns the _point right away.
// otherwise, _target becomes the transfer proxy of _point.
//
// Requirements:
// - _point must not be active
// - _point must not be a planet with a galaxy prefix
// - _point's prefix must be linked and under its spawn limit
// - :msg.sender must be either the owner of _point's prefix,
// or an authorized spawn proxy for it
//
function spawn(uint32 _point, address _target)
external
{
// only currently unowned (and thus also inactive) points can be spawned
//
require(azimuth.isOwner(_point, 0x0));
// prefix: half-width prefix of _point
//
uint16 prefix = azimuth.getPrefix(_point);
// only allow spawning of points of the size directly below the prefix
//
// this is possible because of how the address space works,
// but supporting it introduces complexity through broken assumptions.
//
// example:
// 0x0000.0000 - galaxy zero
// 0x0000.0100 - the first star of galaxy zero
// 0x0001.0100 - the first planet of the first star
// 0x0001.0000 - the first planet of galaxy zero
//
require( (uint8(azimuth.getPointSize(prefix)) + 1) ==
uint8(azimuth.getPointSize(_point)) );
// prefix point must be linked and able to spawn
//
require( (azimuth.hasBeenLinked(prefix)) &&
( azimuth.getSpawnCount(prefix) <
getSpawnLimit(prefix, block.timestamp) ) );
// the owner of a prefix can always spawn its children;
// other addresses need explicit permission (the role
// of "spawnProxy" in the Azimuth contract)
//
require( azimuth.canSpawnAs(prefix, msg.sender) );
// if the caller is spawning the point to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_point, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern
// making the _point prefix's owner the _point owner in the mean time
//
else
{
doSpawn(_point, _target, false, azimuth.getOwner(prefix));
}
}
// doSpawn(): actual spawning logic, used in spawn(). creates _point,
// making the _target its owner if _direct, or making the
// _holder the owner and the _target the transfer proxy
// if not _direct.
//
function doSpawn( uint32 _point,
address _target,
bool _direct,
address _holder )
internal
{
// register the spawn for _point's prefix, incrementing spawn count
//
azimuth.registerSpawned(_point);
// if the spawn is _direct, assume _target knows what they're doing
// and resolve right away
//
if (_direct)
{
// make the point active and set its new owner
//
azimuth.activatePoint(_point);
azimuth.setOwner(_point, _target);
emit Transfer(0x0, _target, uint256(_point));
}
//
// when spawning indirectly, enforce a withdraw pattern by approving
// the _target for transfer of the _point instead.
// we make the _holder the owner of this _point in the mean time,
// so that it may cancel the transfer (un-approve) if _target flakes.
// we don't make _point active yet, because it still doesn't really
// belong to anyone.
//
else
{
// have _holder hold on to the _point while _target gets to transfer
// ownership of it
//
azimuth.setOwner(_point, _holder);
azimuth.setTransferProxy(_point, _target);
emit Transfer(0x0, _holder, uint256(_point));
emit Approval(_holder, _target, uint256(_point));
}
}
// transferPoint(): transfer _point to _target, clearing all permissions
// data and keys if _reset is true
//
// Note: the _reset flag is useful when transferring the point to
// a recipient who doesn't trust the previous owner.
//
// Requirements:
// - :msg.sender must be either _point's current owner, authorized
// to transfer _point, or authorized to transfer the current
// owner's points (as in ERC721's operator)
// - _target must not be the zero address
//
function transferPoint(uint32 _point, address _target, bool _reset)
public
{
// transfer is legitimate if the caller is the current owner, or
// an operator for the current owner, or the _point's transfer proxy
//
require(azimuth.canTransfer(_point, msg.sender));
// if the point wasn't active yet, that means transferring it
// is part of the "spawn" flow, so we need to activate it
//
if ( !azimuth.isActive(_point) )
{
azimuth.activatePoint(_point);
}
// if the owner would actually change, change it
//
// the only time this deliberately wouldn't be the case is when a
// prefix owner wants to activate a spawned but untransferred child.
//
if ( !azimuth.isOwner(_point, _target) )
{
// remember the previous owner, to be included in the Transfer event
//
address old = azimuth.getOwner(_point);
azimuth.setOwner(_point, _target);
// according to ERC721, the approved address (here, transfer proxy)
// gets cleared during every Transfer event
//
azimuth.setTransferProxy(_point, 0);
emit Transfer(old, _target, uint256(_point));
}
// reset sensitive data
// used when transferring the point to a new owner
//
if ( _reset )
{
// clear the network public keys and break continuity,
// but only if the point has already been linked
//
if ( azimuth.hasBeenLinked(_point) )
{
azimuth.incrementContinuityNumber(_point);
azimuth.setKeys(_point, 0, 0, 0);
}
// clear management proxy
//
azimuth.setManagementProxy(_point, 0);
// clear voting proxy
//
azimuth.setVotingProxy(_point, 0);
// clear transfer proxy
//
// in most cases this is done above, during the ownership transfer,
// but we might not hit that and still be expected to reset the
// transfer proxy.
// doing it a second time is a no-op in Azimuth.
//
azimuth.setTransferProxy(_point, 0);
// clear spawning proxy
//
azimuth.setSpawnProxy(_point, 0);
// clear claims
//
claims.clearClaims(_point);
}
}
// escape(): request escape as _point to _sponsor
//
// if an escape request is already active, this overwrites
// the existing request
//
// Requirements:
// - :msg.sender must be the owner or manager of _point,
// - _point must be able to escape to _sponsor as per to canEscapeTo()
//
function escape(uint32 _point, uint32 _sponsor)
external
activePointManager(_point)
{
require(canEscapeTo(_point, _sponsor));
azimuth.setEscapeRequest(_point, _sponsor);
}
// cancelEscape(): cancel the currently set escape for _point
//
function cancelEscape(uint32 _point)
external
activePointManager(_point)
{
azimuth.cancelEscape(_point);
}
// adopt(): as the relevant sponsor, accept the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function adopt(uint32 _point)
external
{
require( azimuth.isEscaping(_point) &&
azimuth.canManage( azimuth.getEscapeRequest(_point),
msg.sender ) );
// _sponsor becomes _point's sponsor
// its escape request is reset to "not escaping"
//
azimuth.doEscape(_point);
}
// reject(): as the relevant sponsor, deny the _point's request
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function reject(uint32 _point)
external
{
require( azimuth.isEscaping(_point) &&
azimuth.canManage( azimuth.getEscapeRequest(_point),
msg.sender ) );
// reset the _point's escape request to "not escaping"
//
azimuth.cancelEscape(_point);
}
// detach(): as the _sponsor, stop sponsoring the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's current sponsor
//
function detach(uint32 _point)
external
{
require( azimuth.hasSponsor(_point) &&
azimuth.canManage(azimuth.getSponsor(_point), msg.sender) );
// signal that its sponsor no longer supports _point
//
azimuth.loseSponsor(_point);
}
//
// Point rules
//
// getSpawnLimit(): returns the total number of children the _point
// is allowed to spawn at _time.
//
function getSpawnLimit(uint32 _point, uint256 _time)
public
view
returns (uint32 limit)
{
Azimuth.Size size = azimuth.getPointSize(_point);
if ( size == Azimuth.Size.Galaxy )
{
return 255;
}
else if ( size == Azimuth.Size.Star )
{
// in 2019, stars may spawn at most 1024 planets. this limit doubles
// for every subsequent year.
//
// Note: 1546300800 corresponds to 2019-01-01
//
uint256 yearsSince2019 = (_time - 1546300800) / 365 days;
if (yearsSince2019 < 6)
{
limit = uint32( 1024 * (2 ** yearsSince2019) );
}
else
{
limit = 65535;
}
return limit;
}
else // size == Azimuth.Size.Planet
{
// planets can create moons, but moons aren't on the chain
//
return 0;
}
}
// canEscapeTo(): true if _point could try to escape to _sponsor
//
function canEscapeTo(uint32 _point, uint32 _sponsor)
public
view
returns (bool canEscape)
{
// can't escape to a sponsor that hasn't been linked
//
if ( !azimuth.hasBeenLinked(_sponsor) ) return false;
// Can only escape to a point one size higher than ourselves,
// except in the special case where the escaping point hasn't
// been linked yet -- in that case we may escape to points of
// the same size, to support lightweight invitation chains.
//
// The use case for lightweight invitations is that a planet
// owner should be able to invite their friends onto an
// Azimuth network in a two-party transaction, without a new
// star relationship.
// The lightweight invitation process works by escaping your
// own active (but never linked) point to one of your own
// points, then transferring the point to your friend.
//
// These planets can, in turn, sponsor other unlinked planets,
// so the "planet sponsorship chain" can grow to arbitrary
// length. Most users, especially deep down the chain, will
// want to improve their performance by switching to direct
// star sponsors eventually.
//
Azimuth.Size pointSize = azimuth.getPointSize(_point);
Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor);
return ( // normal hierarchical escape structure
//
( (uint8(sponsorSize) + 1) == uint8(pointSize) ) ||
//
// special peer escape
//
( (sponsorSize == pointSize) &&
//
// peer escape is only for points that haven't been linked
// yet, because it's only for lightweight invitation chains
//
!azimuth.hasBeenLinked(_point) ) );
}
//
// Permission management
//
// setManagementProxy(): configure the management proxy for _point
//
// The management proxy may perform "reversible" operations on
// behalf of the owner. This includes public key configuration and
// operations relating to sponsorship.
//
function setManagementProxy(uint32 _point, address _manager)
external
activePointOwner(_point)
{
azimuth.setManagementProxy(_point, _manager);
}
// setSpawnProxy(): give _spawnProxy the right to spawn points
// with the prefix _prefix
//
function setSpawnProxy(uint16 _prefix, address _spawnProxy)
external
activePointOwner(_prefix)
{
azimuth.setSpawnProxy(_prefix, _spawnProxy);
}
// setVotingProxy(): configure the voting proxy for _galaxy
//
// the voting proxy is allowed to start polls and cast votes
// on the point's behalf.
//
function setVotingProxy(uint8 _galaxy, address _voter)
external
activePointOwner(_galaxy)
{
azimuth.setVotingProxy(_galaxy, _voter);
}
// setTransferProxy(): give _transferProxy the right to transfer _point
//
// Requirements:
// - :msg.sender must be either _point's current owner,
// or be an operator for the current owner
//
function setTransferProxy(uint32 _point, address _transferProxy)
public
{
// owner: owner of _point
//
address owner = azimuth.getOwner(_point);
// caller must be :owner, or an operator designated by the owner.
//
require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender));
// set transfer proxy field in Azimuth contract
//
azimuth.setTransferProxy(_point, _transferProxy);
// emit Approval event
//
emit Approval(owner, _transferProxy, uint256(_point));
}
//
// Poll actions
//
// startUpgradePoll(): as _galaxy, start a poll for the ecliptic
// upgrade _proposal
//
// Requirements:
// - :msg.sender must be the owner or voting proxy of _galaxy,
// - the _proposal must expect to be upgraded from this specific
// contract, as indicated by its previousEcliptic attribute
//
function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal)
external
activePointVoter(_galaxy)
{
// ensure that the upgrade target expects this contract as the source
//
require(_proposal.previousEcliptic() == address(this));
polls.startUpgradePoll(_proposal);
}
// startDocumentPoll(): as _galaxy, start a poll for the _proposal
//
// the _proposal argument is the keccak-256 hash of any arbitrary
// document or string of text
//
function startDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
activePointVoter(_galaxy)
{
polls.startDocumentPoll(_proposal);
}
// castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic
// upgrade _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
// If this vote results in a majority for the _proposal, it will
// be upgraded to immediately.
//
function castUpgradeVote(uint8 _galaxy,
EclipticBase _proposal,
bool _vote)
external
activePointVoter(_galaxy)
{
// majority: true if the vote resulted in a majority, false otherwise
//
bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// castDocumentVote(): as _galaxy, cast a _vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote)
external
activePointVoter(_galaxy)
{
polls.castDocumentVote(_galaxy, _proposal, _vote);
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, upgrading to it if it has
//
function updateUpgradePoll(EclipticBase _proposal)
external
{
// majority: true if the poll ended in a majority, false otherwise
//
bool majority = polls.updateUpgradePoll(_proposal);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// updateDocumentPoll(): check whether the _proposal has achieved majority
//
// Note: the polls contract publicly exposes the function this calls,
// but we offer it in the ecliptic interface as a convenience
//
function updateDocumentPoll(bytes32 _proposal)
external
{
polls.updateDocumentPoll(_proposal);
}
//
// Contract owner operations
//
// createGalaxy(): grant _target ownership of the _galaxy and register
// it for voting
//
function createGalaxy(uint8 _galaxy, address _target)
external
onlyOwner
{
// only currently unowned (and thus also inactive) galaxies can be
// created, and only to non-zero addresses
//
require( azimuth.isOwner(_galaxy, 0x0) &&
0x0 != _target );
// new galaxy means a new registered voter
//
polls.incrementTotalVoters();
// if the caller is sending the galaxy to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_galaxy, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern,
// making the caller the owner in the mean time
//
else
{
doSpawn(_galaxy, _target, false, msg.sender);
}
}
function setDnsDomains(string _primary, string _secondary, string _tertiary)
external
onlyOwner
{
azimuth.setDnsDomains(_primary, _secondary, _tertiary);
}
//
// Function modifiers for this contract
//
// validPointId(): require that _id is a valid point
//
modifier validPointId(uint256 _id)
{
require(_id < 0x100000000);
_;
}
// activePointVoter(): require that :msg.sender can vote as _point,
// and that _point is active
//
modifier activePointVoter(uint32 _point)
{
require( azimuth.canVoteAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
}
////////////////////////////////////////////////////////////////////////////////
// DelegatedSending
////////////////////////////////////////////////////////////////////////////////
// DelegatedSending: invite-like point sending
//
// This contract allows planet owners to gift planets to their friends,
// if their prefix has allowed it.
//
// Star owners can set a limit, the amount of "invite planets" each of
// their planets is allowed to send. Enabling this by setting the limit
// to a value higher than zero can help the network grow by providing
// regular users with a way to get their friends and family onto it.
//
// To allow planets to be sent by this contract, stars must set it as
// their spawnProxy using the Ecliptic.
//
contract DelegatedSending is ReadsAzimuth
{
// Sent: :by sent :point
//
event Sent( uint16 indexed prefix,
uint64 indexed fromPool,
uint32 by,
uint32 point,
address to);
// limits: per star, the maximum amount of planets any of its planets may
// give away
//
mapping(uint16 => uint16) public limits;
// pools: per pool, the amount of planets that have been given away by
// the pool's planet itself or the ones it invited
//
// pools are associated with planets by number, pool n belongs to
// planet n - 1.
// pool 0 does not exist, and is used symbolically by :fromPool.
//
mapping(uint64 => uint16) public pools;
// fromPool: per planet, the pool from which they were sent/invited
//
// when invited by planet n, the invitee is registered in pool n + 1.
// a pool of 0 means the planet has its own invite pool.
// this is done so that all planets that were born outside of this
// contract start out with their own pool (0, solidity default),
// while we configure planets created through this contract to use
// their inviter's pool.
//
mapping(uint32 => uint64) public fromPool;
// constructor(): register the azimuth contract
//
constructor(Azimuth _azimuth)
ReadsAzimuth(_azimuth)
public
{
//
}
// configureLimit(): as the owner of a star, configure the amount of
// planets that may be given away per point.
//
function configureLimit(uint16 _prefix, uint16 _limit)
external
activePointOwner(_prefix)
{
limits[_prefix] = _limit;
}
// resetPool(): grant _for their own invite pool in case they still
// share one and reset its counter to zero
//
function resetPool(uint32 _for)
external
activePointOwner(azimuth.getPrefix(_for))
{
fromPool[_for] = 0;
pools[uint64(_for) + 1] = 0;
}
// sendPoint(): as the point _as, spawn the point _point to _to.
//
// Requirements:
// - :msg.sender must be the owner of _as,
// - _to must not be the :msg.sender,
// - _as must be able to send the _point according to canSend()
//
function sendPoint(uint32 _as, uint32 _point, address _to)
external
activePointOwner(_as)
{
require(canSend(_as, _point));
// caller may not send to themselves
//
require(msg.sender != _to);
// recipient must be eligible to receive a planet from this contract
//
require(canReceive(_to));
// increment the sent counter for _as.
//
uint64 pool = getPool(_as);
pools[pool]++;
// associate the _point with this pool
//
fromPool[_point] = pool;
// spawn _point to _to, they still need to accept the transfer manually
//
Ecliptic(azimuth.owner()).spawn(_point, _to);
emit Sent(azimuth.getPrefix(_point), pool, _as, _point, _to);
}
// canSend(): check whether current conditions allow _as to send _point
//
function canSend(uint32 _as, uint32 _point)
public
view
returns (bool result)
{
uint16 prefix = azimuth.getPrefix(_as);
uint64 pool = getPool(_as);
return ( // can only send points with the same prefix
//
(prefix == azimuth.getPrefix(_point)) &&
//
// _as must not have hit the allowed limit yet
//
(pools[pool] < limits[prefix]) &&
//
// _point needs to not be (in the process of being) spawned
//
azimuth.isOwner(_point, 0x0) &&
//
// this contract must have permission to spawn points
//
azimuth.isSpawnProxy(prefix, this) &&
//
// the prefix must be linked
//
azimuth.hasBeenLinked(prefix) &&
//
// the prefix must not have hit its spawn limit yet
//
( azimuth.getSpawnCount(prefix) <
Ecliptic(azimuth.owner())
.getSpawnLimit(prefix, block.timestamp) ) );
}
// getPool(): get the invite pool _point belongs to
//
function getPool(uint32 _point)
internal
view
returns (uint64 pool)
{
pool = fromPool[_point];
// no pool explicitly registered means they have their own pool,
// because they either were not invited by this contract, or have
// been granted their own pool by their star.
//
if (0 == pool)
{
// the pool for planet n is n + 1, see also :fromPool
//
return uint64(_point) + 1;
}
return pool;
}
// canReceive(): whether the _recipient is eligible to receive a planet
// from this contract or not
//
// only those who don't own or are entitled to any points may receive
//
function canReceive(address _recipient)
public
view
returns (bool result)
{
return ( 0 == azimuth.getOwnedPointCount(_recipient) &&
0 == azimuth.getTransferringForCount(_recipient) );
}
}
|
reject(): as the relevant sponsor, deny the _point's request Requirements: - :msg.sender must be the owner or management proxy of _point's requested sponsor reset the _point's escape request to "not escaping"
|
function reject(uint32 _point)
external
{
require( azimuth.isEscaping(_point) &&
azimuth.canManage( azimuth.getEscapeRequest(_point),
msg.sender ) );
azimuth.cancelEscape(_point);
}
| 1,401,185
|
pragma solidity ^0.8.0;
import "@c-layer/common/contracts/operable/Operable.sol";
import "@c-layer/common/contracts/lifecycle/Pausable.sol";
import "../interface/ITokensale.sol";
/**
* @title BaseTokensale
* @dev Base Tokensale contract
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
* SPDX-License-Identifier: MIT
*
* Error messages
* TOS01: token price must be strictly positive
* TOS02: price unit must be strictly positive
* TOS03: Token transfer must be successfull
* TOS04: No ETH to refund
* TOS05: Cannot invest 0 tokens
* TOS06: Cannot invest if there are no tokens to buy
* TOS07: Only exact amount is authorized
*/
contract BaseTokensale is ITokensale, Operable, Pausable {
/* General sale details */
IERC20 internal token_;
address payable internal vaultETH_;
address internal vaultERC20_;
uint256 internal tokenPrice_;
uint256 internal priceUnit_;
uint256 internal totalRaised_;
uint256 internal totalTokensSold_;
uint256 internal totalUnspentETH_;
uint256 internal totalRefundedETH_;
struct Investor {
uint256 unspentETH;
uint256 invested;
uint256 tokens;
}
mapping(address => Investor) internal investors;
/**
* @dev constructor
*/
constructor(
IERC20 _token,
address _vaultERC20,
address payable _vaultETH,
uint256 _tokenPrice,
uint256 _priceUnit
) {
require(_tokenPrice > 0, "TOS01");
require(_priceUnit > 0, "TOS02");
token_ = _token;
vaultERC20_ = _vaultERC20;
vaultETH_ = _vaultETH;
tokenPrice_ = _tokenPrice;
priceUnit_ = _priceUnit;
}
/**
* @dev fallback function
*/
//solhint-disable-next-line no-complex-fallback
receive() external override payable {
investETH();
}
/* Investment */
function investETH() public virtual override payable
{
Investor storage investor = investorInternal(msg.sender);
uint256 amountETH = investor.unspentETH + msg.value;
investInternal(msg.sender, amountETH, false);
}
/**
* @dev returns the token sold
*/
function token() public override view returns (IERC20) {
return token_;
}
/**
* @dev returns the vault use to
*/
function vaultETH() public override view returns (address) {
return vaultETH_;
}
/**
* @dev returns the vault to receive ETH
*/
function vaultERC20() public override view returns (address) {
return vaultERC20_;
}
/**
* @dev returns token price
*/
function tokenPrice() public override view returns (uint256) {
return tokenPrice_;
}
/**
* @dev returns price unit
*/
function priceUnit() public override view returns (uint256) {
return priceUnit_;
}
/**
* @dev returns total raised
*/
function totalRaised() public override view returns (uint256) {
return totalRaised_;
}
/**
* @dev returns total tokens sold
*/
function totalTokensSold() public override view returns (uint256) {
return totalTokensSold_;
}
/**
* @dev returns total unspent ETH
*/
function totalUnspentETH() public override view returns (uint256) {
return totalUnspentETH_;
}
/**
* @dev returns total refunded ETH
*/
function totalRefundedETH() public override view returns (uint256) {
return totalRefundedETH_;
}
/**
* @dev returns the available supply
*/
function availableSupply() public override view returns (uint256) {
uint256 vaultSupply = token_.balanceOf(vaultERC20_);
uint256 allowance = token_.allowance(vaultERC20_, address(this));
return (vaultSupply < allowance) ? vaultSupply : allowance;
}
/* Investor specific attributes */
function investorUnspentETH(address _investor)
public override view returns (uint256)
{
return investorInternal(_investor).unspentETH;
}
function investorInvested(address _investor)
public override view returns (uint256)
{
return investorInternal(_investor).invested;
}
function investorTokens(address _investor) public override view returns (uint256) {
return investorInternal(_investor).tokens;
}
/**
* @dev tokenInvestment
*/
function tokenInvestment(address, uint256 _amount)
public virtual override view returns (uint256)
{
uint256 availableSupplyValue = availableSupply();
uint256 contribution = _amount * priceUnit_ / tokenPrice_;
return (contribution < availableSupplyValue) ? contribution : availableSupplyValue;
}
/**
* @dev refund unspentETH ETH many
*/
function refundManyUnspentETH(address payable[] memory _receivers)
public override onlyOperator returns (bool)
{
for (uint256 i = 0; i < _receivers.length; i++) {
refundUnspentETHInternal(_receivers[i]);
}
return true;
}
/**
* @dev refund unspentETH
*/
function refundUnspentETH() public override returns (bool) {
refundUnspentETHInternal(payable(msg.sender));
return true;
}
/**
* @dev withdraw all ETH funds
*/
function withdrawAllETHFunds() public override onlyOperator returns (bool) {
uint256 balance = address(this).balance;
withdrawETHInternal(balance);
return true;
}
/**
* @dev fund ETH
*/
function fundETH() public override payable onlyOperator {
emit FundETH(msg.value);
}
/**
* @dev investor internal
*/
function investorInternal(address _investor)
internal virtual view returns (Investor storage)
{
return investors[_investor];
}
/**
* @dev eval unspent ETH internal
*/
function evalUnspentETHInternal(
Investor storage _investor, uint256 _investedETH
) internal virtual view returns (uint256)
{
return _investor.unspentETH + msg.value - _investedETH;
}
/**
* @dev eval investment internal
*/
function evalInvestmentInternal(uint256 _tokens)
internal virtual view returns (uint256, uint256)
{
uint256 invested = _tokens * tokenPrice_ / priceUnit_;
return (invested, _tokens);
}
/**
* @dev distribute tokens internal
*/
function distributeTokensInternal(address _investor, uint256 _tokens)
internal virtual
{
require(
token_.transferFrom(vaultERC20_, _investor, _tokens),
"TOS03");
}
/**
* @dev refund unspentETH internal
*/
function refundUnspentETHInternal(address payable _investor) internal virtual {
Investor storage investor = investorInternal(_investor);
require(investor.unspentETH > 0, "TOS04");
uint256 unspentETH = investor.unspentETH;
totalRefundedETH_ = totalRefundedETH_ + unspentETH;
totalUnspentETH_ = totalUnspentETH_ - unspentETH;
investor.unspentETH = 0;
// Multiple sends are required for refundManyUnspentETH
// solhint-disable-next-line multiple-sends
_investor.transfer(unspentETH);
emit RefundETH(_investor, unspentETH);
}
/**
* @dev withdraw ETH internal
*/
function withdrawETHInternal(uint256 _amount) internal virtual {
// Send is used after the ERC20 transfer
// solhint-disable-next-line multiple-sends
vaultETH_.transfer(_amount);
emit WithdrawETH(_amount);
}
/**
* @dev invest internal
*/
function investInternal(address _investor, uint256 _amount, bool _exactAmountOnly)
internal virtual whenNotPaused
{
require(_amount != 0, "TOS05");
Investor storage investor = investorInternal(_investor);
uint256 investment = tokenInvestment(_investor, _amount);
require(investment != 0, "TOS06");
(uint256 invested, uint256 tokens) = evalInvestmentInternal(investment);
if (_exactAmountOnly) {
require(invested == _amount, "TOS07");
} else {
uint256 unspentETH = evalUnspentETHInternal(investor, invested);
totalUnspentETH_ = totalUnspentETH_ - investor.unspentETH + unspentETH;
investor.unspentETH = unspentETH;
}
investor.invested = investor.invested + invested;
investor.tokens = investor.tokens + tokens;
totalRaised_ = totalRaised_ + invested;
totalTokensSold_ = totalTokensSold_ + tokens;
emit Investment(_investor, invested, tokens);
/* Reentrancy risks: No state change must come below */
distributeTokensInternal(_investor, tokens);
uint256 balance = address(this).balance;
uint256 withdrawableETH = balance - totalUnspentETH_;
if (withdrawableETH != 0) {
withdrawETHInternal(withdrawableETH);
}
}
}
|
returns the token sold/
|
function token() public override view returns (IERC20) {
return token_;
}
| 2,531,938
|
./full_match/1/0xABF3e9F15a4529bf1769EAB968250c9243A8E7C1/sources/contracts/CapsuleToken.sol
|
Mints a Capsule. to Address to receive capsule. color Color of Capsule. font Font of Capsule. return capsuleId ID of minted Capsule.
|
function _mintCapsule(
address to,
bytes3 color,
Font calldata font,
bytes32[8] memory text
)
internal
onlyMintableColor(color)
onlyValidFontForRenderer(font, defaultRenderer)
returns (uint256 capsuleId)
{
_mint(to, 1, new bytes(0), false);
capsuleId = _currentIndex - 1;
tokenIdOfColor[color] = capsuleId;
_colorOf[capsuleId] = color;
_fontOf[capsuleId] = font;
_textOf[capsuleId] = text;
emit MintCapsule(capsuleId, to, color, font, text);
}
| 3,144,998
|
pragma solidity ^0.4.25;
contract IStdToken {
function balanceOf(address _owner) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
}
contract EtheramaCommon {
//main adrministrators of the Etherama network
mapping(address => bool) private _administrators;
//main managers of the Etherama network
mapping(address => bool) private _managers;
modifier onlyAdministrator() {
require(_administrators[msg.sender]);
_;
}
modifier onlyAdministratorOrManager() {
require(_administrators[msg.sender] || _managers[msg.sender]);
_;
}
constructor() public {
_administrators[msg.sender] = true;
}
function addAdministator(address addr) onlyAdministrator public {
_administrators[addr] = true;
}
function removeAdministator(address addr) onlyAdministrator public {
_administrators[addr] = false;
}
function isAdministrator(address addr) public view returns (bool) {
return _administrators[addr];
}
function addManager(address addr) onlyAdministrator public {
_managers[addr] = true;
}
function removeManager(address addr) onlyAdministrator public {
_managers[addr] = false;
}
function isManager(address addr) public view returns (bool) {
return _managers[addr];
}
}
contract EtheramaGasPriceLimit is EtheramaCommon {
uint256 public MAX_GAS_PRICE = 0 wei;
event onSetMaxGasPrice(uint256 val);
//max gas price modifier for buy/sell transactions in order to avoid a "front runner" vulnerability.
//It is applied to all network contracts
modifier validGasPrice(uint256 val) {
require(val > 0);
_;
}
constructor(uint256 maxGasPrice) public validGasPrice(maxGasPrice) {
setMaxGasPrice(maxGasPrice);
}
//only main administators or managers can set max gas price
function setMaxGasPrice(uint256 val) public validGasPrice(val) onlyAdministratorOrManager {
MAX_GAS_PRICE = val;
emit onSetMaxGasPrice(val);
}
}
// Core contract for Etherama network
contract EtheramaCore is EtheramaGasPriceLimit {
uint256 constant public MAGNITUDE = 2**64;
// Max and min amount of tokens which can be bought or sold. There are such limits because of math precision
uint256 constant public MIN_TOKEN_DEAL_VAL = 0.1 ether;
uint256 constant public MAX_TOKEN_DEAL_VAL = 1000000 ether;
// same same for ETH
uint256 constant public MIN_ETH_DEAL_VAL = 0.001 ether;
uint256 constant public MAX_ETH_DEAL_VAL = 200000 ether;
// percent of a transaction commission which is taken for Big Promo bonus
uint256 public _bigPromoPercent = 5 ether;
// percent of a transaction commission which is taken for Quick Promo bonus
uint256 public _quickPromoPercent = 5 ether;
// percent of a transaction commission which is taken for Etherama DEV team
uint256 public _devRewardPercent = 15 ether;
// percent of a transaction commission which is taken for Token Owner.
uint256 public _tokenOwnerRewardPercent = 30 ether;
// percent of a transaction commission which is taken for share reward. Each token holder receives a small reward from each buy or sell transaction proportionally his holding.
uint256 public _shareRewardPercent = 25 ether;
// percent of a transaction commission which is taken for a feraral link owner. If there is no any referal then this part of commission goes to share reward.
uint256 public _refBonusPercent = 20 ether;
// interval of blocks for Big Promo bonus. It means that a user which buy a bunch of tokens for X ETH in that particular block will receive a special bonus
uint128 public _bigPromoBlockInterval = 9999;
// same same for Quick Promo
uint128 public _quickPromoBlockInterval = 100;
// minimum eth amount of a purchase which is required to participate in promo.
uint256 public _promoMinPurchaseEth = 1 ether;
// minimum eth purchase which is required to get a referal link.
uint256 public _minRefEthPurchase = 0.5 ether;
// percent of fee which is supposed to distribute.
uint256 public _totalIncomeFeePercent = 100 ether;
// current collected big promo bonus
uint256 public _currentBigPromoBonus;
// current collected quick promo bonus
uint256 public _currentQuickPromoBonus;
uint256 public _devReward;
uint256 public _initBlockNum;
mapping(address => bool) private _controllerContracts;
mapping(uint256 => address) private _controllerIndexer;
uint256 private _controllerContractCount;
//user token balances per data contracts
mapping(address => mapping(address => uint256)) private _userTokenLocalBalances;
//user reward payouts per data contracts
mapping(address => mapping(address => uint256)) private _rewardPayouts;
//user ref rewards per data contracts
mapping(address => mapping(address => uint256)) private _refBalances;
//user won quick promo bonuses per data contracts
mapping(address => mapping(address => uint256)) private _promoQuickBonuses;
//user won big promo bonuses per data contracts
mapping(address => mapping(address => uint256)) private _promoBigBonuses;
//user saldo between buys and sels in eth per data contracts
mapping(address => mapping(address => uint256)) private _userEthVolumeSaldos;
//bonuses per share per data contracts
mapping(address => uint256) private _bonusesPerShare;
//buy counts per data contracts
mapping(address => uint256) private _buyCounts;
//sell counts per data contracts
mapping(address => uint256) private _sellCounts;
//total volume eth per data contracts
mapping(address => uint256) private _totalVolumeEth;
//total volume tokens per data contracts
mapping(address => uint256) private _totalVolumeToken;
event onWithdrawUserBonus(address indexed userAddress, uint256 ethWithdrawn);
modifier onlyController() {
require(_controllerContracts[msg.sender]);
_;
}
constructor(uint256 maxGasPrice) EtheramaGasPriceLimit(maxGasPrice) public {
_initBlockNum = block.number;
}
function getInitBlockNum() public view returns (uint256) {
return _initBlockNum;
}
function addControllerContract(address addr) onlyAdministrator public {
_controllerContracts[addr] = true;
_controllerIndexer[_controllerContractCount] = addr;
_controllerContractCount = SafeMath.add(_controllerContractCount, 1);
}
function removeControllerContract(address addr) onlyAdministrator public {
_controllerContracts[addr] = false;
}
function changeControllerContract(address oldAddr, address newAddress) onlyAdministrator public {
_controllerContracts[oldAddr] = false;
_controllerContracts[newAddress] = true;
}
function setBigPromoInterval(uint128 val) onlyAdministrator public {
_bigPromoBlockInterval = val;
}
function setQuickPromoInterval(uint128 val) onlyAdministrator public {
_quickPromoBlockInterval = val;
}
function addBigPromoBonus() onlyController payable public {
_currentBigPromoBonus = SafeMath.add(_currentBigPromoBonus, msg.value);
}
function addQuickPromoBonus() onlyController payable public {
_currentQuickPromoBonus = SafeMath.add(_currentQuickPromoBonus, msg.value);
}
function setPromoMinPurchaseEth(uint256 val) onlyAdministrator public {
_promoMinPurchaseEth = val;
}
function setMinRefEthPurchase(uint256 val) onlyAdministrator public {
_minRefEthPurchase = val;
}
function setTotalIncomeFeePercent(uint256 val) onlyController public {
require(val > 0 && val <= 100 ether);
_totalIncomeFeePercent = val;
}
// set reward persentages of buy/sell fee. Token owner cannot take more than 40%.
function setRewardPercentages(uint256 tokenOwnerRewardPercent, uint256 shareRewardPercent, uint256 refBonusPercent, uint256 bigPromoPercent, uint256 quickPromoPercent) onlyAdministrator public {
require(tokenOwnerRewardPercent <= 40 ether);
require(shareRewardPercent <= 100 ether);
require(refBonusPercent <= 100 ether);
require(bigPromoPercent <= 100 ether);
require(quickPromoPercent <= 100 ether);
require(tokenOwnerRewardPercent + shareRewardPercent + refBonusPercent + _devRewardPercent + _bigPromoPercent + _quickPromoPercent == 100 ether);
_tokenOwnerRewardPercent = tokenOwnerRewardPercent;
_shareRewardPercent = shareRewardPercent;
_refBonusPercent = refBonusPercent;
_bigPromoPercent = bigPromoPercent;
_quickPromoPercent = quickPromoPercent;
}
function payoutQuickBonus(address userAddress) onlyController public {
address dataContractAddress = Etherama(msg.sender).getDataContractAddress();
_promoQuickBonuses[dataContractAddress][userAddress] = SafeMath.add(_promoQuickBonuses[dataContractAddress][userAddress], _currentQuickPromoBonus);
_currentQuickPromoBonus = 0;
}
function payoutBigBonus(address userAddress) onlyController public {
address dataContractAddress = Etherama(msg.sender).getDataContractAddress();
_promoBigBonuses[dataContractAddress][userAddress] = SafeMath.add(_promoBigBonuses[dataContractAddress][userAddress], _currentBigPromoBonus);
_currentBigPromoBonus = 0;
}
function addDevReward() onlyController payable public {
_devReward = SafeMath.add(_devReward, msg.value);
}
function withdrawDevReward() onlyAdministrator public {
uint256 reward = _devReward;
_devReward = 0;
msg.sender.transfer(reward);
}
function getBlockNumSinceInit() public view returns(uint256) {
return block.number - getInitBlockNum();
}
function getQuickPromoRemainingBlocks() public view returns(uint256) {
uint256 d = getBlockNumSinceInit() % _quickPromoBlockInterval;
d = d == 0 ? _quickPromoBlockInterval : d;
return _quickPromoBlockInterval - d;
}
function getBigPromoRemainingBlocks() public view returns(uint256) {
uint256 d = getBlockNumSinceInit() % _bigPromoBlockInterval;
d = d == 0 ? _bigPromoBlockInterval : d;
return _bigPromoBlockInterval - d;
}
function getBonusPerShare(address dataContractAddress) public view returns(uint256) {
return _bonusesPerShare[dataContractAddress];
}
function getTotalBonusPerShare() public view returns (uint256 res) {
for (uint256 i = 0; i < _controllerContractCount; i++) {
res = SafeMath.add(res, _bonusesPerShare[Etherama(_controllerIndexer[i]).getDataContractAddress()]);
}
}
function addBonusPerShare() onlyController payable public {
EtheramaData data = Etherama(msg.sender)._data();
uint256 shareBonus = (msg.value * MAGNITUDE) / data.getTotalTokenSold();
_bonusesPerShare[address(data)] = SafeMath.add(_bonusesPerShare[address(data)], shareBonus);
}
function getUserRefBalance(address dataContractAddress, address userAddress) public view returns(uint256) {
return _refBalances[dataContractAddress][userAddress];
}
function getUserRewardPayouts(address dataContractAddress, address userAddress) public view returns(uint256) {
return _rewardPayouts[dataContractAddress][userAddress];
}
function resetUserRefBalance(address userAddress) onlyController public {
resetUserRefBalance(Etherama(msg.sender).getDataContractAddress(), userAddress);
}
function resetUserRefBalance(address dataContractAddress, address userAddress) internal {
_refBalances[dataContractAddress][userAddress] = 0;
}
function addUserRefBalance(address userAddress) onlyController payable public {
address dataContractAddress = Etherama(msg.sender).getDataContractAddress();
_refBalances[dataContractAddress][userAddress] = SafeMath.add(_refBalances[dataContractAddress][userAddress], msg.value);
}
function addUserRewardPayouts(address userAddress, uint256 val) onlyController public {
addUserRewardPayouts(Etherama(msg.sender).getDataContractAddress(), userAddress, val);
}
function addUserRewardPayouts(address dataContractAddress, address userAddress, uint256 val) internal {
_rewardPayouts[dataContractAddress][userAddress] = SafeMath.add(_rewardPayouts[dataContractAddress][userAddress], val);
}
function resetUserPromoBonus(address userAddress) onlyController public {
resetUserPromoBonus(Etherama(msg.sender).getDataContractAddress(), userAddress);
}
function resetUserPromoBonus(address dataContractAddress, address userAddress) internal {
_promoQuickBonuses[dataContractAddress][userAddress] = 0;
_promoBigBonuses[dataContractAddress][userAddress] = 0;
}
function trackBuy(address userAddress, uint256 volEth, uint256 volToken) onlyController public {
address dataContractAddress = Etherama(msg.sender).getDataContractAddress();
_buyCounts[dataContractAddress] = SafeMath.add(_buyCounts[dataContractAddress], 1);
_userEthVolumeSaldos[dataContractAddress][userAddress] = SafeMath.add(_userEthVolumeSaldos[dataContractAddress][userAddress], volEth);
trackTotalVolume(dataContractAddress, volEth, volToken);
}
function trackSell(address userAddress, uint256 volEth, uint256 volToken) onlyController public {
address dataContractAddress = Etherama(msg.sender).getDataContractAddress();
_sellCounts[dataContractAddress] = SafeMath.add(_sellCounts[dataContractAddress], 1);
_userEthVolumeSaldos[dataContractAddress][userAddress] = SafeMath.sub(_userEthVolumeSaldos[dataContractAddress][userAddress], volEth);
trackTotalVolume(dataContractAddress, volEth, volToken);
}
function trackTotalVolume(address dataContractAddress, uint256 volEth, uint256 volToken) internal {
_totalVolumeEth[dataContractAddress] = SafeMath.add(_totalVolumeEth[dataContractAddress], volEth);
_totalVolumeToken[dataContractAddress] = SafeMath.add(_totalVolumeToken[dataContractAddress], volToken);
}
function getBuyCount(address dataContractAddress) public view returns (uint256) {
return _buyCounts[dataContractAddress];
}
function getTotalBuyCount() public view returns (uint256 res) {
for (uint256 i = 0; i < _controllerContractCount; i++) {
res = SafeMath.add(res, _buyCounts[Etherama(_controllerIndexer[i]).getDataContractAddress()]);
}
}
function getSellCount(address dataContractAddress) public view returns (uint256) {
return _sellCounts[dataContractAddress];
}
function getTotalSellCount() public view returns (uint256 res) {
for (uint256 i = 0; i < _controllerContractCount; i++) {
res = SafeMath.add(res, _sellCounts[Etherama(_controllerIndexer[i]).getDataContractAddress()]);
}
}
function getTotalVolumeEth(address dataContractAddress) public view returns (uint256) {
return _totalVolumeEth[dataContractAddress];
}
function getTotalVolumeToken(address dataContractAddress) public view returns (uint256) {
return _totalVolumeToken[dataContractAddress];
}
function getUserEthVolumeSaldo(address dataContractAddress, address userAddress) public view returns (uint256) {
return _userEthVolumeSaldos[dataContractAddress][userAddress];
}
function getUserTotalEthVolumeSaldo(address userAddress) public view returns (uint256 res) {
for (uint256 i = 0; i < _controllerContractCount; i++) {
res = SafeMath.add(res, _userEthVolumeSaldos[Etherama(_controllerIndexer[i]).getDataContractAddress()][userAddress]);
}
}
function getTotalCollectedPromoBonus() public view returns (uint256) {
return SafeMath.add(_currentBigPromoBonus, _currentQuickPromoBonus);
}
function getUserTotalPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) {
return SafeMath.add(_promoQuickBonuses[dataContractAddress][userAddress], _promoBigBonuses[dataContractAddress][userAddress]);
}
function getUserQuickPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) {
return _promoQuickBonuses[dataContractAddress][userAddress];
}
function getUserBigPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) {
return _promoBigBonuses[dataContractAddress][userAddress];
}
function getUserTokenLocalBalance(address dataContractAddress, address userAddress) public view returns(uint256) {
return _userTokenLocalBalances[dataContractAddress][userAddress];
}
function addUserTokenLocalBalance(address userAddress, uint256 val) onlyController public {
address dataContractAddress = Etherama(msg.sender).getDataContractAddress();
_userTokenLocalBalances[dataContractAddress][userAddress] = SafeMath.add(_userTokenLocalBalances[dataContractAddress][userAddress], val);
}
function subUserTokenLocalBalance(address userAddress, uint256 val) onlyController public {
address dataContractAddress = Etherama(msg.sender).getDataContractAddress();
_userTokenLocalBalances[dataContractAddress][userAddress] = SafeMath.sub(_userTokenLocalBalances[dataContractAddress][userAddress], val);
}
function getUserReward(address dataContractAddress, address userAddress, bool incShareBonus, bool incRefBonus, bool incPromoBonus) public view returns(uint256 reward) {
EtheramaData data = EtheramaData(dataContractAddress);
if (incShareBonus) {
reward = data.getBonusPerShare() * data.getActualUserTokenBalance(userAddress);
reward = ((reward < data.getUserRewardPayouts(userAddress)) ? 0 : SafeMath.sub(reward, data.getUserRewardPayouts(userAddress))) / MAGNITUDE;
}
if (incRefBonus) reward = SafeMath.add(reward, data.getUserRefBalance(userAddress));
if (incPromoBonus) reward = SafeMath.add(reward, data.getUserTotalPromoBonus(userAddress));
return reward;
}
//user's total reward from all the tokens on the table. includes share reward + referal bonus + promo bonus
function getUserTotalReward(address userAddress, bool incShareBonus, bool incRefBonus, bool incPromoBonus) public view returns(uint256 res) {
for (uint256 i = 0; i < _controllerContractCount; i++) {
address dataContractAddress = Etherama(_controllerIndexer[i]).getDataContractAddress();
res = SafeMath.add(res, getUserReward(dataContractAddress, userAddress, incShareBonus, incRefBonus, incPromoBonus));
}
}
//current user's reward
function getCurrentUserReward(bool incRefBonus, bool incPromoBonus) public view returns(uint256) {
return getUserTotalReward(msg.sender, true, incRefBonus, incPromoBonus);
}
//current user's total reward from all the tokens on the table
function getCurrentUserTotalReward() public view returns(uint256) {
return getUserTotalReward(msg.sender, true, true, true);
}
//user's share bonus from all the tokens on the table
function getCurrentUserShareBonus() public view returns(uint256) {
return getUserTotalReward(msg.sender, true, false, false);
}
//current user's ref bonus from all the tokens on the table
function getCurrentUserRefBonus() public view returns(uint256) {
return getUserTotalReward(msg.sender, false, true, false);
}
//current user's promo bonus from all the tokens on the table
function getCurrentUserPromoBonus() public view returns(uint256) {
return getUserTotalReward(msg.sender, false, false, true);
}
//is ref link available for the user
function isRefAvailable(address refAddress) public view returns(bool) {
return getUserTotalEthVolumeSaldo(refAddress) >= _minRefEthPurchase;
}
//is ref link available for the current user
function isRefAvailable() public view returns(bool) {
return isRefAvailable(msg.sender);
}
//Withdraws all of the user earnings.
function withdrawUserReward() public {
uint256 reward = getRewardAndPrepareWithdraw();
require(reward > 0);
msg.sender.transfer(reward);
emit onWithdrawUserBonus(msg.sender, reward);
}
//gather all the user's reward and prepare it to withdaw
function getRewardAndPrepareWithdraw() internal returns(uint256 reward) {
for (uint256 i = 0; i < _controllerContractCount; i++) {
address dataContractAddress = Etherama(_controllerIndexer[i]).getDataContractAddress();
reward = SafeMath.add(reward, getUserReward(dataContractAddress, msg.sender, true, false, false));
// add share reward to payouts
addUserRewardPayouts(dataContractAddress, msg.sender, reward * MAGNITUDE);
// add ref bonus
reward = SafeMath.add(reward, getUserRefBalance(dataContractAddress, msg.sender));
resetUserRefBalance(dataContractAddress, msg.sender);
// add promo bonus
reward = SafeMath.add(reward, getUserTotalPromoBonus(dataContractAddress, msg.sender));
resetUserPromoBonus(dataContractAddress, msg.sender);
}
return reward;
}
//withdaw all the remamining ETH if there is no one active contract. We don't want to leave them here forever
function withdrawRemainingEthAfterAll() onlyAdministrator public {
for (uint256 i = 0; i < _controllerContractCount; i++) {
if (Etherama(_controllerIndexer[i]).isActive()) revert();
}
msg.sender.transfer(address(this).balance);
}
function calcPercent(uint256 amount, uint256 percent) public pure returns(uint256) {
return SafeMath.div(SafeMath.mul(SafeMath.div(amount, 100), percent), 1 ether);
}
//Converts real num to uint256. Works only with positive numbers.
function convertRealTo256(int128 realVal) public pure returns(uint256) {
int128 roundedVal = RealMath.fromReal(RealMath.mul(realVal, RealMath.toReal(1e12)));
return SafeMath.mul(uint256(roundedVal), uint256(1e6));
}
//Converts uint256 to real num. Possible a little loose of precision
function convert256ToReal(uint256 val) public pure returns(int128) {
uint256 intVal = SafeMath.div(val, 1e6);
require(RealMath.isUInt256ValidIn64(intVal));
return RealMath.fraction(int64(intVal), 1e12);
}
}
// Data contract for Etherama contract controller. Data contract cannot be changed so no data can be lost. On the other hand Etherama controller can be replaced if some error is found.
contract EtheramaData {
// tranding token address
address constant public TOKEN_CONTRACT_ADDRESS = 0x83cee9e086A77e492eE0bB93C2B0437aD6fdECCc;
// token price in the begining
uint256 constant public TOKEN_PRICE_INITIAL = 0.0023 ether;
// a percent of the token price which adds/subs each _priceSpeedInterval tokens
uint64 constant public PRICE_SPEED_PERCENT = 5;
// Token price speed interval. For instance, if PRICE_SPEED_PERCENT = 5 and PRICE_SPEED_INTERVAL = 10000 it means that after 10000 tokens are bought/sold token price will increase/decrease for 5%.
uint64 constant public PRICE_SPEED_INTERVAL = 10000;
// lock-up period in days. Until this period is expeired nobody can close the contract or withdraw users' funds
uint64 constant public EXP_PERIOD_DAYS = 365;
mapping(address => bool) private _administrators;
uint256 private _administratorCount;
uint64 public _initTime;
uint64 public _expirationTime;
uint256 public _tokenOwnerReward;
uint256 public _totalSupply;
int128 public _realTokenPrice;
address public _controllerAddress = address(0x0);
EtheramaCore public _core;
uint256 public _initBlockNum;
bool public _hasMaxPurchaseLimit = false;
IStdToken public _token;
//only main contract
modifier onlyController() {
require(msg.sender == _controllerAddress);
_;
}
constructor(address coreAddress) public {
require(coreAddress != address(0x0));
_core = EtheramaCore(coreAddress);
_initBlockNum = block.number;
}
function init() public {
require(_controllerAddress == address(0x0));
require(TOKEN_CONTRACT_ADDRESS != address(0x0));
require(RealMath.isUInt64ValidIn64(PRICE_SPEED_PERCENT) && PRICE_SPEED_PERCENT > 0);
require(RealMath.isUInt64ValidIn64(PRICE_SPEED_INTERVAL) && PRICE_SPEED_INTERVAL > 0);
_controllerAddress = msg.sender;
_token = IStdToken(TOKEN_CONTRACT_ADDRESS);
_initTime = uint64(now);
_expirationTime = _initTime + EXP_PERIOD_DAYS * 1 days;
_realTokenPrice = _core.convert256ToReal(TOKEN_PRICE_INITIAL);
}
function isInited() public view returns(bool) {
return (_controllerAddress != address(0x0));
}
function getCoreAddress() public view returns(address) {
return address(_core);
}
function setNewControllerAddress(address newAddress) onlyController public {
_controllerAddress = newAddress;
}
function getPromoMinPurchaseEth() public view returns(uint256) {
return _core._promoMinPurchaseEth();
}
function addAdministator(address addr) onlyController public {
_administrators[addr] = true;
_administratorCount = SafeMath.add(_administratorCount, 1);
}
function removeAdministator(address addr) onlyController public {
_administrators[addr] = false;
_administratorCount = SafeMath.sub(_administratorCount, 1);
}
function getAdministratorCount() public view returns(uint256) {
return _administratorCount;
}
function isAdministrator(address addr) public view returns(bool) {
return _administrators[addr];
}
function getCommonInitBlockNum() public view returns (uint256) {
return _core.getInitBlockNum();
}
function resetTokenOwnerReward() onlyController public {
_tokenOwnerReward = 0;
}
function addTokenOwnerReward(uint256 val) onlyController public {
_tokenOwnerReward = SafeMath.add(_tokenOwnerReward, val);
}
function getCurrentBigPromoBonus() public view returns (uint256) {
return _core._currentBigPromoBonus();
}
function getCurrentQuickPromoBonus() public view returns (uint256) {
return _core._currentQuickPromoBonus();
}
function getTotalCollectedPromoBonus() public view returns (uint256) {
return _core.getTotalCollectedPromoBonus();
}
function setTotalSupply(uint256 val) onlyController public {
_totalSupply = val;
}
function setRealTokenPrice(int128 val) onlyController public {
_realTokenPrice = val;
}
function setHasMaxPurchaseLimit(bool val) onlyController public {
_hasMaxPurchaseLimit = val;
}
function getUserTokenLocalBalance(address userAddress) public view returns(uint256) {
return _core.getUserTokenLocalBalance(address(this), userAddress);
}
function getActualUserTokenBalance(address userAddress) public view returns(uint256) {
return SafeMath.min(getUserTokenLocalBalance(userAddress), _token.balanceOf(userAddress));
}
function getBonusPerShare() public view returns(uint256) {
return _core.getBonusPerShare(address(this));
}
function getUserRewardPayouts(address userAddress) public view returns(uint256) {
return _core.getUserRewardPayouts(address(this), userAddress);
}
function getUserRefBalance(address userAddress) public view returns(uint256) {
return _core.getUserRefBalance(address(this), userAddress);
}
function getUserReward(address userAddress, bool incRefBonus, bool incPromoBonus) public view returns(uint256) {
return _core.getUserReward(address(this), userAddress, true, incRefBonus, incPromoBonus);
}
function getUserTotalPromoBonus(address userAddress) public view returns(uint256) {
return _core.getUserTotalPromoBonus(address(this), userAddress);
}
function getUserBigPromoBonus(address userAddress) public view returns(uint256) {
return _core.getUserBigPromoBonus(address(this), userAddress);
}
function getUserQuickPromoBonus(address userAddress) public view returns(uint256) {
return _core.getUserQuickPromoBonus(address(this), userAddress);
}
function getRemainingTokenAmount() public view returns(uint256) {
return _token.balanceOf(_controllerAddress);
}
function getTotalTokenSold() public view returns(uint256) {
return _totalSupply - getRemainingTokenAmount();
}
function getUserEthVolumeSaldo(address userAddress) public view returns(uint256) {
return _core.getUserEthVolumeSaldo(address(this), userAddress);
}
}
contract Etherama {
IStdToken public _token;
EtheramaData public _data;
EtheramaCore public _core;
bool public isActive = false;
bool public isMigrationToNewControllerInProgress = false;
bool public isActualContractVer = true;
address public migrationContractAddress = address(0x0);
bool public isMigrationApproved = false;
address private _creator = address(0x0);
event onTokenPurchase(address indexed userAddress, uint256 incomingEth, uint256 tokensMinted, address indexed referredBy);
event onTokenSell(address indexed userAddress, uint256 tokensBurned, uint256 ethEarned);
event onReinvestment(address indexed userAddress, uint256 ethReinvested, uint256 tokensMinted);
event onWithdrawTokenOwnerReward(address indexed toAddress, uint256 ethWithdrawn);
event onWinQuickPromo(address indexed userAddress, uint256 ethWon);
event onWinBigPromo(address indexed userAddress, uint256 ethWon);
// only people with tokens
modifier onlyContractUsers() {
require(getUserLocalTokenBalance(msg.sender) > 0);
_;
}
// administrators can:
// -> change minimal amout of tokens to get a ref link.
// administrators CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
// -> suspend the contract
modifier onlyAdministrator() {
require(isCurrentUserAdministrator());
_;
}
//core administrator can only approve contract migration after its code review
modifier onlyCoreAdministrator() {
require(_core.isAdministrator(msg.sender));
_;
}
// only active state of the contract. Administator can activate it, but canncon deactive untill lock-up period is expired.
modifier onlyActive() {
require(isActive);
_;
}
// maximum gas price for buy/sell transactions to avoid "front runner" vulnerability.
modifier validGasPrice() {
require(tx.gasprice <= _core.MAX_GAS_PRICE());
_;
}
// eth value must be greater than 0 for purchase transactions
modifier validPayableValue() {
require(msg.value > 0);
_;
}
modifier onlyCoreContract() {
require(msg.sender == _data.getCoreAddress());
_;
}
// dataContractAddress - data contract address where all the data is collected and separated from the controller
constructor(address dataContractAddress) public {
require(dataContractAddress != address(0x0));
_data = EtheramaData(dataContractAddress);
if (!_data.isInited()) {
_data.init();
_data.addAdministator(msg.sender);
_creator = msg.sender;
}
_token = _data._token();
_core = _data._core();
}
function addAdministator(address addr) onlyAdministrator public {
_data.addAdministator(addr);
}
function removeAdministator(address addr) onlyAdministrator public {
_data.removeAdministator(addr);
}
// transfer ownership request of the contract to token owner from contract creator. The new administator has to accept ownership to finish the transferring.
function transferOwnershipRequest(address addr) onlyAdministrator public {
addAdministator(addr);
}
// accept transfer ownership.
function acceptOwnership() onlyAdministrator public {
require(_creator != address(0x0));
removeAdministator(_creator);
require(_data.getAdministratorCount() == 1);
}
// if there is a maximim purchase limit then a user can buy only amount of tokens which he had before, not more.
function setHasMaxPurchaseLimit(bool val) onlyAdministrator public {
_data.setHasMaxPurchaseLimit(val);
}
// activate the controller contract. After calling this function anybody can start trading the contrant's tokens
function activate() onlyAdministrator public {
require(!isActive);
if (getTotalTokenSupply() == 0) setTotalSupply();
require(getTotalTokenSupply() > 0);
isActive = true;
isMigrationToNewControllerInProgress = false;
}
// Close the contract and withdraw all the funds. The contract cannot be closed before lock up period is expired.
function finish() onlyActive onlyAdministrator public {
require(uint64(now) >= _data._expirationTime());
_token.transfer(msg.sender, getRemainingTokenAmount());
msg.sender.transfer(getTotalEthBalance());
isActive = false;
}
//Converts incoming eth to tokens
function buy(address refAddress, uint256 minReturn) onlyActive validGasPrice validPayableValue public payable returns(uint256) {
return purchaseTokens(msg.value, refAddress, minReturn);
}
//sell tokens for eth. before call this func you have to call "approve" in the ERC20 token contract
function sell(uint256 tokenAmount, uint256 minReturn) onlyActive onlyContractUsers validGasPrice public returns(uint256) {
if (tokenAmount > getCurrentUserLocalTokenBalance() || tokenAmount == 0) return 0;
uint256 ethAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0;
(ethAmount, totalFeeEth, tokenPrice) = estimateSellOrder(tokenAmount, true);
require(ethAmount >= minReturn);
subUserTokens(msg.sender, tokenAmount);
msg.sender.transfer(ethAmount);
updateTokenPrice(-_core.convert256ToReal(tokenAmount));
distributeFee(totalFeeEth, address(0x0));
uint256 userEthVol = _data.getUserEthVolumeSaldo(msg.sender);
_core.trackSell(msg.sender, ethAmount > userEthVol ? userEthVol : ethAmount, tokenAmount);
emit onTokenSell(msg.sender, tokenAmount, ethAmount);
return ethAmount;
}
function transferTokens(address toUser, uint256 tokenAmount) onlyActive onlyContractUsers public {
require(getUserLocalTokenBalance(msg.sender) >= tokenAmount);
_core.subUserTokenLocalBalance(msg.sender, tokenAmount);
_core.addUserTokenLocalBalance(toUser, tokenAmount);
_token.transferFrom(msg.sender, toUser, tokenAmount);
}
//Fallback function to handle eth that was sent straight to the contract
function() onlyActive validGasPrice validPayableValue payable external {
purchaseTokens(msg.value, address(0x0), 1);
}
// withdraw token owner's reward
function withdrawTokenOwnerReward() onlyAdministrator public {
uint256 reward = getTokenOwnerReward();
require(reward > 0);
_data.resetTokenOwnerReward();
msg.sender.transfer(reward);
emit onWithdrawTokenOwnerReward(msg.sender, reward);
}
// prepare the contract for migration to another one in case of some errors or refining
function prepareForMigration() onlyAdministrator public {
require(!isMigrationToNewControllerInProgress);
isMigrationToNewControllerInProgress = true;
}
// accept funds transfer to a new controller during a migration.
function migrateFunds() payable public {
require(isMigrationToNewControllerInProgress);
}
//HELPERS
// max gas price for buy/sell transactions
function getMaxGasPrice() public view returns(uint256) {
return _core.MAX_GAS_PRICE();
}
// max gas price for buy/sell transactions
function getExpirationTime() public view returns (uint256) {
return _data._expirationTime();
}
// time till lock-up period is expired
function getRemainingTimeTillExpiration() public view returns (uint256) {
if (_data._expirationTime() <= uint64(now)) return 0;
return _data._expirationTime() - uint64(now);
}
function isCurrentUserAdministrator() public view returns(bool) {
return _data.isAdministrator(msg.sender);
}
//data contract address where all the data is holded
function getDataContractAddress() public view returns(address) {
return address(_data);
}
// get trading token contract address
function getTokenAddress() public view returns(address) {
return address(_token);
}
// request migration to new contract. After request Etherama dev team should review its code and approve it if it is OK
function requestControllerContractMigration(address newControllerAddr) onlyAdministrator public {
require(!isMigrationApproved);
migrationContractAddress = newControllerAddr;
}
// Dev team gives a pervission to updagrade the contract after code review, transfer all the funds, activate new abilities or fix some errors.
function approveControllerContractMigration() onlyCoreAdministrator public {
isMigrationApproved = true;
}
//migrate to new controller contract in case of some mistake in the contract and transfer there all the tokens and eth. It can be done only after code review by Etherama developers.
function migrateToNewNewControllerContract() onlyAdministrator public {
require(isMigrationApproved && migrationContractAddress != address(0x0) && isActualContractVer);
isActive = false;
Etherama newController = Etherama(address(migrationContractAddress));
_data.setNewControllerAddress(migrationContractAddress);
uint256 remainingTokenAmount = getRemainingTokenAmount();
uint256 ethBalance = getTotalEthBalance();
if (remainingTokenAmount > 0) _token.transfer(migrationContractAddress, remainingTokenAmount);
if (ethBalance > 0) newController.migrateFunds.value(ethBalance)();
isActualContractVer = false;
}
//total buy count
function getBuyCount() public view returns(uint256) {
return _core.getBuyCount(getDataContractAddress());
}
//total sell count
function getSellCount() public view returns(uint256) {
return _core.getSellCount(getDataContractAddress());
}
//total eth volume
function getTotalVolumeEth() public view returns(uint256) {
return _core.getTotalVolumeEth(getDataContractAddress());
}
//total token volume
function getTotalVolumeToken() public view returns(uint256) {
return _core.getTotalVolumeToken(getDataContractAddress());
}
//current bonus per 1 token in ETH
function getBonusPerShare() public view returns (uint256) {
return SafeMath.div(SafeMath.mul(_data.getBonusPerShare(), 1 ether), _core.MAGNITUDE());
}
//token initial price in ETH
function getTokenInitialPrice() public view returns(uint256) {
return _data.TOKEN_PRICE_INITIAL();
}
function getDevRewardPercent() public view returns(uint256) {
return _core._devRewardPercent();
}
function getTokenOwnerRewardPercent() public view returns(uint256) {
return _core._tokenOwnerRewardPercent();
}
function getShareRewardPercent() public view returns(uint256) {
return _core._shareRewardPercent();
}
function getRefBonusPercent() public view returns(uint256) {
return _core._refBonusPercent();
}
function getBigPromoPercent() public view returns(uint256) {
return _core._bigPromoPercent();
}
function getQuickPromoPercent() public view returns(uint256) {
return _core._quickPromoPercent();
}
function getBigPromoBlockInterval() public view returns(uint256) {
return _core._bigPromoBlockInterval();
}
function getQuickPromoBlockInterval() public view returns(uint256) {
return _core._quickPromoBlockInterval();
}
function getPromoMinPurchaseEth() public view returns(uint256) {
return _core._promoMinPurchaseEth();
}
function getPriceSpeedPercent() public view returns(uint64) {
return _data.PRICE_SPEED_PERCENT();
}
function getPriceSpeedTokenBlock() public view returns(uint64) {
return _data.PRICE_SPEED_INTERVAL();
}
function getMinRefEthPurchase() public view returns (uint256) {
return _core._minRefEthPurchase();
}
function getTotalCollectedPromoBonus() public view returns (uint256) {
return _data.getTotalCollectedPromoBonus();
}
function getCurrentBigPromoBonus() public view returns (uint256) {
return _data.getCurrentBigPromoBonus();
}
function getCurrentQuickPromoBonus() public view returns (uint256) {
return _data.getCurrentQuickPromoBonus();
}
//current token price
function getCurrentTokenPrice() public view returns(uint256) {
return _core.convertRealTo256(_data._realTokenPrice());
}
//contract's eth balance
function getTotalEthBalance() public view returns(uint256) {
return address(this).balance;
}
//amount of tokens which were funded to the contract initially
function getTotalTokenSupply() public view returns(uint256) {
return _data._totalSupply();
}
//amount of tokens which are still available for selling on the contract
function getRemainingTokenAmount() public view returns(uint256) {
return _token.balanceOf(address(this));
}
//amount of tokens which where sold by the contract
function getTotalTokenSold() public view returns(uint256) {
return getTotalTokenSupply() - getRemainingTokenAmount();
}
//user's token amount which were bought from the contract
function getUserLocalTokenBalance(address userAddress) public view returns(uint256) {
return _data.getUserTokenLocalBalance(userAddress);
}
//current user's token amount which were bought from the contract
function getCurrentUserLocalTokenBalance() public view returns(uint256) {
return getUserLocalTokenBalance(msg.sender);
}
//is referal link available for the current user
function isCurrentUserRefAvailable() public view returns(bool) {
return _core.isRefAvailable();
}
function getCurrentUserRefBonus() public view returns(uint256) {
return _data.getUserRefBalance(msg.sender);
}
function getCurrentUserPromoBonus() public view returns(uint256) {
return _data.getUserTotalPromoBonus(msg.sender);
}
//max and min values of a deal in tokens
function getTokenDealRange() public view returns(uint256, uint256) {
return (_core.MIN_TOKEN_DEAL_VAL(), _core.MAX_TOKEN_DEAL_VAL());
}
//max and min values of a deal in ETH
function getEthDealRange() public view returns(uint256, uint256) {
uint256 minTokenVal; uint256 maxTokenVal;
(minTokenVal, maxTokenVal) = getTokenDealRange();
return ( SafeMath.max(_core.MIN_ETH_DEAL_VAL(), tokensToEth(minTokenVal, true)), SafeMath.min(_core.MAX_ETH_DEAL_VAL(), tokensToEth(maxTokenVal, true)) );
}
//user's total reward from all the tokens on the table. includes share reward + referal bonus + promo bonus
function getUserReward(address userAddress, bool isTotal) public view returns(uint256) {
return isTotal ?
_core.getUserTotalReward(userAddress, true, true, true) :
_data.getUserReward(userAddress, true, true);
}
//price for selling 1 token. mostly useful only for frontend
function get1TokenSellPrice() public view returns(uint256) {
uint256 tokenAmount = 1 ether;
uint256 ethAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0;
(ethAmount, totalFeeEth, tokenPrice) = estimateSellOrder(tokenAmount, true);
return ethAmount;
}
//price for buying 1 token. mostly useful only for frontend
function get1TokenBuyPrice() public view returns(uint256) {
uint256 ethAmount = 1 ether;
uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0;
(tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true);
return SafeMath.div(ethAmount * 1 ether, tokenAmount);
}
//calc current reward for holding @tokenAmount tokens
function calcReward(uint256 tokenAmount) public view returns(uint256) {
return (uint256) ((int256)(_data.getBonusPerShare() * tokenAmount)) / _core.MAGNITUDE();
}
//esimate buy order by amount of ETH/tokens. returns tokens/eth amount after the deal, total fee in ETH and average token price
function estimateBuyOrder(uint256 amount, bool fromEth) public view returns(uint256, uint256, uint256) {
uint256 minAmount; uint256 maxAmount;
(minAmount, maxAmount) = fromEth ? getEthDealRange() : getTokenDealRange();
//require(amount >= minAmount && amount <= maxAmount);
uint256 ethAmount = fromEth ? amount : tokensToEth(amount, true);
require(ethAmount > 0);
uint256 tokenAmount = fromEth ? ethToTokens(amount, true) : amount;
uint256 totalFeeEth = calcTotalFee(tokenAmount, true);
require(ethAmount > totalFeeEth);
uint256 tokenPrice = SafeMath.div(ethAmount * 1 ether, tokenAmount);
return (fromEth ? tokenAmount : SafeMath.add(ethAmount, totalFeeEth), totalFeeEth, tokenPrice);
}
//esimate sell order by amount of tokens/ETH. returns eth/tokens amount after the deal, total fee in ETH and average token price
function estimateSellOrder(uint256 amount, bool fromToken) public view returns(uint256, uint256, uint256) {
uint256 minAmount; uint256 maxAmount;
(minAmount, maxAmount) = fromToken ? getTokenDealRange() : getEthDealRange();
//require(amount >= minAmount && amount <= maxAmount);
uint256 tokenAmount = fromToken ? amount : ethToTokens(amount, false);
require(tokenAmount > 0);
uint256 ethAmount = fromToken ? tokensToEth(tokenAmount, false) : amount;
uint256 totalFeeEth = calcTotalFee(tokenAmount, false);
require(ethAmount > totalFeeEth);
uint256 tokenPrice = SafeMath.div(ethAmount * 1 ether, tokenAmount);
return (fromToken ? ethAmount : tokenAmount, totalFeeEth, tokenPrice);
}
//returns max user's purchase limit in tokens if _hasMaxPurchaseLimit pamam is set true. If it is a user cannot by more tokens that hs already bought on some other exchange
function getUserMaxPurchase(address userAddress) public view returns(uint256) {
return _token.balanceOf(userAddress) - SafeMath.mul(getUserLocalTokenBalance(userAddress), 2);
}
//current urser's max purchase limit in tokens
function getCurrentUserMaxPurchase() public view returns(uint256) {
return getUserMaxPurchase(msg.sender);
}
//token owener collected reward
function getTokenOwnerReward() public view returns(uint256) {
return _data._tokenOwnerReward();
}
//current user's won promo bonuses
function getCurrentUserTotalPromoBonus() public view returns(uint256) {
return _data.getUserTotalPromoBonus(msg.sender);
}
//current user's won big promo bonuses
function getCurrentUserBigPromoBonus() public view returns(uint256) {
return _data.getUserBigPromoBonus(msg.sender);
}
//current user's won quick promo bonuses
function getCurrentUserQuickPromoBonus() public view returns(uint256) {
return _data.getUserQuickPromoBonus(msg.sender);
}
//amount of block since core contract is deployed
function getBlockNumSinceInit() public view returns(uint256) {
return _core.getBlockNumSinceInit();
}
//remaing amount of blocks to win a quick promo bonus
function getQuickPromoRemainingBlocks() public view returns(uint256) {
return _core.getQuickPromoRemainingBlocks();
}
//remaing amount of blocks to win a big promo bonus
function getBigPromoRemainingBlocks() public view returns(uint256) {
return _core.getBigPromoRemainingBlocks();
}
// INTERNAL FUNCTIONS
function purchaseTokens(uint256 ethAmount, address refAddress, uint256 minReturn) internal returns(uint256) {
uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0;
(tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true);
require(tokenAmount >= minReturn);
if (_data._hasMaxPurchaseLimit()) {
//user has to have at least equal amount of tokens which he's willing to buy
require(getCurrentUserMaxPurchase() >= tokenAmount);
}
require(tokenAmount > 0 && (SafeMath.add(tokenAmount, getTotalTokenSold()) > getTotalTokenSold()));
if (refAddress == msg.sender || !_core.isRefAvailable(refAddress)) refAddress = address(0x0);
distributeFee(totalFeeEth, refAddress);
addUserTokens(msg.sender, tokenAmount);
// the user is not going to receive any reward for the current purchase
_core.addUserRewardPayouts(msg.sender, _data.getBonusPerShare() * tokenAmount);
checkAndSendPromoBonus(ethAmount);
updateTokenPrice(_core.convert256ToReal(tokenAmount));
_core.trackBuy(msg.sender, ethAmount, tokenAmount);
emit onTokenPurchase(msg.sender, ethAmount, tokenAmount, refAddress);
return tokenAmount;
}
function setTotalSupply() internal {
require(_data._totalSupply() == 0);
uint256 tokenAmount = _token.balanceOf(address(this));
_data.setTotalSupply(tokenAmount);
}
function checkAndSendPromoBonus(uint256 purchaseAmountEth) internal {
if (purchaseAmountEth < _data.getPromoMinPurchaseEth()) return;
if (getQuickPromoRemainingBlocks() == 0) sendQuickPromoBonus();
if (getBigPromoRemainingBlocks() == 0) sendBigPromoBonus();
}
function sendQuickPromoBonus() internal {
_core.payoutQuickBonus(msg.sender);
emit onWinQuickPromo(msg.sender, _data.getCurrentQuickPromoBonus());
}
function sendBigPromoBonus() internal {
_core.payoutBigBonus(msg.sender);
emit onWinBigPromo(msg.sender, _data.getCurrentBigPromoBonus());
}
function distributeFee(uint256 totalFeeEth, address refAddress) internal {
addProfitPerShare(totalFeeEth, refAddress);
addDevReward(totalFeeEth);
addTokenOwnerReward(totalFeeEth);
addBigPromoBonus(totalFeeEth);
addQuickPromoBonus(totalFeeEth);
}
function addProfitPerShare(uint256 totalFeeEth, address refAddress) internal {
uint256 refBonus = calcRefBonus(totalFeeEth);
uint256 totalShareReward = calcTotalShareRewardFee(totalFeeEth);
if (refAddress != address(0x0)) {
_core.addUserRefBalance.value(refBonus)(refAddress);
} else {
totalShareReward = SafeMath.add(totalShareReward, refBonus);
}
if (getTotalTokenSold() == 0) {
_data.addTokenOwnerReward(totalShareReward);
} else {
_core.addBonusPerShare.value(totalShareReward)();
}
}
function addDevReward(uint256 totalFeeEth) internal {
_core.addDevReward.value(calcDevReward(totalFeeEth))();
}
function addTokenOwnerReward(uint256 totalFeeEth) internal {
_data.addTokenOwnerReward(calcTokenOwnerReward(totalFeeEth));
}
function addBigPromoBonus(uint256 totalFeeEth) internal {
_core.addBigPromoBonus.value(calcBigPromoBonus(totalFeeEth))();
}
function addQuickPromoBonus(uint256 totalFeeEth) internal {
_core.addQuickPromoBonus.value(calcQuickPromoBonus(totalFeeEth))();
}
function addUserTokens(address user, uint256 tokenAmount) internal {
_core.addUserTokenLocalBalance(user, tokenAmount);
_token.transfer(msg.sender, tokenAmount);
}
function subUserTokens(address user, uint256 tokenAmount) internal {
_core.subUserTokenLocalBalance(user, tokenAmount);
_token.transferFrom(user, address(this), tokenAmount);
}
function updateTokenPrice(int128 realTokenAmount) public {
_data.setRealTokenPrice(calc1RealTokenRateFromRealTokens(realTokenAmount));
}
function ethToTokens(uint256 ethAmount, bool isBuy) internal view returns(uint256) {
int128 realEthAmount = _core.convert256ToReal(ethAmount);
int128 t0 = RealMath.div(realEthAmount, _data._realTokenPrice());
int128 s = getRealPriceSpeed();
int128 tn = RealMath.div(t0, RealMath.toReal(100));
for (uint i = 0; i < 100; i++) {
int128 tns = RealMath.mul(tn, s);
int128 exptns = RealMath.exp( RealMath.mul(tns, RealMath.toReal(isBuy ? int64(1) : int64(-1))) );
int128 tn1 = RealMath.div(
RealMath.mul( RealMath.mul(tns, tn), exptns ) + t0,
RealMath.mul( exptns, RealMath.toReal(1) + tns )
);
if (RealMath.abs(tn-tn1) < RealMath.fraction(1, 1e18)) break;
tn = tn1;
}
return _core.convertRealTo256(tn);
}
function tokensToEth(uint256 tokenAmount, bool isBuy) internal view returns(uint256) {
int128 realTokenAmount = _core.convert256ToReal(tokenAmount);
int128 s = getRealPriceSpeed();
int128 expArg = RealMath.mul(RealMath.mul(realTokenAmount, s), RealMath.toReal(isBuy ? int64(1) : int64(-1)));
int128 realEthAmountFor1Token = RealMath.mul(_data._realTokenPrice(), RealMath.exp(expArg));
int128 realEthAmount = RealMath.mul(realTokenAmount, realEthAmountFor1Token);
return _core.convertRealTo256(realEthAmount);
}
function calcTotalFee(uint256 tokenAmount, bool isBuy) internal view returns(uint256) {
int128 realTokenAmount = _core.convert256ToReal(tokenAmount);
int128 factor = RealMath.toReal(isBuy ? int64(1) : int64(-1));
int128 rateAfterDeal = calc1RealTokenRateFromRealTokens(RealMath.mul(realTokenAmount, factor));
int128 delta = RealMath.div(rateAfterDeal - _data._realTokenPrice(), RealMath.toReal(2));
int128 fee = RealMath.mul(realTokenAmount, delta);
//commission for sells is a bit lower due to rounding error
if (!isBuy) fee = RealMath.mul(fee, RealMath.fraction(95, 100));
return _core.calcPercent(_core.convertRealTo256(RealMath.mul(fee, factor)), _core._totalIncomeFeePercent());
}
function calc1RealTokenRateFromRealTokens(int128 realTokenAmount) internal view returns(int128) {
int128 expArg = RealMath.mul(realTokenAmount, getRealPriceSpeed());
return RealMath.mul(_data._realTokenPrice(), RealMath.exp(expArg));
}
function getRealPriceSpeed() internal view returns(int128) {
require(RealMath.isUInt64ValidIn64(_data.PRICE_SPEED_PERCENT()));
require(RealMath.isUInt64ValidIn64(_data.PRICE_SPEED_INTERVAL()));
return RealMath.div(RealMath.fraction(int64(_data.PRICE_SPEED_PERCENT()), 100), RealMath.toReal(int64(_data.PRICE_SPEED_INTERVAL())));
}
function calcTotalShareRewardFee(uint256 totalFee) internal view returns(uint256) {
return _core.calcPercent(totalFee, _core._shareRewardPercent());
}
function calcRefBonus(uint256 totalFee) internal view returns(uint256) {
return _core.calcPercent(totalFee, _core._refBonusPercent());
}
function calcTokenOwnerReward(uint256 totalFee) internal view returns(uint256) {
return _core.calcPercent(totalFee, _core._tokenOwnerRewardPercent());
}
function calcDevReward(uint256 totalFee) internal view returns(uint256) {
return _core.calcPercent(totalFee, _core._devRewardPercent());
}
function calcQuickPromoBonus(uint256 totalFee) internal view returns(uint256) {
return _core.calcPercent(totalFee, _core._quickPromoPercent());
}
function calcBigPromoBonus(uint256 totalFee) internal view returns(uint256) {
return _core.calcPercent(totalFee, _core._bigPromoPercent());
}
}
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;
}
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 ? b : a;
}
}
//taken from https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol and a bit modified
library RealMath {
int64 constant MIN_INT64 = int64((uint64(1) << 63));
int64 constant MAX_INT64 = int64(~((uint64(1) << 63)));
/**
* How many total bits are there?
*/
int256 constant REAL_BITS = 128;
/**
* How many fractional bits are there?
*/
int256 constant REAL_FBITS = 64;
/**
* How many integer bits are there?
*/
int256 constant REAL_IBITS = REAL_BITS - REAL_FBITS;
/**
* What's the first non-fractional bit
*/
int128 constant REAL_ONE = int128(1) << REAL_FBITS;
/**
* What's the last fractional bit?
*/
int128 constant REAL_HALF = REAL_ONE >> 1;
/**
* What's two? Two is pretty useful.
*/
int128 constant REAL_TWO = REAL_ONE << 1;
/**
* And our logarithms are based on ln(2).
*/
int128 constant REAL_LN_TWO = 762123384786;
/**
* It is also useful to have Pi around.
*/
int128 constant REAL_PI = 3454217652358;
/**
* And half Pi, to save on divides.
* TODO: That might not be how the compiler handles constants.
*/
int128 constant REAL_HALF_PI = 1727108826179;
/**
* And two pi, which happens to be odd in its most accurate representation.
*/
int128 constant REAL_TWO_PI = 6908435304715;
/**
* What's the sign bit?
*/
int128 constant SIGN_MASK = int128(1) << 127;
function getMinInt64() internal pure returns (int64) {
return MIN_INT64;
}
function getMaxInt64() internal pure returns (int64) {
return MAX_INT64;
}
function isUInt256ValidIn64(uint256 val) internal pure returns (bool) {
return val >= 0 && val <= uint256(getMaxInt64());
}
function isInt256ValidIn64(int256 val) internal pure returns (bool) {
return val >= int256(getMinInt64()) && val <= int256(getMaxInt64());
}
function isUInt64ValidIn64(uint64 val) internal pure returns (bool) {
return val >= 0 && val <= uint64(getMaxInt64());
}
function isInt128ValidIn64(int128 val) internal pure returns (bool) {
return val >= int128(getMinInt64()) && val <= int128(getMaxInt64());
}
/**
* Convert an integer to a real. Preserves sign.
*/
function toReal(int64 ipart) internal pure returns (int128) {
return int128(ipart) * REAL_ONE;
}
/**
* Convert a real to an integer. Preserves sign.
*/
function fromReal(int128 real_value) internal pure returns (int64) {
int128 intVal = real_value / REAL_ONE;
require(isInt128ValidIn64(intVal));
return int64(intVal);
}
/**
* Get the absolute value of a real. Just the same as abs on a normal int128.
*/
function abs(int128 real_value) internal pure returns (int128) {
if (real_value > 0) {
return real_value;
} else {
return -real_value;
}
}
/**
* Get the fractional part of a real, as a real. Ignores sign (so fpart(-0.5) is 0.5).
*/
function fpart(int128 real_value) internal pure returns (int128) {
// This gets the fractional part but strips the sign
return abs(real_value) % REAL_ONE;
}
/**
* Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5).
*/
function fpartSigned(int128 real_value) internal pure returns (int128) {
// This gets the fractional part but strips the sign
int128 fractional = fpart(real_value);
return real_value < 0 ? -fractional : fractional;
}
/**
* Get the integer part of a fixed point value.
*/
function ipart(int128 real_value) internal pure returns (int128) {
// Subtract out the fractional part to get the real part.
return real_value - fpartSigned(real_value);
}
/**
* Multiply one real by another. Truncates overflows.
*/
function mul(int128 real_a, int128 real_b) internal pure returns (int128) {
// When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.
// So we just have to clip off the extra REAL_FBITS fractional bits.
return int128((int256(real_a) * int256(real_b)) >> REAL_FBITS);
}
/**
* Divide one real by another real. Truncates overflows.
*/
function div(int128 real_numerator, int128 real_denominator) internal pure returns (int128) {
// We use the reverse of the multiplication trick: convert numerator from
// x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
return int128((int256(real_numerator) * REAL_ONE) / int256(real_denominator));
}
/**
* Create a real from a rational fraction.
*/
function fraction(int64 numerator, int64 denominator) internal pure returns (int128) {
return div(toReal(numerator), toReal(denominator));
}
// Now we have some fancy math things (like pow and trig stuff). This isn't
// in the RealMath that was deployed with the original Macroverse
// deployment, so it needs to be linked into your contract statically.
/**
* Raise a number to a positive integer power in O(log power) time.
* See <https://stackoverflow.com/a/101613>
*/
function ipow(int128 real_base, int64 exponent) internal pure returns (int128) {
if (exponent < 0) {
// Negative powers are not allowed here.
revert();
}
// Start with the 0th power
int128 real_result = REAL_ONE;
while (exponent != 0) {
// While there are still bits set
if ((exponent & 0x1) == 0x1) {
// If the low bit is set, multiply in the (many-times-squared) base
real_result = mul(real_result, real_base);
}
// Shift off the low bit
exponent = exponent >> 1;
// Do the squaring
real_base = mul(real_base, real_base);
}
// Return the final result.
return real_result;
}
/**
* Zero all but the highest set bit of a number.
* See <https://stackoverflow.com/a/53184>
*/
function hibit(uint256 val) internal pure returns (uint256) {
// Set all the bits below the highest set bit
val |= (val >> 1);
val |= (val >> 2);
val |= (val >> 4);
val |= (val >> 8);
val |= (val >> 16);
val |= (val >> 32);
val |= (val >> 64);
val |= (val >> 128);
return val ^ (val >> 1);
}
/**
* Given a number with one bit set, finds the index of that bit.
*/
function findbit(uint256 val) internal pure returns (uint8 index) {
index = 0;
// We and the value with alternating bit patters of various pitches to find it.
if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) {
// Picth 1
index |= 1;
}
if (val & 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC != 0) {
// Pitch 2
index |= 2;
}
if (val & 0xF0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0 != 0) {
// Pitch 4
index |= 4;
}
if (val & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00 != 0) {
// Pitch 8
index |= 8;
}
if (val & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000 != 0) {
// Pitch 16
index |= 16;
}
if (val & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000 != 0) {
// Pitch 32
index |= 32;
}
if (val & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000 != 0) {
// Pitch 64
index |= 64;
}
if (val & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 != 0) {
// Pitch 128
index |= 128;
}
}
/**
* Shift real_arg left or right until it is between 1 and 2. Return the
* rescaled value, and the number of bits of right shift applied. Shift may be negative.
*
* Expresses real_arg as real_scaled * 2^shift, setting shift to put real_arg between [1 and 2).
*
* Rejects 0 or negative arguments.
*/
function rescale(int128 real_arg) internal pure returns (int128 real_scaled, int64 shift) {
if (real_arg <= 0) {
// Not in domain!
revert();
}
require(isInt256ValidIn64(REAL_FBITS));
// Find the high bit
int64 high_bit = findbit(hibit(uint256(real_arg)));
// We'll shift so the high bit is the lowest non-fractional bit.
shift = high_bit - int64(REAL_FBITS);
if (shift < 0) {
// Shift left
real_scaled = real_arg << -shift;
} else if (shift >= 0) {
// Shift right
real_scaled = real_arg >> shift;
}
}
/**
* Calculate the natural log of a number. Rescales the input value and uses
* the algorithm outlined at <https://math.stackexchange.com/a/977836> and
* the ipow implementation.
*
* Lets you artificially limit the number of iterations.
*
* Note that it is potentially possible to get an un-converged value; lack
* of convergence does not throw.
*/
function lnLimited(int128 real_arg, int max_iterations) internal pure returns (int128) {
if (real_arg <= 0) {
// Outside of acceptable domain
revert();
}
if (real_arg == REAL_ONE) {
// Handle this case specially because people will want exactly 0 and
// not ~2^-39 ish.
return 0;
}
// We know it's positive, so rescale it to be between [1 and 2)
int128 real_rescaled;
int64 shift;
(real_rescaled, shift) = rescale(real_arg);
// Compute the argument to iterate on
int128 real_series_arg = div(real_rescaled - REAL_ONE, real_rescaled + REAL_ONE);
// We will accumulate the result here
int128 real_series_result = 0;
for (int64 n = 0; n < max_iterations; n++) {
// Compute term n of the series
int128 real_term = div(ipow(real_series_arg, 2 * n + 1), toReal(2 * n + 1));
// And add it in
real_series_result += real_term;
if (real_term == 0) {
// We must have converged. Next term is too small to represent.
break;
}
// If we somehow never converge I guess we will run out of gas
}
// Double it to account for the factor of 2 outside the sum
real_series_result = mul(real_series_result, REAL_TWO);
// Now compute and return the overall result
return mul(toReal(shift), REAL_LN_TWO) + real_series_result;
}
/**
* Calculate a natural logarithm with a sensible maximum iteration count to
* wait until convergence. Note that it is potentially possible to get an
* un-converged value; lack of convergence does not throw.
*/
function ln(int128 real_arg) internal pure returns (int128) {
return lnLimited(real_arg, 100);
}
/**
* Calculate e^x. Uses the series given at
* <http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html>.
*
* Lets you artificially limit the number of iterations.
*
* Note that it is potentially possible to get an un-converged value; lack
* of convergence does not throw.
*/
function expLimited(int128 real_arg, int max_iterations) internal pure returns (int128) {
// We will accumulate the result here
int128 real_result = 0;
// We use this to save work computing terms
int128 real_term = REAL_ONE;
for (int64 n = 0; n < max_iterations; n++) {
// Add in the term
real_result += real_term;
// Compute the next term
real_term = mul(real_term, div(real_arg, toReal(n + 1)));
if (real_term == 0) {
// We must have converged. Next term is too small to represent.
break;
}
// If we somehow never converge I guess we will run out of gas
}
// Return the result
return real_result;
}
function expLimited(int128 real_arg, int max_iterations, int k) internal pure returns (int128) {
// We will accumulate the result here
int128 real_result = 0;
// We use this to save work computing terms
int128 real_term = REAL_ONE;
for (int64 n = 0; n < max_iterations; n++) {
// Add in the term
real_result += real_term;
// Compute the next term
real_term = mul(real_term, div(real_arg, toReal(n + 1)));
if (real_term == 0) {
// We must have converged. Next term is too small to represent.
break;
}
if (n == k) return real_term;
// If we somehow never converge I guess we will run out of gas
}
// Return the result
return real_result;
}
/**
* Calculate e^x with a sensible maximum iteration count to wait until
* convergence. Note that it is potentially possible to get an un-converged
* value; lack of convergence does not throw.
*/
function exp(int128 real_arg) internal pure returns (int128) {
return expLimited(real_arg, 100);
}
/**
* Raise any number to any power, except for negative bases to fractional powers.
*/
function pow(int128 real_base, int128 real_exponent) internal pure returns (int128) {
if (real_exponent == 0) {
// Anything to the 0 is 1
return REAL_ONE;
}
if (real_base == 0) {
if (real_exponent < 0) {
// Outside of domain!
revert();
}
// Otherwise it's 0
return 0;
}
if (fpart(real_exponent) == 0) {
// Anything (even a negative base) is super easy to do to an integer power.
if (real_exponent > 0) {
// Positive integer power is easy
return ipow(real_base, fromReal(real_exponent));
} else {
// Negative integer power is harder
return div(REAL_ONE, ipow(real_base, fromReal(-real_exponent)));
}
}
if (real_base < 0) {
// It's a negative base to a non-integer power.
// In general pow(-x^y) is undefined, unless y is an int or some
// weird rational-number-based relationship holds.
revert();
}
// If it's not a special case, actually do it.
return exp(mul(real_exponent, ln(real_base)));
}
}
|
remaing amount of blocks to win a quick promo bonus
|
function getQuickPromoRemainingBlocks() public view returns(uint256) {
return _core.getQuickPromoRemainingBlocks();
}
| 1,321,888
|
./partial_match/1/0x30ba0890cFb7c6D42a33154B81413AfEBaE8a742/sources/HMaker.sol
|
if amount == uint256(-1) return balance of Proxy selector of "safeLockETH(address,address,uint256,address)"
|
function safeLockETH(
uint256 value,
address ethJoin,
uint256 cdp
) external payable {
IDSProxy proxy = IDSProxy(_getProxy(address(this)));
address owner = _getProxy(_getSender());
value = _getBalance(address(0), value);
try
proxy.execute.value(value)(
PROXY_ACTIONS,
abi.encodeWithSelector(
0xee284576,
CDP_MANAGER,
ethJoin,
cdp,
owner
)
)
_revertMsg("safeLockETH", reason);
_revertMsg("safeLockETH");
}
| 2,705,460
|
/**
......''''......
.',:cldxxkOOO0kddk0OOOkxxdlc:;'.
.,:lxkO00000000000k, .;k00000000000Okxl:,.
.;ldO0000000000000000O; :O0000000000000000Odl;.
':dk00000000000000000000Ol. .o000000000000000000000kd:'
.:dO0000000000000000000000000o;:d0000000000000000000000000Od:.
,ok000000000000000000000000000000000000000000000000000000000000ko,
.;dO0000000000000000000000000000000000000000000000000000000000000000Od;.
;d0000000000000000000000000000000000000000000000000000000000000000000000d;
'dO000000000000000000000000000000000000000000000000000000000000000000000000Od'
.cO0000000000000000000000000000000000000000000000000000000000000000000000000000Oc.
'd00000000000000000000000000000000000000000000000000000000000000000000000000000000d'
;k0000000000000000000000000000000000000000000000000000000000000000000000000000000000k;
cO000000000000000000000000000000000000000000000000000000000000000000000000000000000000Oc
cO00000000000000000000000000000000000000000000000000000000000000000000000000000000000000Oc
:O0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000O:
;k000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000k;
.x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000x.
l0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000l
'k0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000k'
c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c
.x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000x.
,k00000000000000000000000000000000000OOOO000000000000000000000000000000000000000000000000000000000k,
;O000OO00000000000000000000000000000x,...'',,;;;:::cccclloooddxxkkkOOOO000000000000000000000000000O;
:0ko:'.,ldO0000000000000000000000000d. ........'',,;;;::ccccllooodddxxkkkOO:
cOd;. .:k0000000000000000000000000d. .......'',,;:cclodxxk:
:000kocok000000000000000000000000000d. ...'',,;;;::cccclloodddxxkkkOOOO0000000000000:
;O0000000000000000000000000000000000koccllood; .o0O00000000000000000000000000000000000000000O;
'k0000000000000000000000000000000000000000000d. .x0000000000000000000000000000000000000000000k'
.o0000000000000000000000000000000000000000000x. ,k0000000000000000000000000000000000000000000o.
;O000000000000000000000000000000000000000000k, ;O000000000000000000000000000000000000000000O;
.d000000000000000000000000000000000000000000O; c0000000000000000000000000000000000000000000d.
;O000000000000000000000000000000000000000000c .o000000000000000000000000000000000000000000O;
.l000000000000000000000000000000000000000000o. .x000000000000000000000000000000000000000000l.
.d00000000000000000000000000000000000000000x. 'k00000000000000000000000000000000000000000d.
.x0000000000000000000000000000000000000000k' ;O0000000000000000000000000000000000000000x.
'x000000000000000000000000000000000000000O; c0000000000000000000000000000000000000000x'
.d000000000000000000000000000000000000000c .o000000000000000000000000000000000000000d.
.lO0000000000000000000000000000000000000o. .d0000000000000000000000000000000000000Ol.
;k000000000000000000000000000000000000d. 'k000000000000000000000000000000000000k;
.oO0000000000000000000000000000000000k' ;O0000000000000000000000000000000000Oo.
,d000000000000000000000000000000000O, :0000000000000000000000000000000000d,
.;x00000000000000000000000000000000:..l00000000000000000000000000000000x;.
.;dO00000000000000000000000000000l.,d00000000000000000000000000000Od;.
'lk000000000000000000000000000d;cx000000000000000000000000000kl'
.,lk000000000000000000000000xodk000000000000000000000000kl,.
.,cdO00000000000000000000OkOO00000000000000000000Odc,.
.;cdkO0000000000000000000000000000000000Okdc;.
.';cldkO0000000000000000000000Okdlc;'.
..',;:cclllloollllcc:;,'..
':ccc,
.l0KKKK0d.
'kK0KK0K0;
..'.'.'. .o0KKKKKx.
:000000O, ,cllc;.
:0K000KO,
c0K0K0KO, ..... ..... ......
.cdddk000KKK0kdddddc. :ddddddc. .ldddddl. ,coxkOOOkdol;. 'coxkOOOkdl;. .;loxkOOOkkxoc,.
.xK0KK00KKKKKK0KK0Kd. .oK0KK0Kx. 'OK0K0K0dx0KK0000000KKKOc. ,x0KK0000000KKOl. .:dOKKK00000000KK0Oo,
.kKKKKK0KKKKKKKKKKKd. .oK0KK0Kx. 'OK0KK0KK00KKKKKK00KKK0K0xdOK0KKKKKK000K00Kx' .:kKK0K0KKKKKKKK00K00K0d'
.;cccx0K0K0K0dccccc; .oK0KK0Kx. 'OK0KKK0K0xl;,,:oOK0KK000KKK0kl;,,:oOKK00K0Kd. .o0K0K0K0xl:,,,:lk0K0KK0KO;
:0K0K0KO, .oK0KK0Kx. 'OK0KK0K0l. 'xK00KKK0K0l. .dK0000K0; .l000KK0x,. .:kK0KK0KO,
:0K0K0KO, .oK0KK0Kx. 'OK0KK0Kd. ,OKK0KK0Kd. ,OK0KK0Kl ,OK000Kk,...........:OK0KK0Ko.
:0K0K0KO, .oK0KK0Kx. 'OK0KKKKc 'kXK0000Kl .xK0KK0Ko. :0K000K0kkkkkkkkkkkkO0K0000Kx.
:0K0K0KO, .oK0KK0Kx. 'OK0KKKKc 'kXK0KK0Kl .xK0KK0Ko. :0K0K0K000000000000000000000x.
:0K000KO, .oK0KK0Kx. 'OK0KKK0c 'kXK00K0Kl .xK0KK0Ko. 'OK0K0KOc....................
:0K0K0K0l. .oK0KK0Kx. 'OK0KKKKc 'kXK00K0Kl .xK0KK0Ko. l0K0K0Kk:. 'cl'
,OK0KK0K0xc;,,:. .oK0KK0Kx. 'OK0KKKKc 'kXK0KK0Kl .xK0KK0Ko. .l0K0K0K0ko:,,',;:lx0KKOc.
c0K0KKK0KKKKKKc .oK0KK0Kx. 'OK0KKK0c 'kXK0KK0Kl .xK0KK0Ko. ;x0K0000KKK000KKK00K000x,
;k0KK0000000Kc .oK0KK0Kx. 'OK00000c 'kXK0K00Kl .xK0000Ko. .;oO0KK000000000KKK0Oo:.
.,cdxkOOOkxo' :ddddddc. .ldddddd, .lxdddddd; .cdddddd: .,codxkOOOkkxol:,.
..''... ...''...
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the erc token owner.
*/
function getOwner() external view returns (address);
/**
* @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);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
// silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
this;
return msg.data;
}
}
/**
* @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) {
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;
}
}
/**
* @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 {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already 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;
// solhint-disable-next-line no-inline-assembly
assembly {cs := extcodesize(self)}
return cs == 0;
}
}
contract ERC20TokenImplementation is Context, IERC20, Initializable {
using SafeMath for uint256;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
bool internal _mintable;
constructor() {
}
/**
* @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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Returns if the token is mintable or not
*/
function mintable() external view returns (bool) {
return _mintable;
}
/**
* @dev Returns the erc token owner.
*/
function getOwner() external override view returns (address) {
return _owner;
}
/**
* @dev Returns the token decimals.
*/
function decimals() external override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external override view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external override view returns (string memory) {
return _name;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-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) external 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 {ERC20-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 {ERC20-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 Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
* - `_mintable` must be true
*/
function mint(uint256 amount) public onlyOwner returns (bool) {
require(_mintable, "this token is not mintable");
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Burn `amount` tokens and decreasing the total supply.
*/
function burn(uint256 amount) public returns (bool) {
_burn(_msgSender(), amount);
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, "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);
}
/**
* @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 {
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);
}
/**
* @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"));
}
}
contract Time is ERC20TokenImplementation {
/**
* @dev TimeZones are candidates possible to be yield farmed
*/
function _max_int() pure private returns (uint256) {
return 2 ** 256 - 1;
}
function _seconds_in_day() pure private returns (uint256) {
return 86400;
}
struct TimeZone {
uint256 index;
string id;
string description;
address contractAddress;
}
mapping(string => TimeZone) private _timeZoneMap;
string[] private _timeZoneKeys;
function _upsertTimeZone(string calldata id, string calldata description, address contractAddress) onlyOwner private returns (bool) {
TimeZone storage timeZoneToUpsert = _timeZoneMap[id];
timeZoneToUpsert.id = id;
timeZoneToUpsert.description = description;
timeZoneToUpsert.contractAddress = contractAddress;
if (timeZoneToUpsert.index > 0) {// entry exists
// do nothing
return true;
} else {// new entry
_timeZoneKeys.push(id);
uint keyListIndex = _timeZoneKeys.length - 1;
timeZoneToUpsert.index = keyListIndex + 1;
}
return true;
}
function _removeTimeZone(string calldata id) onlyOwner private returns (bool) {
TimeZone storage timeZoneToRemove = _timeZoneMap[id];
// entry not exist
require(timeZoneToRemove.index != 0);
// invalid index value
require(timeZoneToRemove.index <= _timeZoneKeys.length);
// Move an last element of array into the vacated key slot.
uint keyListIndex = timeZoneToRemove.index - 1;
uint keyListLastIndex = _timeZoneKeys.length - 1;
_timeZoneMap[_timeZoneKeys[keyListLastIndex]].index = keyListIndex + 1;
_timeZoneKeys[keyListIndex] = _timeZoneKeys[keyListLastIndex];
_timeZoneKeys.pop();
delete _timeZoneMap[id];
return true;
}
function _timeZonesSize() view private returns (uint) {
return uint(_timeZoneKeys.length);
}
function _timeZoneExists(string calldata id) view private returns (bool) {
return _timeZoneMap[id].index > 0;
}
function _timeZoneById(string calldata id) view private returns (TimeZone memory) {
return _timeZoneMap[id];
}
function _timeZoneByIndex(uint index) view private returns (TimeZone memory) {
require(index >= 0);
require(index < _timeZoneKeys.length);
return _timeZoneMap[_timeZoneKeys[index]];
}
function _timeZonesKeys() view private returns (string[] memory) {
return _timeZoneKeys;
}
/**
* @dev Voting proportion of an account for which time zone to farm from
*/
struct VotingProportion {
uint256 index;
string[] zoneIds;
uint256[] proportions;
}
mapping(address => VotingProportion) private _votingProportionMap;
address[] private _votingProportionKeys;
function _upsertVotingProportion(address key, string[] memory zoneIds, uint256[] memory proportions) private returns (bool) {
VotingProportion storage votingProportionToUpsert = _votingProportionMap[key];
votingProportionToUpsert.zoneIds = zoneIds;
votingProportionToUpsert.proportions = proportions;
if (votingProportionToUpsert.index > 0) {// entry exists
// do nothing
return true;
} else {// new entry
_votingProportionKeys.push(key);
uint keyListIndex = _votingProportionKeys.length - 1;
votingProportionToUpsert.index = keyListIndex + 1;
}
return true;
}
function _removeVotingProportion(address key) private returns (bool) {
VotingProportion storage votingProportionToRemove = _votingProportionMap[key];
// entry not exist
require(votingProportionToRemove.index != 0);
// invalid index value
require(votingProportionToRemove.index <= _votingProportionKeys.length);
// Move an last element of array into the vacated key slot.
uint keyListIndex = votingProportionToRemove.index - 1;
uint keyListLastIndex = _votingProportionKeys.length - 1;
_votingProportionMap[_votingProportionKeys[keyListLastIndex]].index = keyListIndex + 1;
_votingProportionKeys[keyListIndex] = _votingProportionKeys[keyListLastIndex];
_votingProportionKeys.pop();
delete _votingProportionMap[key];
return true;
}
function _votingProportionSize() view private returns (uint) {
return uint(_votingProportionKeys.length);
}
function _votingProportionExists(address key) view private returns (bool) {
return _votingProportionMap[key].index > 0;
}
function _votingProportionByKey(address key) view private returns (VotingProportion memory) {
return _votingProportionMap[key];
}
function _votingProportionByIndex(uint index) view private returns (VotingProportion memory) {
require(index >= 0);
require(index < _votingProportionKeys.length);
return _votingProportionMap[_votingProportionKeys[index]];
}
struct PriceInfo {
uint256 timeStampFrom;
uint256 timeStampTo;
uint256 priceFrom;
uint256 priceTo;
uint256 computedPrice;
}
/**
* @dev Admin private variables
*/
address private _liquidity;
address private _baseCurrency;
uint256 private _expense;
/**
* @dev Time pricing related private variables
*/
uint256 private _minTimeStamp;
uint256 private _maxTimeStamp;
mapping(uint256 => uint256) private _timeStampToPrice;
// Voting Events
event TimeZoneUpdated(string id, string description, address contractAddress);
event TimeZoneRemoved(string id);
event Voted(address votingAccount, string[] zoneIds, uint256[] proportions);
event Unvoted(address votingAccount);
event TimeZonesCleaned();
event VotingProportionCleaned();
// Admin Events
event LiquidityChanged(address previousLiquidity, address newLiquidity);
event BaseCurrencyChanged(address previousBaseCurrency, address newBaseCurrency, uint256 rate);
// Time Events
event TimeBought(uint256 timeAmount, uint256 baseCurrencyAmount, address buyer);
event TimeSold(uint256 timeAmount, uint256 baseCurrencyAmount, address seller);
event LapseProved(uint256 newPrice, uint256 newTimeStamp, uint256 expense);
event Reimbursed(uint256 expense);
constructor() {
_timeZoneKeys = new string[](0);
_votingProportionKeys = new address[](0);
_maxTimeStamp = 0;
_minTimeStamp = _max_int();
_expense = 0;
}
/**
* @dev sets initials supply and the owner
*/
function initialize(string memory name, string memory symbol, uint8 decimals, uint256 amount, bool mintable, address owner, address liquidityIn, address baseCurrencyIn) external initializer {
_owner = owner;
_name = name;
_symbol = symbol;
_decimals = decimals;
_mintable = mintable;
_liquidity = liquidityIn;
_baseCurrency = baseCurrencyIn;
_mint(owner, amount);
}
function addOrUpdateTimeZone(string calldata id, string calldata description, address contractAddress) onlyOwner external returns (bool) {
require(_upsertTimeZone(id, description, contractAddress), "Failed to upsert new time zone!");
emit TimeZoneUpdated(id, description, contractAddress);
return true;
}
function removeTimeZone(string calldata id) onlyOwner external returns (bool) {
require(_removeTimeZone(id), "Failed to remove time zone!");
emit TimeZoneRemoved(id);
return true;
}
function timeZone(string calldata id) view external returns (TimeZone memory) {
return _timeZoneById(id);
}
function timeZoneIds() view external returns (string[] memory) {
return _timeZoneKeys;
}
function vote(string[] calldata zoneIds, uint256[] calldata proportions) external returns (bool) {
require(zoneIds.length == proportions.length, "Voting zone length and proportion length does not match!");
bool allKeyExists = true;
uint256 proportionSum = 0;
for (uint256 i = 0; i < zoneIds.length; i++) {
allKeyExists = allKeyExists && _timeZoneExists(zoneIds[i]);
proportionSum += proportions[i];
}
require(allKeyExists, "Input contains wrong cadidate id(s)!");
require(proportionSum == 1 ether, "Voting proportion must add up to 1 ether");
require(_upsertVotingProportion(msg.sender, zoneIds, proportions), "Failed to update voting proportions!");
emit Voted(msg.sender, zoneIds, proportions);
return true;
}
function unvote() external returns (bool) {
require(_removeVotingProportion(msg.sender), "Failed to remove voting proportion!");
emit Unvoted(msg.sender);
return true;
}
function votingProportion(address account) view external returns (VotingProportion memory) {
return _votingProportionByKey(account);
}
function votingResult() view external returns (uint256[] memory) {
uint256[] memory votingResultToReturn = new uint256[](_timeZonesSize());
for (uint256 i = 0; i < _votingProportionSize(); i++) {
address account = _votingProportionKeys[i];
uint256 accountBalance = _balances[account];
string[] storage zoneIds = _votingProportionMap[account].zoneIds;
for (uint256 j = 0; j < zoneIds.length; j++) {
uint256 zoneIndex = _timeZoneMap[zoneIds[j]].index - 1;
uint256 accountVotingProportion = _votingProportionMap[account].proportions[j];
votingResultToReturn[zoneIndex] += SafeMath.div(SafeMath.mul(accountBalance, accountVotingProportion), 1 ether);
}
}
return votingResultToReturn;
}
function cleanVotingProportion() onlyOwner external returns (bool) {
for (uint256 i = 0; i < _votingProportionSize(); i++) {
delete _votingProportionMap[_votingProportionKeys[i]];
}
delete _votingProportionKeys;
emit VotingProportionCleaned();
return true;
}
function cleanTimeZones() onlyOwner external returns (bool) {
for (uint256 i = 0; i < _timeZonesSize(); i++) {
delete _timeZoneMap[_timeZoneKeys[i]];
}
delete _timeZoneKeys;
emit TimeZonesCleaned();
return true;
}
/**
* @dev changes the liquidity account
*/
function setLiquidity(address liquidity) onlyOwner external returns (bool) {
address previousLiquidity = _liquidity;
_liquidity = liquidity;
emit LiquidityChanged(previousLiquidity, _liquidity);
return true;
}
/**
* @dev main currency that time is backed - most likely one of the fiat base stablecoin
*/
function baseCurrency() view external returns (address) {
return _baseCurrency;
}
/**
* @dev changes base currency contract, need to provide rate which is newBaseCurrency/currentBaseCurrency
*/
function setBaseCurrency(address newBaseCurrency, uint256 rate) onlyOwner external returns (bool) {
address previousBaseCurrency = _baseCurrency;
_baseCurrency = newBaseCurrency;
for (uint256 timeStamp = _minTimeStamp; timeStamp <= _maxTimeStamp; timeStamp = timeStamp + _seconds_in_day()) {
if (_timeStampToPrice[timeStamp] != 0) {
_timeStampToPrice[timeStamp] = _applyRate(_timeStampToPrice[timeStamp], rate);
}
}
emit BaseCurrencyChanged(previousBaseCurrency, _baseCurrency, rate);
return true;
}
function _applyRate(uint256 value, uint256 rate) internal pure returns (uint256) {
return SafeMath.div(SafeMath.mul(value, rate), 1 ether);
}
function _baseLiquidityAmount() internal view returns (uint256) {
return IERC20(_baseCurrency).balanceOf(address(_liquidity));
}
/**
* @dev maximum amount time can be sold back at the moment
* if this value is small, time service will refill liquidity with base currency
*/
function maxTimeSellAmount() view public returns (uint256) {
return SafeMath.div(SafeMath.mul(_baseLiquidityAmount(), 1 ether), currentPrice());
}
/**
* @dev the actual live price - this price is used in maxTimeSellAmount and sellForBase
*/
function currentPrice() view public returns (uint256) {
uint256 currentTimeStamp = block.timestamp;
return _computePriceInfo(currentTimeStamp).computedPrice;
}
/**
* @dev start price of the current timeframe
*/
function currentStartPrice() view public returns (uint256) {
uint256 currentTimeStamp = block.timestamp;
return _computePriceInfo(currentTimeStamp).priceFrom;
}
/**
* @dev end price of the current timeframe
* when buying time, it can be only bought with this price
*/
function currentEndPrice() view public returns (uint256) {
uint256 currentTimeStamp = block.timestamp;
return _computePriceInfo(currentTimeStamp).priceTo;
}
/**
* @dev start timestamp of the current timeframe
*/
function currentStartTimeStamp() view public returns (uint256) {
uint256 currentTimeStamp = block.timestamp;
return _computePriceInfo(currentTimeStamp).timeStampFrom;
}
/**
* @dev end timestamp of the current timeframe
*/
function currentEndTimeStamp() view public returns (uint256) {
uint256 currentTimeStamp = block.timestamp;
return _computePriceInfo(currentTimeStamp).timeStampTo;
}
/**
* @dev full priceinfo object of the current timeframe
*/
function currentPriceInfo() view public returns (PriceInfo memory) {
uint256 currentTimeStamp = block.timestamp;
return _computePriceInfo(currentTimeStamp);
}
/**
* @dev price of a given historical time
*/
function historicalPrice(uint256 timeStamp) view public returns (uint256) {
return _computePriceInfo(timeStamp).computedPrice;
}
/**
* @dev full priceinfo object of a given historical time
*/
function historicalPriceInfo(uint256 timeStamp) view public returns (PriceInfo memory) {
return _computePriceInfo(timeStamp);
}
function _computePriceInfo(uint256 timeStamp) view internal returns (PriceInfo memory) {
if (timeStamp <= _minTimeStamp) {
uint256 minPrice = _timeStampToPrice[_minTimeStamp];
return PriceInfo(_minTimeStamp, _minTimeStamp, minPrice, minPrice, minPrice);
}
if (_maxTimeStamp <= timeStamp) {
uint256 maxPrice = _timeStampToPrice[_maxTimeStamp];
return PriceInfo(_maxTimeStamp, _maxTimeStamp, maxPrice, maxPrice, maxPrice);
}
uint256 secondInDay = SafeMath.mod(timeStamp, _seconds_in_day());
uint256 timeStampFrom = SafeMath.sub(timeStamp, secondInDay);
uint256 timeStampTo = SafeMath.add(timeStampFrom, _seconds_in_day());
uint256 priceFrom = _timeStampToPrice[timeStampFrom];
uint256 priceTo = _timeStampToPrice[timeStampTo];
if (secondInDay == 0) {
return PriceInfo(timeStampFrom, timeStampTo, priceFrom, priceTo, priceFrom);
}
if (priceTo <= priceFrom) {
return PriceInfo(timeStampFrom, timeStampTo, priceFrom, priceTo, priceTo);
}
uint256 priceRange = priceTo - priceFrom;
uint256 timeRange = timeStampTo - timeStampFrom;
uint256 timePassed = timeStamp - timeStampFrom;
uint256 price = SafeMath.add(SafeMath.div(SafeMath.mul(priceRange, timePassed), timeRange), priceFrom);
return PriceInfo(timeStampFrom, timeStampTo, priceFrom, priceTo, price);
}
/**
* @dev buy time coin with base currency end price
*/
function buyForBase(uint256 timeAmount) external returns (bool) {
uint256 baseAmount = SafeMath.div(timeAmount * currentEndPrice(), 1 ether);
IERC20(_baseCurrency).transferFrom(msg.sender, _liquidity, baseAmount);
_mint(msg.sender, timeAmount);
emit TimeBought(timeAmount, baseAmount, msg.sender);
return true;
}
/**
* @dev sell time coin with base currency current price
*/
function sellForBase(uint256 timeAmount) external returns (bool) {
require(maxTimeSellAmount() > timeAmount, "Time amount to sell should be lower than maxTimeSellAmount()");
uint256 baseAmount = SafeMath.div(timeAmount * currentPrice(), 1 ether);
IERC20(_baseCurrency).transferFrom(_liquidity, msg.sender, baseAmount);
_burn(msg.sender, timeAmount);
emit TimeSold(timeAmount, baseAmount, msg.sender);
return true;
}
/**
* @dev reimburse expense
*/
function reimburse() onlyOwner external returns (bool) {
require(_baseLiquidityAmount() > _expense, "Not enough base liquidity amount!");
IERC20(_baseCurrency).transferFrom(_liquidity, msg.sender, _expense);
emit Reimbursed(_expense);
_expense = 0;
return true;
}
function expenseAmount() view external returns (uint256) {
return _expense;
}
/**
* @dev run proof of lapse process using interest gained and amount of released coin (excluding owned by time itself)
*/
function proofOfLapse(uint256 capitalGain, uint256 releasedCoins, uint256 newTimeStamp, uint256 expense) onlyOwner external returns (bool) {
require(SafeMath.mod(newTimeStamp, _seconds_in_day()) == 0, "TimeStamp should be divisible by 86400!");
uint256 previousPrice = historicalPrice(SafeMath.sub(newTimeStamp, _seconds_in_day()));
uint256 newPrice = SafeMath.add(previousPrice, SafeMath.div(SafeMath.mul(SafeMath.sub(SafeMath.sub(capitalGain, expense), _expense), 1 ether), releasedCoins));
return proofOfLapse(newPrice, newTimeStamp, expense);
}
/**
* @dev run proof of lapse process using new end price
*/
function proofOfLapse(uint256 newPrice, uint256 newTimeStamp, uint256 expense) onlyOwner public returns (bool) {
require(SafeMath.mod(newTimeStamp, _seconds_in_day()) == 0, "TimeStamp should be divisible by 86400!");
_expense = SafeMath.add(_expense, expense);
_timeStampToPrice[newTimeStamp] = newPrice;
if (newTimeStamp < _minTimeStamp) {
_minTimeStamp = newTimeStamp;
}
if (_maxTimeStamp < newTimeStamp) {
_maxTimeStamp = newTimeStamp;
}
emit LapseProved(newPrice, newTimeStamp, expense);
return true;
}
}
|
start price of the current timeframe/
|
function currentStartPrice() view public returns (uint256) {
uint256 currentTimeStamp = block.timestamp;
return _computePriceInfo(currentTimeStamp).priceFrom;
}
| 6,065,416
|
// 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;
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: 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPosition Contract
/// @author Enzyme Council <[email protected]>
interface IExternalPosition {
function getDebtAssets() external returns (address[] memory, uint256[] memory);
function getManagedAssets() external returns (address[] memory, uint256[] memory);
function init(bytes memory) external;
function receiveCallFromVault(bytes memory) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionVault interface
/// @author Enzyme Council <[email protected]>
/// Provides an interface to get the externalPositionLib for a given type from the Vault
interface IExternalPositionVault {
function getExternalPositionLibForType(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFreelyTransferableSharesVault Interface
/// @author Enzyme Council <[email protected]>
/// @notice Provides the interface for determining whether a vault's shares
/// are guaranteed to be freely transferable.
/// @dev DO NOT EDIT CONTRACT
interface IFreelyTransferableSharesVault {
function sharesAreFreelyTransferable()
external
view
returns (bool sharesAreFreelyTransferable_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/external-positions/IExternalPosition.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback);
event BuyBackMaxProtocolFeeSharesFailed(
bytes indexed failureReturnData,
uint256 sharesAmount,
uint256 buybackValueInMln,
uint256 gav
);
event DeactivateFeeManagerFailed();
event GasRelayPaymasterSet(address gasRelayPaymaster);
event MigratedSharesDuePaid(uint256 sharesDue);
event PayProtocolFeeDuringDestructFailed();
event PreRedeemSharesHookFailed(
bytes indexed failureReturnData,
address indexed redeemer,
uint256 sharesAmount
);
event RedeemSharesInKindCalcGavFailed();
event SharesBought(
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
address indexed recipient,
uint256 sharesAmount,
address[] receivedAssets,
uint256[] receivedAssetAmounts
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant ONE_HUNDRED_PERCENT = 10000;
uint256 private constant SHARES_UNIT = 10**18;
address
private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa;
address private immutable DISPATCHER;
address private immutable EXTERNAL_POSITION_MANAGER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable MLN_TOKEN;
address private immutable POLICY_MANAGER;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable VALUE_INTERPRETER;
address private immutable WETH_TOKEN;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Attempts to buy back protocol fee shares immediately after collection
bool internal autoProtocolFeeSharesBuyback;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock after the last time shares were bought for an account
// that must expire before that account transfers or redeems their shares
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesBoughtTimestamp;
// The contract which manages paying gas relayers
address private gasRelayPaymaster;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer();
_;
}
modifier onlyGasRelayPaymaster() {
__assertIsGasRelayPaymaster();
_;
}
modifier onlyOwner() {
__assertIsOwner(__msgSender());
_;
}
modifier onlyOwnerNotRelayable() {
__assertIsOwner(msg.sender);
_;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
function __assertIsFundDeployer() private view {
require(msg.sender == getFundDeployer(), "Only FundDeployer callable");
}
function __assertIsGasRelayPaymaster() private view {
require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _vaultProxy, address _account)
private
view
{
uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account);
require(
lastSharesBoughtTimestamp == 0 ||
block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() ||
__hasPendingMigrationOrReconfiguration(_vaultProxy),
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _protocolFeeReserve,
address _fundDeployer,
address _valueInterpreter,
address _externalPositionManager,
address _feeManager,
address _integrationManager,
address _policyManager,
address _gasRelayPaymasterFactory,
address _mlnToken,
address _wethToken
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
DISPATCHER = _dispatcher;
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
MLN_TOKEN = _mlnToken;
POLICY_MANAGER = _policyManager;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
VALUE_INTERPRETER = _valueInterpreter;
WETH_TOKEN = _wethToken;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override locksReentrance allowsPermissionedVaultAction {
require(
_extension == getFeeManager() ||
_extension == getIntegrationManager() ||
_extension == getExternalPositionManager(),
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
/// @return returnData_ The data returned by the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyOwner returns (bytes memory returnData_) {
require(
IFundDeployer(getFundDeployer()).isAllowedVaultCall(
_contract,
_selector,
keccak256(_encodedArgs)
),
"vaultCallOnContract: Not allowed"
);
return
IVault(getVaultProxy()).callOnContract(
_contract,
abi.encodePacked(_selector, _encodedArgs)
);
}
/// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request
function __hasPendingMigrationOrReconfiguration(address _vaultProxy)
private
view
returns (bool hasPendingMigrationOrReconfiguration)
{
return
IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) ||
IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy);
}
//////////////////
// PROTOCOL FEE //
//////////////////
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
function buyBackProtocolFeeShares(uint256 _sharesAmount) external {
address vaultProxyCopy = vaultProxy;
require(
IVault(vaultProxyCopy).canManageAssets(__msgSender()),
"buyBackProtocolFeeShares: Unauthorized"
);
uint256 gav = calcGav();
IVault(vaultProxyCopy).buyBackProtocolFeeShares(
_sharesAmount,
__getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav),
gav
);
}
/// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected
/// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted
/// to be bought back immediately when collected
function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback)
external
onlyOwner
{
autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback;
emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback);
}
/// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback
function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private {
uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve());
uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav);
try
IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav)
{} catch (bytes memory reason) {
emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav);
}
}
/// @dev Helper to buyback the max available protocol fee shares
function __getBuybackValueInMln(
address _vaultProxy,
uint256 _sharesAmount,
uint256 _gav
) private returns (uint256 buybackValueInMln_) {
address denominationAssetCopy = getDenominationAsset();
uint256 grossShareValue = __calcGrossShareValue(
_gav,
ERC20(_vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div(
SHARES_UNIT
);
return
IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
buybackValueInDenominationAsset,
getMlnToken()
);
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData)
external
override
{
__assertPermissionedVaultAction(msg.sender, _action);
// Validate action as needed
if (_action == IVault.VaultAction.RemoveTrackedAsset) {
require(
abi.decode(_actionData, (address)) != getDenominationAsset(),
"permissionedVaultAction: Cannot untrack denomination asset"
);
}
IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData);
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction.
/// Uses this pattern rather than multiple `require` statements to save on contract size.
function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action)
private
view
{
bool validAction;
if (permissionedVaultActionAllowed) {
// Calls are roughly ordered by likely frequency
if (_caller == getIntegrationManager()) {
if (
_action == IVault.VaultAction.AddTrackedAsset ||
_action == IVault.VaultAction.RemoveTrackedAsset ||
_action == IVault.VaultAction.WithdrawAssetTo ||
_action == IVault.VaultAction.ApproveAssetSpender
) {
validAction = true;
}
} else if (_caller == getFeeManager()) {
if (
_action == IVault.VaultAction.MintShares ||
_action == IVault.VaultAction.BurnShares ||
_action == IVault.VaultAction.TransferShares
) {
validAction = true;
}
} else if (_caller == getExternalPositionManager()) {
if (
_action == IVault.VaultAction.CallOnExternalPosition ||
_action == IVault.VaultAction.AddExternalPosition ||
_action == IVault.VaultAction.RemoveExternalPosition
) {
validAction = true;
}
}
}
require(validAction, "__assertPermissionedVaultAction: Action not allowed");
}
///////////////
// LIFECYCLE //
///////////////
// Ordered by execution in the lifecycle
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(getDenominationAsset() == address(0), "init: Already initialized");
require(
IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Sets the VaultProxy
/// @param _vaultProxy The VaultProxy contract
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerProxy has been deployed.
function setVaultProxy(address _vaultProxy) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
}
/// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor`
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(bool _isMigration) external override onlyFundDeployer {
address vaultProxyCopy = getVaultProxy();
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy);
if (sharesDue > 0) {
IVault(vaultProxyCopy).transferShares(
vaultProxyCopy,
IVault(vaultProxyCopy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset());
// Activate extensions
IExtension(getFeeManager()).activateForFund(_isMigration);
IExtension(getPolicyManager()).activateForFund(_isMigration);
}
/// @notice Wind down and destroy a ComptrollerProxy that is active
/// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager
/// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee
/// @dev No need to assert anything beyond FundDeployer access.
/// Uses the try/catch pattern throughout out of an abundance of caution for the function's success.
/// All external calls must use limited forwarded gas to ensure that a migration to another release
/// does not get bricked by logic that consumes too much gas for the block limit.
function destructActivated(
uint256 _deactivateFeeManagerGasLimit,
uint256 _payProtocolFeeGasLimit
) external override onlyFundDeployer allowsPermissionedVaultAction {
// Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic
// will run in the next function call
try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch {
emit PayProtocolFeeDuringDestructFailed();
}
// Do not attempt to auto-buyback protocol fee shares in this case,
// as the call is gav-dependent and can consume too much gas
// Deactivate extensions only as-necessary
// Pays out shares outstanding for fees
try
IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}()
{} catch {
emit DeactivateFeeManagerFailed();
}
__selfDestruct();
}
/// @notice Destroy a ComptrollerProxy that has not been activated
function destructUnactivated() external override onlyFundDeployer {
__selfDestruct();
}
/// @dev Helper to self-destruct the contract.
/// There should never be ETH in the ComptrollerLib,
/// so no need to waste gas to get the fund owner
function __selfDestruct() private {
// Not necessary, but failsafe to protect the lib against selfdestruct
require(!isLib, "__selfDestruct: Only delegate callable");
selfdestruct(payable(address(this)));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @return gav_ The fund GAV
function calcGav() public override returns (uint256 gav_) {
address vaultProxyAddress = getVaultProxy();
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
address[] memory externalPositions = IVault(vaultProxyAddress)
.getActiveExternalPositions();
if (assets.length == 0 && externalPositions.length == 0) {
return 0;
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress);
}
gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
assets,
balances,
getDenominationAsset()
);
if (externalPositions.length > 0) {
for (uint256 i; i < externalPositions.length; i++) {
uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]);
gav_ = gav_.add(externalPositionValue);
}
}
return gav_;
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @return grossShareValue_ The amount of the denomination asset per share
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue() external override returns (uint256 grossShareValue_) {
uint256 gav = calcGav();
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(getVaultProxy()).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
return grossShareValue_;
}
// @dev Helper for calculating a external position value. Prevents from stack too deep
function __calcExternalPositionValue(address _externalPosition)
private
returns (uint256 value_)
{
(address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition(
_externalPosition
)
.getManagedAssets();
uint256 managedValue = IValueInterpreter(getValueInterpreter())
.calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset());
(address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition(
_externalPosition
)
.getDebtAssets();
uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
debtAssets,
debtAmounts,
getDenominationAsset()
);
if (managedValue > debtValue) {
value_ = managedValue.sub(debtValue);
}
return value_;
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares on behalf of another user
/// @param _buyer The account on behalf of whom to buy shares
/// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
/// @dev This function is freely callable if there is no sharesActionTimelock set, but it is
/// limited to a list of trusted callers otherwise, in order to prevent a griefing attack
/// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value.
function buySharesOnBehalf(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) external returns (uint256 sharesReceived_) {
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
require(
!hasSharesActionTimelock ||
IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender),
"buySharesOnBehalf: Unauthorized"
);
return
__buyShares(
_buyer,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @notice Buys shares
/// @param _investmentAmount The amount of the fund's denomination asset
/// with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity)
external
returns (uint256 sharesReceived_)
{
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
return
__buyShares(
canonicalSender,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @dev Helper for buy shares logic
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
bool _hasSharesActionTimelock,
address _canonicalSender
) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) {
// Enforcing a _minSharesQuantity also validates `_investmentAmount > 0`
// and guarantees the function cannot succeed while minting 0 shares
require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0");
address vaultProxyCopy = getVaultProxy();
require(
!_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy),
"__buyShares: Pending migration or reconfiguration"
);
uint256 gav = calcGav();
// Gives Extensions a chance to run logic prior to the minting of bought shares.
// Fees implementing this hook should be aware that
// it might be the case that _investmentAmount != actualInvestmentAmount,
// if the denomination asset charges a transfer fee, for example.
__preBuySharesHook(_buyer, _investmentAmount, gav);
// Pay the protocol fee after running other fees, but before minting new shares
IVault(vaultProxyCopy).payProtocolFee();
if (doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(vaultProxyCopy, gav);
}
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is necessary to
// do this delta balance calculation before calculating shares to mint.
uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount(
getDenominationAsset(),
_canonicalSender,
vaultProxyCopy,
_investmentAmount
);
// Calculate the amount of shares to issue with the investment amount
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer);
IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
if (_hasSharesActionTimelock) {
acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp;
}
emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions immediately prior to issuing shares
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _gav
) private {
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount),
_gav
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
/// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received
function __transferFromWithReceivedAmount(
address _asset,
address _sender,
address _recipient,
uint256 _transferAmount
) private returns (uint256 receivedAmount_) {
uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient);
ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount);
return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance);
}
// REDEEM SHARES
/// @notice Redeems a specified amount of the sender's shares for specified asset proportions
/// @param _recipient The account that will receive the specified assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _payoutAssets The assets to payout
/// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the
/// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego.
/// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption.
function redeemSharesForSpecificAssets(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages
) external locksReentrance returns (uint256[] memory payoutAmounts_) {
address canonicalSender = __msgSender();
require(
_payoutAssets.length == _payoutAssetPercentages.length,
"redeemSharesForSpecificAssets: Unequal arrays"
);
require(
_payoutAssets.isUniqueSet(),
"redeemSharesForSpecificAssets: Duplicate payout asset"
);
uint256 gav = calcGav();
IVault vaultProxyContract = IVault(getVaultProxy());
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
vaultProxyContract,
canonicalSender,
_sharesQuantity,
true,
gav
);
payoutAmounts_ = __payoutSpecifiedAssetPercentages(
vaultProxyContract,
_recipient,
_payoutAssets,
_payoutAssetPercentages,
gav.mul(sharesToRedeem).div(sharesSupply)
);
// Run post-redemption in order to have access to the payoutAmounts
__postRedeemSharesForSpecificAssetsHook(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_,
gav
);
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_
);
return payoutAmounts_;
}
/// @notice Redeems a specified amount of the sender's shares
/// for a proportionate slice of the vault's assets
/// @param _recipient The account that will receive the proportionate slice of assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the _recipient
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function redeemSharesInKind(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
address canonicalSender = __msgSender();
require(
_additionalAssets.isUniqueSet(),
"redeemSharesInKind: _additionalAssets contains duplicates"
);
require(
_assetsToSkip.isUniqueSet(),
"redeemSharesInKind: _assetsToSkip contains duplicates"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
IVault(vaultProxy).getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
// If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees,
// as we will require GAV later during the buyback.
uint256 gavOrZero;
if (doesAutoProtocolFeeSharesBuyback()) {
// Since GAV calculation can fail with a revering price or a no-longer-supported asset,
// we must try/catch GAV calculation to ensure that in-kind redemption can still succeed
try this.calcGav() returns (uint256 gav) {
gavOrZero = gav;
} catch {
emit RedeemSharesInKindCalcGavFailed();
}
}
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
IVault(vaultProxy),
canonicalSender,
_sharesQuantity,
false,
gavOrZero
);
// Calculate and transfer payout asset amounts due to _recipient
payoutAmounts_ = new uint256[](payoutAssets_.length);
for (uint256 i; i < payoutAssets_.length; i++) {
payoutAmounts_[i] = ERC20(payoutAssets_[i])
.balanceOf(vaultProxy)
.mul(sharesToRedeem)
.div(sharesSupply);
// Transfer payout asset to _recipient
if (payoutAmounts_[i] > 0) {
IVault(vaultProxy).withdrawAssetTo(
payoutAssets_[i],
_recipient,
payoutAmounts_[i]
);
}
}
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
payoutAssets_,
payoutAmounts_
);
return (payoutAssets_, payoutAmounts_);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets()
function __payoutSpecifiedAssetPercentages(
IVault vaultProxyContract,
address _recipient,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages,
uint256 _owedGav
) private returns (uint256[] memory payoutAmounts_) {
address denominationAssetCopy = getDenominationAsset();
uint256 percentagesTotal;
payoutAmounts_ = new uint256[](_payoutAssets.length);
for (uint256 i; i < _payoutAssets.length; i++) {
percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]);
// Used to explicitly specify less than 100% in total _payoutAssetPercentages
if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) {
continue;
}
payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
_owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT),
_payoutAssets[i]
);
// Guards against corner case of primitive-to-derivative asset conversion that floors to 0,
// or redeeming a very low shares amount and/or percentage where asset value owed is 0
require(
payoutAmounts_[i] > 0,
"__payoutSpecifiedAssetPercentages: Zero amount for asset"
);
vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]);
}
require(
percentagesTotal == ONE_HUNDRED_PERCENT,
"__payoutSpecifiedAssetPercentages: Percents must total 100%"
);
return payoutAmounts_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(
address _redeemer,
uint256 _sharesToRedeem,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private allowsPermissionedVaultAction {
try
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets),
_gavIfCalculated
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem);
}
}
/// @dev Helper to run policy validation after other logic for redeeming shares for specific assets.
/// Avoids stack-too-deep error.
function __postRedeemSharesForSpecificAssetsHook(
address _redeemer,
address _recipient,
uint256 _sharesToRedeemPostFees,
address[] memory _assets,
uint256[] memory _assetAmounts,
uint256 _gavPreRedeem
) private {
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets,
abi.encode(
_redeemer,
_recipient,
_sharesToRedeemPostFees,
_assets,
_assetAmounts,
_gavPreRedeem
)
);
}
/// @dev Helper to execute common pre-shares redemption logic
function __redeemSharesSetup(
IVault vaultProxyContract,
address _redeemer,
uint256 _sharesQuantityInput,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) {
__assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer);
ERC20 sharesContract = ERC20(address(vaultProxyContract));
uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = preFeesRedeemerSharesBalance;
} else {
sharesToRedeem_ = _sharesQuantityInput;
}
require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem");
__preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated);
// Update the redemption amount if fees were charged (or accrued) to the redeemer
uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = postFeesRedeemerSharesBalance;
} else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) {
sharesToRedeem_ = sharesToRedeem_.sub(
preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance)
);
}
// Pay the protocol fee after running other fees, but before burning shares
vaultProxyContract.payProtocolFee();
if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated);
}
// Destroy the shares after getting the shares supply
sharesSupply_ = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, sharesToRedeem_);
return (sharesToRedeem_, sharesSupply_);
}
// TRANSFER SHARES
/// @notice Runs logic prior to transferring shares that are not freely transferable
/// @param _sender The sender of the shares
/// @param _recipient The recipient of the shares
/// @param _amount The amount of shares
function preTransferSharesHook(
address _sender,
address _recipient,
uint256 _amount
) external override {
address vaultProxyCopy = getVaultProxy();
require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable");
__assertSharesActionNotTimelocked(vaultProxyCopy, _sender);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreTransferShares,
abi.encode(_sender, _recipient, _amount)
);
}
/// @notice Runs logic prior to transferring shares that are freely transferable
/// @param _sender The sender of the shares
/// @dev No need to validate caller, as policies are not run
function preTransferSharesHookFreelyTransferable(address _sender) external view override {
__assertSharesActionNotTimelocked(getVaultProxy(), _sender);
}
/////////////////
// GAS RELAYER //
/////////////////
/// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying
function deployGasRelayPaymaster() external onlyOwnerNotRelayable {
require(
getGasRelayPaymaster() == address(0),
"deployGasRelayPaymaster: Paymaster already deployed"
);
bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy());
address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy(
constructData
);
__setGasRelayPaymaster(paymaster);
__depositToGasRelayPaymaster(paymaster);
}
/// @notice Tops up the gas relay paymaster deposit
function depositToGasRelayPaymaster() external onlyOwner {
__depositToGasRelayPaymaster(getGasRelayPaymaster());
}
/// @notice Pull WETH from vault to gas relay paymaster
/// @param _amount Amount of the WETH to pull from the vault
function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster {
IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount);
}
/// @notice Sets the gasRelayPaymaster variable value
/// @param _nextGasRelayPaymaster The next gasRelayPaymaster value
function setGasRelayPaymaster(address _nextGasRelayPaymaster)
external
override
onlyFundDeployer
{
__setGasRelayPaymaster(_nextGasRelayPaymaster);
}
/// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance
/// and disabling gas relaying
function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable {
IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance();
IVault(vaultProxy).addTrackedAsset(getWethToken());
delete gasRelayPaymaster;
emit GasRelayPaymasterSet(address(0));
}
/// @dev Helper to deposit to the gas relay paymaster
function __depositToGasRelayPaymaster(address _paymaster) private {
IGasRelayPaymaster(_paymaster).deposit();
}
/// @dev Helper to set the next `gasRelayPaymaster` variable
function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private {
gasRelayPaymaster = _nextGasRelayPaymaster;
emit GasRelayPaymasterSet(_nextGasRelayPaymaster);
}
///////////////////
// STATE GETTERS //
///////////////////
// LIB IMMUTABLES
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() public view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable
/// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value
function getExternalPositionManager()
public
view
override
returns (address externalPositionManager_)
{
return EXTERNAL_POSITION_MANAGER;
}
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() public view override returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view override returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() public view override returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
/// @notice Gets the `MLN_TOKEN` variable
/// @return mlnToken_ The `MLN_TOKEN` variable value
function getMlnToken() public view returns (address mlnToken_) {
return MLN_TOKEN;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() public view override returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PROTOCOL_FEE_RESERVE` variable
/// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value
function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) {
return PROTOCOL_FEE_RESERVE;
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() public view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
// PROXY STORAGE
/// @notice Checks if collected protocol fee shares are automatically bought back
/// while buying or redeeming shares
/// @return doesAutoBuyback_ True if shares are automatically bought back
function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) {
return autoProtocolFeeSharesBuyback;
}
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() public view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the `gasRelayPaymaster` variable
/// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value
function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) {
return gasRelayPaymaster;
}
/// @notice Gets the timestamp of the last time shares were bought for a given account
/// @param _who The account for which to get the timestamp
/// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought
function getLastSharesBoughtTimestampForAccount(address _who)
public
view
returns (uint256 lastSharesBoughtTimestamp_)
{
return acctToLastSharesBoughtTimestamp[_who];
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() public view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../vault/IVault.sol";
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
function activate(bool) external;
function calcGav() external returns (uint256);
function calcGrossShareValue() external returns (uint256);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function destructActivated(uint256, uint256) external;
function destructUnactivated() external;
function getDenominationAsset() external view returns (address);
function getExternalPositionManager() external view returns (address);
function getFeeManager() external view returns (address);
function getFundDeployer() external view returns (address);
function getGasRelayPaymaster() external view returns (address);
function getIntegrationManager() external view returns (address);
function getPolicyManager() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(IVault.VaultAction, bytes calldata) external;
function preTransferSharesHook(
address,
address,
uint256
) external;
function preTransferSharesHookFreelyTransferable(address) external view;
function setGasRelayPaymaster(address) external;
function setVaultProxy(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol";
import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol";
import "../../../../persistent/vault/interfaces/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault {
enum VaultAction {
None,
// Shares management
BurnShares,
MintShares,
TransferShares,
// Asset management
AddTrackedAsset,
ApproveAssetSpender,
RemoveTrackedAsset,
WithdrawAssetTo,
// External position management
AddExternalPosition,
CallOnExternalPosition,
RemoveExternalPosition
}
function addTrackedAsset(address) external;
function burnShares(address, uint256) external;
function buyBackProtocolFeeShares(
uint256,
uint256,
uint256
) external;
function callOnContract(address, bytes calldata) external returns (bytes memory);
function canManageAssets(address) external view returns (bool);
function canRelayCalls(address) external view returns (bool);
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getActiveExternalPositions() external view returns (address[] memory);
function getTrackedAssets() external view returns (address[] memory);
function isActiveExternalPosition(address) external view returns (bool);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function payProtocolFee() external;
function receiveValidatedVaultAction(VaultAction, bytes calldata) external;
function setAccessorForFundReconfiguration(address) external;
function setSymbol(string calldata) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
// When updating PolicyHook, also update these functions in PolicyManager:
// 1. __getAllPolicyHooks()
// 2. __policyHookRestrictsCurrentInvestorActions()
enum PolicyHook {
PostBuyShares,
PostCallOnIntegration,
PreTransferShares,
RedeemSharesForSpecificAssets,
AddTrackedAssets,
RemoveTrackedAssets,
CreateExternalPosition,
PostCallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "./IGasRelayPaymaster.sol";
pragma solidity 0.6.12;
/// @title GasRelayRecipientMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin that enables receiving GSN-relayed calls
/// @dev IMPORTANT: Do not use storage var in this contract,
/// unless it is no longer inherited by the VaultLib
abstract contract GasRelayRecipientMixin {
address internal immutable GAS_RELAY_PAYMASTER_FACTORY;
constructor(address _gasRelayPaymasterFactory) internal {
GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory;
}
/// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed
function __msgSender() internal view returns (address payable canonicalSender_) {
if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) {
assembly {
canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20)))
}
return canonicalSender_;
}
return msg.sender;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable
/// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value
function getGasRelayPaymasterFactory()
public
view
returns (address gasRelayPaymasterFactory_)
{
return GAS_RELAY_PAYMASTER_FACTORY;
}
/// @notice Gets the trusted forwarder for GSN relaying
/// @return trustedForwarder_ The trusted forwarder
function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) {
return
IGasRelayPaymaster(
IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib()
)
.trustedForwarder();
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IGsnPaymaster.sol";
/// @title IGasRelayPaymaster Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymaster is IGsnPaymaster {
function deposit() external;
function withdrawBalance() external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGasRelayPaymasterDepositor Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymasterDepositor {
function pullWethForGasRelayer(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256);
function isSupportedAsset(address) external view returns (bool);
function isSupportedDerivativeAsset(address) external view returns (bool);
function isSupportedPrimitiveAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGsnForwarder interface
/// @author Enzyme Council <[email protected]>
interface IGsnForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
uint256 validUntil;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnTypes.sol";
/// @title IGsnPaymaster interface
/// @author Enzyme Council <[email protected]>
interface IGsnPaymaster {
struct GasAndDataLimits {
uint256 acceptanceBudget;
uint256 preRelayedCallGasLimit;
uint256 postRelayedCallGasLimit;
uint256 calldataSizeLimit;
}
function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits);
function getHubAddr() external view returns (address);
function getRelayHubDeposit() external view returns (uint256);
function preRelayedCall(
IGsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
) external returns (bytes memory context, bool rejectOnRecipientRevert);
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
IGsnTypes.RelayData calldata relayData
) external;
function trustedForwarder() external view returns (address);
function versionPaymaster() external view returns (string memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnForwarder.sol";
/// @title IGsnTypes Interface
/// @author Enzyme Council <[email protected]>
interface IGsnTypes {
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
address forwarder;
bytes paymasterData;
uint256 clientId;
}
struct RelayRequest {
IGsnForwarder.ForwardRequest request;
RelayData relayData;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund/comptroller/ComptrollerLib.sol";
import "../interfaces/IWETH.sol";
import "../utils/AssetHelpers.sol";
/// @title DepositWrapper Contract
/// @author Enzyme Council <[email protected]>
/// @notice Logic related to wrapping deposit actions
contract DepositWrapper is AssetHelpers {
address private immutable WETH_TOKEN;
constructor(address _weth) public {
WETH_TOKEN = _weth;
}
/// @dev Needed in case WETH not fully used during exchangeAndBuyShares,
/// to unwrap into ETH and refund
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Exchanges ETH into a fund's denomination asset and then buys shares
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH
/// @param _exchange The exchange on which to execute the swap to the denomination asset
/// @param _exchangeApproveTarget The address that should be given an allowance of WETH
/// for the given _exchange
/// @param _exchangeData The data with which to call the exchange to execute the swap
/// to the denomination asset
/// @param _minInvestmentAmount The minimum amount of the denomination asset
/// to receive in the trade for investment (not necessary for WETH)
/// @return sharesReceived_ The actual amount of shares received
/// @dev Use a reasonable _minInvestmentAmount always, in case the exchange
/// does not perform as expected (low incoming asset amount, blend of assets, etc).
/// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData,
/// and _minInvestmentAmount will be ignored.
function exchangeEthAndBuyShares(
address _comptrollerProxy,
address _denominationAsset,
uint256 _minSharesQuantity,
address _exchange,
address _exchangeApproveTarget,
bytes calldata _exchangeData,
uint256 _minInvestmentAmount
) external payable returns (uint256 sharesReceived_) {
// Wrap ETH into WETH
IWETH(payable(getWethToken())).deposit{value: msg.value}();
// If denominationAsset is WETH, can just buy shares directly
if (_denominationAsset == getWethToken()) {
__approveAssetMaxAsNeeded(getWethToken(), _comptrollerProxy, msg.value);
return __buyShares(_comptrollerProxy, msg.sender, msg.value, _minSharesQuantity);
}
// Exchange ETH to the fund's denomination asset
__approveAssetMaxAsNeeded(getWethToken(), _exchangeApproveTarget, msg.value);
(bool success, bytes memory returnData) = _exchange.call(_exchangeData);
require(success, string(returnData));
// Confirm the amount received in the exchange is above the min acceptable amount
uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this));
require(
investmentAmount >= _minInvestmentAmount,
"exchangeAndBuyShares: _minInvestmentAmount not met"
);
// Give the ComptrollerProxy max allowance for its denomination asset as necessary
__approveAssetMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount);
// Buy fund shares
sharesReceived_ = __buyShares(
_comptrollerProxy,
msg.sender,
investmentAmount,
_minSharesQuantity
);
// Unwrap and refund any remaining WETH not used in the exchange
uint256 remainingWeth = ERC20(getWethToken()).balanceOf(address(this));
if (remainingWeth > 0) {
IWETH(payable(getWethToken())).withdraw(remainingWeth);
(success, returnData) = msg.sender.call{value: remainingWeth}("");
require(success, string(returnData));
}
return sharesReceived_;
}
// PRIVATE FUNCTIONS
/// @dev Helper for buying shares
function __buyShares(
address _comptrollerProxy,
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) private returns (uint256 sharesReceived_) {
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
sharesReceived_ = comptrollerProxyContract.buySharesOnBehalf(
_buyer,
_investmentAmount,
_minSharesQuantity
);
return sharesReceived_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
uint256 allowance = ERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
ERC20(_asset).safeApprove(_target, 0);
}
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
}
|
Initializes a fund with its core config _denominationAsset The asset in which the fund's value should be denominated _sharesActionTimelock The minimum number of seconds between any two "shares actions" (buying or selling shares) by the same user Pseudo-constructor per proxy. No need to assert access because this is called atomically on deployment, and once it's called, it cannot be called again.
|
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(getDenominationAsset() == address(0), "init: Already initialized");
require(
IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
| 122,342
|
/*
Copyright 2019 Wanchain Foundation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
pragma experimental ABIEncoderV2;
import "./RapidityTxLib.sol";
import "./CrossTypes.sol";
import "../../interfaces/ITokenManager.sol";
// import "../../interfaces/IRC20Protocol.sol";
import "../../interfaces/ISmgFeeProxy.sol";
library RapidityLib {
using SafeMath for uint;
using RapidityTxLib for RapidityTxLib.Data;
/**
*
* STRUCTURES
*
*/
/// @notice struct of Rapidity storeman mint lock parameters
struct RapidityUserMintParams {
bytes32 smgID; /// ID of storeman group which user has selected
uint tokenPairID; /// token pair id on cross chain
uint value; /// exchange token value
bytes userShadowAccount; /// account of shadow chain, used to receive token
}
/// @notice struct of Rapidity storeman mint lock parameters
struct RapiditySmgMintParams {
bytes32 uniqueID; /// Rapidity random number
bytes32 smgID; /// ID of storeman group which user has selected
uint tokenPairID; /// token pair id on cross chain
uint value; /// exchange token value
address userShadowAccount; /// account of shadow chain, used to receive token
}
/// @notice struct of Rapidity user burn lock parameters
struct RapidityUserBurnParams {
bytes32 smgID; /// ID of storeman group which user has selected
uint tokenPairID; /// token pair id on cross chain
uint value; /// exchange token value
bytes userOrigAccount; /// account of token original chain, used to receive token
}
/// @notice struct of Rapidity user burn lock parameters
struct RapiditySmgBurnParams {
bytes32 uniqueID; /// Rapidity random number
bytes32 smgID; /// ID of storeman group which user has selected
uint tokenPairID; /// token pair id on cross chain
uint value; /// exchange token value
address userOrigAccount; /// account of token original chain, used to receive token
}
/**
*
* EVENTS
*
**/
/// @notice event of exchange WRC-20 token with original chain token request
/// @notice event invoked by storeman group
/// @param smgID ID of storemanGroup
/// @param tokenPairID token pair ID of cross chain token
/// @param value Rapidity value
/// @param userAccount account of shadow chain, used to receive token
event UserFastMintLogger(bytes32 indexed smgID, uint indexed tokenPairID, uint value, uint fee, bytes userAccount);
/// @notice event of exchange WRC-20 token with original chain token request
/// @notice event invoked by storeman group
/// @param uniqueID unique random number
/// @param smgID ID of storemanGroup
/// @param tokenPairID token pair ID of cross chain token
/// @param value Rapidity value
/// @param userAccount account of original chain, used to receive token
event SmgFastMintLogger(bytes32 indexed uniqueID, bytes32 indexed smgID, uint indexed tokenPairID, uint value, address userAccount);
/// @notice event of exchange WRC-20 token with original chain token request
/// @notice event invoked by storeman group
/// @param smgID ID of storemanGroup
/// @param tokenPairID token pair ID of cross chain token
/// @param value Rapidity value
/// @param userAccount account of shadow chain, used to receive token
event UserFastBurnLogger(bytes32 indexed smgID, uint indexed tokenPairID, uint value, uint fee, bytes userAccount);
/// @notice event of exchange WRC-20 token with original chain token request
/// @notice event invoked by storeman group
/// @param uniqueID unique random number
/// @param smgID ID of storemanGroup
/// @param tokenPairID token pair ID of cross chain token
/// @param value Rapidity value
/// @param userAccount account of original chain, used to receive token
event SmgFastBurnLogger(bytes32 indexed uniqueID, bytes32 indexed smgID, uint indexed tokenPairID, uint value, address userAccount);
/**
*
* MANIPULATIONS
*
*/
/// @notice mintBridge, user lock token on token original chain
/// @notice event invoked by user mint lock
/// @param storageData Cross storage data
/// @param params parameters for user mint lock token on token original chain
function userFastMint(CrossTypes.Data storage storageData, RapidityUserMintParams memory params)
public
{
uint origChainID;
uint shadowChainID;
bytes memory tokenOrigAccount;
(origChainID,tokenOrigAccount,shadowChainID) = storageData.tokenManager.getTokenPairInfoSlim(params.tokenPairID);
require(origChainID != 0, "Token does not exist");
uint lockFee = storageData.mapLockFee[origChainID][shadowChainID];
storageData.quota.userFastMint(params.tokenPairID, params.smgID, params.value);
if (lockFee > 0) {
if (storageData.smgFeeProxy == address(0)) {
storageData.mapStoremanFee[params.smgID] = storageData.mapStoremanFee[params.smgID].add(lockFee);
} else {
ISmgFeeProxy(storageData.smgFeeProxy).smgTransfer.value(lockFee)(params.smgID);
}
}
address tokenScAddr = CrossTypes.bytesToAddress(tokenOrigAccount);
uint left;
if (tokenScAddr == address(0)) {
left = (msg.value).sub(params.value).sub(lockFee);
} else {
left = (msg.value).sub(lockFee);
// require(IRC20Protocol(tokenScAddr).transferFrom(msg.sender, this, params.value), "Lock token failed");
require(CrossTypes.transferFrom(tokenScAddr, msg.sender, this, params.value), "Lock token failed");
}
if (left != 0) {
(msg.sender).transfer(left);
}
emit UserFastMintLogger(params.smgID, params.tokenPairID, params.value, lockFee, params.userShadowAccount);
}
/// @notice mintBridge, storeman mint lock token on token shadow chain
/// @notice event invoked by user mint lock
/// @param storageData Cross storage data
/// @param params parameters for storeman mint lock token on token shadow chain
function smgFastMint(CrossTypes.Data storage storageData, RapiditySmgMintParams memory params)
public
{
storageData.rapidityTxData.addRapidityTx(params.uniqueID);
storageData.quota.smgFastMint(params.tokenPairID, params.smgID, params.value);
storageData.tokenManager.mintToken(params.tokenPairID, params.userShadowAccount, params.value);
emit SmgFastMintLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.userShadowAccount);
}
/// @notice burnBridge, user lock token on token original chain
/// @notice event invoked by user burn lock
/// @param storageData Cross storage data
/// @param params parameters for user burn lock token on token original chain
function userFastBurn(CrossTypes.Data storage storageData, RapidityUserBurnParams memory params)
public
{
uint origChainID;
uint shadowChainID;
bytes memory tokenShadowAccount;
(origChainID,,shadowChainID,tokenShadowAccount) = storageData.tokenManager.getTokenPairInfo(params.tokenPairID);
require(origChainID != 0, "Token does not exist");
uint lockFee = storageData.mapLockFee[origChainID][shadowChainID];
storageData.quota.userFastBurn(params.tokenPairID, params.smgID, params.value);
address tokenScAddr = CrossTypes.bytesToAddress(tokenShadowAccount);
// require(IRC20Protocol(tokenScAddr).transferFrom(msg.sender, this, params.value), "Lock token failed");
require(CrossTypes.transferFrom(tokenScAddr, msg.sender, this, params.value), "Lock token failed");
storageData.tokenManager.burnToken(params.tokenPairID, params.value);
if (lockFee > 0) {
if (storageData.smgFeeProxy == address(0)) {
storageData.mapStoremanFee[params.smgID] = storageData.mapStoremanFee[params.smgID].add(lockFee);
} else {
ISmgFeeProxy(storageData.smgFeeProxy).smgTransfer.value(lockFee)(params.smgID);
}
}
uint left = (msg.value).sub(lockFee);
if (left != 0) {
(msg.sender).transfer(left);
}
emit UserFastBurnLogger(params.smgID, params.tokenPairID, params.value, lockFee, params.userOrigAccount);
}
/// @notice burnBridge, storeman burn lock token on token shadow chain
/// @notice event invoked by user burn lock
/// @param storageData Cross storage data
/// @param params parameters for storeman burn lock token on token shadow chain
function smgFastBurn(CrossTypes.Data storage storageData, RapiditySmgBurnParams memory params)
public
{
uint origChainID;
bytes memory tokenOrigAccount;
(origChainID,tokenOrigAccount,) = storageData.tokenManager.getTokenPairInfoSlim(params.tokenPairID);
require(origChainID != 0, "Token does not exist");
storageData.rapidityTxData.addRapidityTx(params.uniqueID);
storageData.quota.smgFastBurn(params.tokenPairID, params.smgID, params.value);
address tokenScAddr = CrossTypes.bytesToAddress(tokenOrigAccount);
if (tokenScAddr == address(0)) {
(params.userOrigAccount).transfer(params.value);
} else {
// require(IRC20Protocol(tokenScAddr).transfer(params.userOrigAccount, params.value), "Transfer token failed");
require(CrossTypes.transfer(tokenScAddr, params.userOrigAccount, params.value), "Transfer token failed");
}
emit SmgFastBurnLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.userOrigAccount);
}
}
|
burnBridge, user lock token on token original chain event invoked by user burn lock storageData Cross storage data params parameters for user burn lock token on token original chain require(IRC20Protocol(tokenScAddr).transferFrom(msg.sender, this, params.value), "Lock token failed");
|
function userFastBurn(CrossTypes.Data storage storageData, RapidityUserBurnParams memory params)
public
{
uint origChainID;
uint shadowChainID;
bytes memory tokenShadowAccount;
(origChainID,,shadowChainID,tokenShadowAccount) = storageData.tokenManager.getTokenPairInfo(params.tokenPairID);
require(origChainID != 0, "Token does not exist");
uint lockFee = storageData.mapLockFee[origChainID][shadowChainID];
storageData.quota.userFastBurn(params.tokenPairID, params.smgID, params.value);
address tokenScAddr = CrossTypes.bytesToAddress(tokenShadowAccount);
require(CrossTypes.transferFrom(tokenScAddr, msg.sender, this, params.value), "Lock token failed");
storageData.tokenManager.burnToken(params.tokenPairID, params.value);
if (lockFee > 0) {
if (storageData.smgFeeProxy == address(0)) {
storageData.mapStoremanFee[params.smgID] = storageData.mapStoremanFee[params.smgID].add(lockFee);
ISmgFeeProxy(storageData.smgFeeProxy).smgTransfer.value(lockFee)(params.smgID);
}
}
uint left = (msg.value).sub(lockFee);
if (left != 0) {
(msg.sender).transfer(left);
}
emit UserFastBurnLogger(params.smgID, params.tokenPairID, params.value, lockFee, params.userOrigAccount);
}
| 2,485,997
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract Douya is ERC20, AccessControl {
// 将字符串转成byte32
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
event Bought(uint256 amount);
event Sold(uint256 amount);
constructor() ERC20("Douya", "DOU") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
_mint(msg.sender, 100000000 * 10**decimals());
}
function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
function burn(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
_burn(to, amount);
}
function transferRole(address sender, address receiver, uint256 amount) public onlyRole(MINTER_ROLE) {
_transfer(sender, receiver, amount);
}
function setRole(address addr) public onlyRole(DEFAULT_ADMIN_ROLE) {
_grantRole(MINTER_ROLE, addr);
}
// 兑换(合约收取eth后铸造代币给用户)
function exchange() payable public {
uint256 amountTobuy = msg.value;
require(amountTobuy > 0, "You need to send some Ether");
_mint(msg.sender, amountTobuy);
emit Bought(amountTobuy);
}
// 合约拥有者提取eth
function withdrawOwner(uint256 amount) public onlyRole(DEFAULT_ADMIN_ROLE) {
payable(msg.sender).transfer(amount);
emit Sold(amount);
}
uint256 public rate = 1000000;
uint256 public charge=0;
function withdraw(uint256 amount) public {
_burn(msg.sender, amount);
payable(msg.sender).transfer(amount*rate/1000000-amount*rate/1000000*charge/100);
emit Sold(amount);
}
function transferOther(address receiver, uint256 amount) public {
transferFrom(msg.sender, receiver, amount);
}
function setRate(uint256 _rate) public onlyRole(DEFAULT_ADMIN_ROLE) {
rate = _rate;
}
function setCharge(uint256 _charge) public onlyRole(DEFAULT_ADMIN_ROLE) {
charge = _charge;
}
}
|
兑换(合约收取eth后铸造代币给用户)
|
function exchange() payable public {
uint256 amountTobuy = msg.value;
require(amountTobuy > 0, "You need to send some Ether");
_mint(msg.sender, amountTobuy);
emit Bought(amountTobuy);
}
| 7,327,527
|
./full_match/1/0x33A8d92B2BE84755441C2b6e39715c4b8938242c/sources/contracts/libraries/Fixed.sol
|
Raise this uint192 to a nonnegative integer power. Requires that x_ <= FIX_ONE Gas cost is O(lg(y)), precision is +- 1e-18. return x_ y as-ints: x_ y / 1e18(y-1) <- technically correct for y = 0. :D
|
function powu(uint192 x_, uint48 y) internal pure returns (uint192) {
require(x_ <= FIX_ONE);
if (y == 1) return x_;
if (x_ == FIX_ONE || y == 0) return FIX_ONE;
while (true) {
if (y & 1 == 1) result = (result * x + FIX_SCALE_SQ / 2) / FIX_SCALE_SQ;
if (y <= 1) break;
y = (y >> 1);
x = (x * x + FIX_SCALE_SQ / 2) / FIX_SCALE_SQ;
}
return _safeWrap(result / FIX_SCALE);
}
| 3,864,924
|
/**
*Submitted for verification at Etherscan.io on 2021-02-17
*/
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.1;
// bigshortbets.com collection contract
contract BigShortBets {
//minimum to collect
uint256 constant public minETH = 1000 ether;
//maximum pay-in w/o AML/KYC
uint256 constant public noAmlMax = 9 ether;
//list of balances
mapping(address => uint256) private balances;
//you-know-who
address constant public owner = 0x23E7f318C383a5e9af702EE11e342632006A23Cc;
//flags
bool collectEnd = false;
bool failed = false;
// now + 6 months
uint256 constant public failsafe = 1629155926;
//pay in - just send ETH to contract address
receive() external payable {
require(!collectEnd, "Collect ended");
uint256 amount = msg.value + balances[msg.sender];
//if you want pay in more than 9 ETH - contact staff to KYC/AML
//and pay directly to owner address
//not KYC/AML-ed payments will be treated as a donation
require(amount <= noAmlMax, "Need KYC/AML");
balances[msg.sender] = amount;
//fail in case that somethig* happend and collection not closed in 6 months
if (block.timestamp > failsafe) {
collectEnd = true;
failed = true;
}
//*ie you-know-who dies
}
//check balance paid in - will be needed for token distribution
function blanceOf(address user) external view returns (uint256) {
return balances[user];
}
//total collected by this contract and KYC/AML-ed collect to owner address
function totalCollected() public view returns (uint256) {
return address(this).balance + address(owner).balance;
}
//withdraw ETH if collection failed
function withdraw() external {
require(failed, "Collect not failed");
uint256 amount = balances[msg.sender];
balances[msg.sender] = 0;
send(msg.sender, amount);
}
//end collecting - take ETH or fail and allow to withdraw
function end() external {
require(!collectEnd, "Collect ended");
collectEnd = true;
require(msg.sender == owner, "Only for owner");
if (totalCollected() < minETH) {
failed = true;
} else {
send(owner, address(this).balance);
}
}
//internal "gas safe" ETH send function
function send(address user, uint256 amount) private {
bool success = false;
(success, ) = address(user).call{value: amount}("");
require(success, "Send failed");
}
}
//rav3n_pl was here
|
end collecting - take ETH or fail and allow to withdraw
|
function end() external {
require(!collectEnd, "Collect ended");
collectEnd = true;
require(msg.sender == owner, "Only for owner");
if (totalCollected() < minETH) {
failed = true;
send(owner, address(this).balance);
}
}
| 7,939,977
|
pragma solidity ^0.4.24;
contract Ownable {
/**
* @dev set `owner` of the contract to the sender
*/
address 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));
owner = newOwner;
}
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
}
/**
* @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 view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @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);
}
/**
* @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));
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] += _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 view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @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] += _value;
allowed[_from][msg.sender] = allowed[_from][msg.sender].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 view returns (uint256) {
return allowed[_owner][_spender];
}
}
/**
* @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 StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event Burn(address indexed burner, uint value);
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) {
totalSupply += _amount;
balances[_to] += _amount;
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to burn tokens
* @param _addr The address that will have _amount of tokens burned.
* @param _amount The amount of tokens to burn.
*/
function burn(address _addr, uint _amount) onlyOwner public {
require(_amount > 0 && balances[_addr] >= _amount && totalSupply >= _amount);
balances[_addr] -= _amount;
totalSupply -= _amount;
Burn(_addr, _amount);
Transfer(_addr, address(0), _amount);
}
/**
* @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;
}
}
contract WealthBuilderToken is MintableToken {
string public name = "Wealth Builder Token";
string public symbol = "WBT";
uint32 public decimals = 18;
/**
* how many {tokens*10^(-18)} get per 1wei
*/
uint public rate = 10**7;
/**
* multiplicator for rate
*/
uint public mrate = 10**7;
function setRate(uint _rate) onlyOwner public {
rate = _rate;
}
}
contract Data is Ownable {
// node => its parent
mapping (address => address) private parent;
// node => its status
mapping (address => uint8) public statuses;
// node => sum of all his child deposits in USD cents
mapping (address => uint) public referralDeposits;
// client => balance in wei*10^(-6) available for withdrawal
mapping(address => uint256) private balances;
// investor => balance in wei*10^(-6) available for withdrawal
mapping(address => uint256) private investorBalances;
function parentOf(address _addr) public constant returns (address) {
return parent[_addr];
}
function balanceOf(address _addr) public constant returns (uint256) {
return balances[_addr] / 1000000;
}
function investorBalanceOf(address _addr) public constant returns (uint256) {
return investorBalances[_addr] / 1000000;
}
/**
* @dev The Data constructor to set up the first depositer
*/
constructor() public {
// DirectorOfRegion - 7
statuses[msg.sender] = 7;
}
function addBalance(address _addr, uint256 amount) onlyOwner public {
balances[_addr] += amount;
}
function subtrBalance(address _addr, uint256 amount) onlyOwner public {
require(balances[_addr] >= amount);
balances[_addr] -= amount;
}
function addInvestorBalance(address _addr, uint256 amount) onlyOwner public {
investorBalances[_addr] += amount;
}
function subtrInvestorBalance(address _addr, uint256 amount) onlyOwner public {
require(investorBalances[_addr] >= amount);
investorBalances[_addr] -= amount;
}
function addReferralDeposit(address _addr, uint256 amount) onlyOwner public {
referralDeposits[_addr] += amount;
}
function subtrReferralDeposit(address _addr, uint256 amount) onlyOwner public {
referralDeposits[_addr] -= amount;
}
function setStatus(address _addr, uint8 _status) onlyOwner public {
statuses[_addr] = _status;
}
function setParent(address _addr, address _parent) onlyOwner public {
parent[_addr] = _parent;
}
}
contract Declaration {
// threshold in USD => status
mapping (uint => uint8) statusThreshold;
// status => (depositsNumber => percentage)
mapping (uint8 => mapping (uint8 => uint)) feeDistribution;
// status thresholds in USD
uint[8] thresholds = [
0, 5000, 35000, 150000, 500000, 2500000, 5000000, 10000000
];
uint[5] referralFees = [50, 30, 20, 10, 5];
uint[5] serviceFees = [25, 20, 15, 10, 5];
/**
* @dev The Declaration constructor to define some constants
*/
constructor() public {
setFeeDistributionsAndStatusThresholds();
}
/**
* @dev Set up fee distribution & status thresholds
*/
function setFeeDistributionsAndStatusThresholds() private {
// Agent - 0
setFeeDistributionAndStatusThreshold(0, [12, 8, 5, 2, 1], thresholds[0]);
// SilverAgent - 1
setFeeDistributionAndStatusThreshold(1, [16, 10, 6, 3, 2], thresholds[1]);
// Manager - 2
setFeeDistributionAndStatusThreshold(2, [20, 12, 8, 4, 2], thresholds[2]);
// ManagerOfGroup - 3
setFeeDistributionAndStatusThreshold(3, [25, 15, 10, 5, 3], thresholds[3]);
// ManagerOfRegion - 4
setFeeDistributionAndStatusThreshold(4, [30, 18, 12, 6, 3], thresholds[4]);
// Director - 5
setFeeDistributionAndStatusThreshold(5, [35, 21, 14, 7, 4], thresholds[5]);
// DirectorOfGroup - 6
setFeeDistributionAndStatusThreshold(6, [40, 24, 16, 8, 4], thresholds[6]);
// DirectorOfRegion - 7
setFeeDistributionAndStatusThreshold(7, [50, 30, 20, 10, 5], thresholds[7]);
}
/**
* @dev Set up specific fee and status threshold
* @param _st The status to set up for
* @param _percentages Array of pecentages, which should go to member
* @param _threshold The minimum amount of sum of children deposits to get
* the status _st
*/
function setFeeDistributionAndStatusThreshold(
uint8 _st,
uint8[5] _percentages,
uint _threshold
)
private
{
statusThreshold[_threshold] = _st;
for (uint8 i = 0; i < _percentages.length; i++) {
feeDistribution[_st][i] = _percentages[i];
}
}
}
contract Investors is Ownable {
// investors
/*
"0x418155b19d7350f5a843b826474aa2f7623e99a6","0xbeb7a29a008d69069fd10154966870ff1dda44a0","0xa9cb1b8ba1c8facb92172e459389f80d304595a3","0xf3f2bf9be0ccc8f27a15ccf18d820c0722e8996a","0xa0f36ac9f68c1a4594ef5cec29dc9b1cc67f822c","0xc319278cca404e3a479b088922e4117feb4cec9d","0xe633c933529d6fd7c6147d2b0dc51bfbe3304e56","0x5bd2c1f2f06b16e427a4ec3a6beef6263fd506da","0x52c4f101d0367c3f9933d0c14ea389e74ad00352","0xf7a0d2149f324a0b607ebf23df671acc4e9da6d2","0x0418df662bb2994262bb720d477e558a59e19490","0xf0de6520e0726ba3d84611f84867aa9987391402","0x1e895274a9570f150f11ae0ed86dd42a53208b81","0x95a247bef71f6b234e9805d1493366a302a498e4","0x9daaeaf355f69f7176a0145df6d1769d7f14553b","0x029136181d87c6f0979431255424b5fad78e8491","0x7e1f5669d9e1c593a495c5cec384ca32ad4a09fc","0x46c7e04fdaaa1a9298e63ca2fd47b0004cb236bf","0x5933fa485863da06584057494f0f6660d3c1477c","0x4290231804dd59947aff9fcef925287e44906e7b","0x2feaf2101b3f9943a81567badb56e3780946ce3f","0x5b602c34ba643913908f69a4cd5846a07ed3915b","0x146308896955030ce3bcc6030bab142afddaa1e6","0x9fc61b75451fabf5b5b78e03bacaf8bb592541fc","0x87f7636f7856466b6c6bce999574a784387e2b78","0x024db1f560327ab5174f1a737caf446b5644c709","0x715c248e621cbdb6f091bf653bb4bc331d2f9b1e","0xfe92a23b497140ba055a91ade89d91f95f8e5153","0xc3426e0e0634725a628a7a21bfd49274e1f24733","0xb12a79b9dba8bbb9ed5e329466a9c2703da38dbd","0x44d8336749ebf584a4bcd636cefe83e6e0b33e7d","0x89c91460c3bdc164250e5a27351c743c070c226a","0xe0798a1b847f450b5d4819043d27a380a4715af8","0xeac5e75252d902cb7f8473e45fff9ceb391c536b","0xea53e88876a6da2579d837a559b31b08d6750681","0x5df22fac00c45ef7b5c285c54a006798f42bbc6e","0x09899f20064b5e67d02f6a97ef412564977ee193","0xc572f18d0a4a65f6e612e6de484dbc15b8839df3","0x397b9719e720c0d33fe7dcc004958e56636cbf82","0x577de83b60299df60cc7fce7ac78d3a5d880aa95","0x9a716298949b16c4610b40ba1d19e96d3286c35c","0x60ef523f3845e38a20b63344a4e9ec689773ead6","0xe34252e3efe0514c5fb76c9fb39ff31f554d6659","0xbabfbdf4f422d36c00e448cc562ce0f5dbe47d64","0x2608cca4aff4cc3008ac6bd22e0664348ecee088","0x0dd1d3102f89d4ee7c260048cbe01933f17debde","0xdbb28fafc4ecd7736247aca7dc8e20782ca86a7a","0x6201fc413bb9292527956a70e7575436d5135ce1","0xa836f4cfb8fd3e5bccc9c7a6a678f2a5928b7c79","0x85dce799fd059d86c420eb4e3c1bd89e323b7b12","0xdef2086c6bbdc8b0f6e130907f05345b44af8cc3","0xc1004695ce07ef5efb1d218672e5cfcb659c5900","0x227a5b4bb4cffc2b907d9f586dd100989efeee56","0xd372b3d43ba8ea406f64dbc68f70ec812e54fbc8","0xdf6c417cdb27bc0c877a0e121a2c58ad884e85c6","0x090f4d53b5d7ebcb8e348709cdb708d80cd199f0","0x2499b302b6f5e57f54c1c7a326813e3dffddcd1a","0x3114024a034443e972707522d911fc709f62dd3e","0x30b864f49cef510b1173a5bfc31e77b0b59daf9e","0x9a9680f5ddee6cef96ef36ab506f4b6d3198c35e","0x08018337b9b138b631cd325168c3d5014df6e18b","0x2ac345a4ec1615c3a236099ebbed4911673bbfa5","0x2b9fd54828cd443b7c411419b058b44bd02fdc49","0x208713a63460d44e5a83ae8e8f7333496a05065e","0xe4052eb7ba8891ee7ccd7551faaa5f4c421904e7","0x74bc9db1ac813db06f771bcff359e9237b01c906","0x033dd047a042ea873ca27af36b64ca566a006e97","0xb4721808a3f2830a1708967302443b53f5943429","0xc91fbb815c2f4944d8c6846be6ac0e30f5a037df","0x19ef947c276436ac11a8be15567909a37d824e73","0x079eefd69c5a4c5e4c9ee3fa08c2a2964da3e11a","0x11fb64be296590f948d56daab6c2d102c9842b08","0x06ec97feaeb0f4b9a75f9671d6b62bfadaf18ddd","0xaeda3cff45032695fb2cf4f584cda822bd5d8b7e","0x9f377085d3da85107cd68bd08bdd9a1b862d44e0","0xb46b8d1c313c52fd422fe189dde1b4d0800a5e0f","0x99039fa34510c7321f4d19ea337c80cc14cc885d","0x378aba0f47c7790ed0e5ca61749b0025d1208a5d","0x4395e1db93d4e2f4583a4f87494eb0aea057b8fd","0xa4035578750564e48abfb5ba1d6eec1da1bf366f","0xb611b39eb6c16dae3754e514ddd5f02fcadd765f","0x67d41491ddc004e899a3faf109f526cd717fe6d8","0x58e2c10865f9a1668e800c91b6a3d7b3416fb26c","0x04e34355ced9d532c9bc01d5e569f31b6d46cd50","0xf80358cabdc9b9b79570b6f073a861cf5567bb57","0xbdacb079fc17a00d945f01f4f9bd5d03cfcd5b6c","0x387a723060bc42a7796c76197d2d3b41b4c43d19","0xa04cc8fc56c34ab8104f63c11bf211de4bb7b0aa","0x3bf8b5ede7501519d41792715215735d8f40af10","0x6c3a13bac5cf61b1927562a927e89ca6b5d034d6","0x9899aecef15de43eec04859be649ac4c50330886","0xa4d25bac971ca08b47a908a070b6362102206c12"
"0xf88d963dc3f58fe6e71879543e57734e8152f70d","0x7b30a000f7ae56ee6206cbd9fb20c934b4bbb5d1","0xb2f0e5330e90559a738eda0df156635e18a145fd","0x5b2c07b6cce506f2293f1b32dc33d9928b8c9ada","0x5a967c0e38cb3bfad90df288ce238699cc47b5e3","0x0e686d6f3c897cae3984b80b5f6a7c785c708718","0xa8ea0b6bc70502644c0644fb4c0810540a1fa261","0xc70e278819ef5aec6b3ededc21e2981557e14443","0x477b5ae32ffcd34eb25f0c52866d4f602982dc6f","0x3e72a45fbc6a0858b506a0c7bedff79af75ae37c","0x1430e272a50703ef46d8ed5aa01e1ced71245341","0xc87d0bb90a6105a66fd5105c6746218d381b8207","0x0ed7f98b6177d0c15e27704f2bae4d068b8594d5","0x09a627b57879eb625cd8b7c59ffa363222553c23","0x0fdbc41046590ef7ee2a73b9808fd5bd7e189ac4","0x6a4b68af67a3b4a98fe1a59210dd3d775e567729","0x442a3daf774329fee3e904e86ddec1191f4be3ce","0x9efa8fe7fa51c8b36ab902046f879b035520f556","0x510e8e58b8ce4acaa6866e59dfc0fa339ea358e5","0x374831251283aa63aee6506ac6580479aaf3c22b","0xf758c498d020c0b92f2116d09d7ef6509c2c71bd","0xd83e8281ffcfb0ff96236e99ba66aabb8dcc7920","0x3670c3a5e65b757db8c82b12dd92057ac19d41fa","0xfd28eb7e3e5e3406ce6b82045d487c2be294cd38","0x2d23cd492096b903e4595ccdac74e49692a6ea8e","0x94d3a0a19ed5448052c549fd1f69f54c5f1fd8c5","0x8e5354ac59cee09d252e379a3534053306022ebe","0xa66f3700dda0147c56c2970202768c956c644ffd","0xf11d32baef6221f36916c58844cd8e9813c0af47","0x384a9bc1de23b36c2a23b963e57c8cd85b0d592c","0xbd00dfbaaa1abaa7948c7b2a6bed6e644293cc1c","0xa99a28afcbd4ab09a2ef2c0932becd0368225ee6","0xe554084d77bc6e510eed7276cb6033865375b669","0xe7582fa53531915a2fef5a81b98969d0091d8d44","0x5f15db1d209fa6fd3c667fb086d3d89e3793511f","0x7e9ff5348d57d3427e24b7e104ad5acf039edaf2","0xb4fb1a01483454d75a0cdfa983b99236c4c91111","0x4a7cc5eebfe019efab06c1fa9ae8453dc63ba84e","0xb6fc08d5043b51ac05cdbd88afaab0e4422762d0","0xb18365f4f1e95287a5f85c8a67cebee9e6164c31","0xaf575cfb94d65eaeaace749868282d0e26e4608a","0x3d07e5ff3a2d29ee17584dff60cc99bb4cd79c3d","0x08f0afc93fbc8188150f4bcab004e259cd4785aa","0x65ac3ed81f101e5651c72c4cc2d74650378b5b0c","0x58aef4fc6b54cb53683a6481655021109b8d4dce","0x6aa43e24604577574a0632524a1f4c21d70a61e2","0xbee55aa5ad9953294ecac83a6b62f10c8155444b","0x99dc885ac6ec9873e2409d5a31e7f525c1897e09","0x53a0622034680d64bd0f139df5e989d70b194a4d","0xa6ba4966f1fdd0e8560516e53490b25cf0c4fbd1","0xbd1b95ee4621ecda41961da61277e17e52f37dbf","0xf6481b881eea526ae36cbe11d58d641f96f04a77","0xd158d53d75eac0dda9d2dedf3418d071a2fd44ee","0xb22697e3f33544da7782c8197d07704e1906a3bf","0xa3237e67df409dca45930c1f5f671251adc202be","0x72b26f2dded753a01f391322b00f9a85a77c7fda","0x203fbf3a77bdf35f7aca220b363272896db91d57","0xb1be2f4d72eb87dfcf7ed93c8ec16e4040e52560","0xc60d8a0313ede22194ebe6285471f72f9bcdcda0","0x9888e7423ea48413a4c90a10c76ca5f90d065e1f","0x0be856768ad0ec5b45464ce5202e2c337224cebf","0x3b54ea00a74b116510c4f73a3fc19a62991aaf64","0xe72aa06ffe7058f73622f219af164369c03e3a41","0x7e71fada017d9af455f38db4957d527f51fe1bc5","0x78430e58934220f37ca6b9dbe622f076ad0eb3f5","0x0c765e201bb43d49ab5b44d40d3cf1d219424821","0x4739d251b40028761bbd8034a21919d926f23b45","0x00a7c7bc71022032f6ef3f699b212c9450875740","0x0d4f50b0d43d34a163b8dd7c33fbcc92a19cfa59","0x9284fbc0cc35d9b835de2b00b6b7093075527f6b","0x3564e101b32fe5f3c99e8da823ac003373c26d33","0xf5a358f228dc964fa7c703cb6ad9f6002ce77b17","0x8297a09b5dac9e60896c787f0995ac06441ab14f","0xed8c9b4fd60a6e4ae66c38f5819cffb360af5dd5","0x23009de4ec4a666ba719656d844e42e264e14c6b","0x63227f4492c6bbd9e1015f2c864a31eef1465cd3","0xf3e0ec409386ea202b15d97bb8dd2d131917e3b1","0x981154fafb3a5aeee43d984ee255e5121ce79790","0x49a4598cdf112b5848c11c465d39989fcb5cb6c1","0x575ca03f00f9e5566d85dc095165998953ab0753","0x09d87f2979c4ac6c9d4077d1f5d94cb9aadf43ca","0x0b4575867757b3982379f4d05c92fd2d019247a0","0x8c666d40e2ac961885d675e58e3115b859dac6c1","0x34a3401ebe8431d44efee9948c4b641142407aa8","0x1683512dbcce189ea6042862a2ba4abd4886623b","0x72d45f733336f6f03ef20c1ad4f51ff6b7f90186","0x569fe010fe2d40037c029537eef78aa9b0e018f9","0x061def9fab3aee4161711d4c040d138a273893b5","0xe77e2ae67e1152425c75ff56291d03d92f5d3cad","0x93ebdeb0b0c967f5cc1a10f481569e1871b7d7cd","0x6d7910f900fc3e3f2e2b6d5d8aad43bc6a232685","0xb16e28be300f579a81f2b80fdd5a95cf168bf3a4"
"0xd69835daeee01601ea991efe9fd0309c64c07d42","0x30b45ed69250a160ee91dadab2986d21626d7f4b","0xd28075489da5f9ef51bcc61668c114296a8e8603","0xb63c5cb479034bacc04266536e32aeeb9f958059","0x5f81fe78b5c238afd97a32c572aa04d87b730147","0xb98c8d7d64ef60cc76410f31c19570da0c4d9f12","0x031eb1c3a9909ea26d07f194abe5ad7f6945a482","0x83691573a4fdb5ff2cdbe2df155da09810a3c2bc","0x6722a482e1f3b797e69f98a3324b6660b9c6baa5","0xbda61db5824240280ed000a57ed5e6f70d552dd6","0x58605742105060e5c3070b88b0f51eca7f022d06","0xb4754815ccfc9c98a80f71a0a2c97471188bd556","0x50503144f253e6f05103b643c082ebf215436d95","0xd0dbef9f712ee0ca05fe48b6a40f5b774a109feb"
*/
address[] public investors;
// investor address => percentage * 10^(-2)
/*
3026,1500,510,462,453,302,250,250,226,220,150,129,100,100,60,50,50,50,50,50,50,50,50,50,50,40,40,30,27,26,25,25,25,25,25,25,25,25,23,20,19,15,15,15,15,15,14,14,13,13,13,13,12,12,11,11,11,11,11,11,10,10,10,10,10,10,10,10,12,9,9,8,8,8,8,7,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,6
6,125,50,5,8,50,23,3,115,14,10,50,5,5
*/
mapping (address => uint) public investorPercentages;
/**
* @dev Add investors
*/
function addInvestors(address[] _investors, uint[] _investorPercentages) onlyOwner public {
for (uint i = 0; i < _investors.length; i++) {
investors.push(_investors[i]);
investorPercentages[_investors[i]] = _investorPercentages[i];
}
}
/**
* @dev Get investors count
* @return uint count
*/
function getInvestorsCount() public constant returns (uint) {
return investors.length;
}
/**
* @dev Get investors' fee depending on the current year
* @return uint8 The fee percentage, which investors get
*/
function getInvestorsFee() public constant returns (uint8) {
//01/01/2020
if (now >= 1577836800) {
return 1;
}
//01/01/2019
if (now >= 1546300800) {
return 5;
}
return 10;
}
}
contract Referral is Declaration, Ownable {
using SafeMath for uint;
// reference to token contract
WealthBuilderToken private token;
// reference to data contract
Data private data;
// reference to investors contract
Investors private investors;
// investors balance to be distributed in wei*10^(2)
uint public investorsBalance;
/**
* how many USD cents get per ETH
*/
uint public ethUsdRate;
/**
* @dev The Referral constructor to set up the first depositer,
* reference to system token, data & investors and set ethUsdRate
*/
constructor(uint _ethUsdRate, address _token, address _data, address _investors, uint _investorsBalance) public {
ethUsdRate = _ethUsdRate;
// instantiate token & data contracts
token = WealthBuilderToken(_token);
data = Data(_data);
investors = Investors(_investors);
investorsBalance = _investorsBalance;
}
/**
* @dev Callback function
*/
function() payable public {
}
function invest(address client, uint8 depositsCount) payable public {
uint amount = msg.value;
// if less then 5 deposits
if (depositsCount < 5) {
uint serviceFee;
uint investorsFee = 0;
if (depositsCount == 0) {
uint8 investorsFeePercentage = investors.getInvestorsFee();
serviceFee = amount * (serviceFees[depositsCount].sub(investorsFeePercentage));
investorsFee = amount * investorsFeePercentage;
investorsBalance += investorsFee;
} else {
serviceFee = amount * serviceFees[depositsCount];
}
uint referralFee = amount * referralFees[depositsCount];
// distribute deposit fee among users above on the branch & update users' statuses
distribute(data.parentOf(client), 0, depositsCount, amount);
// update balance & number of deposits of user
uint active = (amount * 100)
.sub(referralFee)
.sub(serviceFee)
.sub(investorsFee);
token.mint(client, active / 100 * token.rate() / token.mrate());
// update owner`s balance
data.addBalance(owner, serviceFee * 10000);
} else {
token.mint(client, amount * token.rate() / token.mrate());
}
}
/**
* @dev Recursively distribute deposit fee between parents
* @param _node Parent address
* @param _prevPercentage The percentage for previous parent
* @param _depositsCount Count of depositer deposits
* @param _amount The amount of deposit
*/
function distribute(
address _node,
uint _prevPercentage,
uint8 _depositsCount,
uint _amount
)
private
{
address node = _node;
uint prevPercentage = _prevPercentage;
// distribute deposit fee among users above on the branch & update users' statuses
while(node != address(0)) {
uint8 status = data.statuses(node);
// count fee percentage of current node
uint nodePercentage = feeDistribution[status][_depositsCount];
uint percentage = nodePercentage.sub(prevPercentage);
data.addBalance(node, _amount * percentage * 10000);
//update refferals sum amount
data.addReferralDeposit(node, _amount * ethUsdRate / 10**18);
//update status
updateStatus(node, status);
node = data.parentOf(node);
prevPercentage = nodePercentage;
}
}
/**
* @dev Update node status if children sum amount is enough
* @param _node Node address
* @param _status Node current status
*/
function updateStatus(address _node, uint8 _status) private {
uint refDep = data.referralDeposits(_node);
for (uint i = thresholds.length - 1; i > _status; i--) {
uint threshold = thresholds[i] * 100;
if (refDep >= threshold) {
data.setStatus(_node, statusThreshold[threshold]);
break;
}
}
}
/**
* @dev Distribute fee between investors
*/
function distributeInvestorsFee(uint start, uint end) onlyOwner public {
for (uint i = start; i < end; i++) {
address investor = investors.investors(i);
uint investorPercentage = investors.investorPercentages(investor);
data.addInvestorBalance(investor, investorsBalance * investorPercentage);
}
if (end == investors.getInvestorsCount()) {
investorsBalance = 0;
}
}
/**
* @dev Set token exchange rate
* @param _rate wbt/eth rate
*/
function setRate(uint _rate) onlyOwner public {
token.setRate(_rate);
}
/**
* @dev Set ETH exchange rate
* @param _ethUsdRate eth/usd rate
*/
function setEthUsdRate(uint _ethUsdRate) onlyOwner public {
ethUsdRate = _ethUsdRate;
}
/**
* @dev Add new child
* @param _inviter parent
* @param _invitee child
*/
function invite(
address _inviter,
address _invitee
)
public onlyOwner
{
data.setParent(_invitee, _inviter);
// Agent - 0
data.setStatus(_invitee, 0);
}
/**
* @dev Set _status for _addr
* @param _addr address
* @param _status ref. status
*/
function setStatus(address _addr, uint8 _status) public onlyOwner {
data.setStatus(_addr, _status);
}
/**
* @dev Set investors contract address
* @param _addr address
*/
function setInvestors(address _addr) public onlyOwner {
investors = Investors(_addr);
}
/**
* @dev Withdraw _amount for _addr
* @param _addr withdrawal address
* @param _amount withdrawal amount
*/
function withdraw(address _addr, uint256 _amount, bool investor) public onlyOwner {
uint amount = investor ? data.investorBalanceOf(_addr)
: data.balanceOf(_addr);
require(amount >= _amount && address(this).balance >= _amount);
if (investor) {
data.subtrInvestorBalance(_addr, _amount * 1000000);
} else {
data.subtrBalance(_addr, _amount * 1000000);
}
_addr.transfer(_amount);
}
/**
* @dev Withdraw contract balance to _addr
* @param _addr withdrawal address
*/
function withdrawOwner(address _addr, uint256 _amount) public onlyOwner {
require(address(this).balance >= _amount);
_addr.transfer(_amount);
}
/**
* @dev Withdraw corresponding amount of ETH to _addr and burn _value tokens
* @param _addr withdrawal address
* @param _amount amount of tokens to sell
*/
function withdrawToken(address _addr, uint256 _amount) onlyOwner public {
token.burn(_addr, _amount);
uint256 etherValue = _amount * token.mrate() / token.rate();
_addr.transfer(etherValue);
}
/**
* @dev Transfer ownership of token contract to _addr
* @param _addr address
*/
function transferTokenOwnership(address _addr) onlyOwner public {
token.transferOwnership(_addr);
}
/**
* @dev Transfer ownership of data contract to _addr
* @param _addr address
*/
function transferDataOwnership(address _addr) onlyOwner public {
data.transferOwnership(_addr);
}
}
|
Withdraw _amount for _addr _addr withdrawal address _amount withdrawal amount/
|
function withdraw(address _addr, uint256 _amount, bool investor) public onlyOwner {
uint amount = investor ? data.investorBalanceOf(_addr)
: data.balanceOf(_addr);
require(amount >= _amount && address(this).balance >= _amount);
if (investor) {
data.subtrInvestorBalance(_addr, _amount * 1000000);
data.subtrBalance(_addr, _amount * 1000000);
}
_addr.transfer(_amount);
}
| 13,806,575
|
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
// Interface for our erc20 token
interface IToken {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner)
external
view
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
external
view
returns (uint256 remaining);
function transfer(address to, uint256 tokens)
external
returns (bool success);
function approve(address spender, uint256 tokens)
external
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
contract CudlFinance is
Initializable,
ERC721HolderUpgradeable,
OwnableUpgradeable
{
address public mooncats;
address public PONDERWARE;
address public MUSE_DAO;
address public MUSE_DEVS;
uint256 public gas; // if gas higher then this you can't kill
uint256 public lastGas; //here we record last gas paid, to keep track of chain gas. If gas is high, no pets can die.
IToken public token;
struct Pet {
address nft;
uint256 id;
}
mapping(address => bool) public supportedNfts;
mapping(uint256 => Pet) public petDetails;
// mining tokens
mapping(uint256 => uint256) public lastTimeMined;
// Pet properties
mapping(uint256 => uint256) public timeUntilStarving;
mapping(uint256 => uint256) public petScore;
mapping(uint256 => bool) public petDead;
mapping(uint256 => uint256) public timePetBorn;
// items/benefits for the PET could be anything in the future.
mapping(uint256 => uint256) public itemPrice;
mapping(uint256 => uint256) public itemPoints;
mapping(uint256 => string) public itemName;
mapping(uint256 => uint256) public itemTimeExtension;
mapping(uint256 => mapping(address => address)) public careTaker;
mapping(address => mapping(uint256 => bool)) public isNftInTheGame; //keeps track if nft already played
mapping(address => mapping(uint256 => uint256)) public nftToId; //keeps track if nft already played
uint256 public feesEarned;
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _tokenIds;
CountersUpgradeable.Counter private _itemIds;
event Mined(uint256 nftId, uint256 reward, address recipient);
event BuyAccessory(
uint256 nftId,
uint256 itemId,
uint256 amount,
uint256 itemTimeExtension,
address buyer
);
event Fatalize(uint256 opponentId, uint256 nftId, address killer);
event NewPlayer(
address nftAddress,
uint256 nftId,
uint256 playerId,
address owner
);
event Bonk(
uint256 attacker,
uint256 victim,
uint256 winner,
uint256 reward
);
// Rewards algorithm
uint256 public la;
uint256 public lb;
uint256 public ra;
uint256 public rb;
address public lastBonker;
constructor() {}
//
// function initialize(address _token) public initializer {
// __Ownable_init();
// token = IToken(_token);
// la = 2;
// lb = 2;
// ra = 6;
// rb = 7;
// gas = 80000000000;
// mooncats = 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69;
// PONDERWARE = 0xD342a4F0397B4268e6adce89b9B88C746AFA85Ee;
// MUSE_DAO = 0x6fBa46974b2b1bEfefA034e236A32e1f10C5A148;
// MUSE_DEVS = 0x4B5922ABf25858d012d12bb1184e5d3d0B6D6BE4;
// supportedNfts[mooncats] = true;
// }
modifier isAllowed(uint256 _id) {
Pet memory _pet = petDetails[_id];
address ownerOf = IERC721Upgradeable(_pet.nft).ownerOf(_pet.id);
require(
ownerOf == msg.sender || careTaker[_id][ownerOf] == msg.sender,
"!owner"
);
_;
}
// GAME ACTIONS
//can mine once every 24 hours per token.
function claimMiningRewards(uint256 nftId) public isAllowed(nftId) {
lastGas = tx.gasprice;
require(isPetSafe(nftId), "Your pet is starving, you can't mine");
require(
block.timestamp >= lastTimeMined[nftId] + 1 days ||
lastTimeMined[nftId] == 0,
"Current timestamp is over the limit to claim the tokens"
);
//reset last start mined so can't remine and cheat
lastTimeMined[nftId] = block.timestamp;
uint256 _reward = getRewards(nftId);
// 10% fees are for dev/dao/projects
token.mint(msg.sender, _reward);
emit Mined(nftId, _reward, msg.sender);
}
// Buy accesory to the VNFT
function buyAccesory(uint256 nftId, uint256 itemId) public {
require(!petDead[nftId], "ded pet");
uint256 amount = itemPrice[itemId];
require(amount > 0, "item does not exist");
// recalculate time until starving
timeUntilStarving[nftId] = block.timestamp + itemTimeExtension[itemId];
petScore[nftId] += itemPoints[itemId];
token.burnFrom(msg.sender, amount);
feesEarned += amount / 10;
emit BuyAccessory(
nftId,
itemId,
amount,
itemTimeExtension[itemId],
msg.sender
);
}
function feedMultiple(uint256[] calldata ids, uint256[] calldata itemIds)
external
{
for (uint256 i = 0; i < ids.length; i++) {
buyAccesory(ids[i], itemIds[i]);
}
}
function claimMultiple(uint256[] calldata ids) external {
for (uint256 i = 0; i < ids.length; i++) {
claimMiningRewards(ids[i]);
}
}
function bonk(uint256 _victim, uint256 _attacker)
public
isAllowed(_attacker)
{
require(isPetSafe(_victim), "Victim pet is starving, you can't mine");
require(isPetSafe(_attacker), "Your pet is starving, you can't mine");
require(lastBonker != msg.sender, "Can't bonk again");
require(
lastTimeMined[_victim] + 1 minutes >= block.timestamp,
"Can't bonk"
);
lastBonker = msg.sender;
// only bonking allowed when gas price is cheap?
require(tx.gasprice <= gas, "!gas high");
Pet memory victimPet = petDetails[_victim];
address victimOwner = IERC721Upgradeable(victimPet.nft).ownerOf(
victimPet.id
);
require(msg.sender != victimOwner, "forbidden");
uint256 reward = ((level(_attacker) + level(_victim)) * 10) / 100;
uint256 chanceOfAttack = randomNumber(_victim * _attacker, 100);
if (chanceOfAttack <= 80) {
//the attacker win 80% of time
token.mint(msg.sender, reward * 10**18);
} else {
// the defender win 19%
token.mint(victimOwner, reward * 10**18);
}
emit Bonk(
_attacker,
_victim,
chanceOfAttack <= 80 ? _attacker : _victim,
reward
);
}
//TOOD DECIDE FATALITY
function fatality(uint256 _deadId, uint256 _tokenId) external {
require(
!isPetSafe(_deadId) &&
tx.gasprice <= gas && //inspired by NFT GAS by 0Xmons
petDead[_deadId] == false,
"The PET has to be starved or gas below ${gas} to claim his points"
);
petScore[_tokenId] =
petScore[_tokenId] +
(((petScore[_deadId] * (20)) / (100)));
petScore[_deadId] = 0;
petDead[_deadId] = true;
emit Fatalize(_deadId, _tokenId, msg.sender);
}
function getCareTaker(uint256 _tokenId, address _owner)
public
view
returns (address)
{
return (careTaker[_tokenId][_owner]);
}
function setCareTaker(
uint256 _tokenId,
address _careTaker,
bool clearCareTaker
) external isAllowed(_tokenId) {
if (clearCareTaker) {
delete careTaker[_tokenId][msg.sender];
} else {
careTaker[_tokenId][msg.sender] = _careTaker;
}
}
// requires approval
function giveLife(address nft, uint256 _id) external {
require(IERC721Upgradeable(nft).ownerOf(_id) == msg.sender, "!OWNER");
require(
!isNftInTheGame[nft][_id],
"this nft was already registered can't again"
);
require(supportedNfts[nft], "!forbidden");
uint256 newId = _tokenIds.current();
// set the pet struct
petDetails[newId] = Pet(nft, _id);
nftToId[nft][_id] = newId;
isNftInTheGame[nft][_id] = true;
timeUntilStarving[newId] = block.timestamp + 3 days; //start with 3 days of life.
timePetBorn[newId] = block.timestamp;
emit NewPlayer(nft, _id, newId, msg.sender);
_tokenIds.increment();
}
// GETTERS
// check that pet didn't starve
function isPetSafe(uint256 _nftId) public view returns (bool) {
uint256 _timeUntilStarving = timeUntilStarving[_nftId];
if (
(_timeUntilStarving != 0 &&
_timeUntilStarving >= block.timestamp) || lastGas >= gas
) {
return true;
} else {
return false;
}
}
// GETTERS
function getPetInfo(uint256 _nftId)
public
view
returns (
uint256 _pet,
bool _isStarving,
uint256 _score,
uint256 _level,
uint256 _expectedReward,
uint256 _timeUntilStarving,
uint256 _lastTimeMined,
uint256 _timepetBorn,
address _owner,
address _token,
uint256 _tokenId,
bool _isAlive
)
{
Pet memory thisPet = petDetails[_nftId];
_pet = _nftId;
_isStarving = !this.isPetSafe(_nftId);
_score = petScore[_nftId];
_level = level(_nftId);
_expectedReward = getRewards(_nftId);
_timeUntilStarving = timeUntilStarving[_nftId];
_lastTimeMined = lastTimeMined[_nftId];
_timepetBorn = timePetBorn[_nftId];
_owner = IERC721Upgradeable(thisPet.nft).ownerOf(thisPet.id);
_token = petDetails[_nftId].nft;
_tokenId = petDetails[_nftId].id;
_isAlive = !petDead[_nftId];
}
// get the level the pet is on to calculate the token reward
function getRewards(uint256 tokenId) public view returns (uint256) {
// This is the formula to get token rewards R(level)=(level)*6/7+6
uint256 _level = level(tokenId);
if (_level == 1) {
return 6 ether;
}
_level = (_level * 1 ether * ra) / rb;
return (_level + 5 ether);
}
// get the level the pet is on to calculate points
function level(uint256 tokenId) public view returns (uint256) {
// This is the formula L(x) = 2 * sqrt(x * 2)
uint256 _score = petScore[tokenId] / 100;
if (_score == 0) {
return 1;
}
uint256 _level = sqrtu(_score * la);
return (_level * lb);
}
// ADMIN
function editCurves(
uint256 _la,
uint256 _lb,
uint256 _ra,
uint256 _rb
) external onlyOwner {
la = _la;
lb = _lb;
ra = _ra;
rb = _rb;
}
// edit specific item in case token goes up in value and the price for items gets to expensive for normal users.
function editItem(
uint256 _id,
uint256 _price,
uint256 _points,
string calldata _name,
uint256 _timeExtension
) external onlyOwner {
itemPrice[_id] = _price;
itemPoints[_id] = _points;
itemName[_id] = _name;
itemTimeExtension[_id] = _timeExtension;
}
// to support more projects
function setSupported(address _nft, bool isSupported) public onlyOwner {
supportedNfts[_nft] = isSupported;
}
function setGas(uint256 _gas) public onlyOwner {
gas = _gas;
}
// add items/accessories
function createItem(
string calldata name,
uint256 price,
uint256 points,
uint256 timeExtension
) external onlyOwner {
_itemIds.increment();
uint256 newItemId = _itemIds.current();
itemName[newItemId] = name;
itemPrice[newItemId] = price;
itemPoints[newItemId] = points;
itemTimeExtension[newItemId] = timeExtension;
}
function changeEarners(address _newAddress) public {
require(
msg.sender == MUSE_DEVS || msg.sender == PONDERWARE,
"!forbidden"
);
if (msg.sender == MUSE_DEVS) {
MUSE_DEVS = _newAddress;
} else if (msg.sender == PONDERWARE) {
PONDERWARE = _newAddress;
}
}
// anyone can call this
function claimEarnings() public {
token.mint(address(this), feesEarned);
feesEarned = 0;
uint256 balance = token.balanceOf(address(this));
token.transfer(PONDERWARE, balance / 3);
token.transfer(MUSE_DAO, balance / 3);
token.transfer(MUSE_DEVS, balance / 3);
}
function randomNumber(uint256 seed, uint256 max)
public
view
returns (uint256 _randomNumber)
{
uint256 n = 0;
unchecked {
for (uint256 i = 0; i < 5; i++) {
n += uint256(
keccak256(
abi.encodePacked(blockhash(block.number - i - 1), seed)
)
);
}
}
return (n) % max;
}
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.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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 CountersUpgradeable {
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @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
pragma solidity ^0.8.0;
import "../IERC721ReceiverUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable {
function __ERC721Holder_init() internal initializer {
__ERC721Holder_init_unchained();
}
function __ERC721Holder_init_unchained() internal initializer {
}
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
uint256[50] private __gap;
}
// 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 "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// 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 IERC165Upgradeable {
/**
* @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;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @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);
}
|
to support more projects
|
function setSupported(address _nft, bool isSupported) public onlyOwner {
supportedNfts[_nft] = isSupported;
}
| 1,138,290
|
/*
Copyright 2018 Binod Nirvan @ Accept (http://accept.io)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
import "openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol";
import "./CustomPausable.sol";
import "./TransferState.sol";
import "./BulkTransfer.sol";
import "./Reclaimable.sol";
///@title Fulcrum Token Base Contract
///@author Binod Nirvan
///@notice The FULC is our native settlements token used across our marketplace,
///and will enable many important functions within the Accept global marketplace including:
///A medium of exchange (settlements) for Accept.io buyers and sellers A consumptive use (utility) token
///for marketplace users to access premium features in the Accept.io DApp An incentive for users to help
///improve the Accept Marketplace and contribute to the long-term development of Accept.io
contract TokenBase is StandardToken, TransferState, BulkTransfer, Reclaimable, BurnableToken {
//solhint-disable
uint8 public constant decimals = 18;
string public constant name = "Fulcrum Token";
string public constant symbol = "FULC";
//solhint-enable
uint256 internal constant MILLION = 1000000 * 1 ether;
uint256 public constant MAX_SUPPLY = 200 * MILLION;
uint256 public constant INITIAL_SUPPLY = 100 * MILLION;
event Mint(address indexed to, uint256 amount);
constructor() public {
mintTokens(msg.sender, INITIAL_SUPPLY);
}
///@notice Transfers the specified value of FULC tokens to the destination address.
//Transfers can only happen when the transfer state is enabled.
//Transfer state can only be enabled after the end of the crowdsale.
///@param _to The destination wallet address to transfer funds to.
///@param _value The amount of tokens to send to the destination address.
function transfer(address _to, uint256 _value) public canTransfer(msg.sender) returns(bool) {
require(_to != address(0), "Invalid address.");
return super.transfer(_to, _value);
}
///@notice Transfers tokens from a specified wallet address.
///@dev This function is overridden to leverage transfer state feature.
///@param _from The address to transfer funds from.
///@param _to The address to transfer funds to.
///@param _value The amount of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value) public canTransfer(_from) returns(bool) {
require(_to != address(0), "Invalid address.");
return super.transferFrom(_from, _to, _value);
}
///@notice Approves a wallet address to spend on behalf of the sender.
///@dev This function is overridden to leverage transfer state feature.
///@param _spender The address which is approved to spend on behalf of the sender.
///@param _value The amount of tokens approve to spend.
function approve(address _spender, uint256 _value) public canTransfer(msg.sender) returns(bool) {
require(_spender != address(0), "Invalid address.");
return super.approve(_spender, _value);
}
///@notice Increases the approval of the spender.
///@dev This function is overridden to leverage transfer state feature.
///@param _spender The address which is approved to spend on behalf of the sender.
///@param _addedValue The added amount of tokens approved to spend.
function increaseApproval(address _spender, uint256 _addedValue) public canTransfer(msg.sender) returns(bool) {
require(_spender != address(0), "Invalid address.");
return super.increaseApproval(_spender, _addedValue);
}
///@notice Decreases the approval of the spender.
///@dev This function is overridden to leverage transfer state feature.
///@param _spender The address of the spender to decrease the allocation from.
///@param _subtractedValue The amount of tokens to subtract from the approved allocation.
function decreaseApproval(address _spender, uint256 _subtractedValue) public canTransfer(msg.sender) returns(bool) {
require(_spender != address(0), "Invalid address.");
return super.decreaseApproval(_spender, _subtractedValue);
}
///@notice Burns the coins held by the sender.
///@param _value The amount of coins to burn.
///@dev This function is overridden to leverage Pausable feature.
function burn(uint256 _value) public whenNotPaused {
super.burn(_value);
}
///@notice Mints the supplied value of the tokens to the destination address.
//Minting cannot be performed any further once the maximum supply is reached.
//This function cannot be used by anyone except for this contract.
///@param _to The address which will receive the minted tokens.
///@param _value The amount of tokens to mint.
function mintTokens(address _to, uint _value) internal returns(bool) {
require(_to != address(0), "Invalid address.");
require(totalSupply_.add(_value) <= MAX_SUPPLY, "Sorry but the total supply can't exceed the maximum supply.");
balances[_to] = balances[_to].add(_value);
totalSupply_ = totalSupply_.add(_value);
emit Transfer(address(0), _to, _value);
emit Mint(_to, _value);
return true;
}
}
|
Transfers the specified value of FULC tokens to the destination address.Transfers can only happen when the transfer state is enabled.Transfer state can only be enabled after the end of the crowdsale. _to The destination wallet address to transfer funds to. _value The amount of tokens to send to the destination address.
|
function transfer(address _to, uint256 _value) public canTransfer(msg.sender) returns(bool) {
require(_to != address(0), "Invalid address.");
return super.transfer(_to, _value);
}
| 12,804,069
|
./full_match/137/0xcedcB63E71252bFe98E801C5F0Ab671481feAd7c/sources/contracts/WhatThe7uck.sol
|
[Owner] Emergency withdrawal
|
function withdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); }
| 4,704,161
|
// 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;
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: 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IIntegrationManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the IntegrationManager
interface IIntegrationManager {
enum SpendAssetsHandleType {None, Approve, Transfer, Remove}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../IIntegrationManager.sol";
/// @title Integration Adapter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all integration adapters
interface IIntegrationAdapter {
function identifier() external pure returns (string memory identifier_);
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "../utils/actions/CurveGaugeV2RewardsHandlerBase.sol";
import "../utils/actions/CurveSethLiquidityActionsMixin.sol";
import "../utils/actions/UniswapV2ActionsMixin.sol";
import "../utils/AdapterBase2.sol";
/// @title CurveLiquiditySethAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for liquidity provision in Curve's seth pool (https://www.curve.fi/seth)
/// @dev Rewards tokens are not included as spend assets or incoming assets for claimRewards()
/// or claimRewardsAndReinvest(). Rationale:
/// - rewards tokens can be claimed to the vault outside of the IntegrationManager, so no need
/// to enforce policy management or emit an event
/// - rewards tokens can be outside of the asset universe, in which case they cannot be tracked
/// This adapter will need to be re-deployed if UniswapV2 low liquidity becomes
/// a concern for rewards tokens when using claimRewardsAndReinvest().
contract CurveLiquiditySethAdapter is
AdapterBase2,
CurveGaugeV2RewardsHandlerBase,
CurveSethLiquidityActionsMixin,
UniswapV2ActionsMixin
{
address private immutable LIQUIDITY_GAUGE_TOKEN;
address private immutable LP_TOKEN;
address private immutable SETH_TOKEN;
constructor(
address _integrationManager,
address _liquidityGaugeToken,
address _lpToken,
address _minter,
address _pool,
address _crvToken,
address _sethToken,
address _wethToken,
address _uniswapV2Router2
)
public
AdapterBase2(_integrationManager)
CurveGaugeV2RewardsHandlerBase(_minter, _crvToken)
CurveSethLiquidityActionsMixin(_pool, _sethToken, _wethToken)
UniswapV2ActionsMixin(_uniswapV2Router2)
{
LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken;
LP_TOKEN = _lpToken;
SETH_TOKEN = _sethToken;
// Max approve contracts to spend relevant tokens
ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max);
}
/// @dev Needed to receive ETH from redemption and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "CURVE_LIQUIDITY_SETH";
}
/// @notice Approves assets from the vault to be used by this contract.
/// @dev No logic necessary. Exists only to grant adapter with necessary approvals from the vault,
/// which takes place in the IntegrationManager.
function approveAssets(
address,
bytes calldata,
bytes calldata
) external {}
/// @notice Claims rewards from the Curve Minter as well as pool-specific rewards
/// @param _vaultProxy The VaultProxy of the calling fund
function claimRewards(
address _vaultProxy,
bytes calldata,
bytes calldata
) external onlyIntegrationManager {
__curveGaugeV2ClaimAllRewards(LIQUIDITY_GAUGE_TOKEN, _vaultProxy);
}
/// @notice Claims rewards and then compounds the rewards tokens back into the staked LP token
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @dev Requires the adapter to be granted an allowance of each reward token by the vault.
/// For supported assets (e.g., CRV), this must be done via the `approveAssets()` function in this adapter.
/// For unsupported assets, this must be done via `ComptrollerProxy.vaultCallOnContract()`.
/// The `useFullBalances` option indicates whether to use only the newly claimed balances of
/// rewards tokens, or whether to use the full balances of these assets in the vault.
function claimRewardsAndReinvest(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
bool useFullBalances,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeClaimRewardsAndReinvestCallArgs(_encodedCallArgs);
(
address[] memory rewardsTokens,
uint256[] memory rewardsTokenAmountsToUse
) = __curveGaugeV2ClaimRewardsAndPullBalances(
LIQUIDITY_GAUGE_TOKEN,
_vaultProxy,
useFullBalances
);
// Swap all reward tokens to WETH via UniswapV2.
// Note that if a reward token takes a fee on transfer,
// we could not use these memory balances.
__uniswapV2SwapManyToOne(
address(this),
rewardsTokens,
rewardsTokenAmountsToUse,
getCurveSethLiquidityWethToken(),
address(0)
);
// Lend all received WETH for staked LP tokens
uint256 wethBalance = ERC20(getCurveSethLiquidityWethToken()).balanceOf(address(this));
if (wethBalance > 0) {
__curveSethLend(wethBalance, 0, minIncomingLiquidityGaugeTokenAmount);
__curveGaugeV2Stake(
LIQUIDITY_GAUGE_TOKEN,
LP_TOKEN,
ERC20(LP_TOKEN).balanceOf(address(this))
);
}
}
/// @notice Claims rewards and then swaps the rewards tokens to the specified asset via UniswapV2
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @dev Requires the adapter to be granted an allowance of each reward token by the vault.
/// For supported assets (e.g., CRV), this must be done via the `approveAssets()` function in this adapter.
/// For unsupported assets, this must be done via `ComptrollerProxy.vaultCallOnContract()`.
/// The `useFullBalances` option indicates whether to use only the newly claimed balances of
/// rewards tokens, or whether to use the full balances of these assets in the vault.
function claimRewardsAndSwap(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(bool useFullBalances, address incomingAsset, ) = __decodeClaimRewardsAndSwapCallArgs(
_encodedCallArgs
);
(
address[] memory rewardsTokens,
uint256[] memory rewardsTokenAmountsToUse
) = __curveGaugeV2ClaimRewardsAndPullBalances(
LIQUIDITY_GAUGE_TOKEN,
_vaultProxy,
useFullBalances
);
// Swap all reward tokens to the designated incomingAsset via UniswapV2.
// Note that if a reward token takes a fee on transfer,
// we could not use these memory balances.
__uniswapV2SwapManyToOne(
_vaultProxy,
rewardsTokens,
rewardsTokenAmountsToUse,
incomingAsset,
getCurveSethLiquidityWethToken()
);
}
/// @notice Lends assets for seth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingSethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__curveSethLend(
outgoingWethAmount,
outgoingSethAmount,
minIncomingLiquidityGaugeTokenAmount
);
}
/// @notice Lends assets for seth LP tokens, then stakes the received LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lendAndStake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingSethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__curveSethLend(
outgoingWethAmount,
outgoingSethAmount,
minIncomingLiquidityGaugeTokenAmount
);
__curveGaugeV2Stake(
LIQUIDITY_GAUGE_TOKEN,
LP_TOKEN,
ERC20(LP_TOKEN).balanceOf(address(this))
);
}
/// @notice Redeems seth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLpTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingSethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__curveSethRedeem(
outgoingLpTokenAmount,
minIncomingWethAmount,
minIncomingSethAmount,
redeemSingleAsset
);
}
/// @notice Stakes seth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function stake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
__curveGaugeV2Stake(
LIQUIDITY_GAUGE_TOKEN,
LP_TOKEN,
__decodeStakeCallArgs(_encodedCallArgs)
);
}
/// @notice Unstakes seth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
__curveGaugeV2Unstake(LIQUIDITY_GAUGE_TOKEN, __decodeUnstakeCallArgs(_encodedCallArgs));
}
/// @notice Unstakes seth LP tokens, then redeems them
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstakeAndRedeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingSethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__curveGaugeV2Unstake(LIQUIDITY_GAUGE_TOKEN, outgoingLiquidityGaugeTokenAmount);
__curveSethRedeem(
outgoingLiquidityGaugeTokenAmount,
minIncomingWethAmount,
minIncomingSethAmount,
redeemSingleAsset
);
}
/////////////////////////////
// PARSE ASSETS FOR METHOD //
/////////////////////////////
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == APPROVE_ASSETS_SELECTOR) {
return __parseAssetsForApproveAssets(_encodedCallArgs);
} else if (_selector == CLAIM_REWARDS_SELECTOR) {
return __parseAssetsForClaimRewards();
} else if (_selector == CLAIM_REWARDS_AND_REINVEST_SELECTOR) {
return __parseAssetsForClaimRewardsAndReinvest(_encodedCallArgs);
} else if (_selector == CLAIM_REWARDS_AND_SWAP_SELECTOR) {
return __parseAssetsForClaimRewardsAndSwap(_encodedCallArgs);
} else if (_selector == LEND_SELECTOR) {
return __parseAssetsForLend(_encodedCallArgs);
} else if (_selector == LEND_AND_STAKE_SELECTOR) {
return __parseAssetsForLendAndStake(_encodedCallArgs);
} else if (_selector == REDEEM_SELECTOR) {
return __parseAssetsForRedeem(_encodedCallArgs);
} else if (_selector == STAKE_SELECTOR) {
return __parseAssetsForStake(_encodedCallArgs);
} else if (_selector == UNSTAKE_SELECTOR) {
return __parseAssetsForUnstake(_encodedCallArgs);
} else if (_selector == UNSTAKE_AND_REDEEM_SELECTOR) {
return __parseAssetsForUnstakeAndRedeem(_encodedCallArgs);
}
revert("parseAssetsForMethod: _selector invalid");
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during approveAssets() calls
function __parseAssetsForApproveAssets(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(spendAssets_, spendAssetAmounts_) = __decodeApproveAssetsCallArgs(_encodedCallArgs);
require(
spendAssets_.length == spendAssetAmounts_.length,
"__parseAssetsForApproveAssets: Unequal arrays"
);
// Validate that only rewards tokens are given allowances
address[] memory rewardsTokens = __curveGaugeV2GetRewardsTokensWithCrv(
LIQUIDITY_GAUGE_TOKEN
);
for (uint256 i; i < spendAssets_.length; i++) {
// Allow revoking approval for any asset
if (spendAssetAmounts_[i] > 0) {
require(
rewardsTokens.contains(spendAssets_[i]),
"__parseAssetsForApproveAssets: Invalid reward token"
);
}
}
return (
IIntegrationManager.SpendAssetsHandleType.Approve,
spendAssets_,
spendAssetAmounts_,
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewards() calls.
/// No action required, all values empty.
function __parseAssetsForClaimRewards()
private
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
return (
IIntegrationManager.SpendAssetsHandleType.None,
new address[](0),
new uint256[](0),
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewardsAndReinvest() calls.
function __parseAssetsForClaimRewardsAndReinvest(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(, uint256 minIncomingLiquidityGaugeTokenAmount) = __decodeClaimRewardsAndReinvestCallArgs(
_encodedCallArgs
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingLiquidityGaugeTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.None,
new address[](0),
new uint256[](0),
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewardsAndSwap() calls.
function __parseAssetsForClaimRewardsAndSwap(bytes calldata _encodedCallArgs)
private
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeClaimRewardsAndSwapCallArgs(_encodedCallArgs);
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.None,
new address[](0),
new uint256[](0),
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lend() calls
function __parseAssetsForLend(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingWethAmount,
uint256 outgoingSethAmount,
uint256 minIncomingLpTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls(
outgoingWethAmount,
outgoingSethAmount
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingLpTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lendAndStake() calls
function __parseAssetsForLendAndStake(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingWethAmount,
uint256 outgoingSethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls(
outgoingWethAmount,
outgoingSethAmount
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingLiquidityGaugeTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during redeem() calls
function __parseAssetsForRedeem(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingLpTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingSethAmount,
bool receiveSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLpTokenAmount;
(incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls(
minIncomingWethAmount,
minIncomingSethAmount,
receiveSingleAsset
);
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during stake() calls
function __parseAssetsForStake(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
uint256 outgoingLpTokenAmount = __decodeStakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLpTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLpTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstake() calls
function __parseAssetsForUnstake(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstakeAndRedeem() calls
function __parseAssetsForUnstakeAndRedeem(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingSethAmount,
bool receiveSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
(incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls(
minIncomingWethAmount,
minIncomingSethAmount,
receiveSingleAsset
);
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend assets for redeem() and unstakeAndRedeem() calls
function __parseIncomingAssetsForRedemptionCalls(
uint256 _minIncomingWethAmount,
uint256 _minIncomingSethAmount,
bool _receiveSingleAsset
)
private
view
returns (address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_)
{
if (_receiveSingleAsset) {
incomingAssets_ = new address[](1);
minIncomingAssetAmounts_ = new uint256[](1);
if (_minIncomingWethAmount == 0) {
require(
_minIncomingSethAmount > 0,
"__parseIncomingAssetsForRedemptionCalls: No min asset amount specified"
);
incomingAssets_[0] = SETH_TOKEN;
minIncomingAssetAmounts_[0] = _minIncomingSethAmount;
} else {
require(
_minIncomingSethAmount == 0,
"__parseIncomingAssetsForRedemptionCalls: Too many min asset amounts specified"
);
incomingAssets_[0] = getCurveSethLiquidityWethToken();
minIncomingAssetAmounts_[0] = _minIncomingWethAmount;
}
} else {
incomingAssets_ = new address[](2);
incomingAssets_[0] = getCurveSethLiquidityWethToken();
incomingAssets_[1] = SETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = _minIncomingWethAmount;
minIncomingAssetAmounts_[1] = _minIncomingSethAmount;
}
return (incomingAssets_, minIncomingAssetAmounts_);
}
/// @dev Helper function to parse spend assets for lend() and lendAndStake() calls
function __parseSpendAssetsForLendingCalls(
uint256 _outgoingWethAmount,
uint256 _outgoingSethAmount
) private view returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_) {
if (_outgoingWethAmount > 0 && _outgoingSethAmount > 0) {
spendAssets_ = new address[](2);
spendAssets_[0] = getCurveSethLiquidityWethToken();
spendAssets_[1] = SETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = _outgoingWethAmount;
spendAssetAmounts_[1] = _outgoingSethAmount;
} else if (_outgoingWethAmount > 0) {
spendAssets_ = new address[](1);
spendAssets_[0] = getCurveSethLiquidityWethToken();
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = _outgoingWethAmount;
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = SETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = _outgoingSethAmount;
}
return (spendAssets_, spendAssetAmounts_);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
/// @dev Helper to decode the encoded call arguments for approving asset allowances
function __decodeApproveAssetsCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address[] memory assets_, uint256[] memory amounts_)
{
return abi.decode(_encodedCallArgs, (address[], uint256[]));
}
/// @dev Helper to decode the encoded call arguments for claiming rewards
function __decodeClaimRewardsAndReinvestCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (bool useFullBalances_, uint256 minIncomingLiquidityGaugeTokenAmount_)
{
return abi.decode(_encodedCallArgs, (bool, uint256));
}
/// @dev Helper to decode the encoded call arguments for claiming rewards and swapping
function __decodeClaimRewardsAndSwapCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
bool useFullBalances_,
address incomingAsset_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (bool, address, uint256));
}
/// @dev Helper to decode the encoded call arguments for lending
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingWethAmount_,
uint256 outgoingSethAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256));
}
/// @dev Helper to decode the encoded call arguments for redeeming.
/// If `receiveSingleAsset_` is `true`, then one (and only one) of
/// `minIncomingWethAmount_` and `minIncomingSethAmount_` must be >0
/// to indicate which asset is to be received.
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingAssetAmount_,
uint256 minIncomingWethAmount_,
uint256 minIncomingSethAmount_,
bool receiveSingleAsset_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for staking
function __decodeStakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLpTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
/// @dev Helper to decode the encoded call arguments for unstaking
function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLiquidityGaugeTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable
/// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value
function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) {
return LIQUIDITY_GAUGE_TOKEN;
}
/// @notice Gets the `LP_TOKEN` variable
/// @return lpToken_ The `LP_TOKEN` variable value
function getLpToken() external view returns (address lpToken_) {
return LP_TOKEN;
}
/// @notice Gets the `SETH_TOKEN` variable
/// @return sethToken_ The `SETH_TOKEN` variable value
function getSethToken() external view returns (address sethToken_) {
return SETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../IIntegrationAdapter.sol";
import "./IntegrationSelectors.sol";
/// @title AdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters
abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors {
using SafeERC20 for ERC20;
address internal immutable INTEGRATION_MANAGER;
/// @dev Provides a standard implementation for transferring assets between
/// the fund's VaultProxy and the adapter, by wrapping the adapter action.
/// This modifier should be implemented in almost all adapter actions, unless they
/// do not move assets or can spend and receive assets directly with the VaultProxy
modifier fundAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
(
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
// Take custody of spend assets (if necessary)
if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) {
for (uint256 i = 0; i < spendAssets.length; i++) {
ERC20(spendAssets[i]).safeTransferFrom(
_vaultProxy,
address(this),
spendAssetAmounts[i]
);
}
}
// Execute call
_;
// Transfer remaining assets back to the fund's VaultProxy
__transferContractAssetBalancesToFund(_vaultProxy, incomingAssets);
__transferContractAssetBalancesToFund(_vaultProxy, spendAssets);
}
modifier onlyIntegrationManager {
require(
msg.sender == INTEGRATION_MANAGER,
"Only the IntegrationManager can call this function"
);
_;
}
constructor(address _integrationManager) public {
INTEGRATION_MANAGER = _integrationManager;
}
// INTERNAL FUNCTIONS
/// @dev Helper for adapters to approve their integratees with the max amount of an asset.
/// Since everything is done atomically, and only the balances to-be-used are sent to adapters,
/// there is no need to approve exact amounts on every call.
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call
function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs)
internal
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_
)
{
return
abi.decode(
_encodedAssetTransferArgs,
(IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[])
);
}
/// @dev Helper to transfer full contract balances of assets to the specified VaultProxy
function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets)
private
{
for (uint256 i = 0; i < _assets.length; i++) {
uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this));
if (postCallAmount > 0) {
ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount);
}
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() external view returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./AdapterBase.sol";
/// @title AdapterBase2 Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters that extends AdapterBase
/// @dev This is a temporary contract that will be merged into AdapterBase with the next release
abstract contract AdapterBase2 is AdapterBase {
/// @dev Provides a standard implementation for transferring incoming assets and
/// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action
modifier postActionAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(
,
address[] memory spendAssets,
,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
/// @dev Provides a standard implementation for transferring incoming assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionIncomingAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
}
/// @dev Provides a standard implementation for transferring unspent spend assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionSpendAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
constructor(address _integrationManager) public AdapterBase(_integrationManager) {}
/// @dev Helper to transfer full asset balances of current contract to the specified target
function __transferFullAssetBalances(address _target, address[] memory _assets) internal {
for (uint256 i = 0; i < _assets.length; i++) {
uint256 balance = ERC20(_assets[i]).balanceOf(address(this));
if (balance > 0) {
ERC20(_assets[i]).safeTransfer(_target, balance);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IntegrationSelectors Contract
/// @author Enzyme Council <[email protected]>
/// @notice Selectors for integration actions
/// @dev Selectors are created from their signatures rather than hardcoded for easy verification
abstract contract IntegrationSelectors {
bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4(
keccak256("addTrackedAssets(address,bytes,bytes)")
);
// Asset approval
bytes4 public constant APPROVE_ASSETS_SELECTOR = bytes4(
keccak256("approveAssets(address,bytes,bytes)")
);
// Trading
bytes4 public constant TAKE_ORDER_SELECTOR = bytes4(
keccak256("takeOrder(address,bytes,bytes)")
);
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
// Staking
bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)"));
bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)"));
// Rewards
bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4(
keccak256("claimRewards(address,bytes,bytes)")
);
// Combined
bytes4 public constant CLAIM_REWARDS_AND_REINVEST_SELECTOR = bytes4(
keccak256("claimRewardsAndReinvest(address,bytes,bytes)")
);
bytes4 public constant CLAIM_REWARDS_AND_SWAP_SELECTOR = bytes4(
keccak256("claimRewardsAndSwap(address,bytes,bytes)")
);
bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../interfaces/ICurveLiquidityGaugeV2.sol";
import "../../../../../utils/AssetHelpers.sol";
/// @title CurveGaugeV2ActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with any Curve LiquidityGaugeV2 contract
abstract contract CurveGaugeV2ActionsMixin is AssetHelpers {
uint256 private constant CURVE_GAUGE_V2_MAX_REWARDS = 8;
/// @dev Helper to claim pool-specific rewards
function __curveGaugeV2ClaimRewards(address _gauge, address _target) internal {
ICurveLiquidityGaugeV2(_gauge).claim_rewards(_target);
}
/// @dev Helper to get list of pool-specific rewards tokens
function __curveGaugeV2GetRewardsTokens(address _gauge)
internal
view
returns (address[] memory rewardsTokens_)
{
address[] memory lpRewardsTokensWithEmpties = new address[](CURVE_GAUGE_V2_MAX_REWARDS);
uint256 rewardsTokensCount;
for (uint256 i; i < CURVE_GAUGE_V2_MAX_REWARDS; i++) {
address rewardToken = ICurveLiquidityGaugeV2(_gauge).reward_tokens(i);
if (rewardToken != address(0)) {
lpRewardsTokensWithEmpties[i] = rewardToken;
rewardsTokensCount++;
} else {
break;
}
}
rewardsTokens_ = new address[](rewardsTokensCount);
for (uint256 i; i < rewardsTokensCount; i++) {
rewardsTokens_[i] = lpRewardsTokensWithEmpties[i];
}
return rewardsTokens_;
}
/// @dev Helper to stake LP tokens
function __curveGaugeV2Stake(
address _gauge,
address _lpToken,
uint256 _amount
) internal {
__approveAssetMaxAsNeeded(_lpToken, _gauge, _amount);
ICurveLiquidityGaugeV2(_gauge).deposit(_amount, address(this));
}
/// @dev Helper to unstake LP tokens
function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal {
ICurveLiquidityGaugeV2(_gauge).withdraw(_amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../interfaces/ICurveMinter.sol";
import "../../../../../utils/AddressArrayLib.sol";
import "./CurveGaugeV2ActionsMixin.sol";
/// @title CurveGaugeV2RewardsHandlerBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base contract for handling claiming and reinvesting rewards for a Curve pool
/// that uses the LiquidityGaugeV2 contract
abstract contract CurveGaugeV2RewardsHandlerBase is CurveGaugeV2ActionsMixin {
using AddressArrayLib for address[];
address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN;
address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER;
constructor(address _minter, address _crvToken) public {
CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN = _crvToken;
CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER = _minter;
}
/// @dev Helper to claim all rewards (CRV and pool-specific).
/// Requires contract to be approved to use mint_for().
function __curveGaugeV2ClaimAllRewards(address _gauge, address _target) internal {
// Claim owed $CRV
ICurveMinter(CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER).mint_for(_gauge, _target);
// Claim owed pool-specific rewards
__curveGaugeV2ClaimRewards(_gauge, _target);
}
/// @dev Helper to claim all rewards, then pull either the newly claimed balances only,
/// or full vault balances into the current contract
function __curveGaugeV2ClaimRewardsAndPullBalances(
address _gauge,
address _target,
bool _useFullBalances
)
internal
returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsPulled_)
{
if (_useFullBalances) {
return __curveGaugeV2ClaimRewardsAndPullFullBalances(_gauge, _target);
}
return __curveGaugeV2ClaimRewardsAndPullClaimedBalances(_gauge, _target);
}
/// @dev Helper to claim all rewards, then pull only the newly claimed balances
/// of all rewards tokens into the current contract
function __curveGaugeV2ClaimRewardsAndPullClaimedBalances(address _gauge, address _target)
internal
returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsPulled_)
{
rewardsTokens_ = __curveGaugeV2GetRewardsTokensWithCrv(_gauge);
uint256[] memory rewardsTokenPreClaimBalances = new uint256[](rewardsTokens_.length);
for (uint256 i; i < rewardsTokens_.length; i++) {
rewardsTokenPreClaimBalances[i] = ERC20(rewardsTokens_[i]).balanceOf(_target);
}
__curveGaugeV2ClaimAllRewards(_gauge, _target);
rewardsTokenAmountsPulled_ = __pullPartialAssetBalances(
_target,
rewardsTokens_,
rewardsTokenPreClaimBalances
);
return (rewardsTokens_, rewardsTokenAmountsPulled_);
}
/// @dev Helper to claim all rewards, then pull the full balances of all rewards tokens
/// in the target into the current contract
function __curveGaugeV2ClaimRewardsAndPullFullBalances(address _gauge, address _target)
internal
returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsPulled_)
{
__curveGaugeV2ClaimAllRewards(_gauge, _target);
rewardsTokens_ = __curveGaugeV2GetRewardsTokensWithCrv(_gauge);
rewardsTokenAmountsPulled_ = __pullFullAssetBalances(_target, rewardsTokens_);
return (rewardsTokens_, rewardsTokenAmountsPulled_);
}
/// @dev Helper to get all rewards tokens for staking LP tokens
function __curveGaugeV2GetRewardsTokensWithCrv(address _gauge)
internal
view
returns (address[] memory rewardsTokens_)
{
return
__curveGaugeV2GetRewardsTokens(_gauge).addUniqueItem(
CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable
/// @return crvToken_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable value
function getCurveGaugeV2RewardsHandlerCrvToken() public view returns (address crvToken_) {
return CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN;
}
/// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable
/// @return minter_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable value
function getCurveGaugeV2RewardsHandlerMinter() public view returns (address minter_) {
return CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../../interfaces/ICurveStableSwapSeth.sol";
import "../../../../../interfaces/IWETH.sol";
/// @title CurveSethLiquidityActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with the Curve seth pool's liquidity functions
/// @dev Inheriting contract must have a receive() function
abstract contract CurveSethLiquidityActionsMixin {
using SafeERC20 for ERC20;
int128 private constant CURVE_SETH_POOL_INDEX_ETH = 0;
int128 private constant CURVE_SETH_POOL_INDEX_SETH = 1;
address private immutable CURVE_SETH_LIQUIDITY_POOL;
address private immutable CURVE_SETH_LIQUIDITY_WETH_TOKEN;
constructor(
address _pool,
address _sethToken,
address _wethToken
) public {
CURVE_SETH_LIQUIDITY_POOL = _pool;
CURVE_SETH_LIQUIDITY_WETH_TOKEN = _wethToken;
// Pre-approve pool to use max of seth token
ERC20(_sethToken).safeApprove(_pool, type(uint256).max);
}
/// @dev Helper to add liquidity to the pool
function __curveSethLend(
uint256 _outgoingWethAmount,
uint256 _outgoingSethAmount,
uint256 _minIncomingLPTokenAmount
) internal {
if (_outgoingWethAmount > 0) {
IWETH((CURVE_SETH_LIQUIDITY_WETH_TOKEN)).withdraw(_outgoingWethAmount);
}
ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).add_liquidity{value: _outgoingWethAmount}(
[_outgoingWethAmount, _outgoingSethAmount],
_minIncomingLPTokenAmount
);
}
/// @dev Helper to remove liquidity from the pool.
// Assumes that if _redeemSingleAsset is true, then
// "_minIncomingWethAmount > 0 XOR _minIncomingSethAmount > 0" has already been validated.
function __curveSethRedeem(
uint256 _outgoingLPTokenAmount,
uint256 _minIncomingWethAmount,
uint256 _minIncomingSethAmount,
bool _redeemSingleAsset
) internal {
if (_redeemSingleAsset) {
if (_minIncomingWethAmount > 0) {
ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
CURVE_SETH_POOL_INDEX_ETH,
_minIncomingWethAmount
);
IWETH(payable(CURVE_SETH_LIQUIDITY_WETH_TOKEN)).deposit{
value: payable(address(this)).balance
}();
} else {
ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
CURVE_SETH_POOL_INDEX_SETH,
_minIncomingSethAmount
);
}
} else {
ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).remove_liquidity(
_outgoingLPTokenAmount,
[_minIncomingWethAmount, _minIncomingSethAmount]
);
IWETH(payable(CURVE_SETH_LIQUIDITY_WETH_TOKEN)).deposit{
value: payable(address(this)).balance
}();
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CURVE_SETH_LIQUIDITY_POOL` variable
/// @return pool_ The `CURVE_SETH_LIQUIDITY_POOL` variable value
function getCurveSethLiquidityPool() public view returns (address pool_) {
return CURVE_SETH_LIQUIDITY_POOL;
}
/// @notice Gets the `CURVE_SETH_LIQUIDITY_WETH_TOKEN` variable
/// @return wethToken_ The `CURVE_SETH_LIQUIDITY_WETH_TOKEN` variable value
function getCurveSethLiquidityWethToken() public view returns (address wethToken_) {
return CURVE_SETH_LIQUIDITY_WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../interfaces/IUniswapV2Router2.sol";
import "../../../../../utils/AssetHelpers.sol";
/// @title UniswapV2ActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with Uniswap v2
abstract contract UniswapV2ActionsMixin is AssetHelpers {
address private immutable UNISWAP_V2_ROUTER2;
constructor(address _router) public {
UNISWAP_V2_ROUTER2 = _router;
}
// EXTERNAL FUNCTIONS
/// @dev Helper to add liquidity
function __uniswapV2Lend(
address _recipient,
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired,
uint256 _amountAMin,
uint256 _amountBMin
) internal {
__approveAssetMaxAsNeeded(_tokenA, UNISWAP_V2_ROUTER2, _amountADesired);
__approveAssetMaxAsNeeded(_tokenB, UNISWAP_V2_ROUTER2, _amountBDesired);
// Execute lend on Uniswap
IUniswapV2Router2(UNISWAP_V2_ROUTER2).addLiquidity(
_tokenA,
_tokenB,
_amountADesired,
_amountBDesired,
_amountAMin,
_amountBMin,
_recipient,
__uniswapV2GetActionDeadline()
);
}
/// @dev Helper to remove liquidity
function __uniswapV2Redeem(
address _recipient,
address _poolToken,
uint256 _poolTokenAmount,
address _tokenA,
address _tokenB,
uint256 _amountAMin,
uint256 _amountBMin
) internal {
__approveAssetMaxAsNeeded(_poolToken, UNISWAP_V2_ROUTER2, _poolTokenAmount);
// Execute redeem on Uniswap
IUniswapV2Router2(UNISWAP_V2_ROUTER2).removeLiquidity(
_tokenA,
_tokenB,
_poolTokenAmount,
_amountAMin,
_amountBMin,
_recipient,
__uniswapV2GetActionDeadline()
);
}
/// @dev Helper to execute a swap
function __uniswapV2Swap(
address _recipient,
uint256 _outgoingAssetAmount,
uint256 _minIncomingAssetAmount,
address[] memory _path
) internal {
__approveAssetMaxAsNeeded(_path[0], UNISWAP_V2_ROUTER2, _outgoingAssetAmount);
// Execute fill
IUniswapV2Router2(UNISWAP_V2_ROUTER2).swapExactTokensForTokens(
_outgoingAssetAmount,
_minIncomingAssetAmount,
_path,
_recipient,
__uniswapV2GetActionDeadline()
);
}
/// @dev Helper to swap many assets to a single target asset.
/// The intermediary asset will generally be WETH, and though we could make it
// per-outgoing asset, seems like overkill until there is a need.
function __uniswapV2SwapManyToOne(
address _recipient,
address[] memory _outgoingAssets,
uint256[] memory _outgoingAssetAmounts,
address _incomingAsset,
address _intermediaryAsset
) internal {
bool noIntermediary = _intermediaryAsset == address(0) ||
_intermediaryAsset == _incomingAsset;
for (uint256 i; i < _outgoingAssets.length; i++) {
// Skip cases where outgoing and incoming assets are the same, or
// there is no specified outgoing asset or amount
if (
_outgoingAssetAmounts[i] == 0 ||
_outgoingAssets[i] == address(0) ||
_outgoingAssets[i] == _incomingAsset
) {
continue;
}
address[] memory uniswapPath;
if (noIntermediary || _outgoingAssets[i] == _intermediaryAsset) {
uniswapPath = new address[](2);
uniswapPath[0] = _outgoingAssets[i];
uniswapPath[1] = _incomingAsset;
} else {
uniswapPath = new address[](3);
uniswapPath[0] = _outgoingAssets[i];
uniswapPath[1] = _intermediaryAsset;
uniswapPath[2] = _incomingAsset;
}
__uniswapV2Swap(_recipient, _outgoingAssetAmounts[i], 1, uniswapPath);
}
}
/// @dev Helper to get the deadline for a Uniswap V2 action in a standardized way
function __uniswapV2GetActionDeadline() private view returns (uint256 deadline_) {
return block.timestamp + 1;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `UNISWAP_V2_ROUTER2` variable
/// @return router_ The `UNISWAP_V2_ROUTER2` variable value
function getUniswapV2Router2() public view returns (address router_) {
return UNISWAP_V2_ROUTER2;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeV2 interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityGaugeV2 {
function claim_rewards(address) external;
function deposit(uint256, address) external;
function reward_tokens(uint256) external view returns (address);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveMinter interface
/// @author Enzyme Council <[email protected]>
interface ICurveMinter {
function mint_for(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveStableSwapSeth interface
/// @author Enzyme Council <[email protected]>
interface ICurveStableSwapSeth {
function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256);
function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory);
function remove_liquidity_one_coin(
uint256,
int128,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title UniswapV2Router2 Interface
/// @author Enzyme Council <[email protected]>
/// @dev Minimal interface for our interactions with Uniswap V2's Router2
interface IUniswapV2Router2 {
function addLiquidity(
address,
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256
)
external
returns (
uint256,
uint256,
uint256
);
function removeLiquidity(
address,
address,
uint256,
uint256,
uint256,
address,
uint256
) external returns (uint256, uint256);
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to reassign all items in an array with a specified value
function fill(address[] memory _self, address _value)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length);
for (uint256 i; i < nextArray_.length; i++) {
nextArray_[i] = _value;
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to get the balances of specified assets for a target
function __getAssetBalances(address _target, address[] memory _assets)
internal
view
returns (uint256[] memory balances_)
{
balances_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
balances_[i] = ERC20(_assets[i]).balanceOf(_target);
}
return balances_;
}
/// @dev Helper to transfer full asset balances from a target to the current contract.
/// Requires an adequate allowance for each asset granted to the current contract for the target.
function __pullFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(_target);
if (amountsTransferred_[i] > 0) {
assetContract.safeTransferFrom(_target, address(this), amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
/// @dev Helper to transfer partial asset balances from a target to the current contract.
/// Requires an adequate allowance for each asset granted to the current contract for the target.
function __pullPartialAssetBalances(
address _target,
address[] memory _assets,
uint256[] memory _amountsToExclude
) internal returns (uint256[] memory amountsTransferred_) {
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(_target).sub(_amountsToExclude[i]);
if (amountsTransferred_[i] > 0) {
assetContract.safeTransferFrom(_target, address(this), amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
|
Helper to decode the encoded call arguments for lending
|
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingWethAmount_,
uint256 outgoingSethAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256));
}
| 5,831,061
|
./partial_match/42/0x2fe63F7CE38D2Cb605B79901F868c91968d377a9/sources/ImpermanentGain.sol
|
burn no more than `max_lp` of liquidity provider share, withdraw `_a` of a and `_b` of b ( 1 - sqrt(_k/k) ) LP
|
function withdrawLP(uint256 _a, uint256 _b, uint256 max_lp) external returns (uint256 _lp) {
require(canBuy, "cannot buy");
uint256 k = poolA.mul(poolB).sqrt();
uint256 _k = poolA.sub(_a).mul(poolB.sub(_b)).sqrt();
_lp = (1e18).sub(_k.mul(1e18).div(k)).mul(_totalSupply).div(1e18);
require(_lp <= max_lp, "SLIPPAGE_DETECTED");
poolA = poolA.sub(_a);
poolB = poolB.sub(_b);
a[msg.sender] = a[msg.sender].add(_a);
b[msg.sender] = b[msg.sender].add(_b);
_burn(msg.sender, _lp);
emit RemoveLP(msg.sender, _lp, _a, _b);
}
|__________________________________*/
| 9,016,742
|
./partial_match/1/0xFC634bfc0f00A2D3dCc93CeB4558Da9DE840fdBC/sources/MetaLifeOgPets.sol
|
Returns a copy of the string in either lowercase or UPPERCASE. WARNING! This function is only compatible with 7-bit ASCII strings.
|
{
mstore(last, 0)
mstore(result, totalLength)
mstore(0x40, and(add(last, 0x1f), w))
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
assembly {
let length := mload(subject)
if length {
result := add(mload(0x40), 0x20)
subject := add(subject, 1)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
let w := not(0)
o := add(o, w)
let b := and(0xff, mload(add(subject, o)))
mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))
}
result := mload(0x40)
let last := add(add(result, 0x20), length)
}
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
assembly {
let length := mload(subject)
if length {
result := add(mload(0x40), 0x20)
subject := add(subject, 1)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
let w := not(0)
o := add(o, w)
let b := and(0xff, mload(add(subject, o)))
mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))
}
result := mload(0x40)
let last := add(add(result, 0x20), length)
}
for { let o := length } 1 {} {
if iszero(o) { break }
}
| 9,237,756
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.