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/1/0x2411C98CC59D88e13Cc9CbFc576F7D40828aC47c/sources/contracts/registry/BDNS.sol | Logged when the owner of a node assigns a new owner to a subnode. Logged when the owner of a node transfers ownership to a new account. Logged when the resolver for a node changes. Logged when the TTL of a node changes Logged when an operator is added or removed. | interface BDNS {
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
event Transfer(bytes32 indexed node, address owner);
event NewResolver(bytes32 indexed node, address resolver);
event NewTTL(bytes32 indexed node, uint64 ttl);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function setRecord(
bytes32 node,
address owner,
address resolver,
uint64 ttl
) external;
function setSubnodeRecord(
bytes32 node,
bytes32 label,
address owner,
address resolver,
uint64 ttl
) external;
function setSubnodeOwner(
bytes32 node,
bytes32 label,
address owner
) external returns (bytes32);
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function setApprovalForAll(address operator, bool approved) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
function recordExists(bytes32 node) external view returns (bool);
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
pragma solidity >=0.8.4;
}
| 9,805,159 |
./partial_match/1/0x1776e1F26f98b1A5dF9cD347953a26dd3Cb46671/sources/NumeraireBackend.sol | constructor is given number of sigs required to do protected "onlymanyowners" transactions as well as the selection of addresses capable of confirming them. | function Shareable(address[] _owners, uint _required) {
owners[1] = msg.sender;
ownerIndex[msg.sender] = 1;
for (uint i = 0; i < _owners.length; ++i) {
owners[2 + i] = _owners[i];
ownerIndex[_owners[i]] = 2 + i;
}
if (required > owners.length) throw;
required = _required;
}
| 4,382,433 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import '@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol';
contract ScinionFactory is Ownable, ERC721 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
string private _baseURIextended;
uint8 private NUMBER_DIGITS_DNA = 16;
Scinion[] internal scinions;
uint minPrice = 0.01 ether;
using SafeMath for uint256;
event NewScinion(uint scinionId, string name, string uri);
address payable gameOwner;
function getOwner() public view returns (address) {
return gameOwner;
}
modifier onlyOwnerOf(uint _scinionId) {
require(msg.sender == ownerOf(_scinionId));
_;
}
struct Scinion {
string name;
string scinionType;
uint16 level;
uint8 energia;
uint dna;
uint habilities;
}
constructor() ERC721("ScinionNFT", "SCTK") {
gameOwner = payable(msg.sender);
_baseURIextended = "ipfs://QmXEqEB9FCEHc34ZsnyCAr9KDfxqhvLqpsZU3Y4s4sm1pg";
}
function rand(uint8 _min, uint8 _max, string memory _name) private pure returns (uint8){
return uint8(uint(keccak256(abi.encodePacked(_name)))%(_min+_max)-_min);
}
function setMinPrice(uint _fee) external onlyOwner() {
minPrice = _fee;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
function setBaseURI(string memory baseURI_) external onlyOwner() {
_baseURIextended = baseURI_;
}
function _createScinion(string memory _name) private view returns(Scinion memory) {
Scinion memory newScinion;
newScinion.name = _name;
newScinion.scinionType = _setScinionType();
newScinion.dna = _setDna();
newScinion.energia = 10;
newScinion.level = 1;
newScinion.habilities = _setPerfectHabilities();
return newScinion;
}
function _createRandomNum(uint256 _mod) internal view returns (uint256) {
uint256 randomNum = uint256(
keccak256(abi.encodePacked(block.timestamp, msg.sender))
);
return randomNum % _mod;
}
function _setPerfectHabilities() pure private returns (uint habilities) {
return 100100100100100100100100100100;
}
function _setScinionType() pure private returns (string memory scinionType) {
return "Scinion";
}
function _setDna() view private returns (uint256 dna) {
return _createRandomNum(10**NUMBER_DIGITS_DNA);
}
function mintScinion(string memory _name) external payable returns(uint id) {
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
Scinion memory newScinion = _createScinion(_name);
//require(msg.value >= minPrice, "Not enough ETH sent; check price!");
// payable(owner()).transfer(msg.value);
_safeMint(msg.sender, tokenId);
tokenURI(tokenId);
scinions.push(newScinion);
emit NewScinion(id, _name, tokenURI(tokenId));
return tokenId;
}
function getScinionsByOwner() public view returns(Scinion[] memory) {
Scinion[] memory result = new Scinion[](balanceOf(msg.sender));
uint counter = 0;
for (uint i = 0; i < scinions.length; i++) {
if (ownerOf(i)==msg.sender) {
result[counter]=scinions[i];
counter++;
}
}
return result;
}
function getBalanceOfOwner() public view returns(uint numberOfScinions){
return balanceOf(msg.sender);
}
function getAllScinions() public view returns(Scinion[] memory) {
return scinions;
}
}
| require(msg.value >= minPrice, "Not enough ETH sent; check price!"); payable(owner()).transfer(msg.value); | function mintScinion(string memory _name) external payable returns(uint id) {
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
Scinion memory newScinion = _createScinion(_name);
_safeMint(msg.sender, tokenId);
tokenURI(tokenId);
scinions.push(newScinion);
emit NewScinion(id, _name, tokenURI(tokenId));
return tokenId;
}
| 2,464,236 |
/**
*Submitted for verification at Etherscan.io on 2022-04-25
*/
// Sources flattened with hardhat v2.9.1 https://hardhat.org
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 contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File contracts/token/ERC20/utils/SafeERC20.sol
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - 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");
}
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity ^0.8.0;
contract MultiTansfer is Ownable {
using SafeERC20 for IERC20;
function airdropTokens(address payable[] memory _toAddress, address[] memory _tokenadds, uint256[] memory _amounts) public payable {
require(_toAddress.length == _tokenadds.length, "address and tokens length do not match");
require(_tokenadds.length == _amounts.length, "tokens and amounts length do not match");
for(uint256 i=0; i<_tokenadds.length; i++) {
if(_tokenadds[i] != address(0)) {
IERC20 token = IERC20(_tokenadds[i]);
token.safeTransferFrom(msg.sender, _toAddress[i], _amounts[i]);
} else {
_toAddress[i].transfer(_amounts[i]);
}
}
}
function airdropNFTs(address[] memory _collections, uint256[] memory _tokenids, address[] memory _useradds) public {
require(_collections.length == _tokenids.length, "tokenids length do not match");
require(_tokenids.length == _useradds.length, "length do not match");
for(uint256 i=0; i<_tokenids.length; i++) {
if(_useradds[i] != address(0)) {
IERC721(_collections[i]).safeTransferFrom(address(msg.sender), _useradds[i], _tokenids[i]);
}
}
}
// **** Claim Taxed Token FUNCTIONS ****
function claimToken(address token, uint amount, address to) external onlyOwner {
IERC20(token).transfer(to, amount);
}
function claim(uint amount, address to) external onlyOwner {
payable(to).transfer(amount);
}
} | Claim Taxed Token FUNCTIONS | function claimToken(address token, uint amount, address to) external onlyOwner {
IERC20(token).transfer(to, amount);
}
| 2,162,520 |
./partial_match/1/0x8687DCac0AE3C150C947Ec14B0BB86FA2B119773/sources/OwnedUpgradeabilityProxy.sol | Allows the proxy owner to upgrade the current version of the proxy and call the new implementation to initialize whatever is needed through a low level call. implementation representing the address of the new implementation to be set. data represents the msg.data to bet sent in the low level call. This parameter may include the function signature of the implementation to be called with the needed payload/ | function upgradeToAndCall(address implementation, bytes memory data) public payable onlyProxyOwner {
upgradeTo(implementation);
bool success;
bytes memory result;
(success, result) = address(this).call.value(msg.value)(data);
require(success);
}
| 9,137,294 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import { IERC20 } from "./interfaces/IERC20.sol";
import { IVault } from "./interfaces/IVault.sol";
import { IExchange } from "./interfaces/IExchange.sol";
import { IKeeperCompatible } from "./interfaces/IKeeperCompatible.sol";
import { ReentrancyGuard } from "./ReentrancyGuard.sol";
library Errors {
string internal constant _AmountZero = "Amount can't be 0";
string internal constant _WrongToken = "Token not allowed";
string internal constant _ExceedsBalance = "Amount exceeds balance";
string internal constant _BalanceZero = "Token balance is 0";
string internal constant _NothingToSell = "Nothing to sell";
}
// TODO: Rename to DCA1 (or smth. similar --> also update deployment scripts, tests, etc. (do global search))
contract Vault is ReentrancyGuard, IVault, IKeeperCompatible {
IERC20 public from;
IERC20 public to;
IExchange public exchange;
address[] public participants;
mapping(address => uint256) public amountPerDay;
mapping(address => mapping(IERC20 => uint256)) public balances;
constructor(
IERC20 from_,
IERC20 to_,
IExchange exchange_
) {
from = from_;
to = to_;
exchange = exchange_;
}
function deposit(uint256 amount) external override {
require(amount > 0, Errors._AmountZero);
// TODO: Add upper-bound for array
balances[msg.sender][from] += amount;
if (!_isInArray(participants, msg.sender)) {
participants.push(msg.sender);
}
IERC20(from).transferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, amount);
}
function withdraw(IERC20 token, uint256 amount) external override nonReentrant {
require(amount > 0, Errors._AmountZero);
require(token == from || token == to, Errors._WrongToken);
uint256 fromBalance = balances[msg.sender][from];
uint256 toBalance = balances[msg.sender][to];
require(amount <= fromBalance || amount <= toBalance, Errors._ExceedsBalance);
// TODO: Remove user from array once (s)he closes her position
balances[msg.sender][token] -= amount;
IERC20(token).transfer(msg.sender, amount);
emit Withdraw(msg.sender, token, amount);
}
function allocate(uint256 amountPerDay_) external override {
require(amountPerDay_ > 0, Errors._AmountZero);
require(amountPerDay_ <= balances[msg.sender][from], Errors._ExceedsBalance);
amountPerDay[msg.sender] = amountPerDay_;
emit Allocate(msg.sender, amountPerDay_);
}
function performUpkeep(bytes calldata) external override {
buy();
}
function checkUpkeep(bytes calldata) external view override returns (bool, bytes memory) {
bool upkeepNeeded;
bytes memory performData = new bytes(0);
uint256 toSell = _calcAmountToSell();
uint256 vaultBalance = from.balanceOf(address(this));
if (vaultBalance > 0 && toSell > 0 && toSell <= vaultBalance) upkeepNeeded = true;
return (upkeepNeeded, performData);
}
function buy() public override returns (uint256) {
require(from.balanceOf(address(this)) > 0, Errors._BalanceZero);
// TODO: Check if sell was already done today
uint256 fromSold = _calcAmountToSell();
require(fromSold > 0, Errors._NothingToSell);
from.approve(address(exchange), fromSold);
uint256 toBought = exchange.swap(from, to, fromSold);
for (uint256 i = 0; i < participants.length; i++) {
address participant = participants[i];
uint256 balance = balances[participant][from];
uint256 perDay = amountPerDay[participant];
// Exclude users who haven't allocated yet or don't have enough funds
if (perDay == 0 || balance < perDay) continue;
// Basis Points describing the user's ownership over the `from` tokens sold
uint256 bps = (perDay * 10000) / fromSold;
// The amount of the bought `to` tokens the user should receive based on the `bps` calculation above
uint256 slice = (toBought * bps) / 10000;
// Remove the user's `from` tokens from the internal balance sheet
balances[participant][from] -= perDay;
// Add the user's slice of the bought `to` tokens to the internal balance sheet
balances[participant][to] += slice;
}
emit Buy(fromSold, toBought);
return toBought;
}
function _calcAmountToSell() private view returns (uint256) {
uint256 result;
for (uint256 i = 0; i < participants.length; i++) {
address participant = participants[i];
uint256 balance = balances[participant][from];
uint256 perDay = amountPerDay[participant];
// Exclude users who haven't allocated yet or don't have enough funds
if (perDay == 0 || balance < perDay) continue;
// Update the running total of `from` tokens to sell
result += perDay;
}
return result;
}
function _isInArray(address[] storage haystack, address needle) private view returns (bool) {
for (uint256 i = 0; i < haystack.length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
}
| TODO: Remove user from array once (s)he closes her position | function withdraw(IERC20 token, uint256 amount) external override nonReentrant {
require(amount > 0, Errors._AmountZero);
require(token == from || token == to, Errors._WrongToken);
uint256 fromBalance = balances[msg.sender][from];
uint256 toBalance = balances[msg.sender][to];
require(amount <= fromBalance || amount <= toBalance, Errors._ExceedsBalance);
balances[msg.sender][token] -= amount;
IERC20(token).transfer(msg.sender, amount);
emit Withdraw(msg.sender, token, amount);
}
| 2,531,972 |
/**
*Submitted for verification at Etherscan.io on 2022-03-25
*/
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity >=0.8.0;
/**
* @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;
}
}
/**
* @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(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 (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(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, 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));
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public returns(bool) {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
return true;
}
}
interface Token {
function transferFrom(address, address, uint) external returns (bool);
function transfer(address, uint) external returns (bool);
}
contract MetaDM_LiquidityFarming is Ownable {
using SafeMath for uint;
using EnumerableSet for EnumerableSet.AddressSet;
event Deposited(address farmer, uint amount);
event Withdrawn(address farmer, uint amount);
event RewardsTransferred(address farmer, uint amount);
// META token contract address
address public constant tokenAddress = 0xEc068b286D09E1650175caB9B93bFbb733eaC335;
// UNI-V2 token contract address
address public constant LPTokenAddress = 0x3d7E4674b3A78d7Aa5892fB43D380292F6910b1D;
// amount disbursed per week
uint public amountToDisburse = 25000000000000000000; // 25 META PER DISBURSE
// unfarming possible after ...
uint public constant unstakeTime = 30 days;
// claiming possible after ...
uint public claimTime = 10 days;
uint public totalClaimedRewards = 0;
uint public totalDeposited = 0;
uint public totalDisbursed = 0;
uint public maxFarmers = 500;
bool public ended = false;
EnumerableSet.AddressSet private holders;
mapping (address => uint) public depositedTokens;
mapping (address => uint) public pending;
mapping (address => uint) public totalEarnedTokens;
mapping (address => uint) public lastDepositTime;
mapping (address => uint) public lastClaimTime;
function disburse () public onlyOwner returns (bool){
require(!ended, "Staking already ended");
address _hold;
uint _add;
for(uint i = 0; i < holders.length(); i = i.add(1)){
_hold = holders.at(i);
_add = depositedTokens[_hold].mul(amountToDisburse).div(totalDeposited);
pending[_hold] = pending[_hold].add(_add);
}
totalDisbursed = totalDisbursed.add(amountToDisburse);
return true;
}
//End the farming pool
function end() public onlyOwner returns (bool){
require(!ended, "Staking already ended");
ended = true;
return true;
}
function getPendingDivs(address _holder) public view returns (uint) {
uint pendingDivs = pending[_holder];
return pendingDivs;
}
function getNumberOfHolders() public view returns (uint) {
return holders.length();
}
function deposit(uint amountToStake) public returns (bool) {
require(!ended, "Staking has ended");
require(amountToStake > 0, "Cannot deposit 0 Tokens");
require(holders.length() < maxFarmers, "Max Farmers reached");
require(Token(LPTokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToStake);
totalDeposited = totalDeposited.add(amountToStake);
lastDepositTime[msg.sender] = block.timestamp;
lastClaimTime[msg.sender] = block.timestamp;
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
}
emit Deposited(msg.sender, amountToStake);
return true;
}
function claim() public returns(bool){
require(block.timestamp.sub(lastClaimTime[msg.sender]) > claimTime, "Not yet.");
require(pending[msg.sender] > 0);
uint _reward = pending[msg.sender];
pending[msg.sender] = 0;
require(Token(tokenAddress).transfer(msg.sender, _reward), "Could not transfer tokens.");
totalClaimedRewards = totalClaimedRewards.add(_reward);
totalEarnedTokens[msg.sender] = totalEarnedTokens[msg.sender].add(_reward);
lastClaimTime[msg.sender] = block.timestamp;
return true;
}
function withdraw(uint _amount) public returns (bool){
require(block.timestamp.sub(lastDepositTime[msg.sender]) > unstakeTime || ended, "Not yet.");
require(depositedTokens[msg.sender] >= _amount);
require(_amount > 0);
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(_amount);
totalDeposited = totalDeposited.sub(_amount);
require(Token(LPTokenAddress).transfer(msg.sender, _amount), "Could not transfer tokens.");
if(depositedTokens[msg.sender] == 0 && pending[msg.sender] == 0){
holders.remove(msg.sender);
}
emit Withdrawn(msg.sender, _amount);
return true;
}
function getStakersList(uint startIndex, uint endIndex)
public
view
returns (address[] memory stakers,
uint[] memory stakedTokens) {
require (startIndex < endIndex);
uint length = endIndex.sub(startIndex);
address[] memory _stakers = new address[](length);
uint[] memory _stakedTokens = new uint[](length);
for (uint i = startIndex; i < endIndex; i = i.add(1)) {
address staker = holders.at(i);
uint listIndex = i.sub(startIndex);
_stakers[listIndex] = staker;
_stakedTokens[listIndex] = depositedTokens[staker];
}
return (_stakers, _stakedTokens);
}
// function to allow admin to claim *other* ERC20 tokens sent to this contract (by mistake)
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner returns (bool){
require (_tokenAddr != LPTokenAddress , "Cannot Transfer Out this token");
Token(_tokenAddr).transfer(_to, _amount);
return true;
}
function setDisburseAmount(uint _new) public onlyOwner returns (bool){
amountToDisburse = _new;
return true;
}
function setClaimTime(uint _new) public onlyOwner returns (bool){
claimTime = _new;
return true;
}
function setMaxFarmers(uint _new) public onlyOwner returns (bool){
maxFarmers = _new;
return true;
}
} | Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./ | function transferOwnership(address newOwner) onlyOwner public returns(bool) {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
return true;
}
| 2,293,543 |
./full_match/43113/0x891C3eD61c3c039A84D5C4C0c8E40f86dA3202D5/sources/project_/contracts/FoldStaking.sol | Used to only claim their earned rewards | function _claim(Position storage _position, address _recipient) private returns (uint256 rewardsToBeClaimed) {
Pool storage pool = pools[0];
int256 accumulatedFoldTokens = (_position.stakedAmount * uint256(pool.accumulatedRewardsPerShare)).toInt256();
rewardsToBeClaimed = (accumulatedFoldTokens - _position.rewardsDebt).toUint256() / FOLD_TOKEN_PRECISION;
_position.rewardsDebt = accumulatedFoldTokens;
if (rewardsToBeClaimed != 0) {
foldToken.transfer(_recipient, rewardsToBeClaimed);
}
}
| 7,119,085 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "./MSD.sol";
/**
* @dev Interface for Minters, minters now can be iMSD and MSDS
*/
interface IMinter {
function updateInterest() external returns (bool);
}
/**
* @title dForce's Multi-currency Stable Debt Token Controller
* @author dForce
*/
contract MSDController is Initializable, Ownable {
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/// @dev EnumerableSet of all msdTokens
EnumerableSetUpgradeable.AddressSet internal msdTokens;
// @notice Mapping of msd tokens to corresponding minters
mapping(address => EnumerableSetUpgradeable.AddressSet) internal msdMinters;
struct TokenData {
// System earning from borrow interest
uint256 earning;
// System debt from saving interest
uint256 debt;
}
// @notice Mapping of msd tokens to corresponding TokenData
mapping(address => TokenData) public msdTokenData;
/**
* @dev Emitted when `token` is added into msdTokens.
*/
event MSDAdded(address token);
/**
* @dev Emitted when `minter` is added into `tokens`'s minters.
*/
event MinterAdded(address token, address minter);
/**
* @dev Emitted when `minter` is removed from `tokens`'s minters.
*/
event MinterRemoved(address token, address minter);
/**
* @dev Emitted when `token`'s earning is added by `minter`.
*/
event MSDEarningAdded(
address token,
address minter,
uint256 earning,
uint256 totalEarning
);
/**
* @dev Emitted when `token`'s debt is added by `minter`.
*/
event MSDDebtAdded(
address token,
address minter,
uint256 debt,
uint256 totalDebt
);
/**
* @dev Emitted when reserve is withdrawn from `token`.
*/
event ReservesWithdrawn(
address owner,
address token,
uint256 amount,
uint256 oldTotalReserves,
uint256 newTotalReserves
);
/**
* @notice Expects to call only once to initialize the MSD controller.
*/
function initialize() external initializer {
__Ownable_init();
}
/**
* @notice Ensure this is a MSD Controller contract.
*/
function isMSDController() external pure returns (bool) {
return true;
}
/**
* @dev Throws if token is not in msdTokens
*/
function _checkMSD(address _token) internal view {
require(hasMSD(_token), "token is not a valid MSD token");
}
/**
* @dev Throws if token is not a valid MSD token.
*/
modifier onlyMSD(address _token) {
_checkMSD(_token);
_;
}
/**
* @dev Throws if called by any account other than the _token's minters.
*/
modifier onlyMSDMinter(address _token, address caller) {
_checkMSD(_token);
require(
msdMinters[_token].contains(caller),
"onlyMinter: caller is not the token's minter"
);
_;
}
/**
* @notice Add `_token` into msdTokens.
* If `_token` have not been in msdTokens, emits a `MSDTokenAdded` event.
*
* @param _token The token to add
* @param _minters The addresses to add as token's minters
*
* Requirements:
* - the caller must be `owner`.
*/
function _addMSD(address _token, address[] calldata _minters)
external
onlyOwner
{
require(_token != address(0), "MSD token cannot be a zero address");
if (msdTokens.add(_token)) {
emit MSDAdded(_token);
}
_addMinters(_token, _minters);
}
/**
* @notice Add `_minters` into minters.
* If `_minters` have not been in minters, emits a `MinterAdded` event.
*
* @param _minters The addresses to add as minters
*
* Requirements:
* - the caller must be `owner`.
*/
function _addMinters(address _token, address[] memory _minters)
public
onlyOwner
onlyMSD(_token)
{
uint256 _len = _minters.length;
for (uint256 i = 0; i < _len; i++) {
require(
_minters[i] != address(0),
"minter cannot be a zero address"
);
if (msdMinters[_token].add(_minters[i])) {
emit MinterAdded(_token, _minters[i]);
}
}
}
/**
* @notice Remove `minter` from minters.
* If `minter` is a minter, emits a `MinterRemoved` event.
*
* @param _minter The minter to remove
*
* Requirements:
* - the caller must be `owner`, `_token` must be a MSD Token.
*/
function _removeMinter(address _token, address _minter)
external
onlyOwner
onlyMSD(_token)
{
require(_minter != address(0), "_minter cannot be a zero address");
if (msdMinters[_token].remove(_minter)) {
emit MinterRemoved(_token, _minter);
}
}
/**
* @notice Withdraw the reserve of `_token`.
* @param _token The MSD token to withdraw
* @param _amount The amount of token to withdraw
*
* Requirements:
* - the caller must be `owner`, `_token` must be a MSD Token.
*/
function _withdrawReserves(address _token, uint256 _amount)
external
onlyOwner
onlyMSD(_token)
{
(uint256 _equity, ) = calcEquity(_token);
require(_equity >= _amount, "Token do not have enough reserve");
// Increase the token debt
msdTokenData[_token].debt = msdTokenData[_token].debt.add(_amount);
// Directly mint the token to owner
MSD(_token).mint(owner, _amount);
emit ReservesWithdrawn(
owner,
_token,
_amount,
_equity,
_equity.sub(_amount)
);
}
/**
* @notice Mint `amount` of `_token` to `_to`.
* @param _token The MSD token to mint
* @param _to The account to mint to
* @param _amount The amount of token to mint
*
* Requirements:
* - the caller must be `minter` of `_token`.
*/
function mintMSD(
address _token,
address _to,
uint256 _amount
) external onlyMSDMinter(_token, msg.sender) {
MSD(_token).mint(_to, _amount);
}
/*********************************/
/******** MSD Token Equity *******/
/*********************************/
/**
* @notice Add `amount` of debt to `_token`.
* @param _token The MSD token to add debt
* @param _debt The amount of debt to add
*
* Requirements:
* - the caller must be `minter` of `_token`.
*/
function addDebt(address _token, uint256 _debt)
external
onlyMSDMinter(_token, msg.sender)
{
msdTokenData[_token].debt = msdTokenData[_token].debt.add(_debt);
emit MSDDebtAdded(_token, msg.sender, _debt, msdTokenData[_token].debt);
}
/**
* @notice Add `amount` of earning to `_token`.
* @param _token The MSD token to add earning
* @param _earning The amount of earning to add
*
* Requirements:
* - the caller must be `minter` of `_token`.
*/
function addEarning(address _token, uint256 _earning)
external
onlyMSDMinter(_token, msg.sender)
{
msdTokenData[_token].earning = msdTokenData[_token].earning.add(
_earning
);
emit MSDEarningAdded(
_token,
msg.sender,
_earning,
msdTokenData[_token].earning
);
}
/**
* @notice Get the MSD token equity
* @param _token The MSD token to query
* @return token equity, token debt, will call `updateInterest()` on its minters
*
* Requirements:
* - `_token` must be a MSD Token.
*
*/
function calcEquity(address _token)
public
onlyMSD(_token)
returns (uint256, uint256)
{
// Call `updateInterest()` on all minters to get the latest token data
EnumerableSetUpgradeable.AddressSet storage _msdMinters =
msdMinters[_token];
uint256 _len = _msdMinters.length();
for (uint256 i = 0; i < _len; i++) {
IMinter(_msdMinters.at(i)).updateInterest();
}
TokenData storage _tokenData = msdTokenData[_token];
return
_tokenData.earning > _tokenData.debt
? (_tokenData.earning.sub(_tokenData.debt), uint256(0))
: (uint256(0), _tokenData.debt.sub(_tokenData.earning));
}
/*********************************/
/****** General Information ******/
/*********************************/
/**
* @notice Return all of the MSD tokens
* @return _allMSDs The list of MSD token addresses
*/
function getAllMSDs() public view returns (address[] memory _allMSDs) {
EnumerableSetUpgradeable.AddressSet storage _msdTokens = msdTokens;
uint256 _len = _msdTokens.length();
_allMSDs = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_allMSDs[i] = _msdTokens.at(i);
}
}
/**
* @notice Check whether a address is a valid MSD
* @param _token The token address to check for
* @return true if the _token is a valid MSD otherwise false
*/
function hasMSD(address _token) public view returns (bool) {
return msdTokens.contains(_token);
}
/**
* @notice Return all minter of a MSD token
* @param _token The MSD token address to get minters for
* @return _minters The list of MSD token minter addresses
* Will retuen empty if `_token` is not a valid MSD token
*/
function getMSDMinters(address _token)
public
view
returns (address[] memory _minters)
{
EnumerableSetUpgradeable.AddressSet storage _msdMinters =
msdMinters[_token];
uint256 _len = _msdMinters.length();
_minters = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_minters[i] = _msdMinters.at(i);
}
}
}
| Add `_minters` into minters. If `_minters` have not been in minters, emits a `MinterAdded` event. _minters The addresses to add as minters Requirements: - the caller must be `owner`./ | function _addMinters(address _token, address[] memory _minters)
public
onlyOwner
onlyMSD(_token)
{
uint256 _len = _minters.length;
for (uint256 i = 0; i < _len; i++) {
require(
_minters[i] != address(0),
"minter cannot be a zero address"
);
if (msdMinters[_token].add(_minters[i])) {
emit MinterAdded(_token, _minters[i]);
}
}
}
| 12,630,486 |
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Owned.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
date: 2018-2-26
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
An Owned contract, to be inherited by other contracts.
Requires its owner to be explicitly set in the constructor.
Provides an onlyOwner access modifier.
To change owner, the current owner must nominate the next owner,
who then has to accept the nomination. The nomination can be
cancelled before it is accepted by the new owner by having the
previous owner change the nomination (setting it to 0).
-----------------------------------------------------------------
*/
pragma solidity 0.4.24;
/**
* @title A contract with an owner.
* @notice Contract ownership can be transferred by first nominating the new owner,
* who must then accept the ownership, which prevents accidental incorrect ownership transfers.
*/
contract Owned {
address public owner;
address public nominatedOwner;
/**
* @dev Owned Constructor
*/
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
/**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
/**
* @notice Accept the nomination to be owner.
*/
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SelfDestructible.sol
version: 1.2
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be destroyed after
its owner indicates an intention and then waits for a period
without changing their mind. All ether contained in the contract
is forwarded to a nominated beneficiary upon destruction.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be destroyed by its owner after a delay elapses.
*/
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
/**
* @notice Set the beneficiary address of this contract.
* @dev Only the contract owner may call this. The provided beneficiary must be non-null.
* @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction.
*/
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
/**
* @notice Begin the self-destruction counter of this contract.
* Once the delay has elapsed, the contract may be self-destructed.
* @dev Only the contract owner may call this.
*/
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
/**
* @notice Terminate and reset the self-destruction timer.
* @dev Only the contract owner may call this.
*/
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
/**
* @notice If the self-destruction delay has elapsed, destroy this contract and
* remit any ether it owns to the beneficiary address.
* @dev Only the contract owner may call this.
*/
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Pausable.sol
version: 1.0
author: Kevin Brown
date: 2018-05-22
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be marked as
paused. It also defines a modifier which can be used by the
inheriting contract to prevent actions while paused.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be paused by its owner
*/
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused)
external
onlyOwner
{
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SafeDecimalMath.sol
version: 1.0
author: Anton Jurisevic
date: 2018-2-5
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A fixed point decimal library that provides basic mathematical
operations, and checks for unsafe arguments, for example that
would lead to overflows.
Exceptions are thrown whenever those unsafe operations
occur.
-----------------------------------------------------------------
*/
/**
* @title Safely manipulate unsigned fixed-point decimals at a given precision level.
* @dev Functions accepting uints in this contract and derived contracts
* are taken to be such fixed point decimals (including fiat, ether, and nomin quantities).
*/
contract SafeDecimalMath {
/* Number of decimal places in the representation. */
uint8 public constant decimals = 18;
/* The number representing 1.0. */
uint public constant UNIT = 10 ** uint(decimals);
/**
* @return True iff adding x and y will not overflow.
*/
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
/**
* @return The result of adding x and y, throwing an exception in case of overflow.
*/
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y, "Safe add failed");
return x + y;
}
/**
* @return True iff subtracting y from x will not overflow in the negative direction.
*/
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
/**
* @return The result of subtracting y from x, throwing an exception in case of overflow.
*/
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x, "Safe sub failed");
return x - y;
}
/**
* @return True iff multiplying x and y would not overflow.
*/
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
/**
* @return The result of multiplying x and y, throwing an exception in case of overflow.
*/
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y, "Safe mul failed");
return p;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals. Throws an exception in case of overflow.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256.
* Incidentally, the internal division always rounds down: one could have rounded to the nearest integer,
* but then one would be spending a significant fraction of a cent (of order a microether
* at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands
* contain small enough fractional components. It would also marginally diminish the
* domain this function is defined upon.
*/
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Divide by UNIT to remove the extra factor introduced by the product. */
return safeMul(x, y) / UNIT;
}
/**
* @return True iff the denominator of x/y is nonzero.
*/
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
/**
* @return The result of dividing x by y, throwing an exception if the divisor is zero.
*/
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
/* Although a 0 denominator already throws an exception,
* it is equivalent to a THROW operation, which consumes all gas.
* A require statement emits REVERT instead, which remits remaining gas. */
require(y != 0, "Denominator cannot be zero");
return x / y;
}
/**
* @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers.
* @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT.
* Internal rounding is downward: a similar caveat holds as with safeDecMul().
*/
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Reintroduce the UNIT factor that will be divided out by y. */
return safeDiv(safeMul(x, UNIT), y);
}
/**
* @dev Convert an unsigned integer to a unsigned fixed-point decimal.
* Throw an exception if the result would be out of range.
*/
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: State.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: TokenState.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract that holds the state of an ERC20 compliant token.
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token State
* @notice Stores balance information of an ERC20 token contract.
*/
contract TokenState is State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _associatedContract The ERC20 contract whose state this composes.
*/
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxy.sol
version: 1.3
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxy contract that, if it does not recognise the function
being called on it, passes all value and call data to an
underlying target contract.
This proxy has the capacity to toggle between DELEGATECALL
and CALL style proxy functionality.
The former executes in the proxy's context, and so will preserve
msg.sender and store data at the proxy address. The latter will not.
Therefore, any contract the proxy wraps in the CALL style must
implement the Proxyable interface, in order that it can pass msg.sender
into the underlying contract as the state parameter, messageSender.
-----------------------------------------------------------------
*/
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics,
bytes32 topic1, bytes32 topic2,
bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
/* Copy call data into free memory region. */
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* Forward all gas and call data to the target contract. */
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
/* Revert if the call failed, otherwise return the result. */
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
/* Here we are as above, but must send the messageSender explicitly
* since we are using CALL rather than DELEGATECALL. */
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxyable.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxyable contract that works hand in hand with the Proxy contract
to allow for anyone to interact with the underlying contract both
directly and through the proxy.
-----------------------------------------------------------------
*/
// This contract should be treated like an abstract contract
contract Proxyable is Owned {
/* The proxy this contract exists behind. */
Proxy public proxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.0
author: Kevin Brown
date: 2018-08-06
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract offers a modifer that can prevent reentrancy on
particular actions. It will not work if you put it on multiple
functions that can be called from each other. Specifically guard
external entry points to the contract with the modifier only.
-----------------------------------------------------------------
*/
contract ReentrancyPreventer {
/* ========== MODIFIERS ========== */
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A partial ERC20 token contract, designed to operate with a proxy.
To produce a complete ERC20 token, transfer and transferFrom
tokens must be implemented, using the provided _byProxy internal
functions.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state and designed to operate behind a proxy.
*/
contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, ReentrancyPreventer {
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields.
* Note that the decimals field is defined in SafeDecimalMath.*/
string public name;
string public symbol;
uint public totalSupply;
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _tokenState The TokenState contract address.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
tokenState = _tokenState;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value)
internal
preventReentrancy
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value));
/*
If we're transferring to a contract and it implements the havvenTokenFallback function, call it.
This isn't ERC223 compliant because:
1. We don't revert if the contract doesn't implement havvenTokenFallback.
This is because many DEXes and other contracts that expect to work with the standard
approve / transferFrom workflow don't implement tokenFallback but can still process our tokens as
usual, so it feels very harsh and likely to cause trouble if we add this restriction after having
previously gone live with a vanilla ERC20.
2. We don't pass the bytes parameter.
This is because of this solidity bug: https://github.com/ethereum/solidity/issues/2884
3. We also don't let the user use a custom tokenFallback. We figure as we're already not standards
compliant, there won't be a use case where users can't just implement our specific function.
As such we've called the function havvenTokenFallback to be clear that we are not following the standard.
*/
// Is the to address a contract? We can check the code size on that address and know.
uint length;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Retrieve the size of the code on the recipient address
length := extcodesize(to)
}
// If there's code there, it's a contract
if (length > 0) {
// Now we need to optionally call havvenTokenFallback(address from, uint value).
// We can't call it the normal way because that reverts when the recipient doesn't implement the function.
// We'll use .call(), which means we need the function selector. We've pre-computed
// abi.encodeWithSignature("havvenTokenFallback(address,uint256)"), to save some gas.
// solium-disable-next-line security/no-low-level-calls
to.call(0xcbff5d96, messageSender, value);
// And yes, we specifically don't care if this call fails, so we're not checking the return value.
}
// Emit a standard ERC20 transfer event
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transfer_byProxy(address from, address to, uint value)
internal
returns (bool)
{
return _internalTransfer(from, to, value);
}
/**
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: FeeToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A token which also has a configurable fee rate
charged on its transfers. This is designed to be overridden in
order to produce an ERC20-compliant token.
These fees accrue into a pool, from which a nominated authority
may withdraw.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state.
* Additionally charges fees on each transfer.
*/
contract FeeToken is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* ERC20 members are declared in ExternStateToken. */
/* A percentage fee charged on each transfer. */
uint public transferFeeRate;
/* Fee may not exceed 10%. */
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
/* The address with the authority to distribute fees. */
address public feeAuthority;
/* The address that fees will be pooled in. */
address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _transferFeeRate The fee rate to charge on transfers.
* @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply,
uint _transferFeeRate, address _feeAuthority, address _owner)
ExternStateToken(_proxy, _tokenState,
_name, _symbol, _totalSupply,
_owner)
public
{
feeAuthority = _feeAuthority;
/* Constructed transfer fee rate should respect the maximum fee rate. */
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate");
transferFeeRate = _transferFeeRate;
}
/* ========== SETTERS ========== */
/**
* @notice Set the transfer fee, anywhere within the range 0-10%.
* @dev The fee rate is in decimal format, with UNIT being the value of 100%.
*/
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE");
transferFeeRate = _transferFeeRate;
emitTransferFeeRateUpdated(_transferFeeRate);
}
/**
* @notice Set the address of the user/contract responsible for collecting or
* distributing fees.
*/
function setFeeAuthority(address _feeAuthority)
public
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
/* ========== VIEWS ========== */
/**
* @notice Calculate the Fee charged on top of a value being sent
* @return Return the fee charged
*/
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
/* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
* This is on the basis that transfers less than this value will result in a nil fee.
* Probably too insignificant to worry about, but the following code will achieve it.
* if (fee == 0 && transferFeeRate != 0) {
* return _value;
* }
* return fee;
*/
}
/**
* @notice The value that you would need to send so that the recipient receives
* a specified value.
*/
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
/**
* @notice The amount the recipient will receive if you send a certain number of tokens.
*/
function amountReceived(uint value)
public
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
/**
* @notice Collected fees sit here until they are distributed.
* @dev The balance of the nomin contract itself is the fee pool.
*/
function feePool()
external
view
returns (uint)
{
return tokenState.balanceOf(FEE_ADDRESS);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Base of transfer functions
*/
function _internalTransfer(address from, address to, uint amount, uint fee)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee)));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee));
/* Emit events for both the transfer itself and the fee. */
emitTransfer(from, to, amount);
emitTransfer(from, FEE_ADDRESS, fee);
return true;
}
/**
* @notice ERC20 friendly transfer function.
*/
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
return _internalTransfer(sender, to, received, fee);
}
/**
* @notice ERC20 friendly transferFrom function.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is deducted from the amount sent. */
uint received = amountReceived(value);
uint fee = safeSub(value, received);
/* Reduce the allowance by the amount we're transferring.
* The safeSub call will handle an insufficient allowance. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, received, fee);
}
/**
* @notice Ability to transfer where the sender pays the fees (not ERC20)
*/
function _transferSenderPaysFee_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
return _internalTransfer(sender, to, value, fee);
}
/**
* @notice Ability to transferFrom where they sender pays the fees (not ERC20).
*/
function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
uint total = safeAdd(value, fee);
/* Reduce the allowance by the amount we're transferring. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total));
return _internalTransfer(from, to, value, fee);
}
/**
* @notice Withdraw tokens from the fee pool into a given account.
* @dev Only the fee authority may call this.
*/
function withdrawFees(address account, uint value)
external
onlyFeeAuthority
returns (bool)
{
require(account != address(0), "Must supply an account address to withdraw fees");
/* 0-value withdrawals do nothing. */
if (value == 0) {
return false;
}
/* Safe subtraction ensures an exception is thrown if the balance is insufficient. */
tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value));
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value));
emitFeesWithdrawn(account, value);
emitTransfer(FEE_ADDRESS, account, value);
return true;
}
/**
* @notice Donate tokens from the sender's balance into the fee pool.
*/
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
/* Empty donations are disallowed. */
uint balance = tokenState.balanceOf(sender);
require(balance != 0, "Must have a balance in order to donate to the fee pool");
/* safeSub ensures the donor has sufficient balance. */
tokenState.setBalanceOf(sender, safeSub(balance, n));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n));
emitFeesDonated(sender, n);
emitTransfer(sender, FEE_ADDRESS, n);
return true;
}
/* ========== MODIFIERS ========== */
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority, "Only the fee authority can do this action");
_;
}
/* ========== EVENTS ========== */
event TransferFeeRateUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)");
function emitTransferFeeRateUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0);
}
event FeeAuthorityUpdated(address newFeeAuthority);
bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event FeesDonated(address indexed donor, uint value);
bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)");
function emitFeesDonated(address donor, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Nomin.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven-backed nomin stablecoin contract.
This contract issues nomins, which are tokens worth 1 USD each.
Nomins are issuable by Havven holders who have to lock up some
value of their havvens to issue H * Cmax nomins. Where Cmax is
some value less than 1.
A configurable fee is charged on nomin transfers and deposited
into a common pot, which havven holders may withdraw from once
per fee period.
-----------------------------------------------------------------
*/
contract Nomin is FeeToken {
/* ========== STATE VARIABLES ========== */
Havven public havven;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
// Nomin transfers incur a 15 bp fee by default.
uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000;
string constant TOKEN_NAME = "Nomin USD";
string constant TOKEN_SYMBOL = "nUSD";
/* ========== CONSTRUCTOR ========== */
constructor(address _proxy, TokenState _tokenState, Havven _havven,
uint _totalSupply,
address _owner)
FeeToken(_proxy, _tokenState,
TOKEN_NAME, TOKEN_SYMBOL, _totalSupply,
TRANSFER_FEE_RATE,
_havven, // The havven contract is the fee authority.
_owner)
public
{
require(_proxy != 0, "_proxy cannot be 0");
require(address(_havven) != 0, "_havven cannot be 0");
require(_owner != 0, "_owner cannot be 0");
// It should not be possible to transfer to the fee pool directly (or confiscate its balance).
frozen[FEE_ADDRESS] = true;
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
optionalProxy_onlyOwner
{
// havven should be set as the feeAuthority after calling this depending on
// havven's internal logic
havven = _havven;
setFeeAuthority(_havven);
emitHavvenUpdated(_havven);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFrom_byProxy(messageSender, from, to, value);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferSenderPaysFee_byProxy(messageSender, to, value);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address");
frozen[target] = false;
emitAccountUnfrozen(target);
}
/* Allow havven to issue a certain number of
* nomins from an account. */
function issue(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount));
totalSupply = safeAdd(totalSupply, amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
/* Allow havven to burn a certain number of
* nomins from an account. */
function burn(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount));
totalSupply = safeSub(totalSupply, amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
/* ========== MODIFIERS ========== */
modifier onlyHavven() {
require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)");
function emitHavvenUpdated(address newHavven) internal {
proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0);
}
event AccountFrozen(address indexed target, uint balance);
bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)");
function emitAccountFrozen(address target, uint balance) internal {
proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0);
}
event AccountUnfrozen(address indexed target);
bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)");
function emitAccountUnfrozen(address target) internal {
proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0);
}
event Issued(address indexed account, uint amount);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint amount);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: LimitedSetup.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract with a limited setup period. Any function modified
with the setup modifier will cease to work after the
conclusion of the configurable-length post-construction setup period.
-----------------------------------------------------------------
*/
/**
* @title Any function decorated with the modifier this contract provides
* deactivates after a specified setup period.
*/
contract LimitedSetup {
uint setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: HavvenEscrow.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
Mike Spain
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows the foundation to apply unique vesting
schedules to havven funds sold at various discounts in the token
sale. HavvenEscrow gives users the ability to inspect their
vested funds, their quantities and vesting dates, and to withdraw
the fees that accrue on those funds.
The fees are handled by withdrawing the entire fee allocation
for all havvens inside the escrow contract, and then allowing
the contract itself to subdivide that pool up proportionally within
itself. Every time the fee period rolls over in the main Havven
contract, the HavvenEscrow fee pool is remitted back into the
main fee pool to be redistributed in the next fee period.
-----------------------------------------------------------------
*/
/**
* @title A contract to hold escrowed havvens and free them at given schedules.
*/
contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) {
/* The corresponding Havven contract. */
Havven public havven;
/* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
* These are the times at which each given quantity of havvens vests. */
mapping(address => uint[2][]) public vestingSchedules;
/* An account's total vested havven balance to save recomputing this for fee extraction purposes. */
mapping(address => uint) public totalVestedAccountBalance;
/* The total remaining vested balance, for verifying the actual havven balance of this contract against. */
uint public totalVestedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
/* Limit vesting entries to disallow unbounded iteration over vesting schedules. */
uint constant MAX_VESTING_ENTRIES = 20;
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return A pair of uints: (timestamp, havven quantity).
*/
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
/**
* @notice Get the time at which a given schedule entry will vest.
*/
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
/**
* @notice Get the quantity of havvens associated with a given schedule entry.
*/
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
/**
* @notice Obtain the index of the next schedule entry that will vest for a given user.
*/
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/**
* @notice Obtain the next schedule entry that will vest for a given user.
* @return A pair of uints: (timestamp, havven quantity). */
function getNextVestingEntry(address account)
public
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/**
* @notice Obtain the time at which the next schedule entry will vest for a given user.
*/
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
/**
* @notice Obtain the quantity which the next schedule entry will vest for a given user.
*/
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Withdraws a quantity of havvens back to the havven contract.
* @dev This may only be called by the owner during the contract's setup period.
*/
function withdrawHavvens(uint quantity)
external
onlyOwner
onlyDuringSetup
{
havven.transfer(havven, quantity);
}
/**
* @notice Destroy the vesting information associated with an account.
*/
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as correctly calculating
* the fees.
* This may only be called by the owner during the contract's setup period.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only in the foundation's command to add to these lists.
* @param account The account to append a new vesting entry to.
* @param time The absolute unix timestamp after which the vested quantity may be withdrawn.
* @param quantity The quantity of havvens that will vest.
*/
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
onlyDuringSetup
{
/* No empty or already-passed vesting entries allowed. */
require(now < time, "Time must be in the future");
require(quantity != 0, "Quantity cannot be zero");
/* There must be enough balance in the contract to provide for the vesting entry. */
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry");
/* Disallow arbitrarily long vesting schedules in light of the gas limit. */
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long");
if (scheduleLength == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
/* Disallow adding new vested havvens earlier than the last one.
* Since entries are only appended, this means that no vesting date can be repeated. */
require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one");
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
/**
* @notice Construct a vesting schedule to release a quantities of havvens
* over a series of intervals.
* @dev Assumes that the quantities are nonzero
* and that the sequence of timestamps is strictly increasing.
* This may only be called by the owner during the contract's setup period.
*/
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
onlyDuringSetup
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
/**
* @notice Allow a user to withdraw any havvens in their schedule that have vested.
*/
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
/* The list is sorted; when we reach the first future time, bail out. */
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
event Vested(address indexed beneficiary, uint time, uint value);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Havven.sol
version: 1.2
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven token contract. Havvens are transferable ERC20 tokens,
and also give their holders the following privileges.
An owner of havvens may participate in nomin confiscation votes, they
may also have the right to issue nomins at the discretion of the
foundation for this version of the contract.
After a fee period terminates, the duration and fees collected for that
period are computed, and the next period begins. Thus an account may only
withdraw the fees owed to them for the previous period, and may only do
so once per period. Any unclaimed fees roll over into the common pot for
the next period.
== Average Balance Calculations ==
The fee entitlement of a havven holder is proportional to their average
issued nomin balance over the last fee period. This is computed by
measuring the area under the graph of a user's issued nomin balance over
time, and then when a new fee period begins, dividing through by the
duration of the fee period.
We need only update values when the balances of an account is modified.
This occurs when issuing or burning for issued nomin balances,
and when transferring for havven balances. This is for efficiency,
and adds an implicit friction to interacting with havvens.
A havven holder pays for his own recomputation whenever he wants to change
his position, which saves the foundation having to maintain a pot dedicated
to resourcing this.
A hypothetical user's balance history over one fee period, pictorially:
s ____
| |
| |___ p
|____|___|___ __ _ _
f t n
Here, the balance was s between times f and t, at which time a transfer
occurred, updating the balance to p, until n, when the present transfer occurs.
When a new transfer occurs at time n, the balance being p,
we must:
- Add the area p * (n - t) to the total area recorded so far
- Update the last transfer time to n
So if this graph represents the entire current fee period,
the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f).
The complementary computations must be performed for both sender and
recipient.
Note that a transfer keeps global supply of havvens invariant.
The sum of all balances is constant, and unmodified by any transfer.
So the sum of all balances multiplied by the duration of a fee period is also
constant, and this is equivalent to the sum of the area of every user's
time/balance graph. Dividing through by that duration yields back the total
havven supply. So, at the end of a fee period, we really do yield a user's
average share in the havven supply over that period.
A slight wrinkle is introduced if we consider the time r when the fee period
rolls over. Then the previous fee period k-1 is before r, and the current fee
period k is afterwards. If the last transfer took place before r,
but the latest transfer occurred afterwards:
k-1 | k
s __|_
| | |
| | |____ p
|__|_|____|___ __ _ _
|
f | t n
r
In this situation the area (r-f)*s contributes to fee period k-1, while
the area (t-r)*s contributes to fee period k. We will implicitly consider a
zero-value transfer to have occurred at time r. Their fee entitlement for the
previous period will be finalised at the time of their first transfer during the
current fee period, or when they query or withdraw their fee entitlement.
In the implementation, the duration of different fee periods may be slightly irregular,
as the check that they have rolled over occurs only when state-changing havven
operations are performed.
== Issuance and Burning ==
In this version of the havven contract, nomins can only be issued by
those that have been nominated by the havven foundation. Nomins are assumed
to be valued at $1, as they are a stable unit of account.
All nomins issued require a proportional value of havvens to be locked,
where the proportion is governed by the current issuance ratio. This
means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued.
i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up.
To determine the value of some amount of havvens(H), an oracle is used to push
the price of havvens (P_H) in dollars to the contract. The value of H
would then be: H * P_H.
Any havvens that are locked up by this issuance process cannot be transferred.
The amount that is locked floats based on the price of havvens. If the price
of havvens moves up, less havvens are locked, so they can be issued against,
or transferred freely. If the price of havvens moves down, more havvens are locked,
even going above the initial wallet balance.
-----------------------------------------------------------------
*/
/**
* @title Havven ERC20 contract.
* @notice The Havven contracts does not only facilitate transfers and track balances,
* but it also computes the quantity of fees each havven holder is entitled to.
*/
contract Havven is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* A struct for handing values associated with average balance calculations */
struct IssuanceData {
/* Sums of balances*duration in the current fee period.
/* range: decimals; units: havven-seconds */
uint currentBalanceSum;
/* The last period's average balance */
uint lastAverageBalance;
/* The last time the data was calculated */
uint lastModified;
}
/* Issued nomin balances for individual fee entitlements */
mapping(address => IssuanceData) public issuanceData;
/* The total number of issued nomins for determining fee entitlements */
IssuanceData public totalIssuanceData;
/* The time the current fee period began */
uint public feePeriodStartTime;
/* The time the last fee period began */
uint public lastFeePeriodStartTime;
/* Fee periods will roll over in no shorter a time than this.
* The fee period cannot actually roll over until a fee-relevant
* operation such as withdrawal or a fee period duration update occurs,
* so this is just a target, and the actual duration may be slightly longer. */
uint public feePeriodDuration = 4 weeks;
/* ...and must target between 1 day and six months. */
uint constant MIN_FEE_PERIOD_DURATION = 1 days;
uint constant MAX_FEE_PERIOD_DURATION = 26 weeks;
/* The quantity of nomins that were in the fee pot at the time */
/* of the last fee rollover, at feePeriodStartTime. */
uint public lastFeesCollected;
/* Whether a user has withdrawn their last fees */
mapping(address => bool) public hasWithdrawnFees;
Nomin public nomin;
HavvenEscrow public escrow;
/* The address of the oracle which pushes the havven price to this contract */
address public oracle;
/* The price of havvens written in UNIT */
uint public price;
/* The time the havven price was last updated */
uint public lastPriceUpdateTime;
/* How long will the contract assume the price of havvens is correct */
uint public priceStalePeriod = 3 hours;
/* A quantity of nomins greater than this ratio
* may not be issued against a given value of havvens. */
uint public issuanceRatio = UNIT / 5;
/* No more nomins may be issued than the value of havvens backing them. */
uint constant MAX_ISSUANCE_RATIO = UNIT;
/* Whether the address can issue nomins or not. */
mapping(address => bool) public isIssuer;
/* The number of currently-outstanding nomins the user has issued. */
mapping(address => uint) public nominsIssued;
uint constant HAVVEN_SUPPLY = 1e8 * UNIT;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
string constant TOKEN_NAME = "Havven";
string constant TOKEN_SYMBOL = "HAV";
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _tokenState A pre-populated contract containing token balances.
* If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle,
uint _price, address[] _issuers, Havven _oldHavven)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner)
public
{
oracle = _oracle;
price = _price;
lastPriceUpdateTime = now;
uint i;
if (_oldHavven == address(0)) {
feePeriodStartTime = now;
lastFeePeriodStartTime = now - feePeriodDuration;
for (i = 0; i < _issuers.length; i++) {
isIssuer[_issuers[i]] = true;
}
} else {
feePeriodStartTime = _oldHavven.feePeriodStartTime();
lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime();
uint cbs;
uint lab;
uint lm;
(cbs, lab, lm) = _oldHavven.totalIssuanceData();
totalIssuanceData.currentBalanceSum = cbs;
totalIssuanceData.lastAverageBalance = lab;
totalIssuanceData.lastModified = lm;
for (i = 0; i < _issuers.length; i++) {
address issuer = _issuers[i];
isIssuer[issuer] = true;
uint nomins = _oldHavven.nominsIssued(issuer);
if (nomins == 0) {
// It is not valid in general to skip those with no currently-issued nomins.
// But for this release, issuers with nonzero issuanceData have current issuance.
continue;
}
(cbs, lab, lm) = _oldHavven.issuanceData(issuer);
nominsIssued[issuer] = nomins;
issuanceData[issuer].currentBalanceSum = cbs;
issuanceData[issuer].lastAverageBalance = lab;
issuanceData[issuer].lastModified = lm;
}
}
}
/* ========== SETTERS ========== */
/**
* @notice Set the associated Nomin contract to collect fees from.
* @dev Only the contract owner may call this.
*/
function setNomin(Nomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
emitNominUpdated(_nomin);
}
/**
* @notice Set the associated havven escrow contract.
* @dev Only the contract owner may call this.
*/
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
emitEscrowUpdated(_escrow);
}
/**
* @notice Set the targeted fee period duration.
* @dev Only callable by the contract owner. The duration must fall within
* acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period
* may roll over if the target duration was shortened sufficiently.
*/
function setFeePeriodDuration(uint duration)
external
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION,
"Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION");
feePeriodDuration = duration;
emitFeePeriodDurationUpdated(duration);
rolloverFeePeriodIfElapsed();
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
*/
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emitOracleUpdated(_oracle);
}
/**
* @notice Set the stale period on the updated havven price
* @dev No max/minimum, as changing it wont influence anything but issuance by the foundation
*/
function setPriceStalePeriod(uint time)
external
optionalProxy_onlyOwner
{
priceStalePeriod = time;
}
/**
* @notice Set the issuanceRatio for issuance calculations.
* @dev Only callable by the contract owner.
*/
function setIssuanceRatio(uint _issuanceRatio)
external
optionalProxy_onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emitIssuanceRatioUpdated(_issuanceRatio);
}
/**
* @notice Set whether the specified can issue nomins or not.
*/
function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
/* ========== VIEWS ========== */
function issuanceCurrentBalanceSum(address account)
external
view
returns (uint)
{
return issuanceData[account].currentBalanceSum;
}
function issuanceLastAverageBalance(address account)
external
view
returns (uint)
{
return issuanceData[account].lastAverageBalance;
}
function issuanceLastModified(address account)
external
view
returns (uint)
{
return issuanceData[account].lastModified;
}
function totalIssuanceCurrentBalanceSum()
external
view
returns (uint)
{
return totalIssuanceData.currentBalanceSum;
}
function totalIssuanceLastAverageBalance()
external
view
returns (uint)
{
return totalIssuanceData.lastAverageBalance;
}
function totalIssuanceLastModified()
external
view
returns (uint)
{
return totalIssuanceData.lastModified;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice ERC20 transfer function.
*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens");
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transfer_byProxy(sender, to, value);
return true;
}
/**
* @notice ERC20 transferFrom function.
*/
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens");
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transferFrom_byProxy(sender, from, to, value);
return true;
}
/**
* @notice Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account.
*/
function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
/* Do not deposit fees into frozen accounts. */
require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts");
/* Check the period has rolled over first. */
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
/* Only allow accounts to withdraw fees once per period. */
require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period");
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
/* Sender receives a share of last period's collected fees proportional
* with their average fraction of the last period's issued nomins. */
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
}
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
/**
* @notice Update the havven balance averages since the last transfer
* or entitlement adjustment.
* @dev Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call.
* Also, this will adjust the total issuance at the same time.
*/
function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply)
internal
{
/* update the total balances first */
totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData);
if (issuanceData[account].lastModified < feePeriodStartTime) {
hasWithdrawnFees[account] = false;
}
issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]);
}
/**
* @notice Compute the new IssuanceData on the old balance
*/
function computeIssuanceData(uint preBalance, IssuanceData preIssuance)
internal
view
returns (IssuanceData)
{
uint currentBalanceSum = preIssuance.currentBalanceSum;
uint lastAverageBalance = preIssuance.lastAverageBalance;
uint lastModified = preIssuance.lastModified;
if (lastModified < feePeriodStartTime) {
if (lastModified < lastFeePeriodStartTime) {
/* The balance was last updated before the previous fee period, so the average
* balance in this period is their pre-transfer balance. */
lastAverageBalance = preBalance;
} else {
/* The balance was last updated during the previous fee period. */
/* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified.
* implies these quantities are strictly positive. */
uint timeUpToRollover = feePeriodStartTime - lastModified;
uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime;
uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover));
lastAverageBalance = lastBalanceSum / lastFeePeriodDuration;
}
/* Roll over to the next fee period. */
currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime);
} else {
/* The balance was last updated during the current fee period. */
currentBalanceSum = safeAdd(
currentBalanceSum,
safeMul(preBalance, now - lastModified)
);
}
return IssuanceData(currentBalanceSum, lastAverageBalance, now);
}
/**
* @notice Recompute and return the given account's last average balance.
*/
function recomputeLastAverageBalance(address account)
external
returns (uint)
{
updateIssuanceData(account, nominsIssued[account], nomin.totalSupply());
return issuanceData[account].lastAverageBalance;
}
/**
* @notice Issue nomins against the sender's havvens.
* @dev Issuance is only allowed if the havven price isn't stale and the sender is an issuer.
*/
function issueNomins(uint amount)
public
optionalProxy
requireIssuer(messageSender)
/* No need to check if price is stale, as it is checked in issuableNomins. */
{
address sender = messageSender;
require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins");
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.issue(sender, amount);
nominsIssued[sender] = safeAdd(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function issueMaxNomins()
external
optionalProxy
{
issueNomins(remainingIssuableNomins(messageSender));
}
/**
* @notice Burn nomins to clear issued nomins/free havvens.
*/
function burnNomins(uint amount)
/* it doesn't matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/
external
optionalProxy
{
address sender = messageSender;
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
/* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */
nomin.burn(sender, amount);
/* This safe sub ensures amount <= number issued */
nominsIssued[sender] = safeSub(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
/**
* @notice Check if the fee period has rolled over. If it has, set the new fee period start
* time, and record the fees collected in the nomin contract.
*/
function rolloverFeePeriodIfElapsed()
public
{
/* If the fee period has rolled over... */
if (now >= feePeriodStartTime + feePeriodDuration) {
lastFeesCollected = nomin.feePool();
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emitFeePeriodRollover(now);
}
}
/* ========== Issuance/Burning ========== */
/**
* @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any
* already issued nomins.
*/
function maxIssuableNomins(address issuer)
view
public
priceNotStale
returns (uint)
{
if (!isIssuer[issuer]) {
return 0;
}
if (escrow != HavvenEscrow(0)) {
uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer));
return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio);
} else {
return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio);
}
}
/**
* @notice The remaining nomins an issuer can issue against their total havven quantity.
*/
function remainingIssuableNomins(address issuer)
view
public
returns (uint)
{
uint issued = nominsIssued[issuer];
uint max = maxIssuableNomins(issuer);
if (issued > max) {
return 0;
} else {
return safeSub(max, issued);
}
}
/**
* @notice The total havvens owned by this account, both escrowed and unescrowed,
* against which nomins can be issued.
* This includes those already being used as collateral (locked), and those
* available for further issuance (unlocked).
*/
function collateral(address account)
public
view
returns (uint)
{
uint bal = tokenState.balanceOf(account);
if (escrow != address(0)) {
bal = safeAdd(bal, escrow.balanceOf(account));
}
return bal;
}
/**
* @notice The collateral that would be locked by issuance, which can exceed the account's actual collateral.
*/
function issuanceDraft(address account)
public
view
returns (uint)
{
uint issued = nominsIssued[account];
if (issued == 0) {
return 0;
}
return USDtoHAV(safeDiv_dec(issued, issuanceRatio));
}
/**
* @notice Collateral that has been locked due to issuance, and cannot be
* transferred to other addresses. This is capped at the account's total collateral.
*/
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
/**
* @notice Collateral that is not locked and available for issuance.
*/
function unlockedCollateral(address account)
public
view
returns (uint)
{
uint locked = lockedCollateral(account);
uint collat = collateral(account);
return safeSub(collat, locked);
}
/**
* @notice The number of havvens that are free to be transferred by an account.
* @dev If they have enough available Havvens, it could be that
* their havvens are escrowed, however the transfer would then
* fail. This means that escrowed havvens are locked first,
* and then the actual transferable ones.
*/
function transferableHavvens(address account)
public
view
returns (uint)
{
uint draft = issuanceDraft(account);
uint collat = collateral(account);
// In the case where the issuanceDraft exceeds the collateral, nothing is free
if (draft > collat) {
return 0;
}
uint bal = balanceOf(account);
// In the case where the draft exceeds the escrow, but not the whole collateral
// return the fraction of the balance that remains free
if (draft > safeSub(collat, bal)) {
return safeSub(collat, draft);
}
// In the case where the draft doesn't exceed the escrow, return the entire balance
return bal;
}
/**
* @notice The value in USD for a given amount of HAV
*/
function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(hav_dec, price);
}
/**
* @notice The value in HAV for a given amount of USD
*/
function USDtoHAV(uint usd_dec)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(usd_dec, price);
}
/**
* @notice Access point for the oracle to update the price of havvens.
*/
function updatePrice(uint newPrice, uint timeSent)
external
onlyOracle /* Should be callable only by the oracle. */
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
price = newPrice;
lastPriceUpdateTime = timeSent;
emitPriceUpdated(newPrice, timeSent);
/* Check the fee period rollover within this as the price should be pushed every 15min. */
rolloverFeePeriodIfElapsed();
}
/**
* @notice Check if the price of havvens hasn't been updated for longer than the stale period.
*/
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/* ========== MODIFIERS ========== */
modifier requireIssuer(address account)
{
require(isIssuer[account], "Must be issuer to perform this action");
_;
}
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier priceNotStale
{
require(!priceIsStale(), "Price must not be stale to perform this action");
_;
}
/* ========== EVENTS ========== */
event PriceUpdated(uint newPrice, uint timestamp);
bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)");
function emitPriceUpdated(uint newPrice, uint timestamp) internal {
proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0);
}
event IssuanceRatioUpdated(uint newRatio);
bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)");
function emitIssuanceRatioUpdated(uint newRatio) internal {
proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0);
}
event FeePeriodRollover(uint timestamp);
bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)");
function emitFeePeriodRollover(uint timestamp) internal {
proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint duration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint duration) internal {
proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event OracleUpdated(address newOracle);
bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)");
function emitOracleUpdated(address newOracle) internal {
proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0);
}
event NominUpdated(address newNomin);
bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)");
function emitNominUpdated(address newNomin) internal {
proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0);
}
event EscrowUpdated(address newEscrow);
bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)");
function emitEscrowUpdated(address newEscrow) internal {
proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0);
}
event IssuersUpdated(address indexed account, bool indexed value);
bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)");
function emitIssuersUpdated(address account, bool value) internal {
proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION -----------------------------------------------------------------
file: IssuanceController.sol
version: 2.0
author: Kevin Brown
date: 2018-07-18
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Issuance controller contract. The issuance controller provides
a way for users to acquire nomins (Nomin.sol) and havvens
(Havven.sol) by paying ETH and a way for users to acquire havvens
(Havven.sol) by paying nomins. Users can also deposit their nomins
and allow other users to purchase them with ETH. The ETH is sent
to the user who offered their nomins for sale.
This smart contract contains a balance of each currency, and
allows the owner of the contract (the Havven Foundation) to
manage the available balance of havven at their discretion, while
users are allowed to deposit and withdraw their own nomin deposits
if they have not yet been taken up by another user.
-----------------------------------------------------------------
*/
/**
* @title Issuance Controller Contract.
*/
contract IssuanceController is SafeDecimalMath, SelfDestructible, Pausable {
/* ========== STATE VARIABLES ========== */
Havven public havven;
Nomin public nomin;
// Address where the ether raised is transfered to
address public fundsWallet;
/* The address of the oracle which pushes the USD price havvens and ether to this contract */
address public oracle;
/* Do not allow the oracle to submit times any further forward into the future than
this constant. */
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
/* How long will the contract assume the price of any asset is correct */
uint public priceStalePeriod = 3 hours;
/* The time the prices were last updated */
uint public lastPriceUpdateTime;
/* The USD price of havvens denominated in UNIT */
uint public usdToHavPrice;
/* The USD price of ETH denominated in UNIT */
uint public usdToEthPrice;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _owner The owner of this contract.
* @param _fundsWallet The recipient of ETH and Nomins that are sent to this contract while exchanging.
* @param _havven The Havven contract we'll interact with for balances and sending.
* @param _nomin The Nomin contract we'll interact with for balances and sending.
* @param _oracle The address which is able to update price information.
* @param _usdToEthPrice The current price of ETH in USD, expressed in UNIT.
* @param _usdToHavPrice The current price of Havven in USD, expressed in UNIT.
*/
constructor(
// Ownable
address _owner,
// Funds Wallet
address _fundsWallet,
// Other contracts needed
Havven _havven,
Nomin _nomin,
// Oracle values - Allows for price updates
address _oracle,
uint _usdToEthPrice,
uint _usdToHavPrice
)
/* Owned is initialised in SelfDestructible */
SelfDestructible(_owner)
Pausable(_owner)
public
{
fundsWallet = _fundsWallet;
havven = _havven;
nomin = _nomin;
oracle = _oracle;
usdToEthPrice = _usdToEthPrice;
usdToHavPrice = _usdToHavPrice;
lastPriceUpdateTime = now;
}
/* ========== SETTERS ========== */
/**
* @notice Set the funds wallet where ETH raised is held
* @param _fundsWallet The new address to forward ETH and Nomins to
*/
function setFundsWallet(address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
emit FundsWalletUpdated(fundsWallet);
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
* @param _oracle The new oracle address
*/
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
/**
* @notice Set the Nomin contract that the issuance controller uses to issue Nomins.
* @param _nomin The new nomin contract target
*/
function setNomin(Nomin _nomin)
external
onlyOwner
{
nomin = _nomin;
emit NominUpdated(_nomin);
}
/**
* @notice Set the Havven contract that the issuance controller uses to issue Havvens.
* @param _havven The new havven contract target
*/
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/**
* @notice Set the stale period on the updated price variables
* @param _time The new priceStalePeriod
*/
function setPriceStalePeriod(uint _time)
external
onlyOwner
{
priceStalePeriod = _time;
emit PriceStalePeriodUpdated(priceStalePeriod);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Access point for the oracle to update the prices of havvens / eth.
* @param newEthPrice The current price of ether in USD, specified to 18 decimal places.
* @param newHavvenPrice The current price of havvens in USD, specified to 18 decimal places.
* @param timeSent The timestamp from the oracle when the transaction was created. This ensures we don't consider stale prices as current in times of heavy network congestion.
*/
function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent)
external
onlyOracle
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
usdToEthPrice = newEthPrice;
usdToHavPrice = newHavvenPrice;
lastPriceUpdateTime = timeSent;
emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime);
}
/**
* @notice Fallback function (exchanges ETH to nUSD)
*/
function ()
external
payable
{
exchangeEtherForNomins();
}
/**
* @notice Exchange ETH to nUSD.
*/
function exchangeEtherForNomins()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Nomins (nUSD) received
{
// The multiplication works here because usdToEthPrice is specified in
// 18 decimal places, just like our currency base.
uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice);
// Store the ETH in our funds wallet
fundsWallet.transfer(msg.value);
// Send the nomins.
// Note: Fees are calculated by the Nomin contract, so when
// we request a specific transfer here, the fee is
// automatically deducted and sent to the fee pool.
nomin.transfer(msg.sender, requestedToPurchase);
emit Exchange("ETH", msg.value, "nUSD", requestedToPurchase);
return requestedToPurchase;
}
/**
* @notice Exchange ETH to nUSD while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param guaranteedRate The exchange rate (ether price) which must be honored or the call will revert.
*/
function exchangeEtherForNominsAtRate(uint guaranteedRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Nomins (nUSD) received
{
require(guaranteedRate == usdToEthPrice);
return exchangeEtherForNomins();
}
/**
* @notice Exchange ETH to HAV.
*/
function exchangeEtherForHavvens()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
// How many Havvens are they going to be receiving?
uint havvensToSend = havvensReceivedForEther(msg.value);
// Store the ETH in our funds wallet
fundsWallet.transfer(msg.value);
// And send them the Havvens.
havven.transfer(msg.sender, havvensToSend);
emit Exchange("ETH", msg.value, "HAV", havvensToSend);
return havvensToSend;
}
/**
* @notice Exchange ETH to HAV while insisting on a particular set of rates. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rates.
* @param guaranteedEtherRate The ether exchange rate which must be honored or the call will revert.
* @param guaranteedHavvenRate The havven exchange rate which must be honored or the call will revert.
*/
function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
require(guaranteedEtherRate == usdToEthPrice);
require(guaranteedHavvenRate == usdToHavPrice);
return exchangeEtherForHavvens();
}
/**
* @notice Exchange nUSD for Havvens
* @param nominAmount The amount of nomins the user wishes to exchange.
*/
function exchangeNominsForHavvens(uint nominAmount)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
// How many Havvens are they going to be receiving?
uint havvensToSend = havvensReceivedForNomins(nominAmount);
// Ok, transfer the Nomins to our address.
nomin.transferFrom(msg.sender, this, nominAmount);
// And send them the Havvens.
havven.transfer(msg.sender, havvensToSend);
emit Exchange("nUSD", nominAmount, "HAV", havvensToSend);
return havvensToSend;
}
/**
* @notice Exchange nUSD for Havvens while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param nominAmount The amount of nomins the user wishes to exchange.
* @param guaranteedRate A rate (havven price) the caller wishes to insist upon.
*/
function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
require(guaranteedRate == usdToHavPrice);
return exchangeNominsForHavvens(nominAmount);
}
/**
* @notice Allows the owner to withdraw havvens from this contract if needed.
* @param amount The amount of havvens to attempt to withdraw (in 18 decimal places).
*/
function withdrawHavvens(uint amount)
external
onlyOwner
{
havven.transfer(owner, amount);
// We don't emit our own events here because we assume that anyone
// who wants to watch what the Issuance Controller is doing can
// just watch ERC20 events from the Nomin and/or Havven contracts
// filtered to our address.
}
/**
* @notice Withdraw nomins: Allows the owner to withdraw nomins from this contract if needed.
* @param amount The amount of nomins to attempt to withdraw (in 18 decimal places).
*/
function withdrawNomins(uint amount)
external
onlyOwner
{
nomin.transfer(owner, amount);
// We don't emit our own events here because we assume that anyone
// who wants to watch what the Issuance Controller is doing can
// just watch ERC20 events from the Nomin and/or Havven contracts
// filtered to our address.
}
/* ========== VIEWS ========== */
/**
* @notice Check if the prices haven't been updated for longer than the stale period.
*/
function pricesAreStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/**
* @notice Calculate how many havvens you will receive if you transfer
* an amount of nomins.
* @param amount The amount of nomins (in 18 decimal places) you want to ask about
*/
function havvensReceivedForNomins(uint amount)
public
view
returns (uint)
{
// How many nomins would we receive after the transfer fee?
uint nominsReceived = nomin.amountReceived(amount);
// And what would that be worth in havvens based on the current price?
return safeDiv_dec(nominsReceived, usdToHavPrice);
}
/**
* @notice Calculate how many havvens you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function havvensReceivedForEther(uint amount)
public
view
returns (uint)
{
// How much is the ETH they sent us worth in nUSD (ignoring the transfer fee)?
uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice);
// Now, how many HAV will that USD amount buy?
return havvensReceivedForNomins(valueSentInNomins);
}
/**
* @notice Calculate how many nomins you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function nominsReceivedForEther(uint amount)
public
view
returns (uint)
{
// How many nomins would that amount of ether be worth?
uint nominsTransferred = safeMul_dec(amount, usdToEthPrice);
// And how many of those would you receive after a transfer (deducting the transfer fee)
return nomin.amountReceived(nominsTransferred);
}
/* ========== MODIFIERS ========== */
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier pricesNotStale
{
require(!pricesAreStale(), "Prices must not be stale to perform this action");
_;
}
/* ========== EVENTS ========== */
event FundsWalletUpdated(address newFundsWallet);
event OracleUpdated(address newOracle);
event NominUpdated(Nomin newNominContract);
event HavvenUpdated(Havven newHavvenContract);
event PriceStalePeriodUpdated(uint priceStalePeriod);
event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent);
event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount);
} | Exchange nUSD for Havvens while insisting on a particular rate. This allows a user to exchange while protecting against frontrunning by the contract owner on the exchange rate. nominAmount The amount of nomins the user wishes to exchange. guaranteedRate A rate (havven price) the caller wishes to insist upon./ | function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate)
public
pricesNotStale
notPaused
{
require(guaranteedRate == usdToHavPrice);
return exchangeNominsForHavvens(nominAmount);
}
| 2,140,246 |
pragma solidity ^0.5.4;
library Counters {
using SafeMath for uint256;
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 {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
interface IERC165 {
/**
* @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);
}
contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/*
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 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;
}
}
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply = 1e6;
constructor() public {
_balances[msg.sender] = 1e6;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A 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 to 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) {
_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) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
contract IERC721 is IERC165 {
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 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 memory data) public;
}
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _INTERFACE_ID_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)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId));
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
require(!_exists(tokenId));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
require(to != address(0));
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke `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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract OathForge is ERC721, ERC721Metadata, Ownable {
using SafeMath for uint256;
uint256 private _totalSupply;
uint256 private _nextTokenId;
mapping(uint256 => uint256) private _sunsetInitiatedAt;
mapping(uint256 => uint256) private _sunsetLength;
mapping(uint256 => uint256) private _redemptionCodeHashSubmittedAt;
mapping(uint256 => bytes32) private _redemptionCodeHash;
mapping(address => bool) private _isBlacklisted;
/// @param name The ERC721 Metadata name
/// @param symbol The ERC721 Metadata symbol
constructor(string memory name, string memory symbol) ERC721Metadata(name, symbol) public {}
/// @dev Emits when a sunset has been initiated
/// @param tokenId The token id
event SunsetInitiated(uint256 indexed tokenId);
/// @dev Emits when a redemption code hash has been submitted
/// @param tokenId The token id
/// @param redemptionCodeHash The redemption code hash
event RedemptionCodeHashSubmitted(uint256 indexed tokenId, bytes32 redemptionCodeHash);
/// @dev Returns the total number of tokens (minted - burned) registered
function totalSupply() external view returns(uint256){
return _totalSupply;
}
/// @dev Returns the token id of the next minted token
function nextTokenId() external view returns(uint256){
return _nextTokenId;
}
/// @dev Returns if an address is blacklisted
/// @param to The address to check
function isBlacklisted(address to) external view returns(bool){
return _isBlacklisted[to];
}
/// @dev Returns the timestamp at which a token's sunset was initated. Returns 0 if no sunset has been initated.
/// @param tokenId The token id
function sunsetInitiatedAt(uint256 tokenId) external view returns(uint256){
return _sunsetInitiatedAt[tokenId];
}
/// @dev Returns the sunset length of a token
/// @param tokenId The token id
function sunsetLength(uint256 tokenId) external view returns(uint256){
return _sunsetLength[tokenId];
}
/// @dev Returns the redemption code hash submitted for a token
/// @param tokenId The token id
function redemptionCodeHash(uint256 tokenId) external view returns(bytes32){
return _redemptionCodeHash[tokenId];
}
/// @dev Returns the timestamp at which a redemption code hash was submitted
/// @param tokenId The token id
function redemptionCodeHashSubmittedAt(uint256 tokenId) external view returns(uint256){
return _redemptionCodeHashSubmittedAt[tokenId];
}
/// @dev Mint a token. Only `owner` may call this function.
/// @param to The receiver of the token
/// @param tokenURI The tokenURI of the the tokenURI
/// @param __sunsetLength The length (in seconds) that a sunset period can last
function mint(address to, string memory tokenURI, uint256 __sunsetLength) public onlyOwner {
_mint(to, _nextTokenId);
_sunsetLength[_nextTokenId] = __sunsetLength;
_setTokenURI(_nextTokenId, tokenURI);
_nextTokenId = _nextTokenId.add(1);
_totalSupply = _totalSupply.add(1);
}
/// @dev Initiate a sunset. Sets `sunsetInitiatedAt` to current timestamp. Only `owner` may call this function.
/// @param tokenId The id of the token
function initiateSunset(uint256 tokenId) external onlyOwner {
require(tokenId < _nextTokenId);
require(_sunsetInitiatedAt[tokenId] == 0);
_sunsetInitiatedAt[tokenId] = now;
emit SunsetInitiated(tokenId);
}
/// @dev Submit a redemption code hash for a specific token. Burns the token. Sets `redemptionCodeHashSubmittedAt` to current timestamp. Decreases `totalSupply` by 1.
/// @param tokenId The id of the token
/// @param __redemptionCodeHash The redemption code hash
function submitRedemptionCodeHash(uint256 tokenId, bytes32 __redemptionCodeHash) external {
_burn(msg.sender, tokenId);
_redemptionCodeHashSubmittedAt[tokenId] = now;
_redemptionCodeHash[tokenId] = __redemptionCodeHash;
_totalSupply = _totalSupply.sub(1);
emit RedemptionCodeHashSubmitted(tokenId, __redemptionCodeHash);
}
/// @dev Transfers the ownership of a given token ID to another address. Usage of this method is discouraged, use `safeTransferFrom` whenever possible. Requires the msg sender to be the owner, approved, or operator
/// @param from current owner of the token
/// @param to address to receive the ownership of the given token ID
/// @param tokenId uint256 ID of the token to be transferred
function transferFrom(address from, address to, uint256 tokenId) public {
require(!_isBlacklisted[to]);
if (_sunsetInitiatedAt[tokenId] > 0) {
require(now <= _sunsetInitiatedAt[tokenId].add(_sunsetLength[tokenId]));
}
super.transferFrom(from, to, tokenId);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
require(!_isBlacklisted[to]);
super.approve(to, tokenId);
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(!_isBlacklisted[to]);
super.setApprovalForAll(to, approved);
}
/// @dev Set `tokenUri`. Only `owner` may do this.
/// @param tokenId The id of the token
/// @param tokenURI The token URI
function setTokenURI(uint256 tokenId, string calldata tokenURI) external onlyOwner {
_setTokenURI(tokenId, tokenURI);
}
/// @dev Set if an address is blacklisted
/// @param to The address to change
/// @param __isBlacklisted True if the address should be blacklisted, false otherwise
function setIsBlacklisted(address to, bool __isBlacklisted) external onlyOwner {
_isBlacklisted[to] = __isBlacklisted;
}
}
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
library Address {
/**
* 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 account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) 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.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
contract RiftPact is ERC20, Ownable, ReentrancyGuard {
using SafeMath for uint256;
uint256 private _parentTokenId;
uint256 private _auctionAllowedAt;
address private _currencyAddress;
address private _parentToken;
uint256 private _minAuctionCompleteWait;
uint256 private _minBidDeltaPermille;
uint256 private _auctionStartedAt;
uint256 private _auctionCompletedAt;
uint256 private _minBid = 1;
uint256 private _topBid;
address private _topBidder;
uint256 private _topBidSubmittedAt;
mapping(address => bool) private _isBlacklisted;
/// @param __parentToken The address of the OathForge contract
/// @param __parentTokenId The id of the token on the OathForge contract
/// @param __totalSupply The total supply
/// @param __currencyAddress The address of the currency contract
/// @param __auctionAllowedAt The timestamp at which anyone can start an auction
/// @param __minAuctionCompleteWait The minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed
/// @param __minBidDeltaPermille The minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be
constructor(
address __parentToken,
uint256 __parentTokenId,
uint256 __totalSupply,
address __currencyAddress,
uint256 __auctionAllowedAt,
uint256 __minAuctionCompleteWait,
uint256 __minBidDeltaPermille
) public {
_parentToken = __parentToken;
_parentTokenId = __parentTokenId;
_currencyAddress = __currencyAddress;
_auctionAllowedAt = __auctionAllowedAt;
_minAuctionCompleteWait = __minAuctionCompleteWait;
_minBidDeltaPermille = __minBidDeltaPermille;
_mint(msg.sender, __totalSupply);
}
/// @dev Emits when an auction is started
event AuctionStarted();
/// @dev Emits when the auction is completed
/// @param bid The final bid price of the auction
/// @param winner The winner of the auction
event AuctionCompleted(address winner, uint256 bid);
/// @dev Emits when there is a bid
/// @param bid The bid
/// @param bidder The address of the bidder
event Bid(address bidder, uint256 bid);
/// @dev Emits when there is a payout
/// @param to The address of the account paying out
/// @param balance The balance of `to` prior to the paying out
event Payout(address to, uint256 balance);
/// @dev Returns the OathForge contract address. **UI should check for phishing.**.
function parentToken() external view returns(address) {
return _parentToken;
}
/// @dev Returns the OathForge token id. **Does not imply RiftPact has ownership over token.**
function parentTokenId() external view returns(uint256) {
return _parentTokenId;
}
/// @dev Returns the currency contract address.
function currencyAddress() external view returns(address) {
return _currencyAddress;
}
/// @dev Returns the minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed.
function minAuctionCompleteWait() external view returns(uint256) {
return _minAuctionCompleteWait;
}
/// @dev Returns the minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be
function minBidDeltaPermille() external view returns(uint256) {
return _minBidDeltaPermille;
}
/// @dev Returns the timestamp at which anyone can start an auction by calling [`startAuction()`](#startAuction())
function auctionAllowedAt() external view returns(uint256) {
return _auctionAllowedAt;
}
/// @dev Returns the minimum bid in currency
function minBid() external view returns(uint256) {
return _minBid;
}
/// @dev Returns the timestamp at which an auction was started or 0 if no auction has been started
function auctionStartedAt() external view returns(uint256) {
return _auctionStartedAt;
}
/// @dev Returns the timestamp at which an auction was completed or 0 if no auction has been completed
function auctionCompletedAt() external view returns(uint256) {
return _auctionCompletedAt;
}
/// @dev Returns the top bid or 0 if no bids have been placed
function topBid() external view returns(uint256) {
return _topBid;
}
/// @dev Returns the top bidder or `address(0)` if no bids have been placed
function topBidder() external view returns(address) {
return _topBidder;
}
/// @dev Start an auction
function startAuction() external nonReentrant {
require(_auctionStartedAt == 0);
require(
(now >= _auctionAllowedAt)
|| (OathForge(_parentToken).sunsetInitiatedAt(_parentTokenId) > 0)
);
emit AuctionStarted();
_auctionStartedAt = now;
}
/// @dev Submit a bid. Must have sufficient funds approved in currency contract (bid * totalSupply).
/// @param bid Bid in currency
function submitBid(uint256 bid) external nonReentrant {
require(_auctionStartedAt > 0);
require(_auctionCompletedAt == 0);
require(bid >= _minBid);
emit Bid(msg.sender, bid);
uint256 _totalSupply = totalSupply();
if (_topBidder != address(0)) {
/// NOTE: This has been commented out because it's wrong since we don't want to send the total supply multiplied by the bid
/* require(ERC20(_currencyAddress).transfer(_topBidder, _topBid * _totalSupply)); */
require(ERC20(_currencyAddress).transfer(_topBidder, _topBid));
}
/// NOTE: This has been commented out because it's wrong since we don't want to send the total supply multiplied by the bid
/* require(ERC20(_currencyAddress).transferFrom(msg.sender, address(this), bid * _totalSupply)); */
require(ERC20(_currencyAddress).transferFrom(msg.sender, address(this), bid));
_topBid = bid;
_topBidder = msg.sender;
_topBidSubmittedAt = now;
/* 3030 * 10 = 30300
delta = 30300 / 1000 = 30,3
30300 % 1000 = 300 > 0, yes
roundUp = 1
minBid = 3030 + 30 + 1 which is wrong, it should be 3060 instead of 3061 */
uint256 minBidNumerator = bid * _minBidDeltaPermille;
uint256 minBidDelta = minBidNumerator / 1000;
uint256 minBidRoundUp = 0;
/// NOTE commented out because it doesn't work as expected with big bids
/* if((bid * _minBidDeltaPermille) % 1000 > 0) {
minBidRoundUp = 1;
} */
if((bid * _minBidDeltaPermille) < 1000) {
minBidRoundUp = 1;
}
_minBid = bid + minBidDelta + minBidRoundUp;
}
/// @dev Complete auction
function completeAuction() external {
require(_auctionCompletedAt == 0);
require(_topBid > 0);
require((_topBidSubmittedAt + _minAuctionCompleteWait) < now);
emit AuctionCompleted(_topBidder, _topBid);
_auctionCompletedAt = now;
}
/// @dev Payout `currency` after auction completed
function payout() external nonReentrant {
uint256 balance = balanceOf(msg.sender);
require(balance > 0);
require(_auctionCompletedAt > 0);
emit Payout(msg.sender, balance);
/// NOTE this won't work since we can't send more tokens than what's already in this contract
/* require(ERC20(_currencyAddress).transfer(msg.sender, balance * _topBid)); */
require(ERC20(_currencyAddress).transfer(msg.sender, _topBid));
/// NOTE Remove this since the sender doesn't have any riftPact tokens inside this contract so we can't burn them.
/* _burn(msg.sender, balance); */
}
/// @dev Returns if an address is blacklisted
/// @param to The address to check
function isBlacklisted(address to) external view returns(bool){
return _isBlacklisted[to];
}
/// @dev Set if an address is blacklisted
/// @param to The address to change
/// @param __isBlacklisted True if the address should be blacklisted, false otherwise
function setIsBlacklisted(address to, bool __isBlacklisted) external onlyOwner {
_isBlacklisted[to] = __isBlacklisted;
}
/**
* @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(!_isBlacklisted[to]);
return super.transfer(to, value);
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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(!_isBlacklisted[to]);
return super.transferFrom(from, to, value);
}
/**
* @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) {
if (value > 0) {
require(!_isBlacklisted[spender]);
}
return super.approve(spender, value);
}
/**
* @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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(!_isBlacklisted[spender]);
return super.increaseAllowance(spender, addedValue);
}
}
| Transfer tokens from one address to another. Note that while this function emits an Approval event, this is not required as per the specification, and other compliant implementations may not emit the event. from address The address which you want to send tokens from to address The address which you want to transfer to value uint256 the amount of tokens to be transferred/ | function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(!_isBlacklisted[to]);
return super.transferFrom(from, to, value);
}
| 5,390,945 |
./full_match/7700/0xaE51A21554986434303D999660aEfd8f8D9b2658/sources/contracts/FukkenClown69ButtsOnCanto721.sol | Do you own this butt? You can have it a simple on-chain variation rather than the more delightful traditionally hosted version. | function toggleOnChainButtSituation(uint256 tokenId) external {
if(ownerOf(tokenId) != msg.sender){
revert NoAccess();
}
onChainTokenIds[tokenId] = !onChainTokenIds[tokenId];
}
| 4,654,552 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./TestFramework.sol";
//////////////////////////////////////////////
////// TestCrowdfunding helper contracts /////
//////////////////////////////////////////////
contract Investor {
Crowdfunding private crowdfunding;
// Allow contract to receive money.
receive() external payable {}
fallback() external payable {}
constructor(Crowdfunding _crowdfunding) {
crowdfunding = _crowdfunding;
}
function invest(uint256 amount) public returns (bool) {
(bool success, ) = address(crowdfunding).call{value : amount, gas : 200000}(abi.encodeWithSignature("invest()"));
return success;
}
function refund() public returns (bool) {
(bool success, ) = address(crowdfunding).call{gas : 200000}(abi.encodeWithSignature("refund()"));
return success;
}
function claimFunds() public returns (bool) {
(bool success, ) = address(crowdfunding).call{gas : 200000}(abi.encodeWithSignature("claimFunds()"));
return success;
}
}
contract FounderCrowdfunding {
event PrintEvent(string msg);
Crowdfunding private crowdfunding;
// Allow contract to receive money.
receive() external payable {}
fallback() external payable {}
function setCrowdfunding(Crowdfunding _crowdfunding) public {
crowdfunding = _crowdfunding;
}
function claimFunds() public returns (bool) {
(bool success, ) = address(crowdfunding).call{gas:200000}(abi.encodeWithSignature("claimFunds()"));
return success;
}
}
//////////////////////////////////////////////
//////// TestAuction helper contracts ////////
//////////////////////////////////////////////
contract SimpleAuction is Auction {
// constructor
constructor(
address _sellerAddress,
address _judgeAddress,
Timer _timer
) payable Auction(_sellerAddress, _judgeAddress, _timer) {}
function finish(Auction.Outcome _outcome, address _highestBidder) public {
// This is for the test purposes and exposes finish auction to outside.
finishAuction(_outcome, _highestBidder);
}
// Allow contract to receive money.
receive() external payable {}
fallback() external payable {}
}
contract Participant {
Auction auction;
constructor() {}
function setAuction(Auction _auction) public {
auction = _auction;
}
//wrapped call
function callFinalize() public returns (bool) {
(bool success, ) = address(auction).call{gas : 200000}(abi.encodeWithSignature("finalize()"));
return success;
}
//wrapped call
function callRefund() public returns (bool) {
(bool success, ) = address(auction).call{gas : 200000}(abi.encodeWithSignature("refund()"));
return success;
}
// Allow contract to receive money.
receive() external payable {}
fallback() external payable {}
}
//////////////////////////////////////////////
///// TestEnglishAuction helper contract /////
//////////////////////////////////////////////
contract EngAuctionBidder { // lowercase as test naming convention
EnglishAuction auction;
constructor(EnglishAuction _auction) {
auction = _auction;
}
//wrapped call
function bid(uint bidValue) public returns (bool){
(bool success, ) = address(auction).call{value : bidValue, gas : 200000}(abi.encodeWithSignature("bid()"));
return success;
}
// Allow contract to receive money.
receive() external payable {}
fallback() external payable {}
}
//////////////////////////////////////////////
////// TestDutchAuction helper contract //////
//////////////////////////////////////////////
contract DutchAuctionBidder { // lowercase as test naming convention
DutchAuction auction;
// Allow contract to receive money.
receive() external payable {}
fallback() external payable {}
constructor(DutchAuction _auction) {
auction = _auction;
}
//wrapped call
function bid(uint bidValue) public returns (bool) {
(bool success, ) = address(auction).call{value : bidValue,gas : 2000000}(abi.encodeWithSignature("bid()"));
return success;
}
} | This is for the test purposes and exposes finish auction to outside. | function finish(Auction.Outcome _outcome, address _highestBidder) public {
finishAuction(_outcome, _highestBidder);
}
| 14,101,615 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Signature.sol";
contract TGE is Ownable, Signature {
using SafeERC20 for IERC20;
/** @dev Terms and conditions as a keccak256 hash */
string public constant termsAndConditions =
"By signing this message I agree to the $FOREX TOKEN - TERMS AND CONDITIONS identified by the hash: 0x1b42a1c6369d3efbf3b65d757e3f5e804bc26935b45dda1eaf0d90ef297289b4";
/** @dev ERC-191 encoded Terms and Conditions for signature validation */
bytes32 private constant termsAndConditionsERC191 =
keccak256(
abi.encodePacked(
bytes1(0x19),
bytes1("E"),
bytes("thereum Signed Message:\n165"),
abi.encodePacked(termsAndConditions)
)
);
/** @dev Error message for claiming before allowed period */
string private constant notClaimable = "Funds not yet claimable";
/** @dev The amount of FOREX to be generated */
uint256 public constant forexAmount = 20_760_000 ether;
/** @dev The address of this contract's deployed instance */
address private immutable self;
/** @dev Canonical FOREX token address */
address public immutable FOREX;
/** @dev Per-user deposit cap */
uint256 public immutable userCap;
/** @dev Minimum token price in ETH (soft cap parameter) */
uint256 public minTokenPrice;
/** @dev Maximum token price in ETH (if hard cap is met) */
uint256 public maxTokenPrice;
/** @dev Generation duration (seconds) */
uint256 public immutable generationDuration;
/** @dev Start date for the generation; when ETH deposits are accepted */
uint256 public immutable generationStartDate;
/** @dev Maximum deposit cap in ETH from which new deposits are ignored */
uint256 public depositCap;
/** @dev Date from when FOREX claiming is allowed */
uint256 public claimDate;
/** @dev Amount of ETH deposited during the TGE */
uint256 public ethDeposited;
/** @dev Mapping of (depositor => eth amount) for the TGE period */
mapping(address => uint256) private deposits;
/** @dev Mapping of (depositor => T&Cs signature status) */
mapping(address => bool) public signedTermsAndConditions;
/** @dev Mapping of (depositor => claimed eth) */
mapping(address => bool) private claimedEth;
/** @dev Mapping of (depositor => claimed forex) */
mapping(address => bool) private claimedForex;
/** @dev The total ETH deposited under a referral address */
mapping(address => uint256) public referrerDeposits;
/** @dev Number of depositors */
uint256 public depositorCount;
/** @dev Whether leftover FOREX tokens were withdrawn by owner
(only possible if FOREX did not reach the max price) */
bool private withdrawnRemainingForex;
/** @dev Whether the TGE was aborted by the owner */
bool private aborted;
/** @dev ETH withdrawn by owner */
uint256 public ethWithdrawnByOwner;
modifier notAborted() {
require(!aborted, "TGE aborted");
_;
}
constructor(
address _FOREX,
uint256 _userCap,
uint256 _depositCap,
uint256 _minTokenPrice,
uint256 _maxTokenPrice,
uint256 _generationDuration,
uint256 _generationStartDate
) {
require(_generationDuration > 0, "Duration must be > 0");
require(
_generationStartDate > block.timestamp,
"Start date must be in the future"
);
self = address(this);
FOREX = _FOREX;
userCap = _userCap;
depositCap = _depositCap;
minTokenPrice = _minTokenPrice;
maxTokenPrice = _maxTokenPrice;
generationDuration = _generationDuration;
generationStartDate = _generationStartDate;
}
/**
* @dev Deny direct ETH transfers.
*/
receive() external payable {
revert("Must call deposit to participate");
}
/**
* @dev Validates a signature for the hashed terms & conditions message.
* The T&Cs hash is converted to an ERC-191 message before verifying.
* @param signature The signature to validate.
*/
function signTermsAndConditions(bytes memory signature) public {
if (signedTermsAndConditions[msg.sender]) return;
address signer = getSignatureAddress(
termsAndConditionsERC191,
signature
);
require(signer == msg.sender, "Invalid signature");
signedTermsAndConditions[msg.sender] = true;
}
/**
* @dev Allow incoming ETH transfers during the TGE period.
*/
function deposit(address referrer, bytes memory signature)
external
payable
notAborted
{
// Sign T&Cs if the signature is not empty.
// User must pass a valid signature before the first deposit.
if (signature.length != 0) signTermsAndConditions(signature);
// Assert that the user can deposit.
require(signedTermsAndConditions[msg.sender], "Must sign T&Cs");
require(hasTgeBeenStarted(), "TGE has not started yet");
require(!hasTgeEnded(), "TGE has finished");
uint256 currentDeposit = deposits[msg.sender];
// Revert if the user cap or TGE cap has already been met.
require(currentDeposit < userCap, "User cap met");
require(ethDeposited < depositCap, "TGE deposit cap met");
// Assert that the deposit amount is greater than zero.
uint256 deposit = msg.value;
assert(deposit > 0);
// Increase the depositorCount if first deposit by user.
if (currentDeposit == 0) depositorCount++;
if (currentDeposit + deposit > userCap) {
// Ensure deposit over user cap is returned.
safeSendEth(msg.sender, currentDeposit + deposit - userCap);
// Adjust user deposit.
deposit = userCap - currentDeposit;
} else if (ethDeposited + deposit > depositCap) {
// Ensure deposit over TGE cap is returned.
safeSendEth(msg.sender, ethDeposited + deposit - depositCap);
// Adjust user deposit.
deposit -= ethDeposited + deposit - depositCap;
}
// Only contribute to referrals if the hard cap hasn't been met yet.
uint256 hardCap = ethHardCap();
if (ethDeposited < hardCap) {
uint256 referralDepositAmount = deposit;
// Subtract surplus from hard cap if any.
if (ethDeposited + deposit > hardCap)
referralDepositAmount -= ethDeposited + deposit - hardCap;
referrerDeposits[referrer] += referralDepositAmount;
}
// Increase deposit variables.
ethDeposited += deposit;
deposits[msg.sender] += deposit;
}
/**
* @dev Claim depositor funds (FOREX and ETH) once the TGE has closed.
This may be called right after TGE closing for withdrawing surplus
ETH (if FOREX reached max price/hard cap) or once (again when) the
claim period starts for claiming both FOREX along with any surplus.
*/
function claim() external notAborted {
require(hasTgeEnded(), notClaimable);
(uint256 forex, uint256 forexReferred, uint256 eth) = balanceOf(
msg.sender
);
// Revert here if there's no ETH to withdraw as the FOREX claiming
// period may not have yet started.
require(eth > 0 || isTgeClaimable(), notClaimable);
forex += forexReferred;
// Claim forex only if the claimable period has started.
if (isTgeClaimable() && forex > 0) claimForex(forex);
// Claim ETH hardcap surplus if available.
if (eth > 0) claimEthSurplus(eth);
}
/**
* @dev Claims ETH for user.
* @param eth The amount of ETH to claim.
*/
function claimEthSurplus(uint256 eth) private {
if (claimedEth[msg.sender]) return;
claimedEth[msg.sender] = true;
if (eth > 0) safeSendEth(msg.sender, eth);
}
/**
* @dev Claims FOREX for user.
* @param forex The amount of FOREX to claim.
*/
function claimForex(uint256 forex) private {
if (claimedForex[msg.sender]) return;
claimedForex[msg.sender] = true;
IERC20(FOREX).safeTransfer(msg.sender, forex);
}
/**
* @dev Withdraws leftover forex in case the hard cap is not met during TGE.
*/
function withdrawRemainingForex(address recipient) external onlyOwner {
assert(!withdrawnRemainingForex);
// Revert if the TGE has not ended.
require(hasTgeEnded(), "TGE has not finished");
(uint256 forexClaimable, ) = getClaimableData();
uint256 remainingForex = forexAmount - forexClaimable;
withdrawnRemainingForex = true;
// Add address zero (null) referrals to withdrawal.
remainingForex += getReferralForexAmount(address(0));
if (remainingForex == 0) return;
IERC20(FOREX).safeTransfer(recipient, remainingForex);
}
/**
* @dev Returns an account's balance of claimable forex, referral forex,
and ETH.
* @param account The account to fetch the claimable balance for.
*/
function balanceOf(address account)
public
view
returns (
uint256 forex,
uint256 forexReferred,
uint256 eth
)
{
if (!hasTgeEnded()) return (0, 0, 0);
(uint256 forexClaimable, uint256 ethClaimable) = getClaimableData();
uint256 share = shareOf(account);
eth = claimedEth[account] ? 0 : (ethClaimable * share) / (1 ether);
if (claimedForex[account]) {
forex = 0;
forexReferred = 0;
} else {
forex = (forexClaimable * share) / (1 ether);
// Forex earned through referrals is 5% of the referred deposits
// in FOREX.
forexReferred = getReferralForexAmount(account);
}
}
/**
* @dev Returns an account's share over the TGE deposits.
* @param account The account to fetch the share for.
* @return Share value as an 18 decimal ratio. 1 ether = 100%.
*/
function shareOf(address account) public view returns (uint256) {
if (ethDeposited == 0) return 0;
return (deposits[account] * (1 ether)) / ethDeposited;
}
/**
* @dev Returns the ETH deposited by an address.
* @param depositor The depositor address.
*/
function getDeposit(address depositor) external view returns (uint256) {
return deposits[depositor];
}
/**
* @dev Whether the TGE already started. It could be closed even if
this function returns true.
*/
function hasTgeBeenStarted() private view returns (bool) {
return block.timestamp >= generationStartDate;
}
/**
* @dev Whether the TGE has ended and is closed for new deposits.
*/
function hasTgeEnded() private view returns (bool) {
return block.timestamp > generationStartDate + generationDuration;
}
/**
* @dev Whether the TGE funds can be claimed.
*/
function isTgeClaimable() private view returns (bool) {
return claimDate != 0 && block.timestamp >= claimDate;
}
/**
* @dev The amount of ETH required to generate all supply at max price.
*/
function ethHardCap() private view returns (uint256) {
return (forexAmount * maxTokenPrice) / (1 ether);
}
/**
* @dev Returns the forex price as established by the deposit amount.
* The formula for the price is the following:
* minPrice + ([maxPrice - minPrice] * min(deposit, maxDeposit)/maxDeposit)
* Where maxDeposit = ethHardCap()
*/
function forexPrice() public view returns (uint256) {
uint256 hardCap = ethHardCap();
uint256 depositTowardsHardCap = ethDeposited > hardCap
? hardCap
: ethDeposited;
uint256 priceRange = maxTokenPrice - minTokenPrice;
uint256 priceDelta = (priceRange * depositTowardsHardCap) / hardCap;
return minTokenPrice + priceDelta;
}
/**
* @dev Returns TGE data to be used for claims once the TGE closes.
*/
function getClaimableData()
private
view
returns (uint256 forexClaimable, uint256 ethClaimable)
{
assert(hasTgeEnded());
uint256 forexPrice = forexPrice();
uint256 hardCap = ethHardCap();
// ETH is only claimable if the deposits exceeded the hard cap.
ethClaimable = ethDeposited > hardCap ? ethDeposited - hardCap : 0;
// Forex is claimable up to the maximum supply -- when deposits match
// the hard cap amount.
forexClaimable =
((ethDeposited - ethClaimable) * (1 ether)) /
forexPrice;
}
/**
* @dev Returns the amount of FOREX earned by a referrer.
* @param referrer The referrer's address.
*/
function getReferralForexAmount(address referrer)
private
view
returns (uint256)
{
// Referral claims are disabled.
return 0;
}
/**
* @dev Aborts the TGE, stopping new deposits and withdrawing all funds
* for the owner.
* The only use case for this function is in the
* event of an emergency.
*/
function emergencyAbort() external onlyOwner {
assert(!aborted);
aborted = true;
emergencyWithdrawAllFunds();
}
/**
* @dev Withdraws all contract funds for the owner.
* The only use case for this function is in the
* event of an emergency.
*/
function emergencyWithdrawAllFunds() public onlyOwner {
// Transfer ETH.
uint256 balance = self.balance;
if (balance > 0) safeSendEth(msg.sender, balance);
// Transfer FOREX.
IERC20 forex = IERC20(FOREX);
balance = forex.balanceOf(self);
if (balance > 0) forex.transfer(msg.sender, balance);
}
/**
* @dev Withdraws all ETH funds for the owner.
* This function may be called at any time, as it correctly
* withdraws only the correct contribution amount, ignoring
* the ETH amount to be refunded if the deposits exceed
* the hard cap.
*/
function collectContributions() public onlyOwner {
uint256 hardCap = ethHardCap();
require(
ethWithdrawnByOwner < hardCap,
"Cannot withdraw more than hard cap amount"
);
uint256 amount = self.balance;
if (amount + ethWithdrawnByOwner > hardCap)
amount = hardCap - ethWithdrawnByOwner;
ethWithdrawnByOwner += amount;
require(amount > 0, "Nothing available for withdrawal");
safeSendEth(msg.sender, amount);
}
/**
* @dev Enables FOREX claiming from the next block.
* Requires the TGE to have been closed.
*/
function enableForexClaims() external onlyOwner {
assert(hasTgeEnded() && !isTgeClaimable());
claimDate = block.timestamp + 1;
}
/**
* @dev Sets the minimum and maximum token prices before the TGE starts.
* Also sets the deposit cap.
* @param min The minimum token price in ETH.
* @param max The maximum token price in ETH.
* @param _depositCap The ETH deposit cap.
*/
function setMinMaxForexPrices(
uint256 min,
uint256 max,
uint256 _depositCap
) external onlyOwner {
assert(!hasTgeBeenStarted());
require(max > min && _depositCap > max, "Invalid values");
minTokenPrice = min;
maxTokenPrice = max;
depositCap = _depositCap;
}
/**
* @dev Sends ETH and reverts if the transfer fails.
* @param recipient The transfer recipient.
* @param amount The transfer amount.
*/
function safeSendEth(address recipient, uint256 amount) private {
(bool success, ) = recipient.call{value: amount}("");
require(success, "Failed to send ETH");
}
}
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
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'
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - 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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
abstract contract Signature {
/**
* @dev Returns the address that signed a message given a signature.
* @param message The message signed.
* @param signature The signature.
*/
function getSignatureAddress(bytes32 message, bytes memory signature)
internal
pure
returns (address)
{
assert(signature.length == 65);
uint8 v;
bytes32 r;
bytes32 s;
assembly {
// First 32 bytes after length prefix.
r := mload(add(signature, 32))
// Next 32 bytes.
s := mload(add(signature, 64))
// Final byte.
v := byte(0, mload(add(signature, 96)))
}
return ecrecover(message, v, r, s);
}
}
// 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);
}
/**
* @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);
}
}
}
}
| Validates a signature for the hashed terms & conditions message. The T&Cs hash is converted to an ERC-191 message before verifying. signature The signature to validate./ | function signTermsAndConditions(bytes memory signature) public {
if (signedTermsAndConditions[msg.sender]) return;
address signer = getSignatureAddress(
termsAndConditionsERC191,
signature
);
require(signer == msg.sender, "Invalid signature");
signedTermsAndConditions[msg.sender] = true;
}
| 9,961,068 |
// SPDX-License-Identifier: MIT
// todo: add events, add require statements, use chainlink oracles
pragma solidity ^0.6.7;
// add some events to contract
import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/presets/ERC20PresetMinterPauser.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/access/Ownable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.1.0/contracts/math/Math.sol";
contract MainContract is Ownable {
using SafeMath for uint256;
using Math for uint256;
AggregatorV3Interface internal priceFeed_eur_usd;
AggregatorV3Interface internal priceFeed_dai_usd;
/**
* Network: Kovan
* Aggregator:
* - EUR/USD, Address: 0x0c15Ab9A0DB086e062194c273CC79f41597Bbf13
* - DAI/USD, Address: 0x777A68032a88E5A84678A77Af2CD65A7b3c0775a
*
*
*/
constructor() public {
priceFeed_eur_usd = AggregatorV3Interface(0x0c15Ab9A0DB086e062194c273CC79f41597Bbf13);
priceFeed_dai_usd = AggregatorV3Interface(0x777A68032a88E5A84678A77Af2CD65A7b3c0775a);
}
function getLatestPrice_EUR() public view returns (int) {
(
,
int price,
,
uint timeStamp,
) = priceFeed_eur_usd.latestRoundData();
// If the round is not complete yet, timestamp is 0
require(timeStamp > 0, "Round not complete");
return price;
//return 118186500;
}
function getLatestPrice_Dai() public view returns (int) {
(
,
int price,
,
uint timeStamp,
) = priceFeed_dai_usd.latestRoundData();
// If the round is not complete yet, timestamp is 0
require(timeStamp > 0, "Round not complete");
return price;
//return 108186500;
}
// exchange rate informations
uint exchange_rate_start;
uint exchange_rate_end;
uint total_pre_pool_balance;
uint total_pool_balance_start;
uint total_pool_balance_end;
uint total_post_pool_balance;
address aEURs_address;
address aEURu_address;
address aDai_address;
bool round_is_over;
bool saving_is_over;
// some random events
event Invested_in_pool (
address _sender,
uint aDai_amount
);
event Shares_Minted (
address _sender,
uint aDai_amount,
uint exchange_rate
);
event Redeemed_aEURs (
address _sender,
uint aEURs_amount,
uint exchange_rate
);
event Redeemed_aEURu (
address _sender,
uint aEURu_amount,
uint exchange_rate
);
// mappings
mapping(address => uint) public pre_pool_balances;
// aEURu and aEURu are both ERC20 tokens
ERC20PresetMinterPauser public aEURs;
ERC20PresetMinterPauser public aEURu;
ERC20 public aDai;
function get_pre_pool_balance(address _address) public view returns (uint) {
return pre_pool_balances[_address];
}
function start_saving() public onlyOwner {
//round_is_over = true;
exchange_rate_start = uint(getLatestPrice_EUR());
}
function start_redeeming() public onlyOwner {
// saving_is_over = true;
exchange_rate_end = uint(getLatestPrice_EUR());
total_pool_balance_end = aDai.balanceOf(address(this));
total_post_pool_balance = total_pool_balance_end;
}
function fund_pre_pool(uint aDai_amount) public {
bool success = aDai.transferFrom(msg.sender, address(this), aDai_amount);
require(success, "buy failed");
pre_pool_balances[msg.sender] = pre_pool_balances[msg.sender].add(aDai_amount);
total_pool_balance_start = total_pool_balance_start.add(aDai_amount);
emit Invested_in_pool(msg.sender, aDai_amount);
}
function mint_tokens() external {
// require(round_is_over, "Can not mint before investment round ended");
uint aDai_amount = pre_pool_balances[msg.sender];
pre_pool_balances[msg.sender] = pre_pool_balances[msg.sender].sub(aDai_amount);
_mint_euro_stable(aDai_amount.div(2));
_mint_euro_unstable(aDai_amount.div(2));
emit Shares_Minted(msg.sender, aDai_amount, exchange_rate_start);
}
// utilities
function get_contract_adress() public view returns (address) {
return address(this);
}
function get_aEURs_address () public view returns(address) {
return aEURs_address;
}
function get_aEURu_address () public view returns(address) {
return aEURu_address;
}
function get_aDai_address () public view returns(address) {
return aDai_address;
}
// set new address (used for testing)
function set_aEURs_address (address new_token_address) public onlyOwner {
aEURs_address = new_token_address;
aEURs = ERC20PresetMinterPauser(aEURs_address);
}
function set_aEURu_address (address new_token_address) public onlyOwner {
aEURu_address = new_token_address;
aEURu = ERC20PresetMinterPauser(new_token_address);
}
function set_aDai_address (address new_token_address) public onlyOwner {
aDai_address = new_token_address;
aDai = ERC20(new_token_address);
}
// mint derivative tokens
function _mint_euro_stable(uint aDai_amount) internal{
uint256 aEURs_amount = _aDai_to_aEURs(aDai_amount);
aEURs.mint(msg.sender,aEURs_amount);
}
function _aDai_to_aEURs(uint _amount) internal view returns (uint256) {
return _amount.mul(10**8).div(uint(exchange_rate_start));
}
function _mint_euro_unstable(uint aDai_amount) internal{
aEURu.mint(msg.sender,aDai_amount);
}
// view your current balance
function get_aEURs_to_Dai(address _address) public view returns (uint256) {
uint _amount = aEURs.balanceOf(_address);
require(_amount>0, "Balance is zero");
return aEURs_to_aDai(_amount, uint(getLatestPrice_EUR()));
}
function get_aEURs_to_EUR(address _address) public view returns (uint256) {
return _Dai_to_EUR(get_aEURs_to_Dai(_address));
}
function get_aEURu_to_Dai(address _address) public view returns (uint256) {
uint _amount = aEURu.balanceOf(_address);
return aEURu_to_aDai(_amount, uint(getLatestPrice_EUR()));
}
function get_aEURu_to_EUR(address _address) public view returns (uint256) {
return _Dai_to_EUR(get_aEURu_to_Dai(_address));
}
// redeem derivative tokens
function redeem_euro_stable(uint aEURs_amount) external{
// require(saving_is_over, "Saving period has not stopped yet");
uint usd_amount_retail = aEURs_to_aDai(aEURs_amount, exchange_rate_end);
aEURs.burnFrom(msg.sender, aEURs_amount);
aDai.transfer(msg.sender, usd_amount_retail);
emit Redeemed_aEURs(msg.sender, aEURs_amount, exchange_rate_end);
total_post_pool_balance = total_post_pool_balance.sub(usd_amount_retail);
}
function redeem_euro_unstable(uint aEURu_amount) external{
// require(saving_is_over, "Saving period has not stopped yet");
uint usd_amount_hedger = aEURu_to_aDai(aEURu_amount, exchange_rate_end);
aEURu.burnFrom(msg.sender, aEURu_amount);
aDai.transfer(msg.sender, usd_amount_hedger);
emit Redeemed_aEURs(msg.sender, aEURu_amount, exchange_rate_end);
total_post_pool_balance = total_post_pool_balance.sub(usd_amount_hedger);
}
// redeem aEURs tokens
function aEURs_to_aDai(uint _amount, uint _exchange_rate) public view returns (uint256) {
uint interest_part = aEURs_interest(_amount, exchange_rate_start);
uint principal_part = aEURs_to_dollar(_amount, limit_exchange_movement_long(_exchange_rate));
return principal_part.add(interest_part);
}
function aEURs_interest(uint _amount, uint _exchange_rate) internal view returns (uint256) {
return _amount.mul(_exchange_rate).mul(total_pool_balance_end.sub(total_pool_balance_start)).div(total_pool_balance_start).div(10**8); //
}
function aEURs_to_dollar(uint _amount, uint _exchange_rate) internal pure returns (uint256) {
return _amount.mul(_exchange_rate).div(10**8);
}
// redeem aEURu tokens
function aEURu_to_aDai(uint _amount, uint _exchange_rate) public view returns (uint256) {
uint interest_part = aEURu_interest(_amount);
uint principal_part = aEURu_to_dollar(_amount, _exchange_rate);
return principal_part.add(interest_part);
}
function aEURu_interest(uint _amount) internal view returns (uint256) {
return _amount.mul(total_pool_balance_end.sub(total_pool_balance_start)).div(total_pool_balance_start);
}
function aEURu_to_dollar(uint _amount, uint _exchange_rate) internal view returns (uint256) {
return _amount.mul(limit_exchange_movement_short(_exchange_rate)).div(10**8);
}
// exchange rate conversion helper
function _Dai_to_EUR(uint _amount) internal view returns (uint256) {
return _amount.mul(uint(getLatestPrice_EUR())).div(uint(getLatestPrice_Dai()));
}
function _Dai_to_USD(uint _amount) internal view returns (uint256) {
return _amount.mul(uint(getLatestPrice_Dai())).div(10**8);
}
// limit exchange rate movements hedged by the contract to 50% up/down
function limit_exchange_movement_long(uint _exchange_rt) internal view returns (uint256) {
uint exchange_rt_min = exchange_rate_start.mul(5).div(10);
uint exchange_rt_max = exchange_rate_start.mul(15).div(10);
return _exchange_rt.max(exchange_rt_min).min(exchange_rt_max);
}
function limit_exchange_movement_short(uint _exchange_rt) internal view returns (uint256) {
uint ratio = _exchange_rt.mul(10**9).div(exchange_rate_start);
ratio = ratio.max(5*10**8).min(15*10**8);
uint normalizer = 2*10**9;
return normalizer.sub(ratio).div(10);
}
// other utility functions
function show_exchange_rates() public view returns (uint _exchange_rate_start, uint _exchange_rate_end) {
_exchange_rate_start = exchange_rate_start;
_exchange_rate_end = exchange_rate_end;
}
function show_pool_balances() public view returns (uint _total_pool_balance_start, uint _total_pool_balance_end, uint _total_post_pool_balance) {
_total_pool_balance_start = total_pool_balance_start;
_total_pool_balance_end = total_pool_balance_end;
_total_post_pool_balance = total_post_pool_balance;
}
function is_saving_over() public view returns (bool) {
return saving_is_over;
}
function is_round_over() public view returns (bool) {
return round_is_over;
}
}
| redeem aEURs tokens | function aEURs_to_aDai(uint _amount, uint _exchange_rate) public view returns (uint256) {
uint interest_part = aEURs_interest(_amount, exchange_rate_start);
uint principal_part = aEURs_to_dollar(_amount, limit_exchange_movement_long(_exchange_rate));
return principal_part.add(interest_part);
}
| 1,037,423 |
./full_match/1/0xeFFe069b1c62c2f55F41A501eCc3c6Ff4dB6D70a/sources/src/modules/price-router/PriceRouter.sol | Helper function to get an assets price in USD. Returns price in USD with 8 decimals. Favors using cached prices if available./ First check if the price is in the price cache. Did not find our price in the cache. Save the last index. If there is room in the cache, the price fits in a uint96, then find the next spot available. Found an empty cache slot, so fill it. | function _getPriceInUSD(
ERC20 asset,
AssetSettings memory settings,
PriceCache[PRICE_CACHE_SIZE] memory cache
) internal view returns (uint256) {
uint8 lastIndex = PRICE_CACHE_SIZE;
for (uint8 i; i < PRICE_CACHE_SIZE; ++i) {
if (cache[i].asset == address(0)) {
lastIndex = i;
break;
}
}
if (settings.derivative == 1) {
price = _getPriceForChainlinkDerivative(asset, settings.source, cache);
price = _getPriceForCurveDerivative(asset, settings.source, cache);
price = _getPriceForCurveV2Derivative(asset, settings.source, cache);
price = _getPriceForAaveDerivative(asset, settings.source, cache);
} else revert PriceRouter__UnkownDerivative(settings.derivative);
if (lastIndex < PRICE_CACHE_SIZE && price <= type(uint96).max) {
for (uint8 i = lastIndex; i < PRICE_CACHE_SIZE; ++i) {
if (cache[i].asset == address(0)) {
cache[i] = PriceCache(address(asset), uint96(price));
break;
}
}
}
return price;
}
| 3,124,348 |
./partial_match/1/0xdc888B8c76eF26852B6f6c0008D6E2f29A96Cb50/sources/contracts-verify/KIBTAggregator.sol | return Contract version./ | function version() external pure returns (uint8) {
return _VERSION;
}
| 9,350,625 |
pragma solidity 0.6.6;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "@pancakeswap-libs/pancake-swap-core/contracts/interfaces/IPancakeFactory.sol";
import "../../interfaces/IWETH.sol";
import "./PancakeLibraryV2.sol";
import "../pancake/IPancakeRouter02.sol";
import "../../utils/SafeToken.sol";
contract PancakeRouterV2 is IPancakeRouter02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'PancakeRouter: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IPancakeFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IPancakeFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = PancakeLibraryV2.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = PancakeLibraryV2.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'PancakeRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = PancakeLibraryV2.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'PancakeRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = PancakeLibraryV2.pairFor(factory, tokenA, tokenB);
SafeToken.safeTransferFrom(tokenA, msg.sender, pair, amountA);
SafeToken.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IPancakePair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = PancakeLibraryV2.pairFor(factory, token, WETH);
SafeToken.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IPancakePair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) SafeToken.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = PancakeLibraryV2.pairFor(factory, tokenA, tokenB);
IPancakePair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IPancakePair(pair).burn(to);
(address token0,) = PancakeLibraryV2.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'PancakeRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'PancakeRouter: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
SafeToken.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
SafeToken.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = PancakeLibraryV2.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IPancakePair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = PancakeLibraryV2.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IPancakePair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
SafeToken.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
SafeToken.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = PancakeLibraryV2.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IPancakePair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = PancakeLibraryV2.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? PancakeLibraryV2.pairFor(factory, output, path[i + 2]) : _to;
IPancakePair(PancakeLibraryV2.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = PancakeLibraryV2.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT');
SafeToken.safeTransferFrom(
path[0], msg.sender, PancakeLibraryV2.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = PancakeLibraryV2.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'PancakeRouter: EXCESSIVE_INPUT_AMOUNT');
SafeToken.safeTransferFrom(
path[0], msg.sender, PancakeLibraryV2.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'PancakeRouter: INVALID_PATH');
amounts = PancakeLibraryV2.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(PancakeLibraryV2.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'PancakeRouter: INVALID_PATH');
amounts = PancakeLibraryV2.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'PancakeRouter: EXCESSIVE_INPUT_AMOUNT');
SafeToken.safeTransferFrom(
path[0], msg.sender, PancakeLibraryV2.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
SafeToken.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'PancakeRouter: INVALID_PATH');
amounts = PancakeLibraryV2.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT');
SafeToken.safeTransferFrom(
path[0], msg.sender, PancakeLibraryV2.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
SafeToken.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'PancakeRouter: INVALID_PATH');
amounts = PancakeLibraryV2.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'PancakeRouter: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(PancakeLibraryV2.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) SafeToken.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = PancakeLibraryV2.sortTokens(input, output);
IPancakePair pair = IPancakePair(PancakeLibraryV2.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = PancakeLibraryV2.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? PancakeLibraryV2.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
SafeToken.safeTransferFrom(
path[0], msg.sender, PancakeLibraryV2.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'PancakeRouter: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(PancakeLibraryV2.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'PancakeRouter: INVALID_PATH');
SafeToken.safeTransferFrom(
path[0], msg.sender, PancakeLibraryV2.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
SafeToken.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return PancakeLibraryV2.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return PancakeLibraryV2.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return PancakeLibraryV2.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return PancakeLibraryV2.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return PancakeLibraryV2.getAmountsIn(factory, amountOut, path);
}
}
| REMOVE LIQUIDITY | function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = PancakeLibraryV2.pairFor(factory, tokenA, tokenB);
(uint amount0, uint amount1) = IPancakePair(pair).burn(to);
(address token0,) = PancakeLibraryV2.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'PancakeRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'PancakeRouter: INSUFFICIENT_B_AMOUNT');
}
| 2,482,054 |
pragma solidity ^0.4.25;
import "./Register.sol";
import "./Counters.sol";
import "./Roles.sol";
contract IBAC002Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The BAC002 smart contract calls this function on the recipient
*/
function onBAC002Received(address operator, address from, uint256 assetId, bytes memory data)
public returns (bytes4);
}
contract BAC002Holder is IBAC002Receiver {
function onBAC002Received(address, address, uint256, bytes memory) public returns (bytes4) {
return this.onBAC002Received.selector;
}
}
contract IssuerRole {
using Roles for Roles.Role;
event IssuerAdded(address indexed account);
event IssuerRemoved(address indexed account);
Roles.Role private _issuers;
constructor () internal {
_addIssuer(msg.sender);
}
modifier onlyIssuer() {
require(isIssuer(msg.sender), "IssuerRole: caller does not have the Issuer role");
_;
}
function isIssuer(address account) public view returns (bool) {
return _issuers.has(account);
}
function addIssuer(address account) public onlyIssuer {
_addIssuer(account);
}
function renounceIssuer() public {
_removeIssuer(msg.sender);
}
function _addIssuer(address account) internal {
_issuers.add(account);
emit IssuerAdded(account);
}
function _removeIssuer(address account) internal {
_issuers.remove(account);
emit IssuerRemoved(account);
}
}
contract SuspenderRole {
using Roles for Roles.Role;
event SuspenderAdded(address indexed account);
event SuspenderRemoved(address indexed account);
Roles.Role private _suspenders;
constructor () internal {
_addSuspender(msg.sender);
}
modifier onlySuspender() {
require(isSuspender(msg.sender), "SuspenderRole: caller does not have the Suspender role");
_;
}
function isSuspender(address account) public view returns (bool) {
return _suspenders.has(account);
}
function addSuspender(address account) public onlySuspender {
_addSuspender(account);
}
function renounceSuspender() public {
_removeSuspender(msg.sender);
}
function _addSuspender(address account) internal {
_suspenders.add(account);
emit SuspenderAdded(account);
}
function _removeSuspender(address account) internal {
_suspenders.remove(account);
emit SuspenderRemoved(account);
}
}
contract Suspendable is SuspenderRole {
event Suspended(address account);
event UnSuspended(address account);
bool private _suspended;
constructor () internal {
_suspended = false;
}
/**
* @return True if the contract is suspended, false otherwise.
*/
function suspended() public view returns (bool) {
return _suspended;
}
/**
* @dev Modifier to make a function callable only when the contract is not suspended.
*/
modifier whenNotSuspended() {
require(!_suspended, "Suspendable: suspended");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is suspended.
*/
modifier whenSuspended() {
require(_suspended, "Suspendable: not suspended");
_;
}
/**
* @dev Called by a Suspender to suspend, triggers stopped state.
*/
function suspend() public onlySuspender whenNotSuspended {
_suspended = true;
emit Suspended(msg.sender);
}
/**
* @dev Called by a Suspender to unSuspend, returns to normal state.
*/
function unSuspend() public onlySuspender whenSuspended {
_suspended = false;
emit UnSuspended(msg.sender);
}
}
//delete register
contract BAC002 is IssuerRole, Suspendable {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onBAC002Received(address,address,uint256,bytes)"))`
bytes4 private constant _BAC002_RECEIVED = 0x31f6f50e;
// Mapping from asset ID to owner
mapping(uint256 => address) private _assetOwner;
// Mapping from asset ID to approved address
mapping(uint256 => address) private _assetApprovals;
// Mapping from owner to number of owned asset
mapping(address => Counters.Counter) private _ownedAssetsCount;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
string private _description;
string private _shortName;
// Optional mapping for asset URIs
mapping(uint256 => string) private _assetURIs;
// Mapping from owner to list of owned asset IDs
mapping(address => uint256[]) private _ownedAssets;
// Mapping from asset ID to index of the owner assets list
mapping(uint256 => uint256) private _ownedAssetsIndex;
// Array with all asset ids, used for enumeration
uint256[] private _allAssets;
// Mapping from asset id to position in the allAssets array
mapping(uint256 => uint256) private _allAssetsIndex;
event Send(address indexed operator, address indexed from, address indexed to, uint256 assetId, bytes data);
event Approval( address indexed owner, address approved, uint256 assetId);
event ApprovalForAll( address indexed owner, address indexed operator, bool approved);
// constructor
constructor(string description, string shortName) public
{
_description = description;
_shortName = shortName;
}
/**
* @dev Gets the balance of the specified address.
*/
function balance(address owner) public view returns (uint256) {
require(owner != address(0), "BAC002: balance query for the zero address");
return _ownedAssetsCount[owner].current();
}
/**
* @dev Gets the owner of the specified asset ID.
*/
function ownerOf(uint256 assetId) public view returns (address) {
address owner = _assetOwner[assetId];
require(owner != address(0), "BAC002: owner query for nonexistent asset");
return owner;
}
function assetOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balance(owner), "BAC002Enumerable: owner index out of bounds");
return _ownedAssets[owner][index];
}
function assetOfOwner(address owner) public view returns (uint256[]) {
return _ownedAssets[owner];
}
function assetByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "BAC002Enumerable: global index out of bounds");
return _allAssets[index];
}
/**
* @dev Approves another address to send the given asset ID
*/
function approve(address to, uint256 assetId) public whenNotSuspended {
address owner = ownerOf(assetId);
require(to != owner, "BAC002: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"BAC002: approve caller is not owner nor approved for all"
);
_assetApprovals[assetId] = to;
emit Approval( owner, to, assetId);
}
/**
* @dev Gets the approved address for a asset ID, or zero if no address set
*/
function getApproved(uint256 assetId) public view returns (address) {
require(_exists(assetId), "BAC002: approved query for nonexistent asset");
return _assetApprovals[assetId];
}
/**
* @dev Sets or unsets the approval of a given operator
*/
function setApprovalForAll(address to, bool approved) public whenNotSuspended {
require(to != msg.sender, "BAC002: approve to caller");
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll( msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
// /**
// * @dev Sends the ownership of a given asset ID to another address.
// */
// function sendFrom(address from, address to, uint256 assetId, bytes memory data) public whenNotSuspended {
// //solhint-disable-next-line max-line-length
// require(_isApprovedOrOwner(msg.sender, assetId), "BAC002: send caller is not owner nor approved");
// _sendFrom(from, to, assetId, data);
// }
// /**
// * @dev Safely sends the ownership of a given asset ID to another address
// */
// function safeSendFrom(address from, address to, uint256 assetId) public whenNotSuspended {
// safeSendFrom(from, to, assetId, "");
// }
/**
* @dev Safely sends the ownership of a given asset ID to another address
*/
function sendFrom(address from, address to, uint256 assetId, bytes memory data) public whenNotSuspended {
require(_isApprovedOrOwner(msg.sender, assetId), "BAC002: send caller is not owner nor approved");
_sendFrom(from, to, assetId, data);
require(_checkOnBAC002Received(from, to, assetId, data), "BAC002: send to non BAC002Receiver implementer");
}
function batchSendFrom(address from, address[] to, uint256[] assetId, bytes memory data) public whenNotSuspended {
require(to.length == assetId.length, "to and assetId array lenght must match.");
for (uint256 i = 0; i < to.length; ++i) {
require(to[i] != address(0x0), "destination address must be non-zero.");
sendFrom(from, to[i], assetId[i], data);
}
}
function destroy(uint256 assetId, bytes data) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, assetId), "BAC002Burnable: caller is not owner nor approved");
_destroy(assetId, data);
}
//add issuerAddress
function issueWithAssetURI(address to, uint256 assetId, string memory assetURI, bytes data) public onlyIssuer returns (bool) {
_issue( to, assetId, data);
_setAssetURI(assetId, assetURI);
return true;
}
function description() external view returns (string memory) {
return _description;
}
function shortName() external view returns (string memory) {
return _shortName;
}
/**
* @dev Returns an URI for a given asset ID.
*/
function assetURI(uint256 assetId) external view returns (string memory) {
require(_exists(assetId), "BAC002Metadata: URI query for nonexistent asset");
return _assetURIs[assetId];
}
/**
* @dev Internal function to set the asset URI for a given asset.
*/
function _setAssetURI(uint256 assetId, string memory uri) internal {
require(_exists(assetId), "BAC002Metadata: URI set of nonexistent asset");
_assetURIs[assetId] = uri;
}
/**
* @dev Returns whether the specified asset exists.
*/
function _exists(uint256 assetId) internal view returns (bool) {
address owner = _assetOwner[assetId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can send a given asset ID.
*/
function _isApprovedOrOwner(address spender, uint256 assetId) internal view returns (bool) {
require(_exists(assetId), "BAC002: operator query for nonexistent asset");
address owner = ownerOf(assetId);
return (spender == owner || getApproved(assetId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new asset.
*/
function _issue( address to, uint256 assetId, bytes data) internal {
require(to != address(0), "BAC002: mint to the zero address");
require(!_exists(assetId), "BAC002: asset already minted");
_assetOwner[assetId] = to;
_ownedAssetsCount[to].increment();
emit Send(msg.sender, address(0), to, assetId, data);
_addAssetToOwnerEnumeration(to, assetId);
_addAssetToAllAssetsEnumeration(assetId);
}
/**
* @dev Internal function to destroy a specific asset.
* Reverts if the asset does not exist.
*/
function _destroy(address owner, uint256 assetId, bytes data) internal {
require(ownerOf(assetId) == owner, "BAC002: destroy of asset that is not own");
_clearApproval(assetId);
_ownedAssetsCount[owner].decrement();
_assetOwner[assetId] = address(0);
if (bytes(_assetURIs[assetId]).length != 0) {
delete _assetURIs[assetId];
}
emit Send(this, owner, address(0), assetId, data);
_removeAssetFromOwnerEnumeration(owner, assetId);
// Since assetId will be deleted, we can clear its slot in _ownedAssetsIndex to trigger a gas refund
_ownedAssetsIndex[assetId] = 0;
_removeAssetFromAllAssetsEnumeration(assetId);
}
/**
* @dev Gets the total amount of assets stored by the contract.
* @return uint256 representing the total amount of assets
*/
function totalSupply() public view returns (uint256) {
return _allAssets.length;
}
function _assetsOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedAssets[owner];
}
/**
* @dev Private function to add a asset to this extension's ownership-tracking data structures.
*/
function _addAssetToOwnerEnumeration(address to, uint256 assetId) private {
_ownedAssetsIndex[assetId] = _ownedAssets[to].length;
_ownedAssets[to].push(assetId);
}
/**
* @dev Private function to add a asset to this extension's asset tracking data structures.
*/
function _addAssetToAllAssetsEnumeration(uint256 assetId) private {
_allAssetsIndex[assetId] = _allAssets.length;
_allAssets.push(assetId);
}
/**
* @dev Private function to remove a asset from this extension's ownership-tracking data structures. Note that
*/
function _removeAssetFromOwnerEnumeration(address from, uint256 assetId) private {
// To prevent a gap in from's assets array, we store the last asset in the index of the asset to delete, and
// then delete the last slot (swap and pop).
uint256 lastAssetIndex = _ownedAssets[from].length.sub(1);
uint256 assetIndex = _ownedAssetsIndex[assetId];
// When the asset to delete is the last asset, the swap operation is unnecessary
if (assetIndex != lastAssetIndex) {
uint256 lastAssetId = _ownedAssets[from][lastAssetIndex];
_ownedAssets[from][assetIndex] = lastAssetId;
// Move the last asset to the slot of the to-delete asset
_ownedAssetsIndex[lastAssetId] = assetIndex;
// Update the moved asset's index
}
// This also deletes the contents at the last position of the array
_ownedAssets[from].length--;
// Note that _ownedAssetsIndex[assetId] hasn't been cleared: it still points to the old slot (now occupied by
// lastAssetId, or just over the end of the array if the asset was the last one).
}
/**
* @dev Private function to remove a asset from this extension's asset tracking data structures.
*/
function _removeAssetFromAllAssetsEnumeration(uint256 assetId) private {
// To prevent a gap in the assets array, we store the last asset in the index of the asset to delete, and
// then delete the last slot (swap and pop).
uint256 lastAssetIndex = _allAssets.length.sub(1);
uint256 assetIndex = _allAssetsIndex[assetId];
// When the asset to delete is the last asset, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted asset is destroyt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeAssetFromOwnerEnumeration)
uint256 lastAssetId = _allAssets[lastAssetIndex];
_allAssets[assetIndex] = lastAssetId;
// Move the last asset to the slot of the to-delete asset
_allAssetsIndex[lastAssetId] = assetIndex;
// Update the moved asset's index
// This also deletes the contents at the last position of the array
_allAssets.length--;
_allAssetsIndex[assetId] = 0;
}
/**
* @dev Internal function to destroy a specific asset.
*/
function _destroy(uint256 assetId, bytes data) internal {
_destroy(ownerOf(assetId), assetId, data);
}
/**
* @dev Internal function to send ownership of a given asset ID to another address.
*/
function _sendFrom(address from, address to, uint256 assetId, bytes data) internal {
require(ownerOf(assetId) == from, "BAC002: send of asset that is not own");
require(to != address(0), "BAC002: send to the zero address");
_clearApproval(assetId);
_ownedAssetsCount[from].decrement();
_ownedAssetsCount[to].increment();
_assetOwner[assetId] = to;
emit Send(msg.sender, from, to, assetId, data);
_removeAssetFromOwnerEnumeration(from, assetId);
_addAssetToOwnerEnumeration(to, assetId);
}
/**
* @dev Internal function to invoke `onBAC002Received` on a target address.
*/
function _checkOnBAC002Received(address from, address to, uint256 assetId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IBAC002Receiver(to).onBAC002Received(msg.sender, from, assetId, _data);
return (retval == _BAC002_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given asset ID.
*/
function _clearApproval(uint256 assetId) private {
if (_assetApprovals[assetId] != address(0)) {
_assetApprovals[assetId] = address(0);
}
}
} | Safely sends the ownership of a given asset ID to another address/ | function sendFrom(address from, address to, uint256 assetId, bytes memory data) public whenNotSuspended {
require(_isApprovedOrOwner(msg.sender, assetId), "BAC002: send caller is not owner nor approved");
_sendFrom(from, to, assetId, data);
require(_checkOnBAC002Received(from, to, assetId, data), "BAC002: send to non BAC002Receiver implementer");
}
| 12,696,217 |
pragma solidity ^0.4.24;
// import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
// pragma solidity ^0.4.24;
/**
* @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;
}
}
contract Owned {
address public owner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value);
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
// uint8 public decimals = 18;
uint8 public decimals = 4;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(uint256 initialSupply) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = "WADCoin"; // Set the name for display purposes
symbol = "wad"; // Set the symbol for display purposes
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
//_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/******************************************/
/* WADTOKEN STARTS HERE */
/******************************************/
contract WADCoin is Owned, TokenERC20 {
using SafeMath for uint256;
uint256 public sellPrice;
uint256 public buyPrice;
address public migrationAgent;
uint256 public totalMigrated;
address public migrationMaster;
mapping(address => bytes32[]) public lockReason;
mapping(address => mapping(bytes32 => lockToken)) public locked;
struct lockToken {
uint256 amount;
uint256 validity;
}
// event Lock(
// address indexed _of,
// bytes32 indexed _reason,
// uint256 _amount,
// uint256 _validity
// );
/* This generates a public event on the blockchain that will notify clients */
event Migrate(address indexed _from, address indexed _to, uint256 _value);
/* Initializes contract with initial supply tokens to the creator of the contract */
// function MyAdvancedToken(
function WADCoin( uint256 _initialSupply) TokenERC20(_initialSupply) public {
// initialSupply = _initialSupply;
// tokenName = _tokenName;
// tokenSymbol = _tokenSymbol;
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(transferableBalanceOf(_from) >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
*/
function lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
onlyOwner
public
returns (bool)
{
uint256 validUntil = block.timestamp.add(_time);
// If tokens are already locked, the functions extendLock or
// increaseLockAmount should be used to make any changes
//require(tokensLocked(_of, _reason, block.timestamp) == 0);
require(_amount <= transferableBalanceOf(_of));
if (locked[_of][_reason].amount == 0)
lockReason[_of].push(_reason);
if(tokensLocked(_of, _reason, block.timestamp) == 0){
locked[_of][_reason] = lockToken(_amount, validUntil);
}else{
locked[_of][_reason].amount += _amount;
}
//emit Lock(_of, _reason, _amount, validUntil);
return true;
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLock(bytes32 _reason, uint256 _time)
public
returns (bool)
{
require(tokensLocked(msg.sender, _reason, block.timestamp) > 0);
locked[msg.sender][_reason].validity += _time;
// emit Lock(msg.sender, _reason, locked[msg.sender][_reason].amount, locked[msg.sender][_reason].validity);
return true;
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specified time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time)
amount = locked[_of][_reason].amount;
}
function transferableBalanceOf(address _of)
public
view
returns (uint256 amount)
{
uint256 lockedAmount = 0;
for (uint256 i=0; i < lockReason[_of].length; i++) {
lockedAmount += tokensLocked(_of,lockReason[_of][i], block.timestamp);
}
// amount = balances[_of].sub(lockedAmount);
amount = balanceOf[_of].sub(lockedAmount);
return amount;
}
/// @notice Set address of migration target contract and enable migration
/// process.
/// @dev Required state: Operational Normal
/// @dev State transition: -> Operational Migration
/// @param _agent The address of the MigrationAgent contract
function setMigrationAgent(address _agent) external {
// Abort if not in Operational Normal state.
if (migrationAgent != 0) throw;
if (msg.sender != migrationMaster) throw;
migrationAgent = _agent;
}
function setMigrationMaster(address _master) external {
if (msg.sender != migrationMaster) throw;
if (_master == 0) throw;
migrationMaster = _master;
}
} | Initializes contract with initial supply tokens to the creator of the contract / function MyAdvancedToken( initialSupply = _initialSupply; tokenName = _tokenName; tokenSymbol = _tokenSymbol; | function WADCoin( uint256 _initialSupply) TokenERC20(_initialSupply) public {
}
| 12,760,736 |
./partial_match/1/0x591bb8bB94D2FF406A5E8Ce6962D37210606dfB6/sources/WePiggyRewardToken.sol | Claim for recipient Emits a {Claim} event./ Make sure this reward has not already been claimed (and claim it) | function _claim(bytes32[] memory proof_, address recipient) internal {
require(!_claimPaused, "Claim is paused.");
require(!claimed[recipient], "You have already claimed your rewards.");
require(verifyProof(proof_, recipient), "The proof could not be verified.");
claimed[recipient] = true;
_tokenIds.increment();
uint256 newTokenId = _tokenIds.current();
_safeMint(recipient, newTokenId);
emit Claim(recipient, newTokenId);
}
| 3,907,196 |
// SPDX-License-Identifier: WTFPL
pragma solidity 0.8.12;
import "./libraries/EIP712s.sol";
import "./libraries/Signatures.sol";
import "./Timelock.sol";
import "./MultiSigGovernance.sol";
contract CoreTeam is Timelock, MultiSigGovernance {
// keccak256("QueueTransactions(address[] target,uint256[] value,string[] signature,bytes[] data,uint64[] eta)");
bytes32 public constant QUEUE_TRANSACTIONS_TYPEHASH =
0xb4c35086675bb65432758e1391df7d84e686ccfdfa7e7be39250320aa1a67355;
// keccak256("CancelTransactions(address[] target,uint256[] value,string[] signature,bytes[] data,uint64[] eta)");
bytes32 public constant CANCEL_TRANSACTIONS_TYPEHASH =
0xfb3dc1e5b5409e1cc1de0693d7ee84a4f7d85a5192bf0cb142f4652689f838b7;
modifier calledBySelf {
require(msg.sender == address(this), "DAOKIT: FORBIDDEN");
_;
}
constructor(
uint64 _delay,
address[] memory _members,
uint128 _required
) Timelock(_delay) MultiSigGovernance(members, _required) {
// Empty
}
/**
* @notice This function needs to be called by itself, which means it needs to be done by `queueTransactions()` and
* `executeTransactions()` with this address as `target`
*/
function addMember(address member) external calledBySelf {
_addMember(member);
}
/**
* @notice This function needs to be called by itself, which means it needs to be done by `queueTransactions()` and
* `executeTransactions()` with this address as `target`
*/
function removeMember(address member) external calledBySelf {
_removeMember(member);
}
/**
* @notice This function needs to be called by itself, which means it needs to be done by `queueTransactions()` and
* `executeTransactions()` with this address as `target`
*/
function changeRequirement(uint128 _required) external calledBySelf {
_changeRequirement(_required);
}
/**
* @notice Core team can call this to queue multiple transactions with a number of signatures higher than quorum
*/
function queueTransactions(
address[] memory target,
uint256[] memory value,
string[] memory signature,
bytes[] memory data,
uint64[] memory eta,
address[] memory signers,
Signatures.Signature[] memory signatures
) external requirementMet(uint128(signatures.length)) {
bytes32 hash = keccak256(
abi.encode(
QUEUE_TRANSACTIONS_TYPEHASH,
keccak256(abi.encodePacked(target)),
keccak256(abi.encodePacked(value)),
EIP712s.hashStringArray(signature),
EIP712s.hashBytesArray(data),
keccak256(abi.encodePacked(eta))
)
);
_verifySignatures(hash, signers, signatures);
for (uint256 i; i < target.length; i++) {
_queueTransaction(target[i], value[i], signature[i], data[i], eta[i]);
}
}
/**
* @notice Core team can call this to cancel multiple transactions with a number of signatures higher than quorum
*/
function cancelTransactions(
address[] memory target,
uint256[] memory value,
string[] memory signature,
bytes[] memory data,
uint64[] memory eta,
address[] memory signers,
Signatures.Signature[] memory signatures
) external requirementMet(uint128(signatures.length)) {
bytes32 hash = keccak256(
abi.encode(
CANCEL_TRANSACTIONS_TYPEHASH,
keccak256(abi.encodePacked(target)),
keccak256(abi.encodePacked(value)),
EIP712s.hashStringArray(signature),
EIP712s.hashBytesArray(data),
keccak256(abi.encodePacked(eta))
)
);
_verifySignatures(hash, signers, signatures);
for (uint256 i; i < target.length; i++) {
_cancelTransaction(target[i], value[i], signature[i], data[i], eta[i]);
}
}
/**
* @notice Anyone can call this to execute queued transactions that passed their eta
*/
function executeTransactions(
address[] memory target,
uint256[] memory value,
string[] memory signature,
bytes[] memory data,
uint64[] memory eta
) external {
for (uint256 i; i < target.length; i++) {
_executeTransaction(target[i], value[i], signature[i], data[i], eta[i]);
}
}
}
| Core team can call this to queue multiple transactions with a number of signatures higher than quorum/ | function queueTransactions(
address[] memory target,
uint256[] memory value,
string[] memory signature,
bytes[] memory data,
uint64[] memory eta,
address[] memory signers,
Signatures.Signature[] memory signatures
) external requirementMet(uint128(signatures.length)) {
bytes32 hash = keccak256(
abi.encode(
QUEUE_TRANSACTIONS_TYPEHASH,
keccak256(abi.encodePacked(target)),
keccak256(abi.encodePacked(value)),
EIP712s.hashStringArray(signature),
EIP712s.hashBytesArray(data),
keccak256(abi.encodePacked(eta))
)
);
_verifySignatures(hash, signers, signatures);
for (uint256 i; i < target.length; i++) {
_queueTransaction(target[i], value[i], signature[i], data[i], eta[i]);
}
}
| 2,551,014 |
pragma solidity =0.6.6;
import '@uniswap/v2-core/contracts/interfaces/IOzonepieCallee.sol';
import '../libraries/OzonepieLibrary.sol';
import '../interfaces/V1/IUniswapV1Factory.sol';
import '../interfaces/V1/IUniswapV1Exchange.sol';
import '../interfaces/IOzonepieRouter01.sol';
import '../interfaces/IERC20.sol';
import '../interfaces/IWETH.sol';
contract ExampleFlashSwap is IOzonepieCallee {
IUniswapV1Factory immutable factoryV1;
address immutable factory;
IWETH immutable WETH;
constructor(address _factory, address _factoryV1, address router) public {
factoryV1 = IUniswapV1Factory(_factoryV1);
factory = _factory;
WETH = IWETH(IOzonepieRouter01(router).WETH());
}
// needs to accept ETH from any V1 exchange and WETH. ideally this could be enforced, as in the router,
// but it's not possible because it requires a call to the v1 factory, which takes too much gas
receive() external payable {}
// gets tokens/WETH via a V2 flash swap, swaps for the ETH/tokens on V1, repays V2, and keeps the rest!
function OzonepieCall(address sender, uint amount0, uint amount1, bytes calldata data) external override {
address[] memory path = new address[](2);
uint amountToken;
uint amountETH;
{ // scope for token{0,1}, avoids stack too deep errors
address token0 = IOzonepiePair(msg.sender).token0();
address token1 = IOzonepiePair(msg.sender).token1();
assert(msg.sender == OzonepieLibrary.pairFor(factory, token0, token1)); // ensure that msg.sender is actually a V2 pair
assert(amount0 == 0 || amount1 == 0); // this strategy is unidirectional
path[0] = amount0 == 0 ? token0 : token1;
path[1] = amount0 == 0 ? token1 : token0;
amountToken = token0 == address(WETH) ? amount1 : amount0;
amountETH = token0 == address(WETH) ? amount0 : amount1;
}
assert(path[0] == address(WETH) || path[1] == address(WETH)); // this strategy only works with a V2 WETH pair
IERC20 token = IERC20(path[0] == address(WETH) ? path[1] : path[0]);
IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(address(token))); // get V1 exchange
if (amountToken > 0) {
(uint minETH) = abi.decode(data, (uint)); // slippage parameter for V1, passed in by caller
token.approve(address(exchangeV1), amountToken);
uint amountReceived = exchangeV1.tokenToEthSwapInput(amountToken, minETH, uint(-1));
uint amountRequired = OzonepieLibrary.getAmountsIn(factory, amountToken, path)[0];
assert(amountReceived > amountRequired); // fail if we didn't get enough ETH back to repay our flash loan
WETH.deposit{value: amountRequired}();
assert(WETH.transfer(msg.sender, amountRequired)); // return WETH to V2 pair
(bool success,) = sender.call{value: amountReceived - amountRequired}(new bytes(0)); // keep the rest! (ETH)
assert(success);
} else {
(uint minTokens) = abi.decode(data, (uint)); // slippage parameter for V1, passed in by caller
WETH.withdraw(amountETH);
uint amountReceived = exchangeV1.ethToTokenSwapInput{value: amountETH}(minTokens, uint(-1));
uint amountRequired = OzonepieLibrary.getAmountsIn(factory, amountETH, path)[0];
assert(amountReceived > amountRequired); // fail if we didn't get enough tokens back to repay our flash loan
assert(token.transfer(msg.sender, amountRequired)); // return tokens to V2 pair
assert(token.transfer(sender, amountReceived - amountRequired)); // keep the rest! (tokens)
}
}
}
| gets tokens/WETH via a V2 flash swap, swaps for the ETH/tokens on V1, repays V2, and keeps the rest! | function OzonepieCall(address sender, uint amount0, uint amount1, bytes calldata data) external override {
address[] memory path = new address[](2);
uint amountToken;
uint amountETH;
address token0 = IOzonepiePair(msg.sender).token0();
address token1 = IOzonepiePair(msg.sender).token1();
path[0] = amount0 == 0 ? token0 : token1;
path[1] = amount0 == 0 ? token1 : token0;
amountToken = token0 == address(WETH) ? amount1 : amount0;
amountETH = token0 == address(WETH) ? amount0 : amount1;
}
IERC20 token = IERC20(path[0] == address(WETH) ? path[1] : path[0]);
| 14,053,669 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Strings.sol";
import "./interfaces/RarelifeLibrary.sol";
contract RarelifeTalents is IRarelifeTalents, RarelifeConfigurable {
/* *******
* Globals
* *******
*/
uint public immutable ACTOR_DESIGNER = 0; //God authority
uint constant POINT_BUY = 20;
uint[] public talent_ids;
mapping(uint => string) public talent_names;
mapping(uint => string) public talent_descriptions;
mapping(uint => uint[]) public _talent_exclusivity;
mapping(uint => int) public override talent_attr_points_modifiers;
mapping(uint => RarelifeStructs.SAbilityModifiers) public _talent_attribute_modifiers;
mapping(uint => address) private talent_conditions;
//map actor to talents
mapping(uint => uint[]) public _actor_talents;
mapping(uint => mapping(uint => bool)) public _actor_talents_map;
mapping(uint => bool) public override actor_talents_initiated;
/* *********
* Modifiers
* *********
*/
modifier onlyApprovedOrOwner(uint _actor) {
require(_isActorApprovedOrOwner(_actor), "RarelifeTalents: not approved or owner");
_;
}
modifier onlyTalentsInitiated(uint _actor) {
require(actor_talents_initiated[_actor], "RarelifeTalents: not initiated yet");
_;
}
/* ****************
* Public Functions
* ****************
*/
constructor(address rlRouteAddress) RarelifeConfigurable(rlRouteAddress) {
}
/* *****************
* Private Functions
* *****************
*/
function _point_modify(uint _p, int _modifier) internal pure returns (uint) {
if(_modifier > 0)
_p += uint(_modifier);
else {
if(_p < uint(-_modifier))
_p = 0;
else
_p -= uint(-_modifier);
}
return _p;
}
/* ****************
* External Functions
* ****************
*/
function set_talent(uint _id, string memory _name, string memory _description, RarelifeStructs.SAbilityModifiers memory _attribute_modifiers, int _attr_point_modifier) external override
onlyApprovedOrOwner(ACTOR_DESIGNER)
{
require(keccak256(abi.encodePacked(_name)) != keccak256(abi.encodePacked("")), "RarelifeTalents: invalid name");
//require(keccak256(abi.encodePacked(talent_names[_id])) == keccak256(abi.encodePacked("")), "RarelifeTalents: already have talent");
if(keccak256(abi.encodePacked(talent_names[_id])) == keccak256(abi.encodePacked(""))) {
//first time
talent_ids.push(_id);
}
talent_names[_id] = _name;
talent_descriptions[_id] = _description;
_talent_attribute_modifiers[_id] = _attribute_modifiers;
talent_attr_points_modifiers[_id] = _attr_point_modifier;
}
function set_talent_exclusive(uint _id, uint[] memory _exclusive) external override
onlyApprovedOrOwner(ACTOR_DESIGNER)
{
require(keccak256(abi.encodePacked(talent_names[_id])) != keccak256(abi.encodePacked("")), "RarelifeTalents: talent have not set");
_talent_exclusivity[_id] = _exclusive;
}
function set_talent_condition(uint _id, address _conditionAddress) external override
onlyApprovedOrOwner(ACTOR_DESIGNER)
{
require(keccak256(abi.encodePacked(talent_names[_id])) != keccak256(abi.encodePacked("")), "RarelifeTalents: talent have not set");
talent_conditions[_id] = _conditionAddress;
}
function talent_character(uint _actor) external
onlyApprovedOrOwner(_actor)
{
require(!actor_talents_initiated[_actor], "RarelifeTalents: already init talents");
IRarelifeRandom rand = rlRoute.random();
uint tltCt = rand.dn(_actor, 4);
if(tltCt > talent_ids.length)
tltCt = talent_ids.length;
if(tltCt > 0) {
for(uint i=0; i<tltCt; i++) {
uint ch = rand.dn(_actor+i, talent_ids.length);
uint _id = talent_ids[ch];
//REVIEW: check exclusivity at first
bool isConflicted = false;
if(_talent_exclusivity[_id].length > 0) {
for(uint k=0; k<_talent_exclusivity[_id].length; k++) {
for(uint j=0; j<_actor_talents[_actor].length; j++) {
if(_actor_talents[_actor][j] == _talent_exclusivity[_id][k]) {
isConflicted = true;
break;
}
}
if(isConflicted)
break;
}
}
if(!isConflicted && !_actor_talents_map[_actor][_id]) {
_actor_talents_map[_actor][_id] = true;
_actor_talents[_actor].push(_id);
}
}
}
actor_talents_initiated[_actor] = true;
emit Created(msg.sender, _actor, _actor_talents[_actor]);
}
/* **************
* View Functions
* **************
*/
function actor_attribute_point_buy(uint _actor) external view override returns (uint) {
uint point = POINT_BUY;
for(uint i=0; i<_actor_talents[_actor].length; i++) {
uint tlt = _actor_talents[_actor][i];
point = _point_modify(point, talent_attr_points_modifiers[tlt]);
}
return point;
}
function actor_talents(uint _actor) external view override returns (uint[] memory) {
return _actor_talents[_actor];
}
function actor_talents_exist(uint _actor, uint[] memory _talents) external view override returns (bool[] memory) {
bool[] memory exists = new bool[](_talents.length);
for(uint i=0; i<_talents.length; i++)
exists[i] = _actor_talents_map[_actor][_talents[i]];
return exists;
}
function talents(uint _id) external view override returns (string memory _name, string memory _description) {
_name = talent_names[_id];
_description = talent_descriptions[_id];
}
function talent_attribute_modifiers(uint _id) external view override returns (RarelifeStructs.SAbilityModifiers memory) {
return _talent_attribute_modifiers[_id];
}
function talent_exclusivity(uint _id) external view override returns (uint[] memory) {
return _talent_exclusivity[_id];
}
function can_occurred(uint _actor, uint _id, uint _age) external view override
onlyTalentsInitiated(_actor)
returns (bool)
{
//REVIEW: check exclusivity at first
if(_talent_exclusivity[_id].length > 0) {
for(uint i=0; i<_talent_exclusivity[_id].length; i++) {
for(uint j=0; j<_actor_talents[_actor].length; j++) {
if(_actor_talents[_actor][j] == _talent_exclusivity[_id][i])
return false;
}
}
}
if(talent_conditions[_id] == address(0)) {
if(_age == 0) //no condition and only age 0
return true;
else
return false;
}
return IRarelifeTalentChecker(talent_conditions[_id]).check(_actor, _age);
}
function tokenURI(uint256 _actor) public view returns (string memory) {
string[7] memory parts;
//start svg
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" />';
parts[1] = '';
string memory tltJson = '';
for(uint i=0; i<_actor_talents[_actor].length; i++) {
uint tlt = _actor_talents[_actor][i];
uint y = 40*i;
parts[1] = string(abi.encodePacked(parts[1],
string(abi.encodePacked('<text x="10" y="', Strings.toString(20+y), '" class="base" stroke="yellow">', talent_names[tlt], '</text>')),
string(abi.encodePacked('<text x="10" y="', Strings.toString(40+y), '" class="base">', talent_descriptions[tlt], '</text>'))));
tltJson = string(abi.encodePacked(tltJson, Strings.toString(tlt), ','));
}
//end svg
parts[2] = string(abi.encodePacked('</svg>'));
string memory svg = string(abi.encodePacked(parts[0], parts[1], parts[2]));
//start json
parts[0] = string(abi.encodePacked('{"name": "Actor #', Strings.toString(_actor), ' talents:"'));
parts[1] = ', "description": "This is not a game"';
parts[2] = string(abi.encodePacked(', "data": {', '"TLT": [', tltJson, ']}'));
//end json with svg
parts[3] = string(abi.encodePacked(', "image": "data:image/svg+xml;base64,', Base64.encode(bytes(svg)), '"}'));
string memory json = Base64.encode(bytes(string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3]))));
//final output
return string(abi.encodePacked('data:application/json;charset=utf-8;base64,', json));
}
}
| REVIEW: check exclusivity at first | function talent_character(uint _actor) external
onlyApprovedOrOwner(_actor)
{
require(!actor_talents_initiated[_actor], "RarelifeTalents: already init talents");
IRarelifeRandom rand = rlRoute.random();
uint tltCt = rand.dn(_actor, 4);
if(tltCt > talent_ids.length)
tltCt = talent_ids.length;
if(tltCt > 0) {
for(uint i=0; i<tltCt; i++) {
uint ch = rand.dn(_actor+i, talent_ids.length);
uint _id = talent_ids[ch];
bool isConflicted = false;
if(_talent_exclusivity[_id].length > 0) {
for(uint k=0; k<_talent_exclusivity[_id].length; k++) {
for(uint j=0; j<_actor_talents[_actor].length; j++) {
if(_actor_talents[_actor][j] == _talent_exclusivity[_id][k]) {
isConflicted = true;
break;
}
}
if(isConflicted)
break;
}
}
if(!isConflicted && !_actor_talents_map[_actor][_id]) {
_actor_talents_map[_actor][_id] = true;
_actor_talents[_actor].push(_id);
}
}
}
actor_talents_initiated[_actor] = true;
emit Created(msg.sender, _actor, _actor_talents[_actor]);
}
| 6,446,931 |
./full_match/80001/0x0392F6416DCA6305A7aB44A7652fE12c6367322c/sources/marketplaceupdated.sol | Cancel an already published order can only be canceled by seller or the contract owner _nftAddress - Address of the NFT registry _assetId - ID of the published NFT/ Remove pending bid if any | function cancelOrder(address _nftAddress, uint256 _assetId) public whenNotPaused {
Order memory order = orderByAssetId[_nftAddress][_assetId];
require(order.seller == msg.sender || msg.sender == owner(), "Marketplace: unauthorized sender");
Bid memory bid = bidByOrderId[_nftAddress][_assetId];
if (bid.id != 0) {
_cancelBid(bid.id, _nftAddress, _assetId, bid.bidder, bid.price);
}
}
| 5,579,266 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../interfaces/ICLeverCVXLocker.sol";
import "../interfaces/ICLeverToken.sol";
import "../interfaces/IConvexCVXLocker.sol";
import "../interfaces/IConvexCVXRewardPool.sol";
import "../interfaces/IFurnace.sol";
import "../interfaces/ISnapshotDelegateRegistry.sol";
import "../interfaces/IZap.sol";
// solhint-disable not-rely-on-time, max-states-count, reason-string
contract CLeverCVXLocker is OwnableUpgradeable, ICLeverCVXLocker {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
event UpdateWhitelist(address indexed _whitelist, bool _status);
event UpdateStakePercentage(uint256 _percentage);
event UpdateStakeThreshold(uint256 _threshold);
event UpdateRepayFeePercentage(uint256 _feePercentage);
event UpdatePlatformFeePercentage(uint256 _feePercentage);
event UpdateHarvestBountyPercentage(uint256 _percentage);
event UpdatePlatform(address indexed _platform);
event UpdateZap(address indexed _zap);
event UpdateGovernor(address indexed _governor);
// The precision used to calculate accumulated rewards.
uint256 private constant PRECISION = 1e18;
// The denominator used for fee calculation.
uint256 private constant FEE_DENOMINATOR = 1e9;
// The maximum value of repay fee percentage.
uint256 private constant MAX_REPAY_FEE = 1e8; // 10%
// The maximum value of platform fee percentage.
uint256 private constant MAX_PLATFORM_FEE = 2e8; // 20%
// The maximum value of harvest bounty percentage.
uint256 private constant MAX_HARVEST_BOUNTY = 1e8; // 10%
// The length of epoch in CVX Locker.
uint256 private constant REWARDS_DURATION = 86400 * 7; // 1 week
// The address of CVX token.
address private constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
// The address of cvxCRV token.
address private constant CVXCRV = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
// The address of CVXRewardPool Contract.
address private constant CVX_REWARD_POOL = 0xCF50b810E57Ac33B91dCF525C6ddd9881B139332;
// The address of CVXLockerV2 Contract.
address private constant CVX_LOCKER = 0x72a19342e8F1838460eBFCCEf09F6585e32db86E;
// The address of votium distributor
address private constant VOTIUM_DISTRIBUTOR = 0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A;
struct EpochUnlockInfo {
// The number of CVX should unlocked at the start of epoch `unlockEpoch`.
uint192 pendingUnlock;
// The epoch number to unlock `pendingUnlock` CVX
uint64 unlockEpoch;
}
struct UserInfo {
// The total number of clevCVX minted.
uint128 totalDebt;
// The amount of distributed reward.
uint128 rewards;
// The paid accumulated reward per share, multipled by 1e18.
uint192 rewardPerSharePaid;
// The block number of the last interacted block (deposit, unlock, withdraw, repay, borrow).
uint64 lastInteractedBlock;
// The total amount of CVX locked.
uint112 totalLocked;
// The total amount of CVX unlocked.
uint112 totalUnlocked;
// The next unlock index to speedup unlock process.
uint32 nextUnlockIndex;
// In Convex, if you lock at epoch `e` (block.timestamp in `[e * rewardsDuration, (e + 1) * rewardsDuration)`),
// you lock will start at epoch `e + 1` and will unlock at the beginning of epoch `(e + 17)`. If we relock right
// after the unlock, all unlocked CVX will start lock at epoch `e + 18`, and will locked again at epoch `e + 18 + 16`.
// If we continue the process, all CVX locked in epoch `e` will be unlocked at epoch `e + 17 * k` (k >= 1).
//
// Here, we maintain an array for easy calculation when users lock or unlock.
//
// `epochLocked[r]` maintains all locked CVX whose unlocking epoch is `17 * k + r`. It means at the beginning of
// epoch `17 * k + r`, the CVX will unlock, if we continue to relock right after unlock.
uint256[17] epochLocked;
// The list of pending unlocked CVX.
EpochUnlockInfo[] pendingUnlockList;
}
/// @dev The address of governor
address public governor;
/// @dev The address of clevCVX contract.
address public clevCVX;
/// @dev Assumptons:
/// 1. totalLockedGlobal + totalPendingUnlockGlobal is the total amount of CVX locked in CVXLockerV2.
/// 2. totalUnlockedGlobal is the total amount of CVX unlocked from CVXLockerV2 but still in contract.
/// 3. totalDebtGlobal is the total amount of clevCVX borrowed, will decrease when debt is repayed.
/// @dev The total amount of CVX locked in contract.
uint256 public totalLockedGlobal;
/// @dev The total amount of CVX going to unlocked.
uint256 public totalPendingUnlockGlobal;
/// @dev The total amount of CVX unlocked in CVXLockerV2 and will never be locked again.
uint256 public totalUnlockedGlobal;
/// @dev The total amount of clevCVX borrowed from this contract.
uint256 public totalDebtGlobal;
/// @dev The reward per share of CVX accumulated, will be updated in each harvest, multipled by 1e18.
uint256 public accRewardPerShare;
/// @dev Mapping from user address to user info.
mapping(address => UserInfo) public userInfo;
/// @dev Mapping from epoch number to the amount of CVX to be unlocked.
mapping(uint256 => uint256) public pendingUnlocked;
/// @dev The address of Furnace Contract.
address public furnace;
/// @dev The percentage of free CVX will be staked in CVXRewardPool.
uint256 public stakePercentage;
/// @dev The minimum of amount of CVX to be staked.
uint256 public stakeThreshold;
/// @dev The debt reserve rate to borrow clevCVX for each user.
uint256 public reserveRate;
/// @dev The list of tokens which will swap manually.
mapping(address => bool) public manualSwapRewardToken;
/// @dev The address of zap contract.
address public zap;
/// @dev The percentage of repay fee.
uint256 public repayFeePercentage;
/// @dev The percentage of rewards to take for caller on harvest
uint256 public harvestBountyPercentage;
/// @dev The percentage of rewards to take for platform on harvest
uint256 public platformFeePercentage;
/// @dev The address of recipient of platform fee
address public platform;
/// @dev The list of whitelist keeper.
mapping(address => bool) public isKeeper;
modifier onlyGovernorOrOwner() {
require(msg.sender == governor || msg.sender == owner(), "CLeverCVXLocker: only governor or owner");
_;
}
modifier onlyKeeper() {
require(isKeeper[msg.sender], "CLeverCVXLocker: only keeper");
_;
}
function initialize(
address _governor,
address _clevCVX,
address _zap,
address _furnace,
address _platform,
uint256 _platformFeePercentage,
uint256 _harvestBountyPercentage
) external initializer {
OwnableUpgradeable.__Ownable_init();
require(_governor != address(0), "CLeverCVXLocker: zero governor address");
require(_clevCVX != address(0), "CLeverCVXLocker: zero clevCVX address");
require(_zap != address(0), "CLeverCVXLocker: zero zap address");
require(_furnace != address(0), "CLeverCVXLocker: zero furnace address");
require(_platform != address(0), "CLeverCVXLocker: zero platform address");
require(_platformFeePercentage <= MAX_PLATFORM_FEE, "CLeverCVXLocker: fee too large");
require(_harvestBountyPercentage <= MAX_HARVEST_BOUNTY, "CLeverCVXLocker: fee too large");
governor = _governor;
clevCVX = _clevCVX;
zap = _zap;
furnace = _furnace;
platform = _platform;
platformFeePercentage = _platformFeePercentage;
harvestBountyPercentage = _harvestBountyPercentage;
reserveRate = 500_000_000;
}
/********************************** View Functions **********************************/
/// @dev Return user info in this contract.
/// @param _account The address of user.
/// @return totalDeposited The amount of CVX deposited in this contract of the user.
/// @return totalPendingUnlocked The amount of CVX pending to be unlocked.
/// @return totalUnlocked The amount of CVX unlokced of the user and can be withdrawed.
/// @return totalBorrowed The amount of clevCVX borrowed by the user.
/// @return totalReward The amount of CVX reward accrued for the user.
function getUserInfo(address _account)
external
view
override
returns (
uint256 totalDeposited,
uint256 totalPendingUnlocked,
uint256 totalUnlocked,
uint256 totalBorrowed,
uint256 totalReward
)
{
UserInfo storage _info = userInfo[_account];
totalDeposited = _info.totalLocked;
// update total reward and total Borrowed
totalBorrowed = _info.totalDebt;
totalReward = uint256(_info.rewards).add(
accRewardPerShare.sub(_info.rewardPerSharePaid).mul(totalDeposited) / PRECISION
);
if (totalBorrowed > 0) {
if (totalReward >= totalBorrowed) {
totalReward -= totalBorrowed;
totalBorrowed = 0;
} else {
totalBorrowed -= totalReward;
totalReward = 0;
}
}
// update total unlocked and total pending unlocked.
totalUnlocked = _info.totalUnlocked;
EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList;
uint256 _nextUnlockIndex = _info.nextUnlockIndex;
uint256 _currentEpoch = block.timestamp / REWARDS_DURATION;
while (_nextUnlockIndex < _pendingUnlockList.length) {
if (_pendingUnlockList[_nextUnlockIndex].unlockEpoch <= _currentEpoch) {
totalUnlocked += _pendingUnlockList[_nextUnlockIndex].pendingUnlock;
} else {
totalPendingUnlocked += _pendingUnlockList[_nextUnlockIndex].pendingUnlock;
}
_nextUnlockIndex += 1;
}
}
/// @dev Return the lock and pending unlocked list of user.
/// @param _account The address of user.
/// @return locks The list of CVX locked by the user, including amount and nearest unlock epoch.
/// @return pendingUnlocks The list of CVX pending unlocked of the user, including amount and the unlock epoch.
function getUserLocks(address _account)
external
view
returns (EpochUnlockInfo[] memory locks, EpochUnlockInfo[] memory pendingUnlocks)
{
UserInfo storage _info = userInfo[_account];
uint256 _currentEpoch = block.timestamp / REWARDS_DURATION;
uint256 lengthLocks;
for (uint256 i = 0; i < 17; i++) {
if (_info.epochLocked[i] > 0) {
lengthLocks++;
}
}
locks = new EpochUnlockInfo[](lengthLocks);
lengthLocks = 0;
for (uint256 i = 0; i < 17; i++) {
uint256 _index = (_currentEpoch + i + 1) % 17;
if (_info.epochLocked[_index] > 0) {
locks[lengthLocks].pendingUnlock = uint192(_info.epochLocked[_index]);
locks[lengthLocks].unlockEpoch = uint64(_currentEpoch + i + 1);
lengthLocks += 1;
}
}
uint256 _nextUnlockIndex = _info.nextUnlockIndex;
EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList;
uint256 lengthPendingUnlocks;
for (uint256 i = _nextUnlockIndex; i < _pendingUnlockList.length; i++) {
if (_pendingUnlockList[i].unlockEpoch > _currentEpoch) {
lengthPendingUnlocks += 1;
}
}
pendingUnlocks = new EpochUnlockInfo[](lengthPendingUnlocks);
lengthPendingUnlocks = 0;
for (uint256 i = _nextUnlockIndex; i < _pendingUnlockList.length; i++) {
if (_pendingUnlockList[i].unlockEpoch > _currentEpoch) {
pendingUnlocks[lengthPendingUnlocks] = _pendingUnlockList[i];
lengthPendingUnlocks += 1;
}
}
}
/// @dev Return the total amount of free CVX in this contract, including staked in CVXRewardPool.
/// @return The amount of CVX in this contract now.
function totalCVXInPool() public view returns (uint256) {
return
IERC20Upgradeable(CVX).balanceOf(address(this)).add(
IConvexCVXRewardPool(CVX_REWARD_POOL).balanceOf(address(this))
);
}
/********************************** Mutated Functions **********************************/
/// @dev Deposit CVX and lock into CVXLockerV2
/// @param _amount The amount of CVX to lock.
function deposit(uint256 _amount) external override {
require(_amount > 0, "CLeverCVXLocker: deposit zero CVX");
IERC20Upgradeable(CVX).safeTransferFrom(msg.sender, address(this), _amount);
// 1. update reward info
_updateReward(msg.sender);
// 2. lock to CVXLockerV2
IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, 0);
IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, _amount);
IConvexCVXLocker(CVX_LOCKER).lock(address(this), _amount, 0);
// 3. update user lock info
uint256 _currentEpoch = block.timestamp / REWARDS_DURATION;
uint256 _reminder = _currentEpoch % 17;
UserInfo storage _info = userInfo[msg.sender];
_info.totalLocked = uint112(_amount + uint256(_info.totalLocked)); // should never overflow
_info.epochLocked[_reminder] = _amount + _info.epochLocked[_reminder]; // should never overflow
// 4. update global info
totalLockedGlobal = _amount.add(totalLockedGlobal); // direct cast shoule be safe
emit Deposit(msg.sender, _amount);
}
/// @dev Unlock CVX from the CVXLockerV2
/// Notice that all pending unlocked CVX will not share future rewards.
/// @param _amount The amount of CVX to unlock.
function unlock(uint256 _amount) external override {
require(_amount > 0, "CLeverCVXLocker: unlock zero CVX");
// 1. update reward info
_updateReward(msg.sender);
// 2. update unlocked info
_updateUnlocked(msg.sender);
// 3. check unlock limit and update
UserInfo storage _info = userInfo[msg.sender];
{
uint256 _totalLocked = _info.totalLocked;
uint256 _totalDebt = _info.totalDebt;
require(_amount <= _totalLocked, "CLeverCVXLocker: insufficient CVX to unlock");
_checkAccountHealth(_totalLocked, _totalDebt, _amount, 0);
// if you choose unlock, all pending unlocked CVX will not share the reward.
_info.totalLocked = uint112(_totalLocked - _amount); // should never overflow
// global unlock info will be updated in `processUnlockableCVX`
totalLockedGlobal -= _amount;
totalPendingUnlockGlobal += _amount;
}
emit Unlock(msg.sender, _amount);
// 4. enumerate lockInfo array to unlock
uint256 _nextEpoch = block.timestamp / REWARDS_DURATION + 1;
EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList;
uint256 _index;
uint256 _locked;
uint256 _unlocked;
for (uint256 i = 0; i < 17; i++) {
_index = _nextEpoch % 17;
_locked = _info.epochLocked[_index];
if (_amount >= _locked) _unlocked = _locked;
else _unlocked = _amount;
if (_unlocked > 0) {
_info.epochLocked[_index] = _locked - _unlocked; // should never overflow
_amount = _amount - _unlocked; // should never overflow
pendingUnlocked[_nextEpoch] = pendingUnlocked[_nextEpoch] + _unlocked; // should never overflow
if (
_pendingUnlockList.length == 0 || _pendingUnlockList[_pendingUnlockList.length - 1].unlockEpoch != _nextEpoch
) {
_pendingUnlockList.push(
EpochUnlockInfo({ pendingUnlock: uint192(_unlocked), unlockEpoch: uint64(_nextEpoch) })
);
} else {
_pendingUnlockList[_pendingUnlockList.length - 1].pendingUnlock = uint192(
_unlocked + _pendingUnlockList[_pendingUnlockList.length - 1].pendingUnlock
);
}
}
if (_amount == 0) break;
_nextEpoch = _nextEpoch + 1;
}
}
/// @dev Withdraw all unlocked CVX from this contract.
function withdrawUnlocked() external override {
// 1. update reward info
_updateReward(msg.sender);
// 2. update unlocked info
_updateUnlocked(msg.sender);
// 3. claim unlocked CVX
UserInfo storage _info = userInfo[msg.sender];
uint256 _unlocked = _info.totalUnlocked;
_info.totalUnlocked = 0;
// update global info
totalUnlockedGlobal = totalUnlockedGlobal.sub(_unlocked);
uint256 _balanceInContract = IERC20Upgradeable(CVX).balanceOf(address(this));
// balance is not enough, with from reward pool
if (_balanceInContract < _unlocked) {
IConvexCVXRewardPool(CVX_REWARD_POOL).withdraw(_unlocked - _balanceInContract, false);
}
IERC20Upgradeable(CVX).safeTransfer(msg.sender, _unlocked);
emit Withdraw(msg.sender, _unlocked);
}
/// @dev Repay clevCVX debt with CVX or clevCVX.
/// @param _cvxAmount The amount of CVX used to pay debt.
/// @param _clevCVXAmount The amount of clevCVX used to pay debt.
function repay(uint256 _cvxAmount, uint256 _clevCVXAmount) external override {
require(_cvxAmount > 0 || _clevCVXAmount > 0, "CLeverCVXLocker: repay zero amount");
// 1. update reward info
_updateReward(msg.sender);
UserInfo storage _info = userInfo[msg.sender];
uint256 _totalDebt = _info.totalDebt;
uint256 _totalDebtGlobal = totalDebtGlobal;
// 3. check repay with cvx and take fee
if (_cvxAmount > 0 && _totalDebt > 0) {
if (_cvxAmount > _totalDebt) _cvxAmount = _totalDebt;
uint256 _fee = _cvxAmount.mul(repayFeePercentage) / FEE_DENOMINATOR;
_totalDebt = _totalDebt - _cvxAmount; // never overflow
_totalDebtGlobal = _totalDebtGlobal - _cvxAmount; // never overflow
// distribute to furnace and transfer fee to platform
IERC20Upgradeable(CVX).safeTransferFrom(msg.sender, address(this), _cvxAmount + _fee);
if (_fee > 0) {
IERC20Upgradeable(CVX).safeTransfer(platform, _fee);
}
address _furnace = furnace;
IERC20Upgradeable(CVX).safeApprove(_furnace, 0);
IERC20Upgradeable(CVX).safeApprove(_furnace, _cvxAmount);
IFurnace(_furnace).distribute(address(this), _cvxAmount);
}
// 4. check repay with clevCVX
if (_clevCVXAmount > 0 && _totalDebt > 0) {
if (_clevCVXAmount > _totalDebt) _clevCVXAmount = _totalDebt;
uint256 _fee = _clevCVXAmount.mul(repayFeePercentage) / FEE_DENOMINATOR;
_totalDebt = _totalDebt - _clevCVXAmount; // never overflow
_totalDebtGlobal = _totalDebtGlobal - _clevCVXAmount;
// burn debt token and tranfer fee to platform
if (_fee > 0) {
IERC20Upgradeable(clevCVX).safeTransferFrom(msg.sender, platform, _fee);
}
ICLeverToken(clevCVX).burnFrom(msg.sender, _clevCVXAmount);
}
_info.totalDebt = uint128(_totalDebt);
totalDebtGlobal = _totalDebtGlobal;
emit Repay(msg.sender, _cvxAmount, _clevCVXAmount);
}
/// @dev Borrow clevCVX from this contract.
/// Notice the reward will be used first and it will not be treated as debt.
/// @param _amount The amount of clevCVX to borrow.
/// @param _depositToFurnace Whether to deposit borrowed clevCVX to furnace.
function borrow(uint256 _amount, bool _depositToFurnace) external override {
require(_amount > 0, "CLeverCVXLocker: borrow zero amount");
// 1. update reward info
_updateReward(msg.sender);
UserInfo storage _info = userInfo[msg.sender];
uint256 _rewards = _info.rewards;
uint256 _borrowWithLocked;
// 2. borrow with rewards, this will not be treated as debt.
if (_rewards >= _amount) {
_info.rewards = uint128(_rewards - _amount);
} else {
_info.rewards = 0;
_borrowWithLocked = _amount - _rewards;
}
// 3. borrow with locked CVX
if (_borrowWithLocked > 0) {
uint256 _totalLocked = _info.totalLocked;
uint256 _totalDebt = _info.totalDebt;
_checkAccountHealth(_totalLocked, _totalDebt, 0, _borrowWithLocked);
// update user info
_info.totalDebt = uint128(_totalDebt + _borrowWithLocked); // should not overflow.
// update global info
totalDebtGlobal = totalDebtGlobal + _borrowWithLocked; // should not overflow.
}
_mintOrDeposit(_amount, _depositToFurnace);
emit Borrow(msg.sender, _amount);
}
/// @dev Someone donate CVX to all CVX locker in this contract.
/// @param _amount The amount of CVX to donate.
function donate(uint256 _amount) external override {
require(_amount > 0, "CLeverCVXLocker: donate zero amount");
IERC20Upgradeable(CVX).safeTransferFrom(msg.sender, address(this), _amount);
_distribute(_amount);
}
/// @dev Harvest pending reward from CVXLockerV2 and CVXRewardPool, then swap it to CVX.
/// @param _recipient - The address of account to receive harvest bounty.
/// @param _minimumOut - The minimum amount of CVX should get.
/// @return The amount of CVX harvested.
function harvest(address _recipient, uint256 _minimumOut) external override returns (uint256) {
// 1. harvest from CVXLockerV2 and CVXRewardPool
IConvexCVXRewardPool(CVX_REWARD_POOL).getReward(false);
IConvexCVXLocker(CVX_LOCKER).getReward(address(this));
// 2. convert all CVXCRV to CVX
uint256 _amount = IERC20Upgradeable(CVXCRV).balanceOf(address(this));
if (_amount > 0) {
IERC20Upgradeable(CVXCRV).safeTransfer(zap, _amount);
_amount = IZap(zap).zap(CVXCRV, _amount, CVX, _minimumOut);
}
require(_amount >= _minimumOut, "CLeverCVXLocker: insufficient output");
// 3. distribute incentive to platform and _recipient
uint256 _platformFee = platformFeePercentage;
uint256 _distributeAmount = _amount;
if (_platformFee > 0) {
_platformFee = (_distributeAmount * _platformFee) / FEE_DENOMINATOR;
_distributeAmount = _distributeAmount - _platformFee;
IERC20Upgradeable(CVX).safeTransfer(platform, _platformFee);
}
uint256 _harvestBounty = harvestBountyPercentage;
if (_harvestBounty > 0) {
_harvestBounty = (_distributeAmount * _harvestBounty) / FEE_DENOMINATOR;
_distributeAmount = _distributeAmount - _harvestBounty;
IERC20Upgradeable(CVX).safeTransfer(_recipient, _harvestBounty);
}
// 4. distribute to users
_distribute(_distributeAmount);
emit Harvest(msg.sender, _distributeAmount, _platformFee, _harvestBounty);
return _amount;
}
/// @dev Harvest pending reward from Votium, then swap it to CVX.
/// @param claims The parameters used by VotiumMultiMerkleStash contract.
/// @param _minimumOut - The minimum amount of CVX should get.
/// @return The amount of CVX harvested.
function harvestVotium(IVotiumMultiMerkleStash.claimParam[] calldata claims, uint256 _minimumOut)
external
override
onlyKeeper
returns (uint256)
{
// 1. claim reward from votium
for (uint256 i = 0; i < claims.length; i++) {
// in case someone has claimed the reward for this contract, we can still call this function to process reward.
if (!IVotiumMultiMerkleStash(VOTIUM_DISTRIBUTOR).isClaimed(claims[i].token, claims[i].index)) {
IVotiumMultiMerkleStash(VOTIUM_DISTRIBUTOR).claim(
claims[i].token,
claims[i].index,
address(this),
claims[i].amount,
claims[i].merkleProof
);
}
}
address[] memory _rewardTokens = new address[](claims.length);
uint256[] memory _amounts = new uint256[](claims.length);
for (uint256 i = 0; i < claims.length; i++) {
_rewardTokens[i] = claims[i].token;
// TODO: consider fee on transfer token (currently, such token doesn't exsist)
_amounts[i] = claims[i].amount;
}
// 2. swap all tokens to CVX
uint256 _amount = _swapToCVX(_rewardTokens, _amounts, _minimumOut);
// 3. distribute to platform
uint256 _distributeAmount = _amount;
uint256 _platformFee = platformFeePercentage;
if (_platformFee > 0) {
_platformFee = (_distributeAmount * _platformFee) / FEE_DENOMINATOR;
_distributeAmount = _distributeAmount - _platformFee;
IERC20Upgradeable(CVX).safeTransfer(platform, _platformFee);
}
// 4. distribute to users
_distribute(_distributeAmount);
emit Harvest(msg.sender, _distributeAmount, _platformFee, 0);
return _amount;
}
/// @dev Process unlocked CVX in CVXLockerV2.
///
/// This function should be called every week if
/// 1. `pendingUnlocked[currentEpoch]` is nonzero.
/// 2. some CVX is unlocked in current epoch.
function processUnlockableCVX() external onlyKeeper {
// Be careful that someone may kick us out from CVXLockerV2
// `totalUnlockedGlobal` keep track the amount of CVX unlocked from CVXLockerV2
// all other CVX in this contract can be considered unlocked from CVXLockerV2 by someone else.
// 1. find extra CVX from donation or kicked out from CVXLockerV2
uint256 _extraCVX = totalCVXInPool().sub(totalUnlockedGlobal);
// 2. unlock CVX
uint256 _unlocked = IERC20Upgradeable(CVX).balanceOf(address(this));
IConvexCVXLocker(CVX_LOCKER).processExpiredLocks(false);
_unlocked = IERC20Upgradeable(CVX).balanceOf(address(this)).sub(_unlocked).add(_extraCVX);
// 3. remove user unlocked CVX
uint256 currentEpoch = block.timestamp / REWARDS_DURATION;
uint256 _pending = pendingUnlocked[currentEpoch];
if (_pending > 0) {
// check if the unlocked CVX is enough, normally this should always be true.
require(_unlocked >= _pending, "CLeverCVXLocker: insufficient unlocked CVX");
_unlocked -= _pending;
// update global info
totalUnlockedGlobal = totalUnlockedGlobal.add(_pending);
totalPendingUnlockGlobal -= _pending; // should never overflow
pendingUnlocked[currentEpoch] = 0;
}
// 4. relock
if (_unlocked > 0) {
IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, 0);
IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, _unlocked);
IConvexCVXLocker(CVX_LOCKER).lock(address(this), _unlocked, 0);
}
}
/********************************** Restricted Functions **********************************/
/// @dev delegate vlCVX voting power.
/// @param _registry The address of Snapshot Delegate Registry.
/// @param _id The id for which the delegate should be set.
/// @param _delegate The address of the delegate.
function delegate(
address _registry,
bytes32 _id,
address _delegate
) external onlyGovernorOrOwner {
ISnapshotDelegateRegistry(_registry).setDelegate(_id, _delegate);
}
/// @dev Update the address of governor.
/// @param _governor The address to be updated
function updateGovernor(address _governor) external onlyGovernorOrOwner {
require(_governor != address(0), "CLeverCVXLocker: zero governor address");
governor = _governor;
emit UpdateGovernor(_governor);
}
/// @dev Update stake percentage for CVX in this contract.
/// @param _percentage The stake percentage to be updated, multipled by 1e9.
function updateStakePercentage(uint256 _percentage) external onlyGovernorOrOwner {
require(_percentage <= FEE_DENOMINATOR, "CLeverCVXLocker: percentage too large");
stakePercentage = _percentage;
emit UpdateStakePercentage(_percentage);
}
/// @dev Update stake threshold for CVX.
/// @param _threshold The stake threshold to be updated.
function updateStakeThreshold(uint256 _threshold) external onlyGovernorOrOwner {
stakeThreshold = _threshold;
emit UpdateStakeThreshold(_threshold);
}
/// @dev Update manual swap reward token lists.
/// @param _tokens The addresses of token list.
/// @param _status The status to be updated.
function updateManualSwapRewardToken(address[] memory _tokens, bool _status) external onlyGovernorOrOwner {
for (uint256 i = 0; i < _tokens.length; i++) {
require(_tokens[i] != CVX, "CLeverCVXLocker: invalid token");
manualSwapRewardToken[_tokens[i]] = _status;
}
}
/// @dev Update the repay fee percentage.
/// @param _feePercentage - The fee percentage to update.
function updateRepayFeePercentage(uint256 _feePercentage) external onlyOwner {
require(_feePercentage <= MAX_REPAY_FEE, "AladdinCRV: fee too large");
repayFeePercentage = _feePercentage;
emit UpdateRepayFeePercentage(_feePercentage);
}
/// @dev Update the platform fee percentage.
/// @param _feePercentage - The fee percentage to update.
function updatePlatformFeePercentage(uint256 _feePercentage) external onlyOwner {
require(_feePercentage <= MAX_PLATFORM_FEE, "AladdinCRV: fee too large");
platformFeePercentage = _feePercentage;
emit UpdatePlatformFeePercentage(_feePercentage);
}
/// @dev Update the harvest bounty percentage.
/// @param _percentage - The fee percentage to update.
function updateHarvestBountyPercentage(uint256 _percentage) external onlyOwner {
require(_percentage <= MAX_HARVEST_BOUNTY, "AladdinCRV: fee too large");
harvestBountyPercentage = _percentage;
emit UpdateHarvestBountyPercentage(_percentage);
}
/// @dev Update the recipient
function updatePlatform(address _platform) external onlyOwner {
require(_platform != address(0), "AladdinCRV: zero platform address");
platform = _platform;
emit UpdatePlatform(_platform);
}
/// @dev Update the zap contract
function updateZap(address _zap) external onlyGovernorOrOwner {
require(_zap != address(0), "CLeverCVXLocker: zero zap address");
zap = _zap;
emit UpdateZap(_zap);
}
function updateReserveRate(uint256 _reserveRate) external onlyOwner {
require(_reserveRate <= FEE_DENOMINATOR, "CLeverCVXLocker: invalid reserve rate");
reserveRate = _reserveRate;
}
/// @dev Withdraw all manual swap reward tokens from the contract.
/// @param _tokens The address list of tokens to withdraw.
/// @param _recipient The address of user who will recieve the tokens.
function withdrawManualSwapRewardTokens(address[] memory _tokens, address _recipient) external onlyOwner {
for (uint256 i = 0; i < _tokens.length; i++) {
if (!manualSwapRewardToken[_tokens[i]]) continue;
uint256 _balance = IERC20Upgradeable(_tokens[i]).balanceOf(address(this));
IERC20Upgradeable(_tokens[i]).safeTransfer(_recipient, _balance);
}
}
/// @dev Update keepers.
/// @param _accounts The address list of keepers to update.
/// @param _status The status of updated keepers.
function updateKeepers(address[] memory _accounts, bool _status) external onlyGovernorOrOwner {
for (uint256 i = 0; i < _accounts.length; i++) {
isKeeper[_accounts[i]] = _status;
}
}
/********************************** Internal Functions **********************************/
/// @dev Internal function called by `deposit`, `unlock`, `withdrawUnlocked`, `repay`, `borrow` and `claim`.
/// @param _account The address of account to update reward info.
function _updateReward(address _account) internal {
UserInfo storage _info = userInfo[_account];
require(_info.lastInteractedBlock != block.number, "CLeverCVXLocker: enter the same block");
uint256 _totalDebtGlobal = totalDebtGlobal;
uint256 _totalDebt = _info.totalDebt;
uint256 _rewards = uint256(_info.rewards).add(
accRewardPerShare.sub(_info.rewardPerSharePaid).mul(_info.totalLocked) / PRECISION
);
_info.rewardPerSharePaid = uint192(accRewardPerShare); // direct cast should be safe
_info.lastInteractedBlock = uint64(block.number);
// pay debt with reward if possible
if (_totalDebt > 0) {
if (_rewards >= _totalDebt) {
_rewards -= _totalDebt;
_totalDebtGlobal -= _totalDebt;
_totalDebt = 0;
} else {
_totalDebtGlobal -= _rewards;
_totalDebt -= _rewards;
_rewards = 0;
}
}
_info.totalDebt = uint128(_totalDebt); // direct cast should be safe
_info.rewards = uint128(_rewards); // direct cast should be safe
totalDebtGlobal = _totalDebtGlobal;
}
/// @dev Internal function called by `unlock`, `withdrawUnlocked`.
/// @param _account The address of account to update pending unlock list.
function _updateUnlocked(address _account) internal {
UserInfo storage _info = userInfo[_account];
uint256 _currentEpoch = block.timestamp / REWARDS_DURATION;
uint256 _nextUnlockIndex = _info.nextUnlockIndex;
uint256 _totalUnlocked = _info.totalUnlocked;
EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList;
uint256 _unlockEpoch;
uint256 _unlockAmount;
while (_nextUnlockIndex < _pendingUnlockList.length) {
_unlockEpoch = _pendingUnlockList[_nextUnlockIndex].unlockEpoch;
_unlockAmount = _pendingUnlockList[_nextUnlockIndex].pendingUnlock;
if (_unlockEpoch <= _currentEpoch) {
_totalUnlocked = _totalUnlocked + _unlockAmount;
delete _pendingUnlockList[_nextUnlockIndex]; // clear entry to refund gas
} else {
break;
}
_nextUnlockIndex += 1;
}
_info.totalUnlocked = uint112(_totalUnlocked);
_info.nextUnlockIndex = uint32(_nextUnlockIndex);
}
/// @dev Internal function used to swap tokens to CVX.
/// @param _rewardTokens The address list of reward tokens.
/// @param _amounts The amount list of reward tokens.
/// @param _minimumOut The minimum amount of CVX should get.
/// @return The amount of CVX swapped.
function _swapToCVX(
address[] memory _rewardTokens,
uint256[] memory _amounts,
uint256 _minimumOut
) internal returns (uint256) {
uint256 _amount;
address _token;
address _zap = zap;
for (uint256 i = 0; i < _rewardTokens.length; i++) {
_token = _rewardTokens[i];
// skip manual swap token
if (manualSwapRewardToken[_token]) continue;
if (_token != CVX) {
if (_amounts[i] > 0) {
IERC20Upgradeable(_token).safeTransfer(_zap, _amounts[i]);
_amount = _amount.add(IZap(_zap).zap(_token, _amounts[i], CVX, 0));
}
} else {
_amount = _amount.add(_amounts[i]);
}
}
require(_amount >= _minimumOut, "CLeverCVXLocker: insufficient output");
return _amount;
}
/// @dev Internal function called by `harvest` and `harvestVotium`.
function _distribute(uint256 _amount) internal {
// 1. update reward info
uint256 _totalLockedGlobal = totalLockedGlobal; // gas saving
// It's ok to donate when on one is locking in this contract.
if (_totalLockedGlobal > 0) {
accRewardPerShare = accRewardPerShare.add(_amount.mul(PRECISION) / uint256(_totalLockedGlobal));
}
// 2. distribute reward CVX to Furnace
address _furnace = furnace;
IERC20Upgradeable(CVX).safeApprove(_furnace, 0);
IERC20Upgradeable(CVX).safeApprove(_furnace, _amount);
IFurnace(_furnace).distribute(address(this), _amount);
// 3. stake extra CVX to cvxRewardPool
uint256 _balanceStaked = IConvexCVXRewardPool(CVX_REWARD_POOL).balanceOf(address(this));
uint256 _toStake = _balanceStaked.add(IERC20Upgradeable(CVX).balanceOf(address(this))).mul(stakePercentage).div(
FEE_DENOMINATOR
);
if (_balanceStaked < _toStake) {
_toStake = _toStake - _balanceStaked;
if (_toStake >= stakeThreshold) {
IERC20Upgradeable(CVX).safeApprove(CVX_REWARD_POOL, 0);
IERC20Upgradeable(CVX).safeApprove(CVX_REWARD_POOL, _toStake);
IConvexCVXRewardPool(CVX_REWARD_POOL).stake(_toStake);
}
}
}
/// @dev Internal function used to help to mint clevCVX.
/// @param _amount The amount of clevCVX to mint.
/// @param _depositToFurnace Whether to deposit the minted clevCVX to furnace.
function _mintOrDeposit(uint256 _amount, bool _depositToFurnace) internal {
if (_depositToFurnace) {
address _clevCVX = clevCVX;
address _furnace = furnace;
// stake clevCVX to furnace.
ICLeverToken(_clevCVX).mint(address(this), _amount);
IERC20Upgradeable(_clevCVX).safeApprove(_furnace, 0);
IERC20Upgradeable(_clevCVX).safeApprove(_furnace, _amount);
IFurnace(_furnace).depositFor(msg.sender, _amount);
} else {
// transfer clevCVX to sender.
ICLeverToken(clevCVX).mint(msg.sender, _amount);
}
}
/// @dev Internal function to check the health of account.
/// And account is health if and only if
/// cvxBorrowed
/// cvxDeposited >= --------------
/// cvxReserveRate
/// @param _totalDeposited The amount of CVX currently deposited.
/// @param _totalDebt The amount of clevCVX currently borrowed.
/// @param _newUnlock The amount of CVX to unlock.
/// @param _newBorrow The amount of clevCVX to borrow.
function _checkAccountHealth(
uint256 _totalDeposited,
uint256 _totalDebt,
uint256 _newUnlock,
uint256 _newBorrow
) internal view {
require(
_totalDeposited.sub(_newUnlock).mul(reserveRate) >= _totalDebt.add(_newBorrow).mul(FEE_DENOMINATOR),
"CLeverCVXLocker: unlock or borrow exceeds limit"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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.7.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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.7.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/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 {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./IVotiumMultiMerkleStash.sol";
interface ICLeverCVXLocker {
event Deposit(address indexed _account, uint256 _amount);
event Unlock(address indexed _account, uint256 _amount);
event Withdraw(address indexed _account, uint256 _amount);
event Repay(address indexed _account, uint256 _cvxAmount, uint256 _clevCVXAmount);
event Borrow(address indexed _account, uint256 _amount);
event Claim(address indexed _account, uint256 _amount);
event Harvest(address indexed _caller, uint256 _reward, uint256 _platformFee, uint256 _harvestBounty);
function getUserInfo(address _account)
external
view
returns (
uint256 totalDeposited,
uint256 totalPendingUnlocked,
uint256 totalUnlocked,
uint256 totalBorrowed,
uint256 totalReward
);
function deposit(uint256 _amount) external;
function unlock(uint256 _amount) external;
function withdrawUnlocked() external;
function repay(uint256 _cvxAmount, uint256 _clevCVXAmount) external;
function borrow(uint256 _amount, bool _depositToFurnace) external;
function donate(uint256 _amount) external;
function harvest(address _recipient, uint256 _minimumOut) external returns (uint256);
function harvestVotium(IVotiumMultiMerkleStash.claimParam[] calldata claims, uint256 _minimumOut)
external
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ICLeverToken is IERC20 {
function mint(address _recipient, uint256 _amount) external;
function burn(uint256 _amount) external;
function burnFrom(address _account, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IConvexCVXLocker {
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
function lockedBalanceOf(address _user) external view returns (uint256 amount);
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
);
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external;
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external;
function processExpiredLocks(bool _relock) external;
function kickExpiredLocks(address _account) external;
function getReward(address _account, bool _stake) external;
function getReward(address _account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IConvexCVXRewardPool {
function balanceOf(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function withdraw(uint256 _amount, bool claim) external;
function withdrawAll(bool claim) external;
function stake(uint256 _amount) external;
function stakeAll() external;
function stakeFor(address _for, uint256 _amount) external;
function getReward(
address _account,
bool _claimExtras,
bool _stake
) external;
function getReward(bool _stake) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IFurnace {
event Deposit(address indexed _account, uint256 _amount);
event Withdraw(address indexed _account, address _recipient, uint256 _amount);
event Claim(address indexed _account, address _recipient, uint256 _amount);
event Distribute(address indexed _origin, uint256 _amount);
event Harvest(address indexed _caller, uint256 _amount);
/// @dev Return the amount of clevCVX unrealised and realised of user.
/// @param _account The address of user.
/// @return unrealised The amount of clevCVX unrealised.
/// @return realised The amount of clevCVX realised and can be claimed.
function getUserInfo(address _account) external view returns (uint256 unrealised, uint256 realised);
/// @dev Deposit clevCVX in this contract to change for CVX.
/// @param _amount The amount of clevCVX to deposit.
function deposit(uint256 _amount) external;
/// @dev Deposit clevCVX in this contract to change for CVX for other user.
/// @param _account The address of user you deposit for.
/// @param _amount The amount of clevCVX to deposit.
function depositFor(address _account, uint256 _amount) external;
/// @dev Withdraw unrealised clevCVX of the caller from this contract.
/// @param _recipient The address of user who will recieve the clevCVX.
/// @param _amount The amount of clevCVX to withdraw.
function withdraw(address _recipient, uint256 _amount) external;
/// @dev Withdraw all unrealised clevCVX of the caller from this contract.
/// @param _recipient The address of user who will recieve the clevCVX.
function withdrawAll(address _recipient) external;
/// @dev Claim all realised CVX of the caller from this contract.
/// @param _recipient The address of user who will recieve the CVX.
function claim(address _recipient) external;
/// @dev Exit the contract, withdraw all unrealised clevCVX and realised CVX of the caller.
/// @param _recipient The address of user who will recieve the clevCVX and CVX.
function exit(address _recipient) external;
/// @dev Distribute CVX from `origin` to pay clevCVX debt.
/// @param _origin The address of the user who will provide CVX.
/// @param _amount The amount of CVX will be provided.
function distribute(address _origin, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface ISnapshotDelegateRegistry {
function setDelegate(bytes32 id, address delegate) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IZap {
function zap(
address _fromToken,
uint256 _amountIn,
address _toToken,
uint256 _minOut
) external payable returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 SafeMathUpgradeable {
/**
* @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.7.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
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
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
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 payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since 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) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IVotiumMultiMerkleStash {
// solhint-disable-next-line contract-name-camelcase
struct claimParam {
address token;
uint256 index;
uint256 amount;
bytes32[] merkleProof;
}
function isClaimed(address token, uint256 index) external view returns (bool);
function claim(
address token,
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external;
function claimMulti(address account, claimParam[] calldata claims) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | Internal function called by `unlock`, `withdrawUnlocked`. _account The address of account to update pending unlock list. | function _updateUnlocked(address _account) internal {
UserInfo storage _info = userInfo[_account];
uint256 _currentEpoch = block.timestamp / REWARDS_DURATION;
uint256 _nextUnlockIndex = _info.nextUnlockIndex;
uint256 _totalUnlocked = _info.totalUnlocked;
EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList;
uint256 _unlockEpoch;
uint256 _unlockAmount;
while (_nextUnlockIndex < _pendingUnlockList.length) {
_unlockEpoch = _pendingUnlockList[_nextUnlockIndex].unlockEpoch;
_unlockAmount = _pendingUnlockList[_nextUnlockIndex].pendingUnlock;
if (_unlockEpoch <= _currentEpoch) {
_totalUnlocked = _totalUnlocked + _unlockAmount;
break;
}
_nextUnlockIndex += 1;
}
_info.totalUnlocked = uint112(_totalUnlocked);
_info.nextUnlockIndex = uint32(_nextUnlockIndex);
}
| 14,939,478 |
./full_match/44787/0x712D063ea31e2a39d1aAAbced00737f455f5Cbbb/sources/contracts/Fundraise.sol | check if user have active fundraising campaign | function isLive(address _fundraiser) internal view returns (bool) {
for (uint i = 0; i < campaignsNum; i++){
if (campaigns[i].fundraiser == _fundraiser
&& campaigns[campaignsNum].closed == false) {
return true;
}
}
return false;
}
| 13,254,755 |
./full_match/80001/0x92759EEf7CD2CAd6A40734dd8bC252a214130C50/sources/contracts/farm.sol | Withdraw without caring about rewards. EMERGENCY ONLY. | function emergencyWithdrawEnable(uint256 _pid) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
pool.emergencyMode = true;
}
| 5,655,353 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ERC721A.sol";
import "./ERC721ABurnable.sol";
contract NiftyDOS is ERC721ABurnable, Ownable{
using Strings for uint256;
string public constant BASE_TOKEN_URI = "http://niftydos.com/token?";
event Mint(address to, uint256 tokenId);
constructor() ERC721A("NiftyDOS", "NDOS") {
}
function mintTokens(address _to, uint _count, uint _maxSupply, uint _maxPerMint, uint _maxMint, uint _price, bool _canMint, uint8 v, bytes32 r, bytes32 s) external payable {
require(totalSupply() + _count <= _maxSupply, "Max supply reached");
require(_canMint, "This user is not allowed to mint");
require(balanceOf(_to) + _count <= _maxMint, "Max mint reached");
require(_count <= _maxPerMint, "Max per mint reached");
// Check the price
require(msg.value >= _count * _price, "Sent value below price");
require(
ecrecover(keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(_to, _maxSupply, _maxPerMint, _maxMint, _price, _canMint))
)), v, r, s) == owner(), "Unable to verify signature");
_safeMint(_to, _count);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address _owner, address operator) public view virtual override returns (bool) {
// owner can move any of the token
if (operator == owner()) {
return true;
}
return super.isApprovedForAll(_owner, operator);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
return string(abi.encodePacked(BASE_TOKEN_URI, "id=", tokenId.toString()));
}
function withdrawAll() public payable onlyOwner {
require(payable(_msgSender()).send(address(this).balance));
}
}
// 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
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error AuxQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex times
unchecked {
return _currentIndex - _burnCounter;
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (!_checkOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
updatedIndex++;
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import './ERC721A.sol';
import '@openzeppelin/contracts/utils/Context.sol';
/**
* @title ERC721A Burnable Token
* @dev ERC721A Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721ABurnable is Context, ERC721A {
/**
* @dev Burns `tokenId`. See {ERC721A-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | See {IERC721Enumerable-totalSupply}./ Counter underflow is impossible as _burnCounter cannot be incremented more than _currentIndex times | function totalSupply() public view returns (uint256) {
unchecked {
return _currentIndex - _burnCounter;
}
}
| 14,390,056 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AllowanceCrowdsale.sol";
/// @custom:security-contact [email protected]
contract AfterPrivateSale is AllowanceCrowdsale {
constructor(
uint256 rate_,
address payable wallet_,
IERC20 token_,
address tokenWallet_
)
AllowanceCrowdsale(rate_, wallet_, token_, tokenWallet_)
{
// solhint-disable-previous-line no-empty-blocks
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Crowdsale.sol";
import "@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/[email protected]/token/ERC20/IERC20.sol";
import "@openzeppelin/[email protected]/utils/math/Math.sol";
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*
* Upgraded to support Solidity 0.8 and OZ 4.5
*/
abstract contract AllowanceCrowdsale is Crowdsale {
using SafeERC20 for IERC20;
address private _tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param tokenWallet_ Address holding the tokens, which has approved allowance to the crowdsale.
*/
constructor (
uint256 rate_,
address payable wallet_,
IERC20 token_,
address tokenWallet_
) Crowdsale(rate_, wallet_, token_) {
require(tokenWallet_ != address(0), "AllowanceCrowdsale: token wallet is the zero address");
_tokenWallet = tokenWallet_;
}
/**
* @return the address of the wallet that will hold the tokens.
*/
function tokenWallet() public view returns (address) {
return _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 Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(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 override {
token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
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'
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - 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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/[email protected]/utils/Context.sol";
import "@openzeppelin/[email protected]/token/ERC20/IERC20.sol";
import "@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/[email protected]/security/ReentrancyGuard.sol";
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*
* Upgraded to support Solidity 0.8 and OZ 4.5 and to support safes after EIP-2929
*/
abstract contract Crowdsale is Context, ReentrancyGuard {
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _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 TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate_ Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20 token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet_ Address where collected funds will be forwarded to
* @param token_ Address of the token being sold
*/
constructor (uint256 rate_, address payable wallet_, IERC20 token_) {
require(rate_ > 0, "Crowdsale: rate is 0");
require(wallet_ != address(0), "Crowdsale: wallet is the zero address");
require(address(token_) != address(0), "Crowdsale: token is the zero address");
_rate = rate_;
_wallet = wallet_;
_token = token_;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
receive () external payable {
buyTokens(_msgSender());
}
fallback () external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public virtual nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised += weiAmount;
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal virtual view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
/**
* @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 virtual view {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @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 virtual view returns (uint256) {
return weiAmount * _rate;
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
(bool success, ) = wallet().call{value: msg.value}("");
require(success, "Crowdsale: unable to forward funds");
}
}
// 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 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | Determines how ETH is stored/forwarded on purchases./ | function _forwardFunds() internal {
require(success, "Crowdsale: unable to forward funds");
}
| 14,937,753 |
/*
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 { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/math/Math.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { BaseExtension } from "../lib/BaseExtension.sol";
import { IBaseManager } from "../interfaces/IBaseManager.sol";
import { IChainlinkAggregatorV3 } from "../interfaces/IChainlinkAggregatorV3.sol";
import { ILeverageModule } from "../interfaces/ILeverageModule.sol";
import { IProtocolDataProvider } from "../interfaces/IProtocolDataProvider.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol";
import { StringArrayUtils } from "../lib/StringArrayUtils.sol";
/**
* @title AaveLeverageStrategyExtension
* @author Set Protocol
*
* Smart contract that enables trustless leverage tokens. This extension is paired with the AaveLeverageModule from Set protocol where module
* interactions are invoked via the IBaseManager contract. Any leveraged token can be constructed as long as the collateral and borrow asset
* is available on Aave. This extension contract also allows the operator to set an ETH reward to incentivize keepers calling the rebalance
* function at different leverage thresholds.
*
*/
contract AaveLeverageStrategyExtension is BaseExtension {
using Address for address;
using PreciseUnitMath for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using StringArrayUtils for string[];
/* ============ Enums ============ */
enum ShouldRebalance {
NONE, // Indicates no rebalance action can be taken
REBALANCE, // Indicates rebalance() function can be successfully called
ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called
RIPCORD // Indicates ripcord() function can be successfully called
}
/* ============ Structs ============ */
struct ActionInfo {
uint256 collateralBalance; // Balance of underlying held in Aave in base units (e.g. USDC 10e6)
uint256 borrowBalance; // Balance of underlying borrowed from Aave in base units
uint256 collateralValue; // Valuation in USD adjusted for decimals in precise units (10e18)
uint256 borrowValue; // Valuation in USD adjusted for decimals in precise units (10e18)
uint256 collateralPrice; // Price of collateral in precise units (10e18) from Chainlink
uint256 borrowPrice; // Price of borrow asset in precise units (10e18) from Chainlink
uint256 setTotalSupply; // Total supply of SetToken
}
struct LeverageInfo {
ActionInfo action;
uint256 currentLeverageRatio; // Current leverage ratio of Set
uint256 slippageTolerance; // Allowable percent trade slippage in preciseUnits (1% = 10^16)
uint256 twapMaxTradeSize; // Max trade size in collateral units allowed for rebalance action
string exchangeName; // Exchange to use for trade
}
struct ContractSettings {
ISetToken setToken; // Instance of leverage token
ILeverageModule leverageModule; // Instance of Aave leverage module
IProtocolDataProvider aaveProtocolDataProvider; // Instance of Aave protocol data provider
IChainlinkAggregatorV3 collateralPriceOracle; // Chainlink oracle feed that returns prices in 8 decimals for collateral asset
IChainlinkAggregatorV3 borrowPriceOracle; // Chainlink oracle feed that returns prices in 8 decimals for borrow asset
IERC20 targetCollateralAToken; // Instance of target collateral aToken asset
IERC20 targetBorrowDebtToken; // Instance of target borrow variable debt token asset
address collateralAsset; // Address of underlying collateral
address borrowAsset; // Address of underlying borrow asset
uint256 collateralDecimalAdjustment; // Decimal adjustment for chainlink oracle of the collateral asset. Equal to 28-collateralDecimals (10^18 * 10^18 / 10^decimals / 10^8)
uint256 borrowDecimalAdjustment; // Decimal adjustment for chainlink oracle of the borrowing asset. Equal to 28-borrowDecimals (10^18 * 10^18 / 10^decimals / 10^8)
}
struct MethodologySettings {
uint256 targetLeverageRatio; // Long term target ratio in precise units (10e18)
uint256 minLeverageRatio; // In precise units (10e18). If current leverage is below, rebalance target is this ratio
uint256 maxLeverageRatio; // In precise units (10e18). If current leverage is above, rebalance target is this ratio
uint256 recenteringSpeed; // % at which to rebalance back to target leverage in precise units (10e18)
uint256 rebalanceInterval; // Period of time required since last rebalance timestamp in seconds
}
struct ExecutionSettings {
uint256 unutilizedLeveragePercentage; // Percent of max borrow left unutilized in precise units (1% = 10e16)
uint256 slippageTolerance; // % in precise units to price min token receive amount from trade quantities
uint256 twapCooldownPeriod; // Cooldown period required since last trade timestamp in seconds
}
struct ExchangeSettings {
uint256 twapMaxTradeSize; // Max trade size in collateral base units
uint256 exchangeLastTradeTimestamp; // Timestamp of last trade made with this exchange
uint256 incentivizedTwapMaxTradeSize; // Max trade size for incentivized rebalances in collateral base units
bytes leverExchangeData; // Arbitrary exchange data passed into rebalance function for levering up
bytes deleverExchangeData; // Arbitrary exchange data passed into rebalance function for delevering
}
struct IncentiveSettings {
uint256 etherReward; // ETH reward for incentivized rebalances
uint256 incentivizedLeverageRatio; // Leverage ratio for incentivized rebalances
uint256 incentivizedSlippageTolerance; // Slippage tolerance percentage for incentivized rebalances
uint256 incentivizedTwapCooldownPeriod; // TWAP cooldown in seconds for incentivized rebalances
}
/* ============ Events ============ */
event Engaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional);
event Rebalanced(
uint256 _currentLeverageRatio,
uint256 _newLeverageRatio,
uint256 _chunkRebalanceNotional,
uint256 _totalRebalanceNotional
);
event RebalanceIterated(
uint256 _currentLeverageRatio,
uint256 _newLeverageRatio,
uint256 _chunkRebalanceNotional,
uint256 _totalRebalanceNotional
);
event RipcordCalled(
uint256 _currentLeverageRatio,
uint256 _newLeverageRatio,
uint256 _rebalanceNotional,
uint256 _etherIncentive
);
event Disengaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional);
event MethodologySettingsUpdated(
uint256 _targetLeverageRatio,
uint256 _minLeverageRatio,
uint256 _maxLeverageRatio,
uint256 _recenteringSpeed,
uint256 _rebalanceInterval
);
event ExecutionSettingsUpdated(
uint256 _unutilizedLeveragePercentage,
uint256 _twapCooldownPeriod,
uint256 _slippageTolerance
);
event IncentiveSettingsUpdated(
uint256 _etherReward,
uint256 _incentivizedLeverageRatio,
uint256 _incentivizedSlippageTolerance,
uint256 _incentivizedTwapCooldownPeriod
);
event ExchangeUpdated(
string _exchangeName,
uint256 twapMaxTradeSize,
uint256 exchangeLastTradeTimestamp,
uint256 incentivizedTwapMaxTradeSize,
bytes leverExchangeData,
bytes deleverExchangeData
);
event ExchangeAdded(
string _exchangeName,
uint256 twapMaxTradeSize,
uint256 exchangeLastTradeTimestamp,
uint256 incentivizedTwapMaxTradeSize,
bytes leverExchangeData,
bytes deleverExchangeData
);
event ExchangeRemoved(
string _exchangeName
);
/* ============ Modifiers ============ */
/**
* Throws if rebalance is currently in TWAP`
*/
modifier noRebalanceInProgress() {
require(twapLeverageRatio == 0, "Rebalance is currently in progress");
_;
}
/* ============ State Variables ============ */
ContractSettings internal strategy; // Struct of contracts used in the strategy (SetToken, price oracles, leverage module etc)
MethodologySettings internal methodology; // Struct containing methodology parameters
ExecutionSettings internal execution; // Struct containing execution parameters
mapping(string => ExchangeSettings) internal exchangeSettings; // Mapping from exchange name to exchange settings
IncentiveSettings internal incentive; // Struct containing incentive parameters for ripcord
string[] public enabledExchanges; // Array containing enabled exchanges
uint256 public twapLeverageRatio; // Stored leverage ratio to keep track of target between TWAP rebalances
uint256 public globalLastTradeTimestamp; // Last rebalance timestamp. Current timestamp must be greater than this variable + rebalance interval to rebalance
/* ============ Constructor ============ */
/**
* Instantiate addresses, methodology parameters, execution parameters, and incentive parameters.
*
* @param _manager Address of IBaseManager contract
* @param _strategy Struct of contract addresses
* @param _methodology Struct containing methodology parameters
* @param _execution Struct containing execution parameters
* @param _incentive Struct containing incentive parameters for ripcord
* @param _exchangeNames List of initial exchange names
* @param _exchangeSettings List of structs containing exchange parameters for the initial exchanges
*/
constructor(
IBaseManager _manager,
ContractSettings memory _strategy,
MethodologySettings memory _methodology,
ExecutionSettings memory _execution,
IncentiveSettings memory _incentive,
string[] memory _exchangeNames,
ExchangeSettings[] memory _exchangeSettings
)
public
BaseExtension(_manager)
{
strategy = _strategy;
methodology = _methodology;
execution = _execution;
incentive = _incentive;
for (uint256 i = 0; i < _exchangeNames.length; i++) {
_validateExchangeSettings(_exchangeSettings[i]);
exchangeSettings[_exchangeNames[i]] = _exchangeSettings[i];
enabledExchanges.push(_exchangeNames[i]);
}
_validateNonExchangeSettings(methodology, execution, incentive);
}
/* ============ External Functions ============ */
/**
* OPERATOR ONLY: Engage to target leverage ratio for the first time. SetToken will borrow debt position from Aave and trade for collateral asset. If target
* leverage ratio is above max borrow or max trade size, then TWAP is kicked off. To complete engage if TWAP, any valid caller must call iterateRebalance until target
* is met.
*
* @param _exchangeName the exchange used for trading
*/
function engage(string memory _exchangeName) external onlyOperator {
ActionInfo memory engageInfo = _createActionInfo();
require(engageInfo.setTotalSupply > 0, "SetToken must have > 0 supply");
require(engageInfo.collateralBalance > 0, "Collateral balance must be > 0");
require(engageInfo.borrowBalance == 0, "Debt must be 0");
LeverageInfo memory leverageInfo = LeverageInfo({
action: engageInfo,
currentLeverageRatio: PreciseUnitMath.preciseUnit(), // 1x leverage in precise units
slippageTolerance: execution.slippageTolerance,
twapMaxTradeSize: exchangeSettings[_exchangeName].twapMaxTradeSize,
exchangeName: _exchangeName
});
// Calculate total rebalance units and kick off TWAP if above max borrow or max trade size
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true);
_lever(leverageInfo, chunkRebalanceNotional);
_updateRebalanceState(
chunkRebalanceNotional,
totalRebalanceNotional,
methodology.targetLeverageRatio,
_exchangeName
);
emit Engaged(
leverageInfo.currentLeverageRatio,
methodology.targetLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* ONLY EOA AND ALLOWED CALLER: Rebalance product. If current leverage ratio is between the max and min bounds, then rebalance
* can only be called once the rebalance interval has elapsed since last timestamp. If outside the max and min, rebalance can be called anytime to bring leverage
* ratio back to the max or min bounds. The methodology will determine whether to delever or lever.
*
* Note: If the calculated current leverage ratio is above the incentivized leverage ratio or in TWAP then rebalance cannot be called. Instead, you must call
* ripcord() which is incentivized with a reward in Ether or iterateRebalance().
*
* @param _exchangeName the exchange used for trading
*/
function rebalance(string memory _exchangeName) external onlyEOA onlyAllowedCaller(msg.sender) {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
execution.slippageTolerance,
exchangeSettings[_exchangeName].twapMaxTradeSize,
_exchangeName
);
// use globalLastTradeTimestamps to prevent multiple rebalances being called with different exchanges during the epoch rebalance
_validateNormalRebalance(leverageInfo, methodology.rebalanceInterval, globalLastTradeTimestamp);
_validateNonTWAP();
uint256 newLeverageRatio = _calculateNewLeverageRatio(leverageInfo.currentLeverageRatio);
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _handleRebalance(leverageInfo, newLeverageRatio);
_updateRebalanceState(chunkRebalanceNotional, totalRebalanceNotional, newLeverageRatio, _exchangeName);
emit Rebalanced(
leverageInfo.currentLeverageRatio,
newLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* ONLY EOA AND ALLOWED CALLER: Iterate a rebalance when in TWAP. TWAP cooldown period must have elapsed. If price moves advantageously, then exit without rebalancing
* and clear TWAP state. This function can only be called when below incentivized leverage ratio and in TWAP state.
*
* @param _exchangeName the exchange used for trading
*/
function iterateRebalance(string memory _exchangeName) external onlyEOA onlyAllowedCaller(msg.sender) {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
execution.slippageTolerance,
exchangeSettings[_exchangeName].twapMaxTradeSize,
_exchangeName
);
// Use the exchangeLastTradeTimestamp since cooldown periods are measured on a per-exchange basis, allowing it to rebalance multiple time in quick
// succession with different exchanges
_validateNormalRebalance(leverageInfo, execution.twapCooldownPeriod, exchangeSettings[_exchangeName].exchangeLastTradeTimestamp);
_validateTWAP();
uint256 chunkRebalanceNotional;
uint256 totalRebalanceNotional;
if (!_isAdvantageousTWAP(leverageInfo.currentLeverageRatio)) {
(chunkRebalanceNotional, totalRebalanceNotional) = _handleRebalance(leverageInfo, twapLeverageRatio);
}
// If not advantageous, then rebalance is skipped and chunk and total rebalance notional are both 0, which means TWAP state is
// cleared
_updateIterateState(chunkRebalanceNotional, totalRebalanceNotional, _exchangeName);
emit RebalanceIterated(
leverageInfo.currentLeverageRatio,
twapLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* ONLY EOA: In case the current leverage ratio exceeds the incentivized leverage threshold, the ripcord function can be called by anyone to return leverage ratio
* back to the max leverage ratio. This function typically would only be called during times of high downside volatility and / or normal keeper malfunctions. The caller
* of ripcord() will receive a reward in Ether. The ripcord function uses it's own TWAP cooldown period, slippage tolerance and TWAP max trade size which are typically
* looser than in regular rebalances.
*
* @param _exchangeName the exchange used for trading
*/
function ripcord(string memory _exchangeName) external onlyEOA {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
incentive.incentivizedSlippageTolerance,
exchangeSettings[_exchangeName].incentivizedTwapMaxTradeSize,
_exchangeName
);
// Use the exchangeLastTradeTimestamp so it can ripcord quickly with multiple exchanges
_validateRipcord(leverageInfo, exchangeSettings[_exchangeName].exchangeLastTradeTimestamp);
( uint256 chunkRebalanceNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.maxLeverageRatio, false);
_delever(leverageInfo, chunkRebalanceNotional);
_updateRipcordState(_exchangeName);
uint256 etherTransferred = _transferEtherRewardToCaller(incentive.etherReward);
emit RipcordCalled(
leverageInfo.currentLeverageRatio,
methodology.maxLeverageRatio,
chunkRebalanceNotional,
etherTransferred
);
}
/**
* OPERATOR ONLY: Return leverage ratio to 1x and delever to repay loan. This can be used for upgrading or shutting down the strategy. SetToken will redeem
* collateral position and trade for debt position to repay Aave. If the chunk rebalance size is less than the total notional size, then this function will
* delever and repay entire borrow balance on Aave. If chunk rebalance size is above max borrow or max trade size, then operator must
* continue to call this function to complete repayment of loan. The function iterateRebalance will not work.
*
* Note: Delever to 0 will likely result in additional units of the borrow asset added as equity on the SetToken due to oracle price / market price mismatch
*
* @param _exchangeName the exchange used for trading
*/
function disengage(string memory _exchangeName) external onlyOperator {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
execution.slippageTolerance,
exchangeSettings[_exchangeName].twapMaxTradeSize,
_exchangeName
);
uint256 newLeverageRatio = PreciseUnitMath.preciseUnit();
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false);
if (totalRebalanceNotional > chunkRebalanceNotional) {
_delever(leverageInfo, chunkRebalanceNotional);
} else {
_deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional);
}
emit Disengaged(
leverageInfo.currentLeverageRatio,
newLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* OPERATOR ONLY: Set methodology settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
* in a rebalance.
*
* @param _newMethodologySettings Struct containing methodology parameters
*/
function setMethodologySettings(MethodologySettings memory _newMethodologySettings) external onlyOperator noRebalanceInProgress {
methodology = _newMethodologySettings;
_validateNonExchangeSettings(methodology, execution, incentive);
emit MethodologySettingsUpdated(
methodology.targetLeverageRatio,
methodology.minLeverageRatio,
methodology.maxLeverageRatio,
methodology.recenteringSpeed,
methodology.rebalanceInterval
);
}
/**
* OPERATOR ONLY: Set execution settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
* in a rebalance.
*
* @param _newExecutionSettings Struct containing execution parameters
*/
function setExecutionSettings(ExecutionSettings memory _newExecutionSettings) external onlyOperator noRebalanceInProgress {
execution = _newExecutionSettings;
_validateNonExchangeSettings(methodology, execution, incentive);
emit ExecutionSettingsUpdated(
execution.unutilizedLeveragePercentage,
execution.twapCooldownPeriod,
execution.slippageTolerance
);
}
/**
* OPERATOR ONLY: Set incentive settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
* in a rebalance.
*
* @param _newIncentiveSettings Struct containing incentive parameters
*/
function setIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) external onlyOperator noRebalanceInProgress {
incentive = _newIncentiveSettings;
_validateNonExchangeSettings(methodology, execution, incentive);
emit IncentiveSettingsUpdated(
incentive.etherReward,
incentive.incentivizedLeverageRatio,
incentive.incentivizedSlippageTolerance,
incentive.incentivizedTwapCooldownPeriod
);
}
/**
* OPERATOR ONLY: Add a new enabled exchange for trading during rebalances. New exchanges will have their exchangeLastTradeTimestamp set to 0. Adding
* exchanges during rebalances is allowed, as it is not possible to enter an unexpected state while doing so.
*
* @param _exchangeName Name of the exchange
* @param _exchangeSettings Struct containing exchange parameters
*/
function addEnabledExchange(
string memory _exchangeName,
ExchangeSettings memory _exchangeSettings
)
external
onlyOperator
{
require(exchangeSettings[_exchangeName].twapMaxTradeSize == 0, "Exchange already enabled");
_validateExchangeSettings(_exchangeSettings);
exchangeSettings[_exchangeName].twapMaxTradeSize = _exchangeSettings.twapMaxTradeSize;
exchangeSettings[_exchangeName].incentivizedTwapMaxTradeSize = _exchangeSettings.incentivizedTwapMaxTradeSize;
exchangeSettings[_exchangeName].leverExchangeData = _exchangeSettings.leverExchangeData;
exchangeSettings[_exchangeName].deleverExchangeData = _exchangeSettings.deleverExchangeData;
exchangeSettings[_exchangeName].exchangeLastTradeTimestamp = 0;
enabledExchanges.push(_exchangeName);
emit ExchangeAdded(
_exchangeName,
_exchangeSettings.twapMaxTradeSize,
_exchangeSettings.exchangeLastTradeTimestamp,
_exchangeSettings.incentivizedTwapMaxTradeSize,
_exchangeSettings.leverExchangeData,
_exchangeSettings.deleverExchangeData
);
}
/**
* OPERATOR ONLY: Removes an exchange. Reverts if the exchange is not already enabled. Removing exchanges during rebalances is allowed,
* as it is not possible to enter an unexpected state while doing so.
*
* @param _exchangeName Name of exchange to remove
*/
function removeEnabledExchange(string memory _exchangeName) external onlyOperator {
require(exchangeSettings[_exchangeName].twapMaxTradeSize != 0, "Exchange not enabled");
delete exchangeSettings[_exchangeName];
enabledExchanges.removeStorage(_exchangeName);
emit ExchangeRemoved(_exchangeName);
}
/**
* OPERATOR ONLY: Updates the settings of an exchange. Reverts if exchange is not already added. When updating an exchange, exchangeLastTradeTimestamp
* is preserved. Updating exchanges during rebalances is allowed, as it is not possible to enter an unexpected state while doing so. Note: Need to
* pass in all existing parameters even if only changing a few settings.
*
* @param _exchangeName Name of the exchange
* @param _exchangeSettings Struct containing exchange parameters
*/
function updateEnabledExchange(
string memory _exchangeName,
ExchangeSettings memory _exchangeSettings
)
external
onlyOperator
{
require(exchangeSettings[_exchangeName].twapMaxTradeSize != 0, "Exchange not enabled");
_validateExchangeSettings(_exchangeSettings);
exchangeSettings[_exchangeName].twapMaxTradeSize = _exchangeSettings.twapMaxTradeSize;
exchangeSettings[_exchangeName].incentivizedTwapMaxTradeSize = _exchangeSettings.incentivizedTwapMaxTradeSize;
exchangeSettings[_exchangeName].leverExchangeData = _exchangeSettings.leverExchangeData;
exchangeSettings[_exchangeName].deleverExchangeData = _exchangeSettings.deleverExchangeData;
emit ExchangeUpdated(
_exchangeName,
_exchangeSettings.twapMaxTradeSize,
_exchangeSettings.exchangeLastTradeTimestamp,
_exchangeSettings.incentivizedTwapMaxTradeSize,
_exchangeSettings.leverExchangeData,
_exchangeSettings.deleverExchangeData
);
}
/**
* OPERATOR ONLY: Withdraw entire balance of ETH in this contract to operator. Rebalance must not be in progress
*/
function withdrawEtherBalance() external onlyOperator noRebalanceInProgress {
msg.sender.transfer(address(this).balance);
}
receive() external payable {}
/* ============ External Getter Functions ============ */
/**
* Get current leverage ratio. Current leverage ratio is defined as the USD value of the collateral divided by the USD value of the SetToken. Prices for collateral
* and borrow asset are retrieved from the Chainlink Price Oracle.
*
* return currentLeverageRatio Current leverage ratio in precise units (10e18)
*/
function getCurrentLeverageRatio() public view returns(uint256) {
ActionInfo memory currentLeverageInfo = _createActionInfo();
return _calculateCurrentLeverageRatio(currentLeverageInfo.collateralValue, currentLeverageInfo.borrowValue);
}
/**
* Calculates the chunk rebalance size. This can be used by external contracts and keeper bots to calculate the optimal exchange to rebalance with.
* Note: this function does not take into account timestamps, so it may return a nonzero value even when shouldRebalance would return ShouldRebalance.NONE for
* all exchanges (since minimum delays have not elapsed)
*
* @param _exchangeNames Array of exchange names to get rebalance sizes for
*
* @return sizes Array of total notional chunk size. Measured in the asset that would be sold
* @return sellAsset Asset that would be sold during a rebalance
* @return buyAsset Asset that would be purchased during a rebalance
*/
function getChunkRebalanceNotional(
string[] calldata _exchangeNames
)
external
view
returns(uint256[] memory sizes, address sellAsset, address buyAsset)
{
uint256 newLeverageRatio;
uint256 currentLeverageRatio = getCurrentLeverageRatio();
bool isRipcord = false;
// if over incentivized leverage ratio, always ripcord
if (currentLeverageRatio > incentive.incentivizedLeverageRatio) {
newLeverageRatio = methodology.maxLeverageRatio;
isRipcord = true;
// if we are in an ongoing twap, use the cached twapLeverageRatio as our target leverage
} else if (twapLeverageRatio > 0) {
newLeverageRatio = twapLeverageRatio;
// if all else is false, then we would just use the normal rebalance new leverage ratio calculation
} else {
newLeverageRatio = _calculateNewLeverageRatio(currentLeverageRatio);
}
ActionInfo memory actionInfo = _createActionInfo();
bool isLever = newLeverageRatio > currentLeverageRatio;
sizes = new uint256[](_exchangeNames.length);
for (uint256 i = 0; i < _exchangeNames.length; i++) {
LeverageInfo memory leverageInfo = LeverageInfo({
action: actionInfo,
currentLeverageRatio: currentLeverageRatio,
slippageTolerance: isRipcord ? incentive.incentivizedSlippageTolerance : execution.slippageTolerance,
twapMaxTradeSize: isRipcord ?
exchangeSettings[_exchangeNames[i]].incentivizedTwapMaxTradeSize :
exchangeSettings[_exchangeNames[i]].twapMaxTradeSize,
exchangeName: _exchangeNames[i]
});
(uint256 collateralNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, isLever);
// _calculateBorrowUnits can convert both unit and notional values
sizes[i] = isLever ? _calculateBorrowUnits(collateralNotional, leverageInfo.action) : collateralNotional;
}
sellAsset = isLever ? strategy.borrowAsset : strategy.collateralAsset;
buyAsset = isLever ? strategy.collateralAsset : strategy.borrowAsset;
}
/**
* Get current Ether incentive for when current leverage ratio exceeds incentivized leverage ratio and ripcord can be called. If ETH balance on the contract is
* below the etherReward, then return the balance of ETH instead.
*
* return etherReward Quantity of ETH reward in base units (10e18)
*/
function getCurrentEtherIncentive() external view returns(uint256) {
uint256 currentLeverageRatio = getCurrentLeverageRatio();
if (currentLeverageRatio >= incentive.incentivizedLeverageRatio) {
// If ETH reward is below the balance on this contract, then return ETH balance on contract instead
return incentive.etherReward < address(this).balance ? incentive.etherReward : address(this).balance;
} else {
return 0;
}
}
/**
* Helper that checks if conditions are met for rebalance or ripcord. Returns an enum with 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance()
* 3 = call ripcord()
*
* @return (string[] memory, ShouldRebalance[] memory) List of exchange names and a list of enums representing whether that exchange should rebalance
*/
function shouldRebalance() external view returns(string[] memory, ShouldRebalance[] memory) {
uint256 currentLeverageRatio = getCurrentLeverageRatio();
return _shouldRebalance(currentLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio);
}
/**
* Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the
* logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with
* 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance(), 3 = call ripcord()
*
* @param _customMinLeverageRatio Min leverage ratio passed in by caller
* @param _customMaxLeverageRatio Max leverage ratio passed in by caller
*
* @return (string[] memory, ShouldRebalance[] memory) List of exchange names and a list of enums representing whether that exchange should rebalance
*/
function shouldRebalanceWithBounds(
uint256 _customMinLeverageRatio,
uint256 _customMaxLeverageRatio
)
external
view
returns(string[] memory, ShouldRebalance[] memory)
{
require (
_customMinLeverageRatio <= methodology.minLeverageRatio && _customMaxLeverageRatio >= methodology.maxLeverageRatio,
"Custom bounds must be valid"
);
uint256 currentLeverageRatio = getCurrentLeverageRatio();
return _shouldRebalance(currentLeverageRatio, _customMinLeverageRatio, _customMaxLeverageRatio);
}
/**
* Gets the list of enabled exchanges
*/
function getEnabledExchanges() external view returns (string[] memory) {
return enabledExchanges;
}
/**
* Explicit getter functions for parameter structs are defined as workaround to issues fetching structs that have dynamic types.
*/
function getStrategy() external view returns (ContractSettings memory) { return strategy; }
function getMethodology() external view returns (MethodologySettings memory) { return methodology; }
function getExecution() external view returns (ExecutionSettings memory) { return execution; }
function getIncentive() external view returns (IncentiveSettings memory) { return incentive; }
function getExchangeSettings(string memory _exchangeName) external view returns (ExchangeSettings memory) {
return exchangeSettings[_exchangeName];
}
/* ============ Internal Functions ============ */
/**
* Calculate notional rebalance quantity, whether to chunk rebalance based on max trade size and max borrow and invoke lever on AaveLeverageModule
*
*/
function _lever(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal
{
uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply);
uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action);
uint256 minReceiveCollateralUnits = _calculateMinCollateralReceiveUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance);
bytes memory leverCallData = abi.encodeWithSignature(
"lever(address,address,address,uint256,uint256,string,bytes)",
address(strategy.setToken),
strategy.borrowAsset,
strategy.collateralAsset,
borrowUnits,
minReceiveCollateralUnits,
_leverageInfo.exchangeName,
exchangeSettings[_leverageInfo.exchangeName].leverExchangeData
);
invokeManager(address(strategy.leverageModule), leverCallData);
}
/**
* Calculate delever units Invoke delever on AaveLeverageModule.
*/
function _delever(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal
{
uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply);
uint256 minRepayUnits = _calculateMinRepayUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance, _leverageInfo.action);
bytes memory deleverCallData = abi.encodeWithSignature(
"delever(address,address,address,uint256,uint256,string,bytes)",
address(strategy.setToken),
strategy.collateralAsset,
strategy.borrowAsset,
collateralRebalanceUnits,
minRepayUnits,
_leverageInfo.exchangeName,
exchangeSettings[_leverageInfo.exchangeName].deleverExchangeData
);
invokeManager(address(strategy.leverageModule), deleverCallData);
}
/**
* Invoke deleverToZeroBorrowBalance on AaveLeverageModule.
*/
function _deleverToZeroBorrowBalance(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal
{
// Account for slippage tolerance in redeem quantity for the deleverToZeroBorrowBalance function
uint256 maxCollateralRebalanceUnits = _chunkRebalanceNotional
.preciseMul(PreciseUnitMath.preciseUnit().add(execution.slippageTolerance))
.preciseDiv(_leverageInfo.action.setTotalSupply);
bytes memory deleverToZeroBorrowBalanceCallData = abi.encodeWithSignature(
"deleverToZeroBorrowBalance(address,address,address,uint256,string,bytes)",
address(strategy.setToken),
strategy.collateralAsset,
strategy.borrowAsset,
maxCollateralRebalanceUnits,
_leverageInfo.exchangeName,
exchangeSettings[_leverageInfo.exchangeName].deleverExchangeData
);
invokeManager(address(strategy.leverageModule), deleverToZeroBorrowBalanceCallData);
}
/**
* Check whether to delever or lever based on the current vs new leverage ratios. Used in the rebalance() and iterateRebalance() functions
*
* return uint256 Calculated notional to trade
* return uint256 Total notional to rebalance over TWAP
*/
function _handleRebalance(LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio) internal returns(uint256, uint256) {
uint256 chunkRebalanceNotional;
uint256 totalRebalanceNotional;
if (_newLeverageRatio < _leverageInfo.currentLeverageRatio) {
(
chunkRebalanceNotional,
totalRebalanceNotional
) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, false);
_delever(_leverageInfo, chunkRebalanceNotional);
} else {
(
chunkRebalanceNotional,
totalRebalanceNotional
) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, true);
_lever(_leverageInfo, chunkRebalanceNotional);
}
return (chunkRebalanceNotional, totalRebalanceNotional);
}
/**
* Create the leverage info struct to be used in internal functions
*
* return LeverageInfo Struct containing ActionInfo and other data
*/
function _getAndValidateLeveragedInfo(uint256 _slippageTolerance, uint256 _maxTradeSize, string memory _exchangeName) internal view returns(LeverageInfo memory) {
// Assume if maxTradeSize is 0, then the exchange is not enabled. This is enforced by addEnabledExchange and updateEnabledExchange
require(_maxTradeSize > 0, "Must be valid exchange");
ActionInfo memory actionInfo = _createActionInfo();
require(actionInfo.setTotalSupply > 0, "SetToken must have > 0 supply");
require(actionInfo.collateralBalance > 0, "Collateral balance must be > 0");
require(actionInfo.borrowBalance > 0, "Borrow balance must exist");
// Get current leverage ratio
uint256 currentLeverageRatio = _calculateCurrentLeverageRatio(
actionInfo.collateralValue,
actionInfo.borrowValue
);
return LeverageInfo({
action: actionInfo,
currentLeverageRatio: currentLeverageRatio,
slippageTolerance: _slippageTolerance,
twapMaxTradeSize: _maxTradeSize,
exchangeName: _exchangeName
});
}
/**
* Create the action info struct to be used in internal functions
*
* return ActionInfo Struct containing data used by internal lever and delever functions
*/
function _createActionInfo() internal view returns(ActionInfo memory) {
ActionInfo memory rebalanceInfo;
// Calculate prices from chainlink. Chainlink returns prices with 8 decimal places, but we need 36 - underlyingDecimals decimal places.
// This is so that when the underlying amount is multiplied by the received price, the collateral valuation is normalized to 36 decimals.
// To perform this adjustment, we multiply by 10^(36 - 8 - underlyingDecimals)
int256 rawCollateralPrice = strategy.collateralPriceOracle.latestAnswer();
rebalanceInfo.collateralPrice = rawCollateralPrice.toUint256().mul(10 ** strategy.collateralDecimalAdjustment);
int256 rawBorrowPrice = strategy.borrowPriceOracle.latestAnswer();
rebalanceInfo.borrowPrice = rawBorrowPrice.toUint256().mul(10 ** strategy.borrowDecimalAdjustment);
rebalanceInfo.collateralBalance = strategy.targetCollateralAToken.balanceOf(address(strategy.setToken));
rebalanceInfo.borrowBalance = strategy.targetBorrowDebtToken.balanceOf(address(strategy.setToken));
rebalanceInfo.collateralValue = rebalanceInfo.collateralPrice.preciseMul(rebalanceInfo.collateralBalance);
rebalanceInfo.borrowValue = rebalanceInfo.borrowPrice.preciseMul(rebalanceInfo.borrowBalance);
rebalanceInfo.setTotalSupply = strategy.setToken.totalSupply();
return rebalanceInfo;
}
/**
* Validate non-exchange settings in constructor and setters when updating.
*/
function _validateNonExchangeSettings(
MethodologySettings memory _methodology,
ExecutionSettings memory _execution,
IncentiveSettings memory _incentive
)
internal
pure
{
require (
_methodology.minLeverageRatio <= _methodology.targetLeverageRatio && _methodology.minLeverageRatio > 0,
"Must be valid min leverage"
);
require (
_methodology.maxLeverageRatio >= _methodology.targetLeverageRatio,
"Must be valid max leverage"
);
require (
_methodology.recenteringSpeed <= PreciseUnitMath.preciseUnit() && _methodology.recenteringSpeed > 0,
"Must be valid recentering speed"
);
require (
_execution.unutilizedLeveragePercentage <= PreciseUnitMath.preciseUnit(),
"Unutilized leverage must be <100%"
);
require (
_execution.slippageTolerance <= PreciseUnitMath.preciseUnit(),
"Slippage tolerance must be <100%"
);
require (
_incentive.incentivizedSlippageTolerance <= PreciseUnitMath.preciseUnit(),
"Incentivized slippage tolerance must be <100%"
);
require (
_incentive.incentivizedLeverageRatio >= _methodology.maxLeverageRatio,
"Incentivized leverage ratio must be > max leverage ratio"
);
require (
_methodology.rebalanceInterval >= _execution.twapCooldownPeriod,
"Rebalance interval must be greater than TWAP cooldown period"
);
require (
_execution.twapCooldownPeriod >= _incentive.incentivizedTwapCooldownPeriod,
"TWAP cooldown must be greater than incentivized TWAP cooldown"
);
}
/**
* Validate an ExchangeSettings struct when adding or updating an exchange. Does not validate that twapMaxTradeSize < incentivizedMaxTradeSize since
* it may be useful to disable exchanges for ripcord by setting incentivizedMaxTradeSize to 0.
*/
function _validateExchangeSettings(ExchangeSettings memory _settings) internal pure {
require(_settings.twapMaxTradeSize != 0, "Max TWAP trade size must not be 0");
}
/**
* Validate that current leverage is below incentivized leverage ratio and cooldown / rebalance period has elapsed or outsize max/min bounds. Used
* in rebalance() and iterateRebalance() functions
*/
function _validateNormalRebalance(LeverageInfo memory _leverageInfo, uint256 _coolDown, uint256 _lastTradeTimestamp) internal view {
require(_leverageInfo.currentLeverageRatio < incentive.incentivizedLeverageRatio, "Must be below incentivized leverage ratio");
require(
block.timestamp.sub(_lastTradeTimestamp) > _coolDown
|| _leverageInfo.currentLeverageRatio > methodology.maxLeverageRatio
|| _leverageInfo.currentLeverageRatio < methodology.minLeverageRatio,
"Cooldown not elapsed or not valid leverage ratio"
);
}
/**
* Validate that current leverage is above incentivized leverage ratio and incentivized cooldown period has elapsed in ripcord()
*/
function _validateRipcord(LeverageInfo memory _leverageInfo, uint256 _lastTradeTimestamp) internal view {
require(_leverageInfo.currentLeverageRatio >= incentive.incentivizedLeverageRatio, "Must be above incentivized leverage ratio");
// If currently in the midst of a TWAP rebalance, ensure that the cooldown period has elapsed
require(_lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp, "TWAP cooldown must have elapsed");
}
/**
* Validate TWAP in the iterateRebalance() function
*/
function _validateTWAP() internal view {
require(twapLeverageRatio > 0, "Not in TWAP state");
}
/**
* Validate not TWAP in the rebalance() function
*/
function _validateNonTWAP() internal view {
require(twapLeverageRatio == 0, "Must call iterate");
}
/**
* Check if price has moved advantageously while in the midst of the TWAP rebalance. This means the current leverage ratio has moved over/under
* the stored TWAP leverage ratio on lever/delever so there is no need to execute a rebalance. Used in iterateRebalance()
*/
function _isAdvantageousTWAP(uint256 _currentLeverageRatio) internal view returns (bool) {
return (
(twapLeverageRatio < methodology.targetLeverageRatio && _currentLeverageRatio >= twapLeverageRatio)
|| (twapLeverageRatio > methodology.targetLeverageRatio && _currentLeverageRatio <= twapLeverageRatio)
);
}
/**
* Calculate the current leverage ratio given a valuation of the collateral and borrow asset, which is calculated as collateral USD valuation / SetToken USD valuation
*
* return uint256 Current leverage ratio
*/
function _calculateCurrentLeverageRatio(
uint256 _collateralValue,
uint256 _borrowValue
)
internal
pure
returns(uint256)
{
return _collateralValue.preciseDiv(_collateralValue.sub(_borrowValue));
}
/**
* Calculate the new leverage ratio. The methodology reduces the size of each rebalance by weighting
* the current leverage ratio against the target leverage ratio by the recentering speed percentage. The lower the recentering speed, the slower
* the leverage token will move towards the target leverage each rebalance.
*
* return uint256 New leverage ratio
*/
function _calculateNewLeverageRatio(uint256 _currentLeverageRatio) internal view returns(uint256) {
// CLRt+1 = max(MINLR, min(MAXLR, CLRt * (1 - RS) + TLR * RS))
// a: TLR * RS
// b: (1- RS) * CLRt
// c: (1- RS) * CLRt + TLR * RS
// d: min(MAXLR, CLRt * (1 - RS) + TLR * RS)
uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed);
uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio);
uint256 c = a.add(b);
uint256 d = Math.min(c, methodology.maxLeverageRatio);
return Math.max(methodology.minLeverageRatio, d);
}
/**
* Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units.
*
* return uint256 Chunked rebalance notional in collateral units
* return uint256 Total rebalance notional in collateral units
*/
function _calculateChunkRebalanceNotional(
LeverageInfo memory _leverageInfo,
uint256 _newLeverageRatio,
bool _isLever
)
internal
view
returns (uint256, uint256)
{
// Calculate absolute value of difference between new and current leverage ratio
uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio);
uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance);
uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever);
uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize);
return (chunkRebalanceNotional, totalRebalanceNotional);
}
/**
* Calculate the max borrow / repay amount allowed in base units for lever / delever. This is due to overcollateralization requirements on
* assets deposited in lending protocols for borrowing.
*
* For lever, max borrow is calculated as:
* (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals
*
* For delever, max repay is calculated as:
* Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD
*
* Net borrow limit for levering is calculated as:
* The collateral value in USD * Aave collateral factor * (1 - unutilized leverage %)
*
* Net repay limit for delevering is calculated as:
* The collateral value in USD * Aave liquiditon threshold * (1 - unutilized leverage %)
*
* return uint256 Max borrow notional denominated in collateral asset
*/
function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) {
// Retrieve collateral factor and liquidation threshold for the collateral asset in precise units (1e16 = 1%)
( , uint256 maxLtvRaw, uint256 liquidationThresholdRaw, , , , , , ,) = strategy.aaveProtocolDataProvider.getReserveConfigurationData(address(strategy.collateralAsset));
// Normalize LTV and liquidation threshold to precise units. LTV is measured in 4 decimals in Aave which is why we must multiply by 1e14
// for example ETH has an LTV value of 8000 which represents 80%
if (_isLever) {
uint256 netBorrowLimit = _actionInfo.collateralValue
.preciseMul(maxLtvRaw.mul(10 ** 14))
.preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));
return netBorrowLimit
.sub(_actionInfo.borrowValue)
.preciseDiv(_actionInfo.collateralPrice);
} else {
uint256 netRepayLimit = _actionInfo.collateralValue
.preciseMul(liquidationThresholdRaw.mul(10 ** 14))
.preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));
return _actionInfo.collateralBalance
.preciseMul(netRepayLimit.sub(_actionInfo.borrowValue))
.preciseDiv(netRepayLimit);
}
}
/**
* Derive the borrow units for lever. The units are calculated by the collateral units multiplied by collateral / borrow asset price.
* Output is measured to borrow unit decimals.
*
* return uint256 Position units to borrow
*/
function _calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internal pure returns (uint256) {
return _collateralRebalanceUnits.preciseMul(_actionInfo.collateralPrice).preciseDiv(_actionInfo.borrowPrice);
}
/**
* Calculate the min receive units in collateral units for lever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance
* Output is measured in collateral asset decimals.
*
* return uint256 Min position units to receive after lever trade
*/
function _calculateMinCollateralReceiveUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance) internal pure returns (uint256) {
return _collateralRebalanceUnits.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));
}
/**
* Derive the min repay units from collateral units for delever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance
* and pair price (collateral oracle price / borrow oracle price). Output is measured in borrow unit decimals.
*
* return uint256 Min position units to repay in borrow asset
*/
function _calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internal pure returns (uint256) {
return _collateralRebalanceUnits
.preciseMul(_actionInfo.collateralPrice)
.preciseDiv(_actionInfo.borrowPrice)
.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));
}
/**
* Update last trade timestamp and if chunk rebalance size is less than total rebalance notional, store new leverage ratio to kick off TWAP. Used in
* the engage() and rebalance() functions
*/
function _updateRebalanceState(
uint256 _chunkRebalanceNotional,
uint256 _totalRebalanceNotional,
uint256 _newLeverageRatio,
string memory _exchangeName
)
internal
{
_updateLastTradeTimestamp(_exchangeName);
if (_chunkRebalanceNotional < _totalRebalanceNotional) {
twapLeverageRatio = _newLeverageRatio;
}
}
/**
* Update last trade timestamp and if chunk rebalance size is equal to the total rebalance notional, end TWAP by clearing state. This function is used
* in iterateRebalance()
*/
function _updateIterateState(uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional, string memory _exchangeName) internal {
_updateLastTradeTimestamp(_exchangeName);
// If the chunk size is equal to the total notional meaning that rebalances are not chunked, then clear TWAP state.
if (_chunkRebalanceNotional == _totalRebalanceNotional) {
delete twapLeverageRatio;
}
}
/**
* Update last trade timestamp and if currently in a TWAP, delete the TWAP state. Used in the ripcord() function.
*/
function _updateRipcordState(string memory _exchangeName) internal {
_updateLastTradeTimestamp(_exchangeName);
// If TWAP leverage ratio is stored, then clear state. This may happen if we are currently in a TWAP rebalance, and the leverage ratio moves above the
// incentivized threshold for ripcord.
if (twapLeverageRatio > 0) {
delete twapLeverageRatio;
}
}
/**
* Update globalLastTradeTimestamp and exchangeLastTradeTimestamp values. This function updates both the exchange-specific and global timestamp so that the
* epoch rebalance can use the global timestamp (since the global timestamp is always equal to the most recently used exchange timestamp). This allows for
* multiple rebalances to occur simultaneously since only the exchange-specific timestamp is checked for non-epoch rebalances.
*/
function _updateLastTradeTimestamp(string memory _exchangeName) internal {
globalLastTradeTimestamp = block.timestamp;
exchangeSettings[_exchangeName].exchangeLastTradeTimestamp = block.timestamp;
}
/**
* Transfer ETH reward to caller of the ripcord function. If the ETH balance on this contract is less than required
* incentive quantity, then transfer contract balance instead to prevent reverts.
*
* return uint256 Amount of ETH transferred to caller
*/
function _transferEtherRewardToCaller(uint256 _etherReward) internal returns(uint256) {
uint256 etherToTransfer = _etherReward < address(this).balance ? _etherReward : address(this).balance;
msg.sender.transfer(etherToTransfer);
return etherToTransfer;
}
/**
* Internal function returning the ShouldRebalance enum used in shouldRebalance and shouldRebalanceWithBounds external getter functions
*
* return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action
*/
function _shouldRebalance(
uint256 _currentLeverageRatio,
uint256 _minLeverageRatio,
uint256 _maxLeverageRatio
)
internal
view
returns(string[] memory, ShouldRebalance[] memory)
{
ShouldRebalance[] memory shouldRebalanceEnums = new ShouldRebalance[](enabledExchanges.length);
for (uint256 i = 0; i < enabledExchanges.length; i++) {
// If none of the below conditions are satisfied, then should not rebalance
shouldRebalanceEnums[i] = ShouldRebalance.NONE;
// If above ripcord threshold, then check if incentivized cooldown period has elapsed
if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) {
if (exchangeSettings[enabledExchanges[i]].exchangeLastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) {
shouldRebalanceEnums[i] = ShouldRebalance.RIPCORD;
}
} else {
// If TWAP, then check if the cooldown period has elapsed
if (twapLeverageRatio > 0) {
if (exchangeSettings[enabledExchanges[i]].exchangeLastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) {
shouldRebalanceEnums[i] = ShouldRebalance.ITERATE_REBALANCE;
}
} else {
// If not TWAP, then check if the rebalance interval has elapsed OR current leverage is above max leverage OR current leverage is below
// min leverage
if (
block.timestamp.sub(globalLastTradeTimestamp) > methodology.rebalanceInterval
|| _currentLeverageRatio > _maxLeverageRatio
|| _currentLeverageRatio < _minLeverageRatio
) {
shouldRebalanceEnums[i] = ShouldRebalance.REBALANCE;
}
}
}
}
return (enabledExchanges, shouldRebalanceEnums);
}
}
// 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
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 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 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.
*/
pragma solidity 0.6.10;
import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
import { IBaseManager } from "../interfaces/IBaseManager.sol";
/**
* @title BaseExtension
* @author Set Protocol
*
* Abstract class that houses common extension-related state and functions.
*/
abstract contract BaseExtension {
using AddressArrayUtils for address[];
/* ============ Events ============ */
event CallerStatusUpdated(address indexed _caller, bool _status);
event AnyoneCallableUpdated(bool indexed _status);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == manager.operator(), "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == manager.methodologist(), "Must be methodologist");
_;
}
/**
* Throws if caller is a contract, can be used to stop flash loan and sandwich attacks
*/
modifier onlyEOA() {
require(msg.sender == tx.origin, "Caller must be EOA Address");
_;
}
/**
* Throws if not allowed caller
*/
modifier onlyAllowedCaller(address _caller) {
require(isAllowedCaller(_caller), "Address not permitted to call");
_;
}
/* ============ State Variables ============ */
// Instance of manager contract
IBaseManager public manager;
// Boolean indicating if anyone can call function
bool public anyoneCallable;
// Mapping of addresses allowed to call function
mapping(address => bool) public callAllowList;
/* ============ Constructor ============ */
constructor(IBaseManager _manager) public { manager = _manager; }
/* ============ External Functions ============ */
/**
* OPERATOR ONLY: Toggle ability for passed addresses to call only allowed caller functions
*
* @param _callers Array of caller addresses to toggle status
* @param _statuses Array of statuses for each caller
*/
function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator {
require(_callers.length == _statuses.length, "Array length mismatch");
require(_callers.length > 0, "Array length must be > 0");
require(!_callers.hasDuplicate(), "Cannot duplicate callers");
for (uint256 i = 0; i < _callers.length; i++) {
address caller = _callers[i];
bool status = _statuses[i];
callAllowList[caller] = status;
emit CallerStatusUpdated(caller, status);
}
}
/**
* OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist
*
* @param _status Boolean indicating whether to allow anyone call
*/
function updateAnyoneCallable(bool _status) external onlyOperator {
anyoneCallable = _status;
emit AnyoneCallableUpdated(_status);
}
/* ============ Internal Functions ============ */
/**
* Invoke manager to transfer tokens from manager to other contract.
*
* @param _token Token being transferred from manager contract
* @param _amount Amount of token being transferred
*/
function invokeManagerTransfer(address _token, address _destination, uint256 _amount) internal {
manager.transferTokens(_token, _destination, _amount);
}
/**
* Invoke call from manager
*
* @param _module Module to interact with
* @param _encoded Encoded byte data
*/
function invokeManager(address _module, bytes memory _encoded) internal {
manager.interactManager(_module, _encoded);
}
/**
* Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved.
*
* return bool Boolean indicating if allowed caller
*/
function isAllowedCaller(address _caller) internal view virtual returns (bool) {
return anyoneCallable || callAllowList[_caller];
}
}
/*
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.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ISetToken } from "./ISetToken.sol";
interface IBaseManager {
function setToken() external returns(ISetToken);
function methodologist() external returns(address);
function operator() external returns(address);
function interactManager(address _module, bytes calldata _encoded) external;
function transferTokens(address _token, address _destination, uint256 _amount) external;
}
pragma solidity 0.6.10;
interface IChainlinkAggregatorV3 {
function latestAnswer() external view returns (int256);
}
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ISetToken } from "./ISetToken.sol";
interface ILeverageModule {
function sync(
ISetToken _setToken
) external;
function lever(
ISetToken _setToken,
address _borrowAsset,
address _collateralAsset,
uint256 _borrowQuantity,
uint256 _minReceiveQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
) external;
function delever(
ISetToken _setToken,
address _collateralAsset,
address _repayAsset,
uint256 _redeemQuantity,
uint256 _minRepayQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
) external;
function gulp(
ISetToken _setToken,
address _collateralAsset,
uint256 _minNotionalReceiveQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
interface IProtocolDataProvider {
struct TokenData {
string symbol;
address tokenAddress;
}
function ADDRESSES_PROVIDER() external view returns (address);
function getAllReservesTokens() external view returns (TokenData[] memory);
function getAllATokens() external view returns (TokenData[] memory);
function getReserveConfigurationData(address asset) external view returns (uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen);
function getReserveData(address asset) external view returns (uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp);
function getUserReserveData(address asset, address user) external view returns (uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled);
function getReserveTokensAddresses(address asset) external view returns (address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress);
}
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 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
*/
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;
}
}
/*
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;
/**
* @title StringArrayUtils
* @author Set Protocol
*
* Utility functions to handle String Arrays
*/
library StringArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input string to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(string[] memory A, string memory a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (keccak256(bytes(A[i])) == keccak256(bytes(a))) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* @param A The input array to search
* @param a The string to remove
*/
function removeStorage(string[] storage A, string memory a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("String 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();
}
}
}
/*
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/27/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");
}
}
// 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;
}
} | Create the action info struct to be used in internal functions return ActionInfo Struct containing data used by internal lever and delever functions/ Calculate prices from chainlink. Chainlink returns prices with 8 decimal places, but we need 36 - underlyingDecimals decimal places. This is so that when the underlying amount is multiplied by the received price, the collateral valuation is normalized to 36 decimals. To perform this adjustment, we multiply by 10^(36 - 8 - underlyingDecimals) | function _createActionInfo() internal view returns(ActionInfo memory) {
ActionInfo memory rebalanceInfo;
int256 rawCollateralPrice = strategy.collateralPriceOracle.latestAnswer();
rebalanceInfo.collateralPrice = rawCollateralPrice.toUint256().mul(10 ** strategy.collateralDecimalAdjustment);
int256 rawBorrowPrice = strategy.borrowPriceOracle.latestAnswer();
rebalanceInfo.borrowPrice = rawBorrowPrice.toUint256().mul(10 ** strategy.borrowDecimalAdjustment);
rebalanceInfo.collateralBalance = strategy.targetCollateralAToken.balanceOf(address(strategy.setToken));
rebalanceInfo.borrowBalance = strategy.targetBorrowDebtToken.balanceOf(address(strategy.setToken));
rebalanceInfo.collateralValue = rebalanceInfo.collateralPrice.preciseMul(rebalanceInfo.collateralBalance);
rebalanceInfo.borrowValue = rebalanceInfo.borrowPrice.preciseMul(rebalanceInfo.borrowBalance);
rebalanceInfo.setTotalSupply = strategy.setToken.totalSupply();
return rebalanceInfo;
}
| 6,894,433 |
./full_match/1/0x3C6FBc94288f5af5201085948DdB18aDED2E6879/sources/contracts/ApeFiNFT.sol | Return all the account's MAYC token IDs and its eligibility. account The account/ | function getAccountEligibleMayc(
address account
) public view returns (ApeUsed[] memory) {
uint256 balance = mayc.balanceOf(account);
ApeUsed[] memory apes = new ApeUsed[](balance);
for (uint256 i = 0; i < balance; i++) {
uint256 tokenId = mayc.tokenOfOwnerByIndex(account, i);
}
return apes;
}
| 3,053,455 |
/**
*Submitted for verification at Etherscan.io on 2019-12-06
*/
// File: ../../mosaic-contracts/contracts/lib/RLP.sol
pragma solidity ^0.5.0;
/**
* @title RLPReader
*
* RLPReader is used to read and parse RLP encoded data in memory.
*
* @author Andreas Olofsson ([email protected])
*/
library RLP {
/** Constants */
uint constant DATA_SHORT_START = 0x80;
uint constant DATA_LONG_START = 0xB8;
uint constant LIST_SHORT_START = 0xC0;
uint constant LIST_LONG_START = 0xF8;
uint constant DATA_LONG_OFFSET = 0xB7;
uint constant LIST_LONG_OFFSET = 0xF7;
/** Storage */
struct RLPItem {
uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes.
uint _unsafe_length; // Number of bytes. This is the full length of the string.
}
struct Iterator {
RLPItem _unsafe_item; // Item that's being iterated over.
uint _unsafe_nextPtr; // Position of the next item in the list.
}
/* Internal Functions */
/** Iterator */
function next(
Iterator memory self
)
internal
pure
returns (RLPItem memory subItem_)
{
require(hasNext(self));
uint ptr = self._unsafe_nextPtr;
uint itemLength = _itemLength(ptr);
subItem_._unsafe_memPtr = ptr;
subItem_._unsafe_length = itemLength;
self._unsafe_nextPtr = ptr + itemLength;
}
function next(
Iterator memory self,
bool strict
)
internal
pure
returns (RLPItem memory subItem_)
{
subItem_ = next(self);
require(!(strict && !_validate(subItem_)));
}
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self._unsafe_item;
return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length;
}
/** RLPItem */
/**
* @dev Creates an RLPItem from an array of RLP encoded bytes.
*
* @param self The RLP encoded bytes.
*
* @return An RLPItem.
*/
function toRLPItem(
bytes memory self
)
internal
pure
returns (RLPItem memory)
{
uint len = self.length;
if (len == 0) {
return RLPItem(0, 0);
}
uint memPtr;
/* solium-disable-next-line */
assembly {
memPtr := add(self, 0x20)
}
return RLPItem(memPtr, len);
}
/**
* @dev Creates an RLPItem from an array of RLP encoded bytes.
*
* @param self The RLP encoded bytes.
* @param strict Will throw if the data is not RLP encoded.
*
* @return An RLPItem.
*/
function toRLPItem(
bytes memory self,
bool strict
)
internal
pure
returns (RLPItem memory)
{
RLPItem memory item = toRLPItem(self);
if(strict) {
uint len = self.length;
require(_payloadOffset(item) <= len);
require(_itemLength(item._unsafe_memPtr) == len);
require(_validate(item));
}
return item;
}
/**
* @dev Check if the RLP item is null.
*
* @param self The RLP item.
*
* @return 'true' if the item is null.
*/
function isNull(RLPItem memory self) internal pure returns (bool ret) {
return self._unsafe_length == 0;
}
/**
* @dev Check if the RLP item is a list.
*
* @param self The RLP item.
*
* @return 'true' if the item is a list.
*/
function isList(RLPItem memory self) internal pure returns (bool ret) {
if (self._unsafe_length == 0) {
return false;
}
uint memPtr = self._unsafe_memPtr;
/* solium-disable-next-line */
assembly {
ret := iszero(lt(byte(0, mload(memPtr)), 0xC0))
}
}
/**
* @dev Check if the RLP item is data.
*
* @param self The RLP item.
*
* @return 'true' if the item is data.
*/
function isData(RLPItem memory self) internal pure returns (bool ret) {
if (self._unsafe_length == 0) {
return false;
}
uint memPtr = self._unsafe_memPtr;
/* solium-disable-next-line */
assembly {
ret := lt(byte(0, mload(memPtr)), 0xC0)
}
}
/**
* @dev Check if the RLP item is empty (string or list).
*
* @param self The RLP item.
*
* @return 'true' if the item is null.
*/
function isEmpty(RLPItem memory self) internal pure returns (bool ret) {
if(isNull(self)) {
return false;
}
uint b0;
uint memPtr = self._unsafe_memPtr;
/* solium-disable-next-line */
assembly {
b0 := byte(0, mload(memPtr))
}
return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START);
}
/**
* @dev Get the number of items in an RLP encoded list.
*
* @param self The RLP item.
*
* @return The number of items.
*/
function items(RLPItem memory self) internal pure returns (uint) {
if (!isList(self)) {
return 0;
}
uint b0;
uint memPtr = self._unsafe_memPtr;
/* solium-disable-next-line */
assembly {
b0 := byte(0, mload(memPtr))
}
uint pos = memPtr + _payloadOffset(self);
uint last = memPtr + self._unsafe_length - 1;
uint itms;
while(pos <= last) {
pos += _itemLength(pos);
itms++;
}
return itms;
}
/**
* @dev Create an iterator.
*
* @param self The RLP item.
*
* @return An 'Iterator' over the item.
*/
function iterator(
RLPItem memory self
)
internal
pure
returns (Iterator memory it_)
{
require (isList(self));
uint ptr = self._unsafe_memPtr + _payloadOffset(self);
it_._unsafe_item = self;
it_._unsafe_nextPtr = ptr;
}
/**
* @dev Return the RLP encoded bytes.
*
* @param self The RLPItem.
*
* @return The bytes.
*/
function toBytes(
RLPItem memory self
)
internal
pure
returns (bytes memory bts_)
{
uint len = self._unsafe_length;
if (len == 0) {
return bts_;
}
bts_ = new bytes(len);
_copyToBytes(self._unsafe_memPtr, bts_, len);
}
/**
* @dev Decode an RLPItem into bytes. This will not work if the RLPItem is a list.
*
* @param self The RLPItem.
*
* @return The decoded string.
*/
function toData(
RLPItem memory self
)
internal
pure
returns (bytes memory bts_)
{
require(isData(self));
uint rStartPos;
uint len;
(rStartPos, len) = _decode(self);
bts_ = new bytes(len);
_copyToBytes(rStartPos, bts_, len);
}
/**
* @dev Get the list of sub-items from an RLP encoded list.
* Warning: This is inefficient, as it requires that the list is read twice.
*
* @param self The RLP item.
*
* @return Array of RLPItems.
*/
function toList(
RLPItem memory self
)
internal
pure
returns (RLPItem[] memory list_)
{
require(isList(self));
uint numItems = items(self);
list_ = new RLPItem[](numItems);
Iterator memory it = iterator(self);
uint idx = 0;
while(hasNext(it)) {
list_[idx] = next(it);
idx++;
}
}
/**
* @dev Decode an RLPItem into an ascii string. This will not work if the
* RLPItem is a list.
*
* @param self The RLPItem.
*
* @return The decoded string.
*/
function toAscii(
RLPItem memory self
)
internal
pure
returns (string memory str_)
{
require(isData(self));
uint rStartPos;
uint len;
(rStartPos, len) = _decode(self);
bytes memory bts = new bytes(len);
_copyToBytes(rStartPos, bts, len);
str_ = string(bts);
}
/**
* @dev Decode an RLPItem into a uint. This will not work if the
* RLPItem is a list.
*
* @param self The RLPItem.
*
* @return The decoded string.
*/
function toUint(RLPItem memory self) internal pure returns (uint data_) {
require(isData(self));
uint rStartPos;
uint len;
(rStartPos, len) = _decode(self);
if (len > 32 || len == 0) {
revert();
}
/* solium-disable-next-line */
assembly {
data_ := div(mload(rStartPos), exp(256, sub(32, len)))
}
}
/**
* @dev Decode an RLPItem into a boolean. This will not work if the
* RLPItem is a list.
*
* @param self The RLPItem.
*
* @return The decoded string.
*/
function toBool(RLPItem memory self) internal pure returns (bool data) {
require(isData(self));
uint rStartPos;
uint len;
(rStartPos, len) = _decode(self);
require(len == 1);
uint temp;
/* solium-disable-next-line */
assembly {
temp := byte(0, mload(rStartPos))
}
require (temp <= 1);
return temp == 1 ? true : false;
}
/**
* @dev Decode an RLPItem into a byte. This will not work if the
* RLPItem is a list.
*
* @param self The RLPItem.
*
* @return The decoded string.
*/
function toByte(RLPItem memory self) internal pure returns (byte data) {
require(isData(self));
uint rStartPos;
uint len;
(rStartPos, len) = _decode(self);
require(len == 1);
uint temp;
/* solium-disable-next-line */
assembly {
temp := byte(0, mload(rStartPos))
}
return byte(uint8(temp));
}
/**
* @dev Decode an RLPItem into an int. This will not work if the
* RLPItem is a list.
*
* @param self The RLPItem.
*
* @return The decoded string.
*/
function toInt(RLPItem memory self) internal pure returns (int data) {
return int(toUint(self));
}
/**
* @dev Decode an RLPItem into a bytes32. This will not work if the
* RLPItem is a list.
*
* @param self The RLPItem.
*
* @return The decoded string.
*/
function toBytes32(
RLPItem memory self
)
internal
pure
returns (bytes32 data)
{
return bytes32(toUint(self));
}
/**
* @dev Decode an RLPItem into an address. This will not work if the
* RLPItem is a list.
*
* @param self The RLPItem.
*
* @return The decoded string.
*/
function toAddress(
RLPItem memory self
)
internal
pure
returns (address data)
{
require(isData(self));
uint rStartPos;
uint len;
(rStartPos, len) = _decode(self);
require (len == 20);
/* solium-disable-next-line */
assembly {
data := div(mload(rStartPos), exp(256, 12))
}
}
/**
* @dev Decode an RLPItem into an address. This will not work if the
* RLPItem is a list.
*
* @param self The RLPItem.
*
* @return Get the payload offset.
*/
function _payloadOffset(RLPItem memory self) private pure returns (uint) {
if(self._unsafe_length == 0)
return 0;
uint b0;
uint memPtr = self._unsafe_memPtr;
/* solium-disable-next-line */
assembly {
b0 := byte(0, mload(memPtr))
}
if(b0 < DATA_SHORT_START)
return 0;
if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START))
return 1;
if(b0 < LIST_SHORT_START)
return b0 - DATA_LONG_OFFSET + 1;
return b0 - LIST_LONG_OFFSET + 1;
}
/**
* @dev Decode an RLPItem into an address. This will not work if the
* RLPItem is a list.
*
* @param memPtr Memory pointer.
*
* @return Get the full length of an RLP item.
*/
function _itemLength(uint memPtr) private pure returns (uint len) {
uint b0;
/* solium-disable-next-line */
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START) {
len = 1;
} else if (b0 < DATA_LONG_START) {
len = b0 - DATA_SHORT_START + 1;
} else if (b0 < LIST_SHORT_START) {
/* solium-disable-next-line */
assembly {
let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
} else if (b0 < LIST_LONG_START) {
len = b0 - LIST_SHORT_START + 1;
} else {
/* solium-disable-next-line */
assembly {
let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
}
/**
* @dev Decode an RLPItem into an address. This will not work if the
* RLPItem is a list.
*
* @param self The RLPItem.
*
* @return Get the full length of an RLP item.
*/
function _decode(
RLPItem memory self
)
private
pure
returns (uint memPtr_, uint len_)
{
require(isData(self));
uint b0;
uint start = self._unsafe_memPtr;
/* solium-disable-next-line */
assembly {
b0 := byte(0, mload(start))
}
if (b0 < DATA_SHORT_START) {
memPtr_ = start;
len_ = 1;
return (memPtr_, len_);
}
if (b0 < DATA_LONG_START) {
len_ = self._unsafe_length - 1;
memPtr_ = start + 1;
} else {
uint bLen;
/* solium-disable-next-line */
assembly {
bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET
}
len_ = self._unsafe_length - 1 - bLen;
memPtr_ = start + bLen + 1;
}
}
/**
* @dev Assumes that enough memory has been allocated to store in target.
* Gets the full length of an RLP item.
*
* @param btsPtr Bytes pointer.
* @param tgt Last item to be allocated.
* @param btsLen Bytes length.
*/
function _copyToBytes(
uint btsPtr,
bytes memory tgt,
uint btsLen
)
private
pure
{
// Exploiting the fact that 'tgt' was the last thing to be allocated,
// we can write entire words, and just overwrite any excess.
/* solium-disable-next-line */
assembly {
let i := 0 // Start at arr + 0x20
let stopOffset := add(btsLen, 31)
let rOffset := btsPtr
let wOffset := add(tgt, 32)
for {} lt(i, stopOffset) { i := add(i, 32) }
{
mstore(add(wOffset, i), mload(add(rOffset, i)))
}
}
}
/**
* @dev Check that an RLP item is valid.
*
* @param self The RLPItem.
*/
function _validate(RLPItem memory self) private pure returns (bool ret) {
// Check that RLP is well-formed.
uint b0;
uint b1;
uint memPtr = self._unsafe_memPtr;
/* solium-disable-next-line */
assembly {
b0 := byte(0, mload(memPtr))
b1 := byte(1, mload(memPtr))
}
if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START)
return false;
return true;
}
}
// File: ../../mosaic-contracts/contracts/lib/MerklePatriciaProof.sol
pragma solidity ^0.5.0;
/**
* @title MerklePatriciaVerifier
* @author Sam Mayo ([email protected])
*
* @dev Library for verifing merkle patricia proofs.
*/
library MerklePatriciaProof {
/**
* @dev Verifies a merkle patricia proof.
* @param value The terminating value in the trie.
* @param encodedPath The path in the trie leading to value.
* @param rlpParentNodes The rlp encoded stack of nodes.
* @param root The root hash of the trie.
* @return The boolean validity of the proof.
*/
function verify(
bytes32 value,
bytes calldata encodedPath,
bytes calldata rlpParentNodes,
bytes32 root
)
external
pure
returns (bool)
{
RLP.RLPItem memory item = RLP.toRLPItem(rlpParentNodes);
RLP.RLPItem[] memory parentNodes = RLP.toList(item);
bytes memory currentNode;
RLP.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint pathPtr = 0;
bytes memory path = _getNibbleArray2(encodedPath);
if(path.length == 0) {return false;}
for (uint i=0; i<parentNodes.length; i++) {
if(pathPtr > path.length) {return false;}
currentNode = RLP.toBytes(parentNodes[i]);
if(nodeKey != keccak256(abi.encodePacked(currentNode))) {return false;}
currentNodeList = RLP.toList(parentNodes[i]);
if(currentNodeList.length == 17) {
if(pathPtr == path.length) {
if(keccak256(abi.encodePacked(RLP.toBytes(currentNodeList[16]))) == value) {
return true;
} else {
return false;
}
}
uint8 nextPathNibble = uint8(path[pathPtr]);
if(nextPathNibble > 16) {return false;}
nodeKey = RLP.toBytes32(currentNodeList[nextPathNibble]);
pathPtr += 1;
} else if(currentNodeList.length == 2) {
// Count of matching node key nibbles in path starting from pathPtr.
uint traverseLength = _nibblesToTraverse(RLP.toData(currentNodeList[0]), path, pathPtr);
if(pathPtr + traverseLength == path.length) { //leaf node
if(keccak256(abi.encodePacked(RLP.toData(currentNodeList[1]))) == value) {
return true;
} else {
return false;
}
} else if (traverseLength == 0) { // error: couldn't traverse path
return false;
} else { // extension node
pathPtr += traverseLength;
nodeKey = RLP.toBytes32(currentNodeList[1]);
}
} else {
return false;
}
}
}
function verifyDebug(
bytes32 value,
bytes memory not_encodedPath,
bytes memory rlpParentNodes,
bytes32 root
)
public
pure
returns (bool res_, uint loc_, bytes memory path_debug_)
{
RLP.RLPItem memory item = RLP.toRLPItem(rlpParentNodes);
RLP.RLPItem[] memory parentNodes = RLP.toList(item);
bytes memory currentNode;
RLP.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint pathPtr = 0;
bytes memory path = _getNibbleArray2(not_encodedPath);
path_debug_ = path;
if(path.length == 0) {
loc_ = 0;
res_ = false;
return (res_, loc_, path_debug_);
}
for (uint i=0; i<parentNodes.length; i++) {
if(pathPtr > path.length) {
loc_ = 1;
res_ = false;
return (res_, loc_, path_debug_);
}
currentNode = RLP.toBytes(parentNodes[i]);
if(nodeKey != keccak256(abi.encodePacked(currentNode))) {
res_ = false;
loc_ = 100 + i;
return (res_, loc_, path_debug_);
}
currentNodeList = RLP.toList(parentNodes[i]);
loc_ = currentNodeList.length;
if(currentNodeList.length == 17) {
if(pathPtr == path.length) {
if(keccak256(abi.encodePacked(RLP.toBytes(currentNodeList[16]))) == value) {
res_ = true;
return (res_, loc_, path_debug_);
} else {
loc_ = 3;
return (res_, loc_, path_debug_);
}
}
uint8 nextPathNibble = uint8(path[pathPtr]);
if(nextPathNibble > 16) {
loc_ = 4;
return (res_, loc_, path_debug_);
}
nodeKey = RLP.toBytes32(currentNodeList[nextPathNibble]);
pathPtr += 1;
} else if(currentNodeList.length == 2) {
pathPtr += _nibblesToTraverse(RLP.toData(currentNodeList[0]), path, pathPtr);
if(pathPtr == path.length) {//leaf node
if(keccak256(abi.encodePacked(RLP.toData(currentNodeList[1]))) == value) {
res_ = true;
return (res_, loc_, path_debug_);
} else {
loc_ = 5;
return (res_, loc_, path_debug_);
}
}
//extension node
if(_nibblesToTraverse(RLP.toData(currentNodeList[0]), path, pathPtr) == 0) {
loc_ = 6;
res_ = (keccak256(abi.encodePacked()) == value);
return (res_, loc_, path_debug_);
}
nodeKey = RLP.toBytes32(currentNodeList[1]);
} else {
loc_ = 7;
return (res_, loc_, path_debug_);
}
}
loc_ = 8;
}
function _nibblesToTraverse(
bytes memory encodedPartialPath,
bytes memory path,
uint pathPtr
)
private
pure
returns (uint len_)
{
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath
// and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath);
bytes memory slicedPath = new bytes(partialPath.length);
// pathPtr counts nibbles in path
// partialPath.length is a number of nibbles
for(uint i=pathPtr; i<pathPtr+partialPath.length; i++) {
byte pathNibble = path[i];
slicedPath[i-pathPtr] = pathNibble;
}
if(keccak256(abi.encodePacked(partialPath)) == keccak256(abi.encodePacked(slicedPath))) {
len_ = partialPath.length;
} else {
len_ = 0;
}
}
// bytes b must be hp encoded
function _getNibbleArray(
bytes memory b
)
private
pure
returns (bytes memory nibbles_)
{
if(b.length>0) {
uint8 offset;
uint8 hpNibble = uint8(_getNthNibbleOfBytes(0,b));
if(hpNibble == 1 || hpNibble == 3) {
nibbles_ = new bytes(b.length*2-1);
byte oddNibble = _getNthNibbleOfBytes(1,b);
nibbles_[0] = oddNibble;
offset = 1;
} else {
nibbles_ = new bytes(b.length*2-2);
offset = 0;
}
for(uint i=offset; i<nibbles_.length; i++) {
nibbles_[i] = _getNthNibbleOfBytes(i-offset+2,b);
}
}
}
// normal byte array, no encoding used
function _getNibbleArray2(
bytes memory b
)
private
pure
returns (bytes memory nibbles_)
{
nibbles_ = new bytes(b.length*2);
for (uint i = 0; i < nibbles_.length; i++) {
nibbles_[i] = _getNthNibbleOfBytes(i, b);
}
}
function _getNthNibbleOfBytes(
uint n,
bytes memory str
)
private
pure returns (byte)
{
return byte(n%2==0 ? uint8(str[n/2])/0x10 : uint8(str[n/2])%0x10);
}
}
// File: ../../mosaic-contracts/contracts/lib/SafeMath.sol
pragma solidity ^0.5.0;
// Copyright 2019 OpenST Ltd.
//
// 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.
//
// ----------------------------------------------------------------------------
//
// http://www.simpletoken.org/
//
// Based on the SafeMath library by the OpenZeppelin team.
// Copyright (c) 2018 Smart Contract Solutions, Inc.
// https://github.com/OpenZeppelin/zeppelin-solidity
// The MIT License.
// ----------------------------------------------------------------------------
/**
* @title SafeMath library.
*
* @notice Based on the SafeMath library by the OpenZeppelin team.
*
* @dev Math operations with safety checks that revert on error.
*/
library SafeMath {
/* Internal Functions */
/**
* @notice Multiplies two numbers, reverts on overflow.
*
* @param a Unsigned integer multiplicand.
* @param b Unsigned integer multiplier.
*
* @return uint256 Product.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
/*
* Gas optimization: this is cheaper than requiring 'a' not being zero,
* but the benefit is lost if 'b' is also tested.
* See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
*/
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(
c / a == b,
"Overflow when multiplying."
);
return c;
}
/**
* @notice Integer division of two numbers truncating the quotient, reverts
* on division by zero.
*
* @param a Unsigned integer dividend.
* @param b Unsigned integer divisor.
*
* @return uint256 Quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0.
require(
b > 0,
"Cannot do attempted division by less than or equal to zero."
);
uint256 c = a / b;
// There is no case in which the following doesn't hold:
// assert(a == b * c + a % b);
return c;
}
/**
* @notice Subtracts two numbers, reverts on underflow (i.e. if subtrahend
* is greater than minuend).
*
* @param a Unsigned integer minuend.
* @param b Unsigned integer subtrahend.
*
* @return uint256 Difference.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(
b <= a,
"Underflow when subtracting."
);
uint256 c = a - b;
return c;
}
/**
* @notice Adds two numbers, reverts on overflow.
*
* @param a Unsigned integer augend.
* @param b Unsigned integer addend.
*
* @return uint256 Sum.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(
c >= a,
"Overflow when adding."
);
return c;
}
/**
* @notice Divides two numbers and returns the remainder (unsigned integer
* modulo), reverts when dividing by zero.
*
* @param a Unsigned integer dividend.
* @param b Unsigned integer divisor.
*
* @return uint256 Remainder.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(
b != 0,
"Cannot do attempted division by zero (in `mod()`)."
);
return a % b;
}
}
// File: ../../mosaic-contracts/contracts/lib/BytesLib.sol
pragma solidity ^0.5.0;
library BytesLib {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure returns (bytes memory bytes_)
{
/* solium-disable-next-line */
assembly {
// Get a location of some free memory and store it in bytes_ as
// Solidity does for memory variables.
bytes_ := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for bytes_.
let length := mload(_preBytes)
mstore(bytes_, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(bytes_, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the bytes_ memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of bytes_
// and store it as the new length in the first 32 bytes of the
// bytes_ memory.
length := mload(_postBytes)
mstore(bytes_, add(length, mload(bytes_)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of bytes_ to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
}
// Pad a bytes array to 32 bytes
function leftPad(
bytes memory _bytes
)
internal
pure
returns (bytes memory padded_)
{
bytes memory padding = new bytes(32 - _bytes.length);
padded_ = concat(padding, _bytes);
}
/**
* @notice Convert bytes32 to bytes
*
* @param _inBytes32 bytes32 value
*
* @return bytes value
*/
function bytes32ToBytes(bytes32 _inBytes32)
internal
pure
returns (bytes memory bytes_)
{
bytes_ = new bytes(32);
/* solium-disable-next-line */
assembly {
mstore(add(32, bytes_), _inBytes32)
}
}
}
// File: ../../mosaic-contracts/contracts/lib/MessageBus.sol
pragma solidity ^0.5.0;
// Copyright 2019 OpenST Ltd.
//
// 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.
//
// ----------------------------------------------------------------------------
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
library MessageBus {
/* Usings */
using SafeMath for uint256;
/* Enums */
/** Status of the message state machine. */
enum MessageStatus {
Undeclared,
Declared,
Progressed,
DeclaredRevocation,
Revoked
}
/** Status of the message state machine. */
enum MessageBoxType {
Outbox,
Inbox
}
/* Structs */
/** MessageBox stores the inbox and outbox mapping. */
struct MessageBox {
/** Maps message hash to the MessageStatus. */
mapping(bytes32 => MessageStatus) outbox;
/** Maps message hash to the MessageStatus. */
mapping(bytes32 => MessageStatus) inbox;
}
/** A Message is sent between gateways. */
struct Message {
/** Intent hash of specific request type. */
bytes32 intentHash;
/** Nonce of the sender. */
uint256 nonce;
/** Gas price that sender will pay for reward. */
uint256 gasPrice;
/** Gas limit that sender will pay. */
uint256 gasLimit;
/** Address of the message sender. */
address sender;
/** Hash lock provided by the facilitator. */
bytes32 hashLock;
/**
* The amount of the gas consumed, this is used for reward
* calculation.
*/
uint256 gasConsumed;
}
/* Constants */
bytes32 public constant MESSAGE_TYPEHASH = keccak256(
abi.encode(
"Message(bytes32 intentHash,uint256 nonce,uint256 gasPrice,uint256 gasLimit,address sender,bytes32 hashLock)"
)
);
/**
* Position of outbox in struct MessageBox.
* This is used to generate storage merkel proof.
*/
uint8 public constant OUTBOX_OFFSET = 0;
/**
* Position of inbox in struct MessageBox.
* This is used to generate storage merkel proof.
*/
uint8 public constant INBOX_OFFSET = 1;
/* External Functions */
/**
* @notice Declare a new message. This will update the outbox status to
* `Declared` for the given message hash.
*
* @param _messageBox Message Box.
* @param _message Message object.
*
* @return messageHash_ Message hash
*/
function declareMessage(
MessageBox storage _messageBox,
Message storage _message
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bytes32 messageHash_)
{
messageHash_ = messageDigest(_message);
require(
_messageBox.outbox[messageHash_] == MessageStatus.Undeclared,
"Message on source must be Undeclared."
);
// Update the outbox message status to `Declared`.
_messageBox.outbox[messageHash_] = MessageStatus.Declared;
}
/**
* @notice Confirm a new message that is declared in outbox on the source
* chain. Merkle proof will be performed to verify the declared
* status in source chains outbox. This will update the inbox
* status to `Declared` for the given message hash.
*
* @param _messageBox Message Box.
* @param _message Message object.
* @param _rlpParentNodes RLP encoded parent node data to prove in
* messageBox outbox.
* @param _messageBoxOffset position of the messageBox.
* @param _storageRoot Storage root for proof.
*
* @return messageHash_ Message hash.
*/
function confirmMessage(
MessageBox storage _messageBox,
Message storage _message,
bytes calldata _rlpParentNodes,
uint8 _messageBoxOffset,
bytes32 _storageRoot
)
external
returns (bytes32 messageHash_)
{
messageHash_ = messageDigest(_message);
require(
_messageBox.inbox[messageHash_] == MessageStatus.Undeclared,
"Message on target must be Undeclared."
);
// Get the storage path to verify proof.
bytes memory path = BytesLib.bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
OUTBOX_OFFSET,
messageHash_
)
);
// Verify the merkle proof.
require(
MerklePatriciaProof.verify(
keccak256(abi.encodePacked(MessageStatus.Declared)),
path,
_rlpParentNodes,
_storageRoot
),
"Merkle proof verification failed."
);
// Update the message box inbox status to `Declared`.
_messageBox.inbox[messageHash_] = MessageStatus.Declared;
}
/**
* @notice Update the outbox message hash status to `Progressed`.
*
* @param _messageBox Message Box.
* @param _message Message object.
* @param _unlockSecret Unlock secret for the hash lock provided while
* declaration.
*
* @return messageHash_ Message hash.
*/
function progressOutbox(
MessageBox storage _messageBox,
Message storage _message,
bytes32 _unlockSecret
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bytes32 messageHash_)
{
require(
_message.hashLock == keccak256(abi.encode(_unlockSecret)),
"Invalid unlock secret."
);
messageHash_ = messageDigest(_message);
require(
_messageBox.outbox[messageHash_] == MessageStatus.Declared,
"Message on source must be Declared."
);
// Update the outbox message status to `Progressed`.
_messageBox.outbox[messageHash_] = MessageStatus.Progressed;
}
/**
* @notice Update the status for the outbox for a given message hash to
* `Progressed`. Merkle proof is used to verify status of inbox in
* source chain. This is an alternative approach to hashlocks.
*
* @dev The messsage status for the message hash in the inbox should be
* either `Declared` or `Progresses`. Either of this status will be
* verified with the merkle proof.
*
* @param _messageBox Message Box.
* @param _message Message object.
* @param _rlpParentNodes RLP encoded parent node data to prove in
* messageBox inbox.
* @param _messageBoxOffset Position of the messageBox.
* @param _storageRoot Storage root for proof.
* @param _messageStatus Message status of message hash in the inbox of
* source chain.
*
* @return messageHash_ Message hash.
*/
function progressOutboxWithProof(
MessageBox storage _messageBox,
Message storage _message,
bytes calldata _rlpParentNodes,
uint8 _messageBoxOffset,
bytes32 _storageRoot,
MessageStatus _messageStatus
)
external
returns (bytes32 messageHash_)
{
messageHash_ = messageDigest(_message);
if(_messageBox.outbox[messageHash_] == MessageStatus.Declared) {
/*
* The inbox message status of target must be either `Declared` or
* `Progressed` when outbox message status at source is `Declared`.
*/
require(
_messageStatus == MessageStatus.Declared ||
_messageStatus == MessageStatus.Progressed,
"Message on target must be Declared or Progressed."
);
} else if (_messageBox.outbox[messageHash_] == MessageStatus.DeclaredRevocation) {
/*
* The inbox message status of target must be either `Progressed`
* when outbox message status at source is `DeclaredRevocation`.
*/
require(
_messageStatus == MessageStatus.Progressed,
"Message on target must be Progressed."
);
} else {
revert("Status of message on source must be Declared or DeclareRevocation.");
}
bytes memory storagePath = BytesLib.bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
INBOX_OFFSET,
messageHash_
)
);
// Verify the merkle proof.
require(
MerklePatriciaProof.verify(
keccak256(abi.encodePacked(_messageStatus)),
storagePath,
_rlpParentNodes,
_storageRoot),
"Merkle proof verification failed."
);
_messageBox.outbox[messageHash_] = MessageStatus.Progressed;
}
/**
* @notice Update the status for the inbox for a given message hash to
* `Progressed`
*
* @param _messageBox Message Box.
* @param _message Message object.
* @param _unlockSecret Unlock secret for the hash lock provided while
* declaration.
*
* @return messageHash_ Message hash.
*/
function progressInbox(
MessageBox storage _messageBox,
Message storage _message,
bytes32 _unlockSecret
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bytes32 messageHash_)
{
require(
_message.hashLock == keccak256(abi.encode(_unlockSecret)),
"Invalid unlock secret."
);
messageHash_ = messageDigest(_message);
require(
_messageBox.inbox[messageHash_] == MessageStatus.Declared,
"Message on target status must be Declared."
);
_messageBox.inbox[messageHash_] = MessageStatus.Progressed;
}
/**
* @notice Update the status for the inbox for a given message hash to
* `Progressed`. Merkle proof is used to verify status of outbox in
* source chain. This is an alternative approach to hashlocks.
*
* @dev The messsage status for the message hash in the outbox should be
* either `Declared` or `Progresses`. Either of this status will be
* verified in the merkle proof.
*
* @param _messageBox Message Box.
* @param _message Message object.
* @param _rlpParentNodes RLP encoded parent node data to prove in
* messageBox outbox.
* @param _messageBoxOffset Position of the messageBox.
* @param _storageRoot Storage root for proof.
* @param _messageStatus Message status of message hash in the outbox of
* source chain.
*
* @return messageHash_ Message hash.
*/
function progressInboxWithProof(
MessageBox storage _messageBox,
Message storage _message,
bytes calldata _rlpParentNodes,
uint8 _messageBoxOffset,
bytes32 _storageRoot,
MessageStatus _messageStatus
)
external
returns (bytes32 messageHash_)
{
// Outbox message status must be either `Declared` or `Progressed`.
require(
_messageStatus == MessageStatus.Declared ||
_messageStatus == MessageStatus.Progressed,
"Message on source must be Declared or Progressed."
);
messageHash_ = messageDigest(_message);
require(
_messageBox.inbox[messageHash_] == MessageStatus.Declared,
"Message on target must be Declared."
);
// The outbox is at location OUTBOX_OFFSET of the MessageBox struct.
bytes memory path = BytesLib.bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
OUTBOX_OFFSET,
messageHash_
)
);
// Perform the merkle proof.
require(
MerklePatriciaProof.verify(
keccak256(abi.encodePacked(_messageStatus)),
path,
_rlpParentNodes,
_storageRoot
),
"Merkle proof verification failed."
);
_messageBox.inbox[messageHash_] = MessageStatus.Progressed;
}
/**
* @notice Declare a new revocation message. This will update the outbox
* status to `DeclaredRevocation` for the given message hash.
*
* @dev In order to declare revocation the existing message status for the
* given message hash should be `Declared`.
*
* @param _messageBox Message Box.
* @param _message Message object.
*
* @return messageHash_ Message hash.
*/
function declareRevocationMessage(
MessageBox storage _messageBox,
Message storage _message
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bytes32 messageHash_)
{
messageHash_ = messageDigest(_message);
require(
_messageBox.outbox[messageHash_] == MessageStatus.Declared,
"Message on source must be Declared."
);
_messageBox.outbox[messageHash_] = MessageStatus.DeclaredRevocation;
}
/**
* @notice Confirm a revocation message that is declared in the outbox of
* source chain. This will update the outbox status to
* `Revoked` for the given message hash.
*
* @dev In order to declare revocation the existing message status for the
* given message hash should be `Declared`.
*
* @param _messageBox Message Box.
* @param _message Message object.
* @param _rlpParentNodes RLP encoded parent node data to prove in
* messageBox outbox.
* @param _messageBoxOffset Position of the messageBox.
* @param _storageRoot Storage root for proof.
*
* @return messageHash_ Message hash.
*/
function confirmRevocation(
MessageBox storage _messageBox,
Message storage _message,
bytes calldata _rlpParentNodes,
uint8 _messageBoxOffset,
bytes32 _storageRoot
)
external
returns (bytes32 messageHash_)
{
messageHash_ = messageDigest(_message);
require(
_messageBox.inbox[messageHash_] == MessageStatus.Declared,
"Message on target must be Declared."
);
// Get the path.
bytes memory path = BytesLib.bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
OUTBOX_OFFSET,
messageHash_
)
);
// Perform the merkle proof.
require(
MerklePatriciaProof.verify(
keccak256(abi.encodePacked(MessageStatus.DeclaredRevocation)),
path,
_rlpParentNodes,
_storageRoot
),
"Merkle proof verification failed."
);
_messageBox.inbox[messageHash_] = MessageStatus.Revoked;
}
/**
* @notice Update the status for the outbox for a given message hash to
* `Revoked`. Merkle proof is used to verify status of inbox in
* source chain.
*
* @dev The messsage status in the inbox should be
* either `DeclaredRevocation` or `Revoked`. Either of this status
* will be verified in the merkle proof.
*
* @param _messageBox Message Box.
* @param _message Message object.
* @param _messageBoxOffset Position of the messageBox.
* @param _rlpParentNodes RLP encoded parent node data to prove in
* messageBox inbox.
* @param _storageRoot Storage root for proof.
* @param _messageStatus Message status of message hash in the inbox of
* source chain.
*
* @return messageHash_ Message hash.
*/
function progressOutboxRevocation(
MessageBox storage _messageBox,
Message storage _message,
uint8 _messageBoxOffset,
bytes calldata _rlpParentNodes,
bytes32 _storageRoot,
MessageStatus _messageStatus
)
external
returns (bytes32 messageHash_)
{
require(
_messageStatus == MessageStatus.Revoked,
"Message on target status must be Revoked."
);
messageHash_ = messageDigest(_message);
require(
_messageBox.outbox[messageHash_] ==
MessageStatus.DeclaredRevocation,
"Message status on source must be DeclaredRevocation."
);
// The inbox is at location INBOX_OFFSET of the MessageBox struct.
bytes memory path = BytesLib.bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
INBOX_OFFSET,
messageHash_
)
);
// Perform the merkle proof.
require(
MerklePatriciaProof.verify(
keccak256(abi.encodePacked(_messageStatus)),
path,
_rlpParentNodes,
_storageRoot
),
"Merkle proof verification failed."
);
_messageBox.outbox[messageHash_] = MessageStatus.Revoked;
}
/**
* @notice Returns the type hash of the type "Message".
*
* @return messageTypehash_ The type hash of the "Message" type.
*/
function messageTypehash() public pure returns(bytes32 messageTypehash_) {
messageTypehash_ = MESSAGE_TYPEHASH;
}
/* Public Functions */
/**
* @notice Generate message hash from the input params
*
* @param _intentHash Intent hash.
* @param _nonce Nonce of the message sender.
* @param _gasPrice Gas price.
*
* @return messageHash_ Message hash.
*/
function messageDigest(
bytes32 _intentHash,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit,
address _sender,
bytes32 _hashLock
)
public
pure
returns (bytes32 messageHash_)
{
messageHash_ = keccak256(
abi.encode(
MESSAGE_TYPEHASH,
_intentHash,
_nonce,
_gasPrice,
_gasLimit,
_sender,
_hashLock
)
);
}
/* Private Functions */
/**
* @notice Creates a hash from a message struct.
*
* @param _message The message to hash.
*
* @return messageHash_ The hash that represents this message.
*/
function messageDigest(
Message storage _message
)
private
view
returns (bytes32 messageHash_)
{
messageHash_ = messageDigest(
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit,
_message.sender,
_message.hashLock
);
}
/**
* @notice Get the storage path of the variable inside the struct.
*
* @param _structPosition Position of struct variable.
* @param _offset Offset of variable inside the struct.
* @param _key Key of variable in case of mapping
*
* @return storagePath_ Storage path of the variable.
*/
function storageVariablePathForStruct(
uint8 _structPosition,
uint8 _offset,
bytes32 _key
)
private
pure
returns(bytes32 storagePath_)
{
if(_offset > 0){
_structPosition = _structPosition + _offset;
}
bytes memory indexBytes = BytesLib.leftPad(
BytesLib.bytes32ToBytes(bytes32(uint256(_structPosition)))
);
bytes memory keyBytes = BytesLib.leftPad(BytesLib.bytes32ToBytes(_key));
bytes memory path = BytesLib.concat(keyBytes, indexBytes);
storagePath_ = keccak256(
abi.encodePacked(keccak256(abi.encodePacked(path)))
);
}
} | Get the number of items in an RLP encoded list. self The RLP item. return The number of items./ solium-disable-next-line / | function items(RLPItem memory self) internal pure returns (uint) {
if (!isList(self)) {
return 0;
}
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
uint pos = memPtr + _payloadOffset(self);
uint last = memPtr + self._unsafe_length - 1;
uint itms;
while(pos <= last) {
pos += _itemLength(pos);
itms++;
}
return itms;
}
| 12,905,842 |
./full_match/420/0xB3201C217e3A466D2eD7a198742d98eF91b25cF2/sources/contracts/libs/Tokens.sol | Get a checksummed string hex representation of an account address. account address The account to get the checksum for./ call internal function for converting an account to a checksummed string. | function _getChecksum(
address account
) internal pure returns (string memory accountChecksum) {
return _toChecksumString(account);
}
| 13,227,767 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./AccessExtension.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
/**
* @title Intelligent NFT Interface
* Version 1
*
* @notice External interface of IntelligentNFTv1 declared to support ERC165 detection.
* See Intelligent NFT documentation below.
*
* @author Basil Gorin
*/
interface IIntelligentNFTv1 {
function totalSupply() external view returns (uint256);
function exists(uint256 recordId) external view returns (bool);
function ownerOf(uint256 recordId) external view returns (address);
}
/**
* @title Intelligent NFT (iNFT)
* Version 1
*
* @notice Intelligent NFT (iNFT) represents an enhancement to an existing NFT
* (we call it a "target" or "target NFT"), it binds a GPT-3 prompt (a "personality prompt")
* to the target to embed intelligence, is controlled and belongs to the owner of the target.
*
* @notice iNFT stores AI Pod and some amount of ALI tokens locked, available to
* unlocking when iNFT is destroyed
*
* @notice iNFT is not an ERC721 token, but it has some very limited similarity to an ERC721:
* every record is identified by ID and this ID has an owner, which is effectively the target NFT owner;
* still, it doesn't store ownership information itself and fully relies on the target ownership instead
*
* @dev Internally iNFTs consist of:
* - personality prompt - a GPT-3 prompt defining its intelligent capabilities
* - target NFT - smart contract address and ID of the NFT the iNFT is bound to
* - AI Pod - ID of the AI Pod used to produce given iNFT, locked within an iNFT
* - ALI tokens amount - amount of the ALI tokens used to produce given iNFT, also locked
*
* @dev iNFTs can be
* - created, this process requires an AI Pod and ALI tokens to be locked
* - destroyed, this process releases an AI Pod and ALI tokens previously locked;
* ALI token fee may get withheld upon destruction
*
* @dev Some known limitations of Version 1:
* - doesn't support ERC1155 as a target NFT
* - only one-to-one iNFT-NFT bindings,
* no many-to-one, one-to-many, or many-to-many bindings not allowed
* - no AI Pod ID -> iNFT ID binding, impossible to look for iNFT by AI Pod ID
* - no enumeration support, iNFT IDs created must be tracked off-chain,
* or [recommended] generated with a predictable deterministic integer sequence,
* for example, 1, 2, 3, ...
* - no support for personality prompt upgrades (no way to update personality prompt)
* - burn: doesn't allow to specify where to send the iNFT burning fee, sends ALI tokens
* burner / transaction sender (iNFT Linker)
* - burn: doesn't verify if its safe to send ALI tokens released back to NFT owner;
* ALI tokens may get lost if iNFT is burnt when NFT belongs to a smart contract which
* is not aware of the ALI tokens being sent to it
* - no target NFT ID optimization; storage usage for IntelliBinding can be optimized
* if short target NFT IDs are recognized and stored optimized
* - AI Pod ERC721 and ALI ERC20 smart contracts are set during the deployment and cannot be changed
*
* @author Basil Gorin
*/
contract IntelligentNFTv1 is IIntelligentNFTv1, AccessExtension {
/**
* @notice Deployer is responsible for AI Pod and ALI tokens contract address initialization
*
* @dev Role ROLE_DEPLOYER allows executing `setPodContract` and `setAliContract` functions
*/
bytes32 public constant ROLE_DEPLOYER = keccak256("ROLE_DEPLOYER");
/**
* @notice Minter is responsible for creating (minting) iNFTs
*
* @dev Role ROLE_MINTER allows minting iNFTs (calling `mint` function)
*/
bytes32 public constant ROLE_MINTER = keccak256("ROLE_MINTER");
/**
* @notice Burner is responsible for destroying (burning) iNFTs
*
* @dev Role ROLE_BURNER allows burning iNFTs (calling `burn` function)
*/
bytes32 public constant ROLE_BURNER = keccak256("ROLE_BURNER");
/**
* @dev Each intelligent token, represented by its unique ID, is bound to the target NFT,
* defined by the pair of the target NFT smart contract address and unique token ID
* within the target NFT smart contract
*
* @dev Effectively iNFT is owned by the target NFT owner
*
* @dev Additionally, each token holds an AI Pod and some amount of ALI tokens bound to it
*
* @dev `IntelliBinding` keeps all the binding information, including target NFT coordinates,
* bound AI Pod ID, and amount of ALI ERC20 tokens bound to the iNFT
*/
struct IntelliBinding {
// Note: structure members are reordered to fit into less memory slots, see EVM memory layout
// ----- SLOT.1 (256/256)
/**
* @dev Personality prompt is a hash of the data used to feed GPT-3 algorithm
*/
uint256 personalityPrompt;
// ----- SLOT.2 (160/256)
/**
* @dev Address of the target NFT deployed smart contract,
* this is a contract a particular iNFT is bound to
*/
address targetContract;
// ----- SLOT.3 (256/256)
/**
* @dev Target NFT ID within the target NFT smart contract,
* effectively target NFT ID and contract address define the owner of an iNFT
*/
uint256 targetId;
// ----- SLOT.4 (160/256)
/**
* @dev AI Pod ID bound to (owned by) the iNFT
*
* @dev Similar to target NFT, specific AI Pod is also defined by pair of AI Pod smart contract address
* and AI Pod ID; the first one, however, is defined globally and stored in `podContract` constant.
*/
uint64 podId;
/**
* @dev Amount of an ALI ERC20 tokens bound to (owned by) the iNFTs
*
* @dev ALI ERC20 smart contract address is defined globally as `aliContract` constant
*/
uint96 aliValue;
}
/**
* @notice iNFT binding storage, stores binding information for each existing iNFT
* @dev Maps iNFT ID to its binding data, which includes underlying NFT data
*/
mapping (uint256 => IntelliBinding) public bindings;
/**
* @notice Reverse iNFT binding allows to find iNFT bound to a particular NFT
* @dev Maps target NFT (smart contract address and unique token ID) to the linked iNFT:
* NFT Contract => NFT ID => iNFT ID
*/
mapping (address => mapping(uint256 => uint256)) reverseBinding;
/**
* @notice Total amount (maximum value estimate) of iNFT in existence.
* This value can be higher than number of effectively accessible iNFTs
* since when underlying NFT gets burned this value doesn't get updated.
*/
uint256 public override totalSupply;
/**
* @notice Each iNFT holds an AI Pod which is tracked by the AI Pod NFT smart contract defined here
*/
address public podContract;
/**
* @notice Each iNFT holds some ALI tokens, which are tracked by the ALI token ERC20 smart contract defined here
*/
address public aliContract;
/**
* @dev Fired in mint() when new iNFT is created
*
* @param by an address which executed the mint function
* @param owner current owner of the NFT
* @param recordId ID of the iNFT to mint (create, bind)
* @param payer and address which funds the creation (supplies AI Pod and ALI tokens)
* @param podId ID of the AI Pod to bind (transfer) to newly created iNFT
* @param aliValue amount of ALI tokens to bind (transfer) to newly created iNFT
* @param targetContract target NFT smart contract
* @param targetId target NFT ID (where this iNFT binds to and belongs to)
* @param personalityPrompt personality prompt for the minted iNFT
*/
event Minted(
address indexed by,
address owner,
uint64 recordId,
address payer,
uint64 podId,
uint96 aliValue,
address targetContract,
uint256 targetId,
uint256 personalityPrompt
);
/**
* @dev Fired in burn() when an existing iNFT gets destroyed
*
* @param by an address which executed the burn function
* @param recordId ID of the iNFT to burn (destroy, unbind)
* @param recipient and address which receives unlocked AI Pod and ALI tokens (NFT owner)
* @param podId ID of the AI Pod to unbind (transfer) from the destroyed iNFT
* @param aliValue amount of ALI tokens to unbind (transfer) from the destroyed iNFT
* @param aliFee service fee in ALI tokens withheld by burn executor
* @param targetContract target NFT smart contract
* @param targetId target NFT ID (where this iNFT was bound to and belonged to)
* @param personalityPrompt personality prompt for that iNFT
*/
event Burnt(
address indexed by,
uint64 recordId,
address recipient,
uint64 podId,
uint96 aliValue,
uint96 aliFee,
address targetContract,
uint256 targetId,
uint256 personalityPrompt
);
/**
* @dev Fired in setPodContract()
*
* @param by an address which set the `podContract`
* @param podContract AI Pod contract address set
*/
event PodContractSet(address indexed by, address podContract);
/**
* @dev Fired in setAliContract()
*
* @param by an address which set the `aliContract`
* @param aliContract ALI token contract address set
*/
event AliContractSet(address indexed by, address aliContract);
/**
* @dev Creates/deploys an iNFT instance not bound to AI Pod / ALI token instances
*/
constructor() {
// setup admin role for smart contract deployer initially
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* @dev Binds an iNFT instance to already deployed AI Pod instance
*
* @param _pod address of the deployed AI Pod instance to bind iNFT to
*/
function setPodContract(address _pod) public {
// verify sender has permission to access this function
require(isSenderInRole(ROLE_DEPLOYER), "access denied");
// verify the input is set
require(_pod != address(0), "AI Pod addr is not set");
// verify _pod is valid ERC721
require(IERC165(_pod).supportsInterface(type(IERC721).interfaceId), "AI Pod addr is not ERC721");
// setup smart contract internal state
podContract = _pod;
// emit an event
emit PodContractSet(_msgSender(), _pod);
}
/**
* @dev Binds an iNFT instance to already deployed ALI Token instance
*
* @param _ali address of the deployed ALI Token instance to bind iNFT to
*/
function setAliContract(address _ali) public {
// verify sender has permission to access this function
require(isSenderInRole(ROLE_DEPLOYER), "access denied");
// verify the input is set
require(_ali != address(0), "ALI Token addr is not set");
// verify _ali is valid ERC20
require(IERC165(_ali).supportsInterface(type(IERC20).interfaceId), "ALI Token addr is not ERC20");
// setup smart contract internal state
aliContract = _ali;
// emit an event
emit AliContractSet(_msgSender(), _ali);
}
/**
* @inheritdoc IERC165
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
// reconstruct from current interface and super interface
return interfaceId == type(IIntelligentNFTv1).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice Verifies if given iNFT exists
*
* @param recordId iNFT ID to verify existence of
* @return true if iNFT exists, false otherwise
*/
function exists(uint256 recordId) public view override returns (bool) {
// verify if biding exists for that tokenId and return the result
return bindings[recordId].targetContract != address(0);
}
/**
* @notice Returns an owner of the given iNFT.
* By definition iNFT owner is an owner of the target NFT
*
* @param recordId iNFT ID to query ownership information for
* @return address of the given iNFT owner
*/
function ownerOf(uint256 recordId) public view override returns (address) {
// read the token binding
IntelliBinding memory binding = bindings[recordId];
// verify the binding exists and throw standard Zeppelin message if not
require(binding.targetContract != address(0), "iNFT doesn't exist");
// delegate `ownerOf` call to the target NFT smart contract
return IERC721(binding.targetContract).ownerOf(binding.targetId);
}
/**
* @dev Restricted access function which creates an iNFT, binding it to the specified
* NFT, locking the AI Pod specified, and funded with the amount of ALI specified
*
* @dev Transfers AI Pod defined by its ID into iNFT smart contract for locking;
* linking funder must authorize the transfer operation before the mint is called
* @dev Transfers specified amount of ALI token into iNFT smart contract for locking;
* funder must authorize the transfer operation before the mint is called
* @dev The NFT to be linked to doesn't required to belong to the funder, but it must exist
*
* @dev Throws if target NFT doesn't exist
*
* @dev This is a restricted function which is accessed by iNFT Linker
*
* @param recordId ID of the iNFT to mint (create, bind)
* @param funder and address which funds the creation (supplies AI Pod and ALI tokens)
* @param personalityPrompt personality prompt for that iNFT
* @param podId ID of the AI Pod to bind (transfer) to newly created iNFT
* @param aliValue amount of ALI tokens to bind (transfer) to newly created iNFT
* @param targetContract target NFT smart contract
* @param targetId target NFT ID (where this iNFT binds to and belongs to)
*/
function mint(
uint64 recordId,
address funder,
uint256 personalityPrompt,
uint64 podId,
uint96 aliValue,
address targetContract,
uint256 targetId
) public {
// verify the access permission
require(isSenderInRole(ROLE_MINTER), "access denied");
// verify this token ID is not yet bound
require(!exists(recordId), "iNFT already exists");
// verify the NFT is not yet bound
require(reverseBinding[targetContract][targetId] == 0, "target NFT already linked");
// transfer the AI Pod from the specified address `_from`
// using unsafe transfer to avoid unnecessary `onERC721Received` triggering
// Note: we explicitly request AI Pod transfer from the linking funder to be safe
// from the scenarios of potential misuse of AI Pods
IERC721(podContract).transferFrom(funder, address(this), podId);
// transfer the ALI tokens from the specified address `_from`
// using unsafe transfer to avoid unnecessary callback triggering
if(aliValue > 0) {
// note: Zeppelin based AliERC20v1 transfer implementation fails on any error
IERC20(aliContract).transferFrom(funder, address(this), aliValue);
}
// retrieve NFT owner and verify if target NFT exists
address owner = IERC721(targetContract).ownerOf(targetId);
// Note: we do not require funder to be NFT owner,
// if required this constraint should be added by the caller (iNFT Linker)
require(owner != address(0), "target NFT doesn't exist");
// bind AI Pod transferred and ALI ERC20 value transferred to an NFT specified
bindings[recordId] = IntelliBinding({
personalityPrompt: personalityPrompt,
targetContract: targetContract,
targetId: targetId,
podId: podId,
aliValue: aliValue
});
// fill in the reverse binding
reverseBinding[targetContract][targetId] = recordId;
// increase total supply counter
totalSupply++;
// emit an event
emit Minted(_msgSender(), owner, recordId, funder, podId, aliValue, targetContract, targetId, personalityPrompt);
}
/**
* @dev Restricted access function which destroys an iNFT, unbinding it from the
* linked NFT, releasing an AI Pod, and ALI tokens locked in the iNFT
*
* @dev Transfers an AI Pod locked in iNFT to its owner via ERC721.safeTransferFrom;
* owner must be an EOA or implement IERC721Receiver.onERC721Received properly
* @dev Transfers ALI tokens locked in iNFT to its owner and a fee specified to
* transaction executor
* @dev Since iNFT owner is determined as underlying NFT owner, this underlying NFT must
* exist and its ownerOf function must not throw and must return non-zero owner address
* for the underlying NFT ID
*
* @dev Doesn't verify if it's safe to send ALI tokens to the NFT owner, this check
* must be handled by the transaction executor
*
* @dev This is a restricted function which is accessed by iNFT Linker
*
* @param recordId ID of the iNFT to burn (destroy, unbind)
* @param aliFee service fee in ALI tokens to be withheld
*/
function burn(uint64 recordId, uint96 aliFee) public {
// verify the access permission
require(isSenderInRole(ROLE_BURNER), "access denied");
// decrease total supply counter
totalSupply--;
// read the token binding
IntelliBinding memory binding = bindings[recordId];
// verify binding exists
require(binding.targetContract != address(0), "not bound");
// destroy binding first to protect from any reentrancy possibility
delete bindings[recordId];
// free the reverse binding
delete reverseBinding[binding.targetContract][binding.targetId];
// make sure fee doesn't exceed what is bound to iNFT
require(aliFee <= binding.aliValue);
// send the fee to transaction sender
if(aliFee > 0) {
// note: Zeppelin based AliERC20v1 transfer implementation fails on any error
require(IERC20(aliContract).transfer(_msgSender(), aliFee));
}
// determine an owner of the underlying NFT
address owner = IERC721(binding.targetContract).ownerOf(binding.targetId);
// verify that owner address is set (not a zero address)
require(owner != address(0), "no such NFT");
// transfer the AI Pod to the NFT owner
// using safe transfer since we don't know if owner address can accept the AI Pod right now
IERC721(podContract).safeTransferFrom(address(this), owner, binding.podId);
// transfer the ALI tokens to the NFT owner
if(binding.aliValue > aliFee) {
// note: Zeppelin based AliERC20v1 transfer implementation fails on any error
IERC20(aliContract).transfer(owner, binding.aliValue - aliFee);
}
// emit an event
emit Burnt(_msgSender(), recordId, owner, binding.podId, binding.aliValue, aliFee, binding.targetContract, binding.targetId, binding.personalityPrompt);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @title Access Control List Extension Interface
*
* @notice External interface of AccessExtension declared to support ERC165 detection.
* See Access Control List Extension documentation below.
*
* @author Basil Gorin
*/
interface IAccessExtension is IAccessControl {
function removeFeature(bytes32 feature) external;
function addFeature(bytes32 feature) external;
function isFeatureEnabled(bytes32 feature) external view returns(bool);
}
/**
* @title Access Control List Extension
*
* @notice Access control smart contract provides an API to check
* if specific operation is permitted globally and/or
* if particular user has a permission to execute it.
*
* @notice It deals with two main entities: features and roles.
*
* @notice Features are designed to be used to enable/disable specific
* functions (public functions) of the smart contract for everyone.
* @notice User roles are designed to restrict access to specific
* functions (restricted functions) of the smart contract to some users.
*
* @notice Terms "role", "permissions" and "set of permissions" have equal meaning
* in the documentation text and may be used interchangeably.
* @notice Terms "permission", "single permission" implies only one permission set.
*
* @dev OpenZeppelin AccessControl based implementation. Features are stored as
* "self"-roles: feature is a role assigned to the smart contract itself
*
* @dev Automatically assigns the deployer an admin permission
*
* @dev This smart contract is designed to be inherited by other
* smart contracts which require access control management capabilities.
*
* @author Basil Gorin
*/
contract AccessExtension is IAccessExtension, AccessControl {
constructor() {
// setup admin role for smart contract deployer initially
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* @inheritdoc IERC165
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
// reconstruct from current interface and super interface
return interfaceId == type(IAccessExtension).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice Removes the feature from the set of the globally enabled features,
* taking into account sender's permissions
*
* @dev Requires transaction sender to have a permission to set the feature requested
*
* @param feature a feature to disable
*/
function removeFeature(bytes32 feature) public override {
// delegate to Zeppelin's `revokeRole`
revokeRole(feature, address(this));
}
/**
* @notice Adds the feature to the set of the globally enabled features,
* taking into account sender's permissions
*
* @dev Requires transaction sender to have a permission to set the feature requested
*
* @param feature a feature to enable
*/
function addFeature(bytes32 feature) public override {
// delegate to Zeppelin's `grantRole`
grantRole(feature, address(this));
}
/**
* @notice Checks if requested feature is enabled globally on the contract
*
* @param feature the feature to check
* @return true if the feature requested is enabled, false otherwise
*/
function isFeatureEnabled(bytes32 feature) public override view returns(bool) {
// delegate to Zeppelin's `hasRole`
return hasRole(feature, address(this));
}
/**
* @notice Checks if transaction sender `msg.sender` has the role required
*
* @param role the role to check against
* @return true if sender has the role required, false otherwise
*/
function isSenderInRole(bytes32 role) public view returns(bool) {
// delegate call to `isOperatorInRole`, passing transaction sender
return hasRole(role, _msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: 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 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
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @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(uint256(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());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
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);
}
| Checks if requested feature is enabled globally on the contract feature the feature to check return true if the feature requested is enabled, false otherwise/ delegate to Zeppelin's `hasRole` | function isFeatureEnabled(bytes32 feature) public override view returns(bool) {
return hasRole(feature, address(this));
}
| 116,686 |
// File contracts/general/Ownable.sol
pragma solidity ^0.6.6;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*
* @dev We've added a second owner to share control of the timelocked owner contract.
*/
contract Ownable {
address private _owner;
address private _pendingOwner;
// Second allows a DAO to share control.
address private _secondOwner;
address private _pendingSecond;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event SecondOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function initializeOwnable() internal {
require(_owner == address(0), "already initialized");
_owner = msg.sender;
_secondOwner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
emit SecondOwnershipTransferred(address(0), msg.sender);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @return the address of the owner.
*/
function secondOwner() public view returns (address) {
return _secondOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "msg.sender is not owner");
_;
}
modifier onlyFirstOwner() {
require(msg.sender == _owner, "msg.sender is not owner");
_;
}
modifier onlySecondOwner() {
require(msg.sender == _secondOwner, "msg.sender is not owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner || msg.sender == _secondOwner;
}
/**
* @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 onlyFirstOwner {
_pendingOwner = newOwner;
}
function receiveOwnership() public {
require(msg.sender == _pendingOwner, "only pending owner can call this function");
_transferOwnership(_pendingOwner);
_pendingOwner = address(0);
}
/**
* @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;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferSecondOwnership(address newOwner) public onlySecondOwner {
_pendingSecond = newOwner;
}
function receiveSecondOwnership() public {
require(msg.sender == _pendingSecond, "only pending owner can call this function");
_transferSecondOwnership(_pendingSecond);
_pendingSecond = address(0);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferSecondOwnership(address newOwner) internal {
require(newOwner != address(0));
emit SecondOwnershipTransferred(_secondOwner, newOwner);
_secondOwner = newOwner;
}
uint256[50] private __gap;
}
// File contracts/libraries/Address.sol
pragma solidity ^0.6.6;
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* 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.
*/
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.
// 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 != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @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].
*
* _Available since v2.4.0._
*/
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");
}
}
// File contracts/libraries/SafeMath.sol
pragma solidity ^0.6.6;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*
* @dev Default OpenZeppelin
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File contracts/interfaces/IERC20.sol
pragma solidity ^0.6.6;
/**
* @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);
function mint(address to, uint256 amount) external returns (bool);
function burn(address from, 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 contracts/libraries/SafeERC20.sol
pragma solidity ^0.6.6;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/interfaces/IWNXM.sol
pragma solidity ^0.6.6;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IWNXM {
/**
* @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);
function mint(address to, uint256 amount) external returns (bool);
function burn(address from, uint256 amount) external returns (bool);
function wrap(uint256 amount) external;
function unwrap(uint256 amount) external;
/**
* @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 contracts/interfaces/INexusMutual.sol
pragma solidity ^0.6.6;
/**
* @dev Quick interface for the Nexus Mutual contract to work with the Armor Contracts.
**/
// to get nexus mutual contract address
interface INxmMaster {
function tokenAddress() external view returns(address);
function owner() external view returns(address);
function pauseTime() external view returns(uint);
function masterInitialized() external view returns(bool);
function isPause() external view returns(bool check);
function isMember(address _add) external view returns(bool);
function getLatestAddress(bytes2 _contractName) external view returns(address payable contractAddress);
}
interface IPooledStaking {
function unstakeRequests(uint256 id) external view returns(uint256 amount, uint256 unstakeAt, address contractAddress, address stakerAddress, uint256 next);
function processPendingActions(uint256 iterations) external returns(bool success);
function MAX_EXPOSURE() external view returns(uint256);
function lastUnstakeRequestId() external view returns(uint256);
function stakerDeposit(address user) external view returns (uint256);
function stakerMaxWithdrawable(address user) external view returns (uint256);
function withdrawReward(address user) external;
function requestUnstake(address[] calldata protocols, uint256[] calldata amounts, uint256 insertAfter) external;
function depositAndStake(uint256 deposit, address[] calldata protocols, uint256[] calldata amounts) external;
function stakerContractCount(address staker) external view returns(uint256);
function stakerContractAtIndex(address staker, uint contractIndex) external view returns (address);
function stakerContractStake(address staker, address protocol) external view returns (uint256);
function stakerContractsArray(address staker) external view returns (address[] memory);
function stakerContractPendingUnstakeTotal(address staker, address protocol) external view returns(uint256);
function withdraw(uint256 amount) external;
function stakerReward(address staker) external view returns (uint256);
}
interface IClaimsData {
function getClaimStatusNumber(uint256 claimId) external view returns (uint256, uint256);
function getClaimDateUpd(uint256 claimId) external view returns (uint256);
}
interface INXMPool {
function buyNXM(uint minTokensOut) external payable;
}
// File contracts/interfaces/IRewardDistributionRecipient.sol
pragma solidity ^0.6.6;
interface IRewardDistributionRecipient {
function notifyRewardAmount(uint256 reward) payable external;
}
// File contracts/interfaces/IRewardManager.sol
pragma solidity ^0.6.6;
interface IRewardManager is IRewardDistributionRecipient {
function initialize(address _rewardToken, address _stakeController) external;
function stake(address _user, address _referral, uint256 _coverPrice) external;
function withdraw(address _user, address _referral, uint256 _coverPrice) external;
function getReward(address payable _user) external;
}
// File contracts/interfaces/IShieldMining.sol
pragma solidity ^0.6.0;
interface IShieldMining {
function claimRewards(
address[] calldata stakedContracts,
address[] calldata sponsors,
address[] calldata tokenAddresses
) external returns (uint[] memory tokensRewarded);
}
pragma solidity ^0.6.0;
interface IGovernance {
function submitVote(
uint256 _proposalId,
uint256 _solutionChosen
) external;
}
// File contracts/core/arNXMVault.sol
pragma solidity ^0.6.6;
/**
* @title arNXM Vault
* @dev Vault to stake wNXM or NXM in Nexus Mutual while maintaining your liquidity.
* This is V2 which replaces V1 behind a proxy. Updated variables at the bottom.
* @author Armor.fi -- Robert M.C. Forster, Taek Lee
* SPDX-License-Identifier: (c) Armor.Fi DAO, 2021
**/
contract arNXMVault is Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
uint256 constant private DENOMINATOR = 1000;
// Amount of time between
uint256 public restakePeriod;
// Amount of time that rewards are distributed over.
uint256 public rewardDuration;
// This used to be unstake percent but has now been deprecated in favor of individual unstakes.
// Paranoia results in this not being replaced but rather deprecated and new variables placed at the bottom.
uint256 public ____deprecated____;
// Amount of wNXM (in token Wei) to reserve each period.
// Overwrites reservePercent in update.
uint256 public reserveAmount;
// Withdrawals may be paused if a hack has recently happened. Timestamp of when the pause happened.
uint256 public withdrawalsPaused;
// Amount of time withdrawals may be paused after a hack.
uint256 public pauseDuration;
// Address that will receive administration funds from the contract.
address public beneficiary;
// Percent of funds to be distributed for administration of the contract. 10 == 1%; 1000 == 100%.
uint256 public adminPercent;
// Percent of staking rewards that referrers get.
uint256 public referPercent;
// Timestamp of when the last restake took place--7 days between each.
uint256 public lastRestake;
// The amount of the last reward.
uint256 public lastReward;
// Uniswap, Maker, Compound, Aave, Curve, Synthetix, Yearn, RenVM, Balancer, dForce.
address[] public protocols;
// Amount to unstake each time.
uint256[] private amounts;
// Protocols being actively used in staking or unstaking.
address[] private activeProtocols;
struct WithdrawalRequest {
uint48 requestTime;
uint104 nAmount;
uint104 arAmount;
}
// Nxm tokens.
IERC20 public wNxm;
IERC20 public nxm;
IERC20 public arNxm;
// Nxm Master address.
INxmMaster public nxmMaster;
// Reward manager for referrers.
IRewardManager public rewardManager;
// Referral => referrer
mapping (address => address) public referrers;
event Deposit(address indexed user, uint256 nAmount, uint256 arAmount, uint256 timestamp);
event WithdrawRequested(address indexed user, uint256 arAmount, uint256 nAmount, uint256 requestTime, uint256 withdrawTime);
event Withdrawal(address indexed user, uint256 nAmount, uint256 arAmount, uint256 timestamp);
event Restake(uint256 withdrawn, uint256 unstaked, uint256 staked, uint256 totalAum, uint256 timestamp);
event NxmReward(uint256 reward, uint256 timestamp, uint256 totalAum);
// Avoid composability issues for liquidation.
modifier notContract {
require(msg.sender == tx.origin, "Sender must be an EOA.");
_;
}
// Functions as re-entrancy protection and more.
// Mapping down below with other update variables.
modifier oncePerTx {
require(block.timestamp > lastCall[tx.origin], "May only call this contract once per transaction.");
lastCall[tx.origin] = block.timestamp;
_;
}
/**
* @param _protocols List of the 10 protocols we're using.
* @param _wNxm Address of the wNxm contract.
* @param _arNxm Address of the arNxm contract.
* @param _nxmMaster Address of Nexus' master address (to fetch others).
* @param _rewardManager Address of the ReferralRewards smart contract.
**/
function initialize(address[] memory _protocols,
address _wNxm,
address _arNxm,
address _nxm,
address _nxmMaster,
address _rewardManager)
public
{
require(address(arNxm) == address(0), "Contract has already been initialized.");
for (uint256 i = 0; i < _protocols.length; i++) protocols.push(_protocols[i]);
Ownable.initializeOwnable();
wNxm = IERC20(_wNxm);
nxm = IERC20(_nxm);
arNxm = IERC20(_arNxm);
nxmMaster = INxmMaster(_nxmMaster);
rewardManager = IRewardManager(_rewardManager);
// unstakePercent = 100;
adminPercent = 0;
referPercent = 25;
reserveAmount = 30 ether;
pauseDuration = 10 days;
beneficiary = msg.sender;
restakePeriod = 3 days;
rewardDuration = 9 days;
// Approve to wrap and send funds to reward manager.
arNxm.approve( _rewardManager, uint256(-1) );
}
/**
* @dev Deposit wNxm or NXM to get arNxm in return.
* @param _nAmount The amount of NXM to stake.
* @param _referrer The address that referred this user.
* @param _isNxm True if the token is NXM, false if the token is wNXM.
**/
function deposit(uint256 _nAmount, address _referrer, bool _isNxm)
external
oncePerTx
{
if ( referrers[msg.sender] == address(0) ) {
referrers[msg.sender] = _referrer != address(0) ? _referrer : beneficiary;
address refToSet = _referrer != address(0) ? _referrer : beneficiary;
referrers[msg.sender] = refToSet;
// A wallet with a previous arNXM balance would be able to subtract referral weight that it never added.
uint256 prevBal = arNxm.balanceOf(msg.sender);
if (prevBal > 0) rewardManager.stake(refToSet, msg.sender, prevBal);
}
// This amount must be determined before arNxm mint.
uint256 arAmount = arNxmValue(_nAmount);
if (_isNxm) {
nxm.safeTransferFrom(msg.sender, address(this), _nAmount);
} else {
wNxm.safeTransferFrom(msg.sender, address(this), _nAmount);
_unwrapWnxm(_nAmount);
}
// Mint also increases sender's referral balance through alertTransfer.
arNxm.mint(msg.sender, arAmount);
emit Deposit(msg.sender, _nAmount, arAmount, block.timestamp);
}
/**
* @dev Withdraw an amount of wNxm or NXM by burning arNxm.
* @param _arAmount The amount of arNxm to burn for the wNxm withdraw.
* @param _payFee Flag to pay fee to withdraw without delay.
**/
function withdraw(uint256 _arAmount, bool _payFee)
external
oncePerTx
{
require(block.timestamp.sub(withdrawalsPaused) > pauseDuration, "Withdrawals are temporarily paused.");
// This amount must be determined before arNxm burn.
uint256 nAmount = nxmValue(_arAmount);
require(totalPending.add(nAmount) <= nxm.balanceOf(address(this)), "Not enough NXM available for witthdrawal.");
if (_payFee) {
uint256 fee = nAmount.mul(withdrawFee).div(1000);
uint256 disbursement = nAmount.sub(fee);
// Burn also decreases sender's referral balance through alertTransfer.
arNxm.burn(msg.sender, _arAmount);
_wrapNxm(disbursement);
wNxm.safeTransfer(msg.sender, disbursement);
emit Withdrawal(msg.sender, nAmount, _arAmount, block.timestamp);
} else {
totalPending = totalPending.add(nAmount);
arNxm.safeTransferFrom(msg.sender, address(this), _arAmount);
WithdrawalRequest memory prevWithdrawal = withdrawals[msg.sender];
withdrawals[msg.sender] = WithdrawalRequest(
uint48(block.timestamp),
prevWithdrawal.nAmount + uint104(nAmount),
prevWithdrawal.arAmount + uint104(_arAmount)
);
emit WithdrawRequested(msg.sender, _arAmount, nAmount, block.timestamp, block.timestamp.add(withdrawDelay));
}
}
/**
* @dev Withdraw from request
**/
function withdrawFinalize()
external
oncePerTx
{
WithdrawalRequest memory withdrawal = withdrawals[msg.sender];
uint256 nAmount = uint256(withdrawal.nAmount);
uint256 arAmount = uint256(withdrawal.arAmount);
uint256 requestTime = uint256(withdrawal.requestTime);
require(block.timestamp.sub(withdrawalsPaused) > pauseDuration, "Withdrawals are temporarily paused.");
require(requestTime.add(withdrawDelay) <= block.timestamp, "Not ready to withdraw");
require(nAmount > 0, "No pending amount to withdraw");
// Burn also decreases sender's referral balance through alertTransfer.
arNxm.burn(address(this), arAmount);
_wrapNxm(nAmount);
wNxm.safeTransfer(msg.sender, nAmount);
delete withdrawals[msg.sender];
totalPending = totalPending.sub(nAmount);
emit Withdrawal(msg.sender, nAmount, arAmount, block.timestamp);
}
/**
* @dev Restake that may be called by anyone.
* @param _lastId Last unstake request ID on Nexus Mutual.
**/
function restake(uint256 _lastId)
external
{
// Check that this is only called once per week.
require(lastRestake.add(restakePeriod) <= block.timestamp, "It has not been enough time since the last restake.");
_restake(_lastId);
}
/**
* @dev Restake that may be called only by owner. Bypasses restake period restrictions.
* @param _lastId Last unstake request ID on Nexus Mutual.
**/
function ownerRestake(uint256 _lastId)
external
onlyOwner
{
_restake(_lastId);
}
/**
* @dev Restake is to be called weekly. It unstakes 7% of what's currently staked, then restakes.
* @param _lastId Frontend must submit last ID because it doesn't work direct from Nexus Mutual.
**/
function _restake(uint256 _lastId)
internal
notContract
oncePerTx
{
// All Nexus functions.
uint256 withdrawn = _withdrawNxm();
// This will unstake from all unstaking protocols
uint256 unstaked = _unstakeNxm(_lastId);
// This will stake for all protocols, including unstaking protocols
uint256 staked = _stakeNxm();
startProtocol = startProtocol + bucketSize >= protocols.length ? checkpointProtocol + (startProtocol + bucketSize) % protocols.length : startProtocol + bucketSize;
lastRestake = block.timestamp;
emit Restake(withdrawn, unstaked, staked, aum(), block.timestamp);
}
/**
* @dev Split off from restake() function to enable reward fetching at any time.
**/
function getRewardNxm()
external
notContract
{
uint256 prevAum = aum();
uint256 rewards = _getRewardsNxm();
if (rewards > 0) {
lastRewardTimestamp = block.timestamp;
emit NxmReward(rewards, block.timestamp, prevAum);
} else if(lastRewardTimestamp == 0) {
lastRewardTimestamp = block.timestamp;
}
}
/**
* @dev claim rewards from shield mining
* @param _shieldMining shield mining contract address
* @param _protocol Protocol funding the rewards.
* @param _sponsor sponsor address who funded the shield mining
* @param _token token address that sponsor is distributing
**/
function getShieldMiningRewards(address _shieldMining, address _protocol, address _sponsor, address _token)
external
notContract
{
address[] memory protocol = new address[](1);
protocol[0] = _protocol;
address[] memory sponsor = new address[](1);
sponsor[0] = _sponsor;
address[] memory token = new address[](1);
token[0] = _token;
IShieldMining(_shieldMining).claimRewards(protocol, sponsor, token);
}
/**
* @dev Find the arNxm value of a certain amount of wNxm.
* @param _nAmount The amount of NXM to check arNxm value of.
* @return arAmount The amount of arNxm the input amount of wNxm is worth.
**/
function arNxmValue(uint256 _nAmount)
public
view
returns (uint256 arAmount)
{
// Get reward allowed to be distributed.
uint256 reward = _currentReward();
// aum() holds full reward so we sub lastReward (which needs to be distributed over time)
// and add reward that has been distributed
uint256 totalN = aum().add(reward).sub(lastReward);
uint256 totalAr = arNxm.totalSupply();
// Find exchange amount of one token, then find exchange amount for full value.
if (totalN == 0) {
arAmount = _nAmount;
} else {
uint256 oneAmount = ( totalAr.mul(1e18) ).div(totalN);
arAmount = _nAmount.mul(oneAmount).div(1e18);
}
}
/**
* @dev Find the wNxm value of a certain amount of arNxm.
* @param _arAmount The amount of arNxm to check wNxm value of.
* @return nAmount The amount of wNxm the input amount of arNxm is worth.
**/
function nxmValue(uint256 _arAmount)
public
view
returns (uint256 nAmount)
{
// Get reward allowed to be distributed.
uint256 reward = _currentReward();
// aum() holds full reward so we sub lastReward (which needs to be distributed over time)
// and add reward that has been distributed
uint256 totalN = aum().add(reward).sub(lastReward);
uint256 totalAr = arNxm.totalSupply();
// Find exchange amount of one token, then find exchange amount for full value.
uint256 oneAmount = ( totalN.mul(1e18) ).div(totalAr);
nAmount = _arAmount.mul(oneAmount).div(1e18);
}
/**
* @dev Used to determine total Assets Under Management.
* @return aumTotal Full amount of assets under management (wNXM balance + stake deposit).
**/
function aum()
public
view
returns (uint256 aumTotal)
{
IPooledStaking pool = IPooledStaking( _getPool() );
uint256 balance = nxm.balanceOf( address(this) );
uint256 stakeDeposit = pool.stakerDeposit( address(this) );
aumTotal = balance.add(stakeDeposit);
}
/**
* @dev Used to determine staked nxm amount in pooled staking contract.
* @return staked Staked nxm amount.
**/
function stakedNxm()
public
view
returns (uint256 staked)
{
IPooledStaking pool = IPooledStaking( _getPool() );
staked = pool.stakerDeposit( address(this) );
}
/**
* @dev Used to unwrap wnxm tokens to nxm
**/
function unwrapWnxm()
external
{
uint256 balance = wNxm.balanceOf(address(this));
_unwrapWnxm(balance);
}
/**
* @dev Used to determine distributed reward amount
* @return reward distributed reward amount
**/
function currentReward()
external
view
returns (uint256 reward)
{
reward = _currentReward();
}
/**
* @dev Anyone may call this function to pause withdrawals for a certain amount of time.
* We check Nexus contracts for a recent accepted claim, then can pause to avoid further withdrawals.
* @param _claimId The ID of the cover that has been accepted for a confirmed hack.
**/
function pauseWithdrawals(uint256 _claimId)
external
{
IClaimsData claimsData = IClaimsData( _getClaimsData() );
(/*coverId*/, uint256 status) = claimsData.getClaimStatusNumber(_claimId);
uint256 dateUpdate = claimsData.getClaimDateUpd(_claimId);
// Status must be 14 and date update must be within the past 7 days.
if (status == 14 && block.timestamp.sub(dateUpdate) <= 7 days) {
withdrawalsPaused = block.timestamp;
}
}
/**
* @dev When arNXM tokens are transferred, the referrer stakes must be adjusted on RewardManager.
* This is taken care of by a "_beforeTokenTransfer" function on the arNXM ERC20.
* @param _from The user that tokens are being transferred from.
* @param _to The user that tokens are being transferred to.
* @param _amount The amount of tokens that are being transferred.
**/
function alertTransfer(address _from, address _to, uint256 _amount)
external
{
require(msg.sender == address(arNxm), "Sender must be the token contract.");
// address(0) means the contract or EOA has not interacted directly with arNXM Vault.
if ( referrers[_from] != address(0) ) rewardManager.withdraw(referrers[_from], _from, _amount);
if ( referrers[_to] != address(0) ) rewardManager.stake(referrers[_to], _to, _amount);
}
/**
* @dev Withdraw any Nxm we can from the staking pool.
* @return amount The amount of funds that are being withdrawn.
**/
function _withdrawNxm()
internal
returns (uint256 amount)
{
IPooledStaking pool = IPooledStaking( _getPool() );
amount = pool.stakerMaxWithdrawable( address(this) );
pool.withdraw(amount);
}
/**
* @dev Withdraw any available rewards from Nexus.
* @return finalReward The amount of rewards to be given to users (full reward - admin reward - referral reward).
**/
function _getRewardsNxm()
internal
returns (uint256 finalReward)
{
IPooledStaking pool = IPooledStaking( _getPool() );
// Find current reward, find user reward (transfers reward to admin within this).
uint256 fullReward = pool.stakerReward( address(this) );
finalReward = _feeRewardsNxm(fullReward);
pool.withdrawReward( address(this) );
lastReward = finalReward;
}
/**
* @dev Find and distribute administrator rewards.
* @param reward Full reward given from this week.
* @return userReward Reward amount given to users (full reward - admin reward).
**/
function _feeRewardsNxm(uint256 reward)
internal
returns (uint256 userReward)
{
// Find both rewards before minting any.
uint256 adminReward = arNxmValue( reward.mul(adminPercent).div(DENOMINATOR) );
uint256 referReward = arNxmValue( reward.mul(referPercent).div(DENOMINATOR) );
// Mint to beneficary then this address (to then transfer to rewardManager).
if (adminReward > 0) {
arNxm.mint(beneficiary, adminReward);
}
if (referReward > 0) {
arNxm.mint(address(this), referReward);
rewardManager.notifyRewardAmount(referReward);
}
userReward = reward.sub(adminReward).sub(referReward);
}
/**
* @dev Unstake an amount from each protocol on Nxm (takes 30 days to unstake).
* @param _lastId The ID of the last unstake request on Nexus Mutual (needed for unstaking).
* @return unstakeAmount The amount of each token that we're unstaking.
**/
function _unstakeNxm(uint256 _lastId)
internal
returns (uint256 unstakeAmount)
{
IPooledStaking pool = IPooledStaking( _getPool() );
for(uint256 i = 0; i < bucketSize; i++) {
uint256 index = (startProtocol + i) % protocols.length;
if(index < checkpointProtocol) index = index + checkpointProtocol;
uint256 unstakePercent = unstakePercents[index];
address unstakeProtocol = protocols[index];
uint256 stake = pool.stakerContractStake(address(this), unstakeProtocol);
unstakeAmount = stake.mul(unstakePercent).div(DENOMINATOR);
uint256 trueUnstakeAmount = _protocolUnstakeable(unstakeProtocol, unstakeAmount);
// Can't unstake less than 20 NXM.
if (trueUnstakeAmount < 20 ether) continue;
amounts.push(trueUnstakeAmount);
activeProtocols.push(unstakeProtocol);
}
pool.requestUnstake(activeProtocols, amounts, _lastId);
delete amounts;
delete activeProtocols;
}
/**
* @dev Returns the amount we can unstake (if we can't unstake the full amount desired).
* @param _protocol The address of the protocol we're checking.
* @param _unstakeAmount Amount we want to unstake.
* @return The amount of funds that can be unstaked from this protocol if not the full amount desired.
**/
function _protocolUnstakeable(address _protocol, uint256 _unstakeAmount)
internal
view
returns (uint256) {
IPooledStaking pool = IPooledStaking( _getPool() );
uint256 stake = pool.stakerContractStake(address(this), _protocol);
uint256 requested = pool.stakerContractPendingUnstakeTotal(address(this), _protocol);
// Scenario in which all staked has already been requested to be unstaked.
if (requested >= stake) {
return 0;
}
uint256 available = stake - requested;
return _unstakeAmount <= available ? _unstakeAmount : available;
}
function stakeNxmManual(address[] calldata _protocols, uint256[] calldata _stakeAmounts) external onlyOwner{
_stakeNxmManual(_protocols, _stakeAmounts);
}
/**
* @dev Stake any wNxm over the amount we need to keep in reserve (bufferPercent% more than withdrawals last week).
* @param _protocols List of protocols to stake in (NOT list of all protocols).
* @param _stakeAmounts List of amounts to stake in each relevant protocol--this is only ADDITIONAL stake rather than full stake.
* @return toStake Amount of token that we will be staking.
**/
function _stakeNxmManual(address[] memory _protocols, uint256[] memory _stakeAmounts)
internal
returns (uint256 toStake)
{
IPooledStaking pool = IPooledStaking( _getPool() );
uint256 balance = nxm.balanceOf( address(this) );
// If we do need to restake funds...
// toStake == additional stake on top of old ones
if (reserveAmount.add(totalPending) > balance) {
toStake = 0;
} else {
toStake = balance.sub(reserveAmount.add(totalPending));
_approveNxm(_getTokenController(), toStake);
}
// get current data from pooled staking
address[] memory currentProtocols = pool.stakerContractsArray(address(this));
// this will be used to calculate the remaining exposure
for (uint256 i = 0; i < currentProtocols.length; i++) {
amounts.push(pool.stakerContractStake(address(this), currentProtocols[i]));
activeProtocols.push(currentProtocols[i]);
}
// push additional stake data
for(uint256 i = 0; i < _protocols.length; i++) {
address protocol = _protocols[i];
uint256 curIndex = addressArrayFind(currentProtocols, protocol);
if(curIndex == type(uint256).max) {
activeProtocols.push(protocol);
amounts.push(_stakeAmounts[i]);
} else {
amounts[curIndex] += _stakeAmounts[i];
}
}
// now calculate the new staking protocols
pool.depositAndStake(toStake, activeProtocols, amounts);
delete activeProtocols;
delete amounts;
}
/**
* @dev Stake any Nxm over the amount we need to keep in reserve (bufferPercent% more than withdrawals last week).
* @return toStake Amount of token that we will be staking.
**/
function _stakeNxm()
internal
returns (uint256 toStake)
{
IPooledStaking pool = IPooledStaking( _getPool() );
uint256 balance = nxm.balanceOf( address(this) );
uint256 deposited = pool.stakerDeposit(address(this));
// If we do need to restake funds...
// toStake == additional stake on top of old ones
if (reserveAmount.add(totalPending) > balance) {
toStake = 0;
} else {
toStake = balance.sub(reserveAmount.add(totalPending));
_approveNxm(_getTokenController(), toStake);
}
// get current data from pooled staking
address[] memory currentProtocols = pool.stakerContractsArray(address(this));
uint256[] memory currentStakes = new uint256[](currentProtocols.length);
// this will be used to calculate the remaining exposure
uint256 exposure = pool.MAX_EXPOSURE();
uint256 remainingStake = (deposited + toStake) * exposure;
for (uint256 i = 0; i < currentProtocols.length; i++) {
currentStakes[i] = pool.stakerContractStake(address(this), currentProtocols[i]);
require(remainingStake >= currentStakes[i], "exposure exceeds limit, try changeProtocol to fully unstake");
remainingStake -= currentStakes[i];
activeProtocols.push(currentProtocols[i]);
amounts.push(currentStakes[i]);
}
// push additional stake data
for(uint256 i = 0; i < bucketSize; i++) {
uint256 index = (startProtocol + i) % protocols.length;
if(index < checkpointProtocol) index = index + checkpointProtocol;
address protocol = protocols[index];
uint256 curIndex = addressArrayFind(currentProtocols, protocol);
if(curIndex == type(uint256).max && remainingStake/bucketSize >= 20 ether) {
activeProtocols.push(protocol);
amounts.push(remainingStake/exposure);
} else if(curIndex != type(uint256).max) {
amounts[curIndex] = currentStakes[curIndex] + remainingStake / bucketSize;
if(amounts[curIndex] < currentStakes[curIndex]) {
amounts[curIndex] = currentStakes[curIndex];
} else if(amounts[curIndex] > deposited + toStake) {
amounts[curIndex] = deposited + toStake;
}
}
}
// now calculate the new staking protocols
pool.depositAndStake(toStake, activeProtocols, amounts);
delete activeProtocols;
delete amounts;
}
function addressArrayFind(address[] memory arr, address elem) internal pure returns(uint256 index) {
for(uint256 i = 0; i<arr.length; i++) {
if(arr[i] == elem) {
return i;
}
}
return type(uint256).max;
}
/**
* @dev Calculate what the current reward is. We stream this to arNxm value to avoid dumps.
* @return reward Amount of reward currently calculated into arNxm value.
**/
function _currentReward()
internal
view
returns (uint256 reward)
{
uint256 duration = rewardDuration;
uint256 timeElapsed = block.timestamp.sub(lastRewardTimestamp);
if(timeElapsed == 0){
return 0;
}
// Full reward is added to the balance if it's been more than the disbursement duration.
if (timeElapsed >= duration) {
reward = lastReward;
// Otherwise, disburse amounts linearly over duration.
} else {
// 1e18 just for a buffer.
uint256 portion = ( duration.mul(1e18) ).div(timeElapsed);
reward = ( lastReward.mul(1e18) ).div(portion);
}
}
/**
* @dev Wrap Nxm tokens to be able to be withdrawn as wNxm.
**/
function _wrapNxm(uint256 _amount)
internal
{
IWNXM(address(wNxm)).wrap(_amount);
}
/**
* @dev Unwrap wNxm tokens to be able to be used within the Nexus Mutual system.
* @param _amount Amount of wNxm tokens to be unwrapped.
**/
function _unwrapWnxm(uint256 _amount)
internal
{
IWNXM(address(wNxm)).unwrap(_amount);
}
/**
* @dev Get current address of the Nexus staking pool.
* @return pool Address of the Nexus staking pool contract.
**/
function _getPool()
internal
view
returns (address pool)
{
pool = nxmMaster.getLatestAddress("PS");
}
/**
* @dev Get the current NXM token controller (for NXM actions) from Nexus Mutual.
* @return controller Address of the token controller.
**/
function _getTokenController()
internal
view
returns(address controller)
{
controller = nxmMaster.getLatestAddress("TC");
}
/**
* @dev Get current address of the Nexus Claims Data contract.
* @return claimsData Address of the Nexus Claims Data contract.
**/
function _getClaimsData()
internal
view
returns (address claimsData)
{
claimsData = nxmMaster.getLatestAddress("CD");
}
/**
* @dev Approve wNxm contract to be able to transferFrom Nxm from this contract.
**/
function _approveNxm(address _to, uint256 _amount)
internal
{
nxm.approve( _to, _amount );
}
/**
* @dev Buy NXM direct from Nexus Mutual. Used by ExchangeManager.
* @param _minNxm Minimum amount of NXM tokens to receive in return for the Ether.
**/
function buyNxmWithEther(uint256 _minNxm)
external
payable
{
require(msg.sender == 0x1337DEF157EfdeF167a81B3baB95385Ce5A14477, "Sender must be ExchangeManager.");
INXMPool pool = INXMPool(nxmMaster.getLatestAddress("P1"));
pool.buyNXM{value:address(this).balance}(_minNxm);
}
/**
* @dev Vote on Nexus Mutual governance proposals using tokens.
* @param _proposalId ID of the proposal to vote on.
* @param _solutionChosen Side of the proposal we're voting for (0 for no, 1 for yes).
**/
function submitVote(uint256 _proposalId, uint256 _solutionChosen)
external
onlyOwner
{
address gov = nxmMaster.getLatestAddress("GV");
IGovernance(gov).submitVote(_proposalId, _solutionChosen);
}
/**
* @dev rescue tokens locked in contract
* @param token address of token to withdraw
*/
function rescueToken(address token)
external
onlyOwner
{
require(token != address(nxm) && token != address(wNxm) && token != address(arNxm), "Cannot rescue NXM-based tokens");
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(msg.sender, balance);
}
/**
* @dev Owner may change how much of the AUM should be saved in reserve each period.
* @param _reserveAmount The amount of wNXM (in token Wei) to reserve each period.
**/
function changeReserveAmount(uint256 _reserveAmount)
external
onlyOwner
{
reserveAmount = _reserveAmount;
}
/**
* @dev Owner can change the size of a bucket.
* @param _bucketSize The new amount of protocols to stake on each week.
**/
function changeBucketSize(uint256 _bucketSize)
external
onlyOwner
{
// 20 is somewhat arbitrary (max plus a bit in case max expands in the future).
require(_bucketSize <= 10 && _bucketSize <= protocols.length, "Bucket size is too large.");
bucketSize = _bucketSize;
}
/**
* @dev Owner can change checkpoint for where we want all rotations to start and the start of the upcoming rotation.
* @param _checkpointProtocol The protocol to begin rotations on if we don't want to stake or unstake on some.
* @param _startProtocol The protocol that the upcoming rotation will begin on.
**/
function changeCheckpointAndStart(uint256 _checkpointProtocol, uint256 _startProtocol)
external
onlyOwner
{
require(_checkpointProtocol < protocols.length && _startProtocol < protocols.length, "Checkpoint or start is too high.");
checkpointProtocol = _checkpointProtocol;
startProtocol = _startProtocol;
}
/**
* @dev Owner may change the percent of insurance fees referrers receive.
* @param _referPercent The percent of fees referrers receive. 50 == 5%.
**/
function changeReferPercent(uint256 _referPercent)
external
onlyOwner
{
require(_referPercent <= 500, "Cannot give referrer more than 50% of rewards.");
referPercent = _referPercent;
}
/**
* @dev Owner may change the withdraw fee.
* @param _withdrawFee The fee of withdraw.
**/
function changeWithdrawFee(uint256 _withdrawFee)
external
onlyOwner
{
require(_withdrawFee <= DENOMINATOR, "Cannot take more than 100% of withdraw");
withdrawFee = _withdrawFee;
}
/**
* @dev Owner may change the withdraw delay.
* @param _withdrawDelay Withdraw delay.
**/
function changeWithdrawDelay(uint256 _withdrawDelay)
external
onlyOwner
{
withdrawDelay = _withdrawDelay;
}
/**
* @dev Change the percent of rewards that are given for administration of the contract.
* @param _adminPercent The percent of rewards to be given for administration (10 == 1%, 1000 == 100%)
**/
function changeAdminPercent(uint256 _adminPercent)
external
onlyOwner
{
require(_adminPercent <= 500, "Cannot give admin more than 50% of rewards.");
adminPercent = _adminPercent;
}
/**
* @dev Owner may change protocols that we stake for and remove any.
* @param _protocols New list of protocols to stake for.
* @param _unstakePercents Percent to unstake for each protocol.
* @param _removedProtocols Protocols removed from our staking that must be 100% unstaked.
**/
function changeProtocols(address[] calldata _protocols, uint256[] calldata _unstakePercents, address[] calldata _removedProtocols, uint256 _lastId)
external
onlyOwner
{
require(_protocols.length == _unstakePercents.length, "array length diff");
protocols = _protocols;
unstakePercents = _unstakePercents;
if (_removedProtocols.length > 0) {
IPooledStaking pool = IPooledStaking( _getPool() );
for (uint256 i = 0; i < _removedProtocols.length; i++) {
uint256 indUnstakeAmount = _protocolUnstakeable(_removedProtocols[i], uint256(~0));
if(indUnstakeAmount == 0){
// skip already fully requested protocols
continue;
}
amounts.push(indUnstakeAmount);
activeProtocols.push(_removedProtocols[i]);
}
pool.requestUnstake(activeProtocols, amounts, _lastId);
delete amounts;
delete activeProtocols;
}
}
/**
* @dev Owner may change the amount of time required to be waited between restaking.
* @param _restakePeriod Amount of time required between restakes (starts at 6 days or 86400 * 6).
**/
function changeRestakePeriod(uint256 _restakePeriod)
external
onlyOwner
{
require(_restakePeriod <= 30 days, "Restake period cannot be more than 30 days.");
restakePeriod = _restakePeriod;
}
/**
* @dev Owner may change the amount of time it takes to distribute rewards from Nexus.
* @param _rewardDuration The amount of time it takes to fully distribute rewards.
**/
function changeRewardDuration(uint256 _rewardDuration)
external
onlyOwner
{
require(_rewardDuration <= 30 days, "Reward duration cannot be more than 30 days.");
rewardDuration = _rewardDuration;
}
/**
* @dev Owner may change the amount of time that withdrawals are paused after a hack is confirmed.
* @param _pauseDuration The new amount of time that withdrawals will be paused.
**/
function changePauseDuration(uint256 _pauseDuration)
external
onlyOwner
{
require(_pauseDuration <= 30 days, "Pause duration cannot be more than 30 days.");
pauseDuration = _pauseDuration;
}
/**
* @dev Change beneficiary of the administration funds.
* @param _newBeneficiary Address of the new beneficiary to receive funds.
**/
function changeBeneficiary(address _newBeneficiary)
external
onlyOwner
{
beneficiary = _newBeneficiary;
}
//// Update addition. Proxy paranoia brought it down here. ////
uint256 public lastRewardTimestamp;
//// Second update additions. ////
// Protocol that the next restaking will begin on.
uint256 public startProtocol;
// Checkpoint in case we want to cut off certain buckets (where we begin the rotations).
// To bar protocols from being staked/unstaked, move them to before checkpointProtocol.
uint256 public checkpointProtocol;
// Number of protocols to stake each time.
uint256 public bucketSize;
// Individual percent to unstake.
uint256[] public unstakePercents;
// Last time an EOA has called this contract.
mapping (address => uint256) public lastCall;
///// Third update additions. /////
// Withdraw fee to withdraw immediately.
uint256 public withdrawFee;
// Delay to withdraw
uint256 public withdrawDelay;
// Total amount of withdrawals pending.
uint256 public totalPending;
mapping (address => WithdrawalRequest) public withdrawals;
} | Find the arNxm value of a certain amount of wNxm. _nAmount The amount of NXM to check arNxm value of. return arAmount The amount of arNxm the input amount of wNxm is worth./ Get reward allowed to be distributed. aum() holds full reward so we sub lastReward (which needs to be distributed over time) and add reward that has been distributed Find exchange amount of one token, then find exchange amount for full value. | function arNxmValue(uint256 _nAmount)
public
view
returns (uint256 arAmount)
{
uint256 reward = _currentReward();
uint256 totalN = aum().add(reward).sub(lastReward);
uint256 totalAr = arNxm.totalSupply();
if (totalN == 0) {
arAmount = _nAmount;
uint256 oneAmount = ( totalAr.mul(1e18) ).div(totalN);
arAmount = _nAmount.mul(oneAmount).div(1e18);
}
}
| 6,135,469 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @artist: FVCKRENDER
/// @title: ESSENCE//
/// @author: manifold.xyz
//////////////////////////////////////////////////////////////////////////////////////////////
// //
// ______ _____ _____ ______ _ __ ______ ______ __ ___ //
// / ____// ___// ___/ / ____// | / // ____// ____/ _/_/_/_/ //
// / __/ \__ \ \__ \ / __/ / |/ // / / __/ _/_/_/_/ //
// / /___ ___/ /___/ // /___ / /| // /___ / /___ _/_/_/_/ //
// /_____/ /____//____//_____//_/ |_/ \____//_____//_/ /_/ //
// //
// //
// ,*69. //
// ,**.*@@@. //
// %.#/.,/ /,/((/@@@@, @@@. //
// ,(@@@@#&/,,@@/(%(& (@@%@&/##@@@.. /%@*@*,. //
// #@.&@@@#@@@@@@%#@@.. @&@.*(,/,*#%&##%#,(@%/(/(@@ //
// &@(@@@@/@@@@*%**,.(%#%&@[email protected]*/@&/&@@#%*/#%#%(##(@@/*. //
// .&%@@@@@@@@@@@@@@@%#(////****//(#(,@.&&%%((//#%%%&*#,, //
// (@%*,#@,*%&@@@@@@@@@%(//////(/**/*/,,.%%%%#*/*/(((*(**,, //
// //,/*/,..#@@@@@@@@@@&%(//********/(/*,,@%%,*/*/////(69/%@. //
// /#@&/#%../#@@@@@@@@@@&%(/*******,*********.%(**#*****/*( //
// (%@(# .*@@@@@@@69#((//***,,,,,,,,,,,,,****,(&**%//(@. //
// //#%*&/(*(%##((///***,,,,.....,,,,,,,,,,,*** @&&/*(/ //
// *(*&. %/,,*/*,,........... ....... . ..,,*.&&&&#*/(,, //
// &%, %**..,,..... ....*(*,,.,,&&&&(,//(** //
// ,*,#%/%%*,/*....... . ....,,.,..%(#(,.**/. //
// */&(*,#(&%/*,,,. ... .,*///@/#%,(.((,/ //
// *@(/(/%(@@.****,.. . ,*, ./*/@/%&. .(,&&/ //
// .,.,#%//*,#%#*,***. *,,, *###@%***#,./(#, //
// *@@@@(@#@*@ *%,*.*. ., &@/**%*#@/*,*(*/@ ,#%& //
// *@@%///*@(%&/,.%.%*&. . /%,,.,&@@&/## %,# ((@@#(( //
// .,@@,@@%&%#**,*//((%**/&,..*,&@.((#%//., @@,@(@. //
// [email protected]@@@@@((/(#///.,,/**/(%,#(%@@@@%%&@@@&#@/./.. //
// ,,,,,%@@@@,,%#/*,,&***(,*/,/#%@&@@@@%@@*(%#/ //
// ,***@@@@,&*/[email protected]*,(,,,,.,. //
// ///@@,..,& .,69., //
// //
// //
//////////////////////////////////////////////////////////////////////////////////////////////
import "@manifoldxyz/libraries-solidity/contracts/access/AdminControl.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "./ERC1155CollectionBase.sol";
contract ESSENCE is ERC1155, ERC1155CollectionBase, AdminControl {
constructor(address signingAddress_) ERC1155('') {
_initialize(
// total supply
12969,
// total supply available to purchase
12969,
// 0.469 eth public sale price
469000000000000000,
// purchase limit (0 for no limit)
0,
// transaction limit (0 for no limit)
1,
// 0.2 eth presale price
200000000000000000,
// presale limit (unused but 0 for no limit)
0,
signingAddress_,
// use dynamic presale purchase limit
true
);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC1155CollectionBase, AdminControl) returns (bool) {
return ERC1155CollectionBase.supportsInterface(interfaceId) || ERC1155.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155Collection-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
return ERC1155.balanceOf(owner, TOKEN_ID);
}
/**
* @dev See {IERC1155Collection-withdraw}.
*/
function withdraw(address payable recipient, uint256 amount) external override adminRequired {
_withdraw(recipient, amount);
}
/**
* @dev See {IERC1155Collection-setTransferLocked}.
*/
function setTransferLocked(bool locked) external override adminRequired {
_setTransferLocked(locked);
}
/**
* @dev See {IERC1155Collection-premint}.
*/
function premint(uint16 amount) external override adminRequired {
_premint(amount, owner());
}
/**
* @dev See {IERC1155Collection-premint}.
*/
function premint(uint16[] calldata amounts, address[] calldata addresses) external override adminRequired {
_premint(amounts, addresses);
}
/**
* @dev See {IERC1155Collection-mintReserve}.
*/
function mintReserve(uint16 amount) external override adminRequired {
_mintReserve(amount, owner());
}
/**
* @dev See {IERC1155Collection-mintReserve}.
*/
function mintReserve(uint16[] calldata amounts, address[] calldata addresses) external override adminRequired {
_mintReserve(amounts, addresses);
}
/**
* @dev See {IERC1155Collection-activate}.
*/
function activate(uint256 startTime_, uint256 duration, uint256 presaleInterval_, uint256 claimStartTime_, uint256 claimEndTime_) external override adminRequired {
_activate(startTime_, duration, presaleInterval_, claimStartTime_, claimEndTime_);
}
/**
* @dev See {IERC1155Collection-deactivate}.
*/
function deactivate() external override adminRequired {
_deactivate();
}
/**
* @dev See {IERC1155Collection-setCollectionURI}.
*/
function setCollectionURI(string calldata uri) external override adminRequired {
_setURI(uri);
}
/**
* @dev See {IERC1155Collection-burn}
*/
function burn(address from, uint16 amount) public virtual override {
require(from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved");
ERC1155._burn(from, TOKEN_ID, amount);
}
/**
* @dev See {ERC1155CollectionBase-_mint}.
*/
function _mintERC1155(address to, uint16 amount) internal virtual override {
ERC1155._mint(to, TOKEN_ID, amount, "");
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(address, address from, address, uint256[] memory, uint256[] memory, bytes memory) internal virtual override {
_validateTokenTransferability(from);
}
/**
* @dev Update royalties
*/
function updateRoyalties(address payable recipient, uint256 bps) external adminRequired {
_updateRoyalties(recipient, bps);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/Strings.sol";
import "./IERC1155Collection.sol";
import "./CollectionBase.sol";
/**
* ERC1155 Collection Drop Contract (Base)
*/
abstract contract ERC1155CollectionBase is CollectionBase, IERC1155Collection {
// Token ID to mint
uint16 internal constant TOKEN_ID = 1;
// Immutable variables that should only be set by the constructor or initializer
uint16 public transactionLimit;
uint16 public purchaseMax;
uint16 public purchaseLimit;
uint256 public purchasePrice;
uint16 public presalePurchaseLimit;
uint256 public presalePurchasePrice;
uint16 public maxSupply;
bool public useDynamicPresalePurchaseLimit;
// Mutable mint state
uint16 public purchaseCount;
uint16 public reserveCount;
mapping(address => uint16) private _mintCount;
// Royalty
uint256 private _royaltyBps;
address payable private _royaltyRecipient;
bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6;
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a;
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
// Transfer lock
bool public transferLocked;
/**
* Initializer
*/
function _initialize(uint16 maxSupply_, uint16 purchaseMax_, uint256 purchasePrice_, uint16 purchaseLimit_, uint16 transactionLimit_, uint256 presalePurchasePrice_, uint16 presalePurchaseLimit_, address signingAddress_, bool useDynamicPresalePurchaseLimit_) internal {
require(_signingAddress == address(0), "Already initialized");
require(maxSupply_ >= purchaseMax_, "Invalid input");
maxSupply = maxSupply_;
purchaseMax = purchaseMax_;
purchasePrice = purchasePrice_;
purchaseLimit = purchaseLimit_;
transactionLimit = transactionLimit_;
presalePurchaseLimit = presalePurchaseLimit_;
presalePurchasePrice = presalePurchasePrice_;
_signingAddress = signingAddress_;
useDynamicPresalePurchaseLimit = useDynamicPresalePurchaseLimit_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) {
return interfaceId == type(IERC1155Collection).interfaceId ||interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE
|| interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981 || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE;
}
/**
* @dev See {IERC1155Collection-claim}.
*/
function claim(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external virtual override {
_validateClaimRestrictions();
_validateClaimRequest(message, signature, nonce, amount);
_mint(msg.sender, amount, true);
}
/**
* @dev See {IERC1155Collection-purchase}.
*/
function purchase(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external virtual override payable {
_validatePurchaseRestrictions();
// Check purchase amounts
require(amount <= purchaseRemaining() && (transactionLimit == 0 || amount <= transactionLimit), "Too many requested");
uint256 balance = _getMintBalance();
bool isPresale = _isPresale();
if (isPresale) {
require((presalePurchaseLimit == 0 || useDynamicPresalePurchaseLimit || amount <= (presalePurchaseLimit - balance)) && (purchaseLimit == 0 || amount <= (purchaseLimit - balance)), "Too many requested");
_validatePresalePrice(amount);
} else {
require(purchaseLimit == 0 || amount <= (purchaseLimit - balance), "Too many requested");
_validatePrice(amount);
}
if (isPresale && useDynamicPresalePurchaseLimit) {
_validatePurchaseRequestWithAmount(message, signature, nonce, amount);
} else {
_validatePurchaseRequest(message, signature, nonce);
}
_mint(msg.sender, amount, isPresale);
}
/**
* @dev See {IERC1155Collection-state}
*/
function state() external override view returns (CollectionState memory) {
// No message sender, no purchase balance
uint16 balance = msg.sender == address(0) ? 0 : uint16(_getMintBalance());
return CollectionState(transactionLimit, purchaseMax, purchaseRemaining(), purchasePrice, purchaseLimit, presalePurchasePrice, presalePurchaseLimit, balance, active, startTime, endTime, presaleInterval, claimStartTime, claimEndTime, useDynamicPresalePurchaseLimit);
}
/**
* @dev Get balance of address. Similar to IERC1155-balanceOf, but doesn't require token ID
* @param owner The address to get the token balance of
*/
function balanceOf(address owner) public virtual override view returns (uint256);
/**
* @dev See {IERC1155Collection-purchaseRemaining}.
*/
function purchaseRemaining() public virtual override view returns (uint16) {
return purchaseMax - purchaseCount;
}
/**
* ROYALTY FUNCTIONS
*/
function getRoyalties(uint256) external view returns (address payable[] memory recipients, uint256[] memory bps) {
if (_royaltyRecipient != address(0x0)) {
recipients = new address payable[](1);
recipients[0] = _royaltyRecipient;
bps = new uint256[](1);
bps[0] = _royaltyBps;
}
return (recipients, bps);
}
function getFeeRecipients(uint256) external view returns (address payable[] memory recipients) {
if (_royaltyRecipient != address(0x0)) {
recipients = new address payable[](1);
recipients[0] = _royaltyRecipient;
}
return recipients;
}
function getFeeBps(uint256) external view returns (uint[] memory bps) {
if (_royaltyRecipient != address(0x0)) {
bps = new uint256[](1);
bps[0] = _royaltyBps;
}
return bps;
}
function royaltyInfo(uint256, uint256 value) external view returns (address, uint256) {
return (_royaltyRecipient, value*_royaltyBps/10000);
}
/**
* Premint tokens to the owner. Purchase must not be active.
*/
function _premint(uint16 amount, address owner) internal virtual {
require(!active, "Already active");
_mint(owner, amount, true);
}
/**
* Premint tokens to the list of addresses. Purchase must not be active.
*/
function _premint(uint16[] calldata amounts, address[] calldata addresses) internal virtual {
require(!active, "Already active");
for (uint256 i = 0; i < addresses.length; i++) {
_mint(addresses[i], amounts[i], true);
}
}
/**
* Mint reserve tokens. Purchase must be completed.
*/
function _mintReserve(uint16 amount, address owner) internal virtual {
require(endTime != 0 && endTime <= block.timestamp, "Cannot mint reserve until after sale complete");
require(purchaseCount + reserveCount + amount <= maxSupply, "Too many requested");
reserveCount += amount;
_mintERC1155(owner, amount);
}
/**
* Mint reserve tokens. Purchase must be completed.
*/
function _mintReserve(uint16[] calldata amounts, address[] calldata addresses) internal virtual {
require(endTime != 0 && endTime <= block.timestamp, "Cannot mint reserve until after sale complete");
uint16 totalAmount;
for (uint256 i = 0; i < addresses.length; i++) {
totalAmount += amounts[i];
}
require(purchaseCount + reserveCount + totalAmount <= maxSupply, "Too many requested");
reserveCount += totalAmount;
for (uint256 i = 0; i < addresses.length; i++) {
_mintERC1155(addresses[i], amounts[i]);
}
}
/**
* Mint function internal to ERC1155CollectionBase to keep track of state
*/
function _mint(address to, uint16 amount, bool presale) internal {
purchaseCount += amount;
// Track total mints per address only if necessary
if (_shouldTrackMints(presale)) {
_mintCount[msg.sender] += amount;
}
_mintERC1155(to, amount);
}
/**
* @dev A _mint function is required that calls the underlying ERC1155 mint.
*/
function _mintERC1155(address to, uint16 amount) internal virtual;
/**
* Validate price (override for custom pricing mechanics)
*/
function _validatePrice(uint16 amount) internal {
require(msg.value == amount * purchasePrice, "Invalid purchase amount sent");
}
/**
* Validate price (override for custom pricing mechanics)
*/
function _validatePresalePrice(uint16 amount) internal virtual {
require(msg.value == amount * presalePurchasePrice, "Invalid purchase amount sent");
}
/**
* If enabled, lock token transfers until after the sale has ended.
*
* This helps enforce purchase limits, so someone can't buy -> transfer -> buy again
* while the token is minting.
*/
function _validateTokenTransferability(address from) internal view {
require(!transferLocked || purchaseRemaining() == 0 || (active && block.timestamp >= endTime) || from == address(0), "Transfer locked until sale ends");
}
/**
* Set whether or not token transfers are locked till end of sale
*/
function _setTransferLocked(bool locked) internal {
transferLocked = locked;
}
/**
* @dev Update royalties
*/
function _updateRoyalties(address payable recipient, uint256 bps) internal {
_royaltyRecipient = recipient;
_royaltyBps = bps;
}
/**
* @dev Return mint count or balanceOf
*/
function _getMintBalance() internal view returns (uint256) {
uint256 balance;
if (_shouldTrackMints()) {
balance = _mintCount[msg.sender];
} else {
balance = balanceOf(msg.sender);
}
return balance;
}
/**
* @dev Return whether mints need to be tracked
*/
function _shouldTrackMints() internal view returns (bool) {
return !transferLocked && ((_isPresale() && (useDynamicPresalePurchaseLimit || presalePurchaseLimit > 0)) || purchaseLimit > 0);
}
/**
* @dev Return whether mints need to be tracked
* @param isPresale - pass in to explicitly consider in presale
*/
function _shouldTrackMints(bool isPresale) internal view returns (bool) {
return !transferLocked && ((isPresale && (useDynamicPresalePurchaseLimit || presalePurchaseLimit > 0)) || purchaseLimit > 0);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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 _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IAdminControl.sol";
abstract contract AdminControl is Ownable, IAdminControl, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
// Track registered admins
EnumerableSet.AddressSet private _admins;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IAdminControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin");
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (!_admins.contains(admin)) {
emit AdminApproved(admin, msg.sender);
_admins.add(admin);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.contains(admin)) {
emit AdminRevoked(admin, msg.sender);
_admins.remove(admin);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public override view returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./ICollectionBase.sol";
/**
* Collection Drop Contract (Base)
*/
abstract contract CollectionBase is ICollectionBase {
using ECDSA for bytes32;
using Strings for uint256;
// Immutable variables that should only be set by the constructor or initializer
address internal _signingAddress;
// Message nonces
mapping(bytes32 => bool) private _usedNonces;
// Sale start/end control
bool public active;
uint256 public startTime;
uint256 public endTime;
uint256 public presaleInterval;
// Claim period start/end control
uint256 public claimStartTime;
uint256 public claimEndTime;
/**
* Withdraw funds
*/
function _withdraw(address payable recipient, uint256 amount) internal {
(bool success,) = recipient.call{value:amount}("");
require(success);
}
/**
* Activate the sale
*/
function _activate(uint256 startTime_, uint256 duration, uint256 presaleInterval_, uint256 claimStartTime_, uint256 claimEndTime_) internal virtual {
require(!active, "Already active");
require(startTime_ > block.timestamp, "Cannot activate in the past");
require(presaleInterval_ < duration, "Presale Interval cannot be longer than the sale");
require(claimStartTime_ <= claimEndTime_ && claimEndTime_ <= startTime_, "Invalid claim times");
startTime = startTime_;
endTime = startTime + duration;
presaleInterval = presaleInterval_;
claimStartTime = claimStartTime_;
claimEndTime = claimEndTime_;
active = true;
emit CollectionActivated(startTime, endTime, presaleInterval, claimStartTime, claimEndTime);
}
/**
* Deactivate the sale
*/
function _deactivate() internal virtual {
startTime = 0;
endTime = 0;
active = false;
claimStartTime = 0;
claimEndTime = 0;
emit CollectionDeactivated();
}
function _getNonceBytes32(string memory nonce) internal pure returns(bytes32 nonceBytes32) {
bytes memory nonceBytes = bytes(nonce);
require(nonceBytes.length <= 32, "Invalid nonce");
assembly {
nonceBytes32 := mload(add(nonce, 32))
}
}
/**
* Validate claim signature
*/
function _validateClaimRequest(bytes32 message, bytes calldata signature, string calldata nonce, uint16 amount) internal virtual {
_validatePurchaseRequestWithAmount(message, signature, nonce, amount);
}
/**
* Validate claim restrictions
*/
function _validateClaimRestrictions() internal virtual {
require(active, "Inactive");
require(block.timestamp >= claimStartTime && block.timestamp <= claimEndTime, "Outside claim period.");
}
/**
* Validate purchase signature
*/
function _validatePurchaseRequest(bytes32 message, bytes calldata signature, string calldata nonce) internal virtual {
// Verify nonce usage/re-use
bytes32 nonceBytes32 = _getNonceBytes32(nonce);
require(!_usedNonces[nonceBytes32], "Cannot replay transaction");
// Verify valid message based on input variables
bytes32 expectedMessage = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", (20+bytes(nonce).length).toString(), msg.sender, nonce));
require(message == expectedMessage, "Malformed message");
// Verify signature was performed by the expected signing address
address signer = message.recover(signature);
require(signer == _signingAddress, "Invalid signature");
_usedNonces[nonceBytes32] = true;
}
/**
* Validate purchase signature with amount
*/
function _validatePurchaseRequestWithAmount(bytes32 message, bytes calldata signature, string calldata nonce, uint16 amount) internal virtual {
// Verify nonce usage/re-use
bytes32 nonceBytes32 = _getNonceBytes32(nonce);
require(!_usedNonces[nonceBytes32], "Cannot replay transaction");
// Verify valid message based on input variables
bytes32 expectedMessage = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", (20+bytes(nonce).length+bytes(uint256(amount).toString()).length).toString(), msg.sender, nonce, uint256(amount).toString()));
require(message == expectedMessage, "Malformed message");
// Verify signature was performed by the expected signing address
address signer = message.recover(signature);
require(signer == _signingAddress, "Invalid signature");
_usedNonces[nonceBytes32] = true;
}
/**
* Perform purchase restriciton checks. Override if more logic is needed
*/
function _validatePurchaseRestrictions() internal virtual {
require(active, "Inactive");
require(block.timestamp >= startTime, "Purchasing not active");
}
/**
* @dev See {ICollectionBase-nonceUsed}.
*/
function nonceUsed(string memory nonce) external view override returns(bool) {
bytes32 nonceBytes32 = _getNonceBytes32(nonce);
return _usedNonces[nonceBytes32];
}
/**
* @dev Check if currently in presale
*/
function _isPresale() internal view returns (bool) {
return block.timestamp - startTime < presaleInterval;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "./ICollectionBase.sol";
/**
* @dev ERC1155 Collection Interface
*/
interface IERC1155Collection is ICollectionBase, IERC165 {
struct CollectionState {
uint16 transactionLimit;
uint16 purchaseMax;
uint16 purchaseRemaining;
uint256 purchasePrice;
uint16 purchaseLimit;
uint256 presalePurchasePrice;
uint16 presalePurchaseLimit;
uint16 purchaseCount;
bool active;
uint256 startTime;
uint256 endTime;
uint256 presaleInterval;
uint256 claimStartTime;
uint256 claimEndTime;
bool useDynamicPresalePurchaseLimit;
}
/**
* @dev Activates the contract.
* @param startTime_ The UNIX timestamp in seconds the sale should start at.
* @param duration The number of seconds the sale should remain active.
* @param presaleInterval_ The period of time the contract should only be active for presale.
*/
function activate(uint256 startTime_, uint256 duration, uint256 presaleInterval_, uint256 claimStartTime_, uint256 claimEndTime_) external;
/**
* @dev Deactivate the contract
*/
function deactivate() external;
/**
* @dev Pre-mint tokens to the owner. Sale must not be active.
* @param amount The number of tokens to mint.
*/
function premint(uint16 amount) external;
/**
* @dev Pre-mint tokens to the list of addresses. Sale must not be active.
* @param amounts The amount of tokens to mint per address.
* @param addresses The list of addresses to mint a token to.
*/
function premint(uint16[] calldata amounts, address[] calldata addresses) external;
/**
* @dev Claim - mint with validation.
* @param amount The number of tokens to mint.
* @param message Signed message to validate input args.
* @param signature Signature of the signer to recover from signed message.
* @param nonce Manifold-generated nonce.
*/
function claim(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external;
/**
* @dev Purchase - mint with validation.
* @param amount The number of tokens to mint.
* @param message Signed message to validate input args.
* @param signature Signature of the signer to recover from signed message.
* @param nonce Manifold-generated nonce.
*/
function purchase(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external payable;
/**
* @dev Mint reserve tokens to the owner. Sale must be complete.
* @param amount The number of tokens to mint.
*/
function mintReserve(uint16 amount) external;
/**
* @dev Mint reserve tokens to the list of addresses. Sale must be complete.
* @param amounts The amount of tokens to mint per address.
* @param addresses The list of addresses to mint a token to.
*/
function mintReserve(uint16[] calldata amounts, address[] calldata addresses) external;
/**
* @dev Set the URI for the metadata for the collection.
* @param uri The metadata URI.
*/
function setCollectionURI(string calldata uri) external;
/**
* @dev returns the collection state
*/
function state() external view returns (CollectionState memory);
/**
* @dev Total amount of tokens remaining for the given token id.
*/
function purchaseRemaining() external view returns (uint16);
/**
* @dev Withdraw funds (requires contract admin).
* @param recipient The address to withdraw funds to
* @param amount The amount to withdraw
*/
function withdraw(address payable recipient, uint256 amount) external;
/**
* @dev Set whether or not token transfers are locked until end of sale.
* @param locked Whether or not transfers are locked
*/
function setTransferLocked(bool locked) external;
/**
* @dev Get balance of address. Similar to IERC1155-balanceOf, but doesn't require token ID
* @param owner The address to get the token balance of
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Destroys `amount` tokens from `from`
* @param from The address to remove tokens from
* @param amount The amount of tokens to remove
*/
function burn(address from, uint16 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControl is IERC165 {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// 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/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 => 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;
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 (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) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// 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));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
/**
* @dev Collection Interface
*/
interface ICollectionBase {
event CollectionActivated(uint256 startTime, uint256 endTime, uint256 presaleInterval, uint256 claimStartTime, uint256 claimEndTime);
event CollectionDeactivated();
/**
* @dev Check if nonce has been used
*/
function nonceUsed(string memory nonce) external view returns(bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
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");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// 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);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (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);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 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 Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
} | Return whether mints need to be tracked isPresale - pass in to explicitly consider in presale/ | function _shouldTrackMints(bool isPresale) internal view returns (bool) {
return !transferLocked && ((isPresale && (useDynamicPresalePurchaseLimit || presalePurchaseLimit > 0)) || purchaseLimit > 0);
}
| 93,949 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IBasketToken } from "../interfaces/IBasketToken.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { PreciseUnitMath } from "../lib/PreciseUnitMath.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 { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
contract BasketToken is ERC20, ReentrancyGuard {
using SafeMath for uint256;
using SafeCast for int256;
using SafeCast for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using Address for address;
using AddressArrayUtils for address[];
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Constants ============ */
/*
The PositionState is the status of the Position, whether it is Default (held on the SetToken)
or otherwise held on a separate smart contract (whether a module or external source).
There are issues with cross-usage of enums, so we are defining position states
as a uint8.
*/
uint8 internal constant DEFAULT = 0;
uint8 internal constant EXTERNAL = 1;
/* ============ Events ============ */
event Invoked(address indexed _target, uint indexed _value, bytes _data, bytes _returnValue);
event ModuleAdded(address indexed _module);
event ModuleRemoved(address indexed _module);
event ModuleInitialized(address indexed _module);
event ManagerEdited(address _newManager, address _oldManager);
event PendingModuleRemoved(address indexed _module);
event PositionMultiplierEdited(int256 _newMultiplier);
event ComponentAdded(address indexed _component);
event ComponentRemoved(address indexed _component);
event DefaultPositionUnitEdited(address indexed _component, int256 _realUnit);
event ExternalPositionUnitEdited(address indexed _component, address indexed _positionModule, int256 _realUnit);
event ExternalPositionDataEdited(address indexed _component, address indexed _positionModule, bytes _data);
event PositionModuleAdded(address indexed _component, address indexed _positionModule);
event PositionModuleRemoved(address indexed _component, address indexed _positionModule);
/**
* Throws if SetToken is locked and called by any account other than the locker.
*/
modifier whenLockedOnlyLocker() {
_validateWhenLockedOnlyLocker();
_;
}
/* ============ State Variables ============ */
// A module that has locked other modules from privileged functionality, typically required
// for multi-block module actions such as auctions
address public locker;
// List of initialized Modules; Modules extend the functionality of SetTokens
address[] public modules;
// When locked, only the locker (a module) can call privileged functionality
// Typically utilized if a module (e.g. Auction) needs multiple transactions to complete an action
// without interruption
bool public isLocked;
// List of components
address[] public components;
// Mapping that stores all Default and External position information for a given component.
// Position quantities are represented as virtual units; Default positions are on the top-level,
// while external positions are stored in a module array and accessed through its externalPositions mapping
mapping(address => IBasketToken.ComponentPosition) private componentPositions;
// The multiplier applied to the virtual position unit to achieve the real/actual unit.
// This multiplier is used for efficiently modifying the entire position units (e.g. streaming fee)
int256 public positionMultiplier;
/* ============ Constructor ============ */
/**
* When a new BasketToken is created, initializes Positions in default state and adds modules into pending state.
* All parameter validations are on the SetTokenCreator contract. Validations are performed already on the
* SetTokenCreator. Initiates the positionMultiplier as 1e18 (no adjustments).
*
* @param _components List of addresses of components for initial Positions
* @param _units List of units. Each unit is the # of components per 10^18 of a SetToken
* @param _name Name of the BasketToken
* @param _symbol Symbol of the BasketToken
*/
constructor(
address[] memory _components,
int256[] memory _units,
string memory _name,
string memory _symbol
)
public
ERC20(_name, _symbol)
{
positionMultiplier = PreciseUnitMath.preciseUnitInt();
components = _components;
// Positions are put in default state initially
for (uint256 j = 0; j < _components.length; j++) {
componentPositions[_components[j]].virtualUnit = _units[j];
}
}
/* ============ External Functions ============ */
/**
* PRIVELEGED MODULE FUNCTION. Low level function that allows a module to make an arbitrary function
* call to any contract.
*
* @param _target Address of the smart contract to call
* @param _value Quantity of Ether to provide the call (typically 0)
* @param _data Encoded function selector and arguments
* @return _returnValue Bytes encoded return value
*/
function invoke(
address _target,
uint256 _value,
bytes calldata _data
)
external
whenLockedOnlyLocker
returns (bytes memory _returnValue)
{
_returnValue = _target.functionCallWithValue(_data, _value);
emit Invoked(_target, _value, _data, _returnValue);
return _returnValue;
}
/**
* Deposits the BasketToken's position components into the BasketToken and mints the BasketToken of the given quantity
* to the specified _to address. This function only handles Default Positions (positionState = 0).
*
* @param _basketToken Instance of the BasketToken contract
* @param _quantity Quantity of the BasketToken to mint
* @param _to Address to mint BasketToken to
*/
/**
* PRIVELEGED MODULE FUNCTION. Low level function that adds a component to the components array.
*/
function addComponent(address _component) external whenLockedOnlyLocker {
//require(!isComponent(_component), "Must not be component");
components.push(_component);
emit ComponentAdded(_component);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that removes a component from the components array.
*/
function removeComponent(address _component) external whenLockedOnlyLocker {
components.removeStorage(_component);
emit ComponentRemoved(_component);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that edits a component's virtual unit. Takes a real unit
* and converts it to virtual before committing.
*/
function editDefaultPositionUnit(address _component, int256 _realUnit) external whenLockedOnlyLocker {
int256 virtualUnit = _convertRealToVirtualUnit(_realUnit);
componentPositions[_component].virtualUnit = virtualUnit;
emit DefaultPositionUnitEdited(_component, _realUnit);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that adds a module to a component's externalPositionModules array
*/
function addExternalPositionModule(address _component, address _positionModule) external whenLockedOnlyLocker {
require(!isExternalPositionModule(_component, _positionModule), "Module already added");
componentPositions[_component].externalPositionModules.push(_positionModule);
emit PositionModuleAdded(_component, _positionModule);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that removes a module from a component's
* externalPositionModules array and deletes the associated externalPosition.
*/
function removeExternalPositionModule(
address _component,
address _positionModule
)
external
whenLockedOnlyLocker
{
componentPositions[_component].externalPositionModules.removeStorage(_positionModule);
delete componentPositions[_component].externalPositions[_positionModule];
emit PositionModuleRemoved(_component, _positionModule);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position virtual unit.
* Takes a real unit and converts it to virtual before committing.
*/
function editExternalPositionUnit(
address _component,
address _positionModule,
int256 _realUnit
)
external
whenLockedOnlyLocker
{
int256 virtualUnit = _convertRealToVirtualUnit(_realUnit);
componentPositions[_component].externalPositions[_positionModule].virtualUnit = virtualUnit;
emit ExternalPositionUnitEdited(_component, _positionModule, _realUnit);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position data
*/
function editExternalPositionData(
address _component,
address _positionModule,
bytes calldata _data
)
external
whenLockedOnlyLocker
{
componentPositions[_component].externalPositions[_positionModule].data = _data;
emit ExternalPositionDataEdited(_component, _positionModule, _data);
}
/**
* PRIVELEGED MODULE FUNCTION. Modifies the position multiplier. This is typically used to efficiently
* update all the Positions' units at once in applications where inflation is awarded (e.g. subscription fees).
*/
function editPositionMultiplier(int256 _newMultiplier) external whenLockedOnlyLocker {
_validateNewMultiplier(_newMultiplier);
positionMultiplier = _newMultiplier;
emit PositionMultiplierEdited(_newMultiplier);
}
/**
* PRIVELEGED MODULE FUNCTION. Increases the "account" balance by the "quantity".
*/
function mint(address _account, uint256 _quantity) external whenLockedOnlyLocker {
_mint(_account, _quantity);
}
/**
* PRIVELEGED MODULE FUNCTION. Decreases the "account" balance by the "quantity".
* _burn checks that the "account" already has the required "quantity".
*/
function burn(address _account, uint256 _quantity) external whenLockedOnlyLocker {
_burn(_account, _quantity);
}
/**
* PRIVELEGED MODULE FUNCTION. When a BasketToken is locked, only the locker can call privileged functions.
*/
function lock() external {
require(!isLocked, "Must not be locked");
locker = msg.sender;
isLocked = true;
}
/**
* PRIVELEGED MODULE FUNCTION. Unlocks the SetToken and clears the locker
*/
function unlock() external {
require(isLocked, "Must be locked");
require(locker == msg.sender, "Must be locker");
delete locker;
isLocked = false;
}
/* ============ External Getter Functions ============ */
function getComponents() external view returns(address[] memory) {
return components;
}
function getDefaultPositionRealUnit(address _component) public view returns(int256) {
return _convertVirtualToRealUnit(_defaultPositionVirtualUnit(_component));
}
function getExternalPositionRealUnit(address _component, address _positionModule) public view returns(int256) {
return _convertVirtualToRealUnit(_externalPositionVirtualUnit(_component, _positionModule));
}
function getExternalPositionModules(address _component) external view returns(address[] memory) {
return _externalPositionModules(_component);
}
function getExternalPositionData(address _component,address _positionModule) external view returns(bytes memory) {
return _externalPositionData(_component, _positionModule);
}
function getModules() external view returns (address[] memory) {
return modules;
}
function isExternalPositionModule(address _component, address _module) public view returns(bool) {
return _externalPositionModules(_component).contains(_module);
}
function getPositions() external view returns (IBasketToken.Position[] memory) {
IBasketToken.Position[] memory positions = new IBasketToken.Position[](_getPositionCount());
uint256 positionCount = 0;
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
// A default position exists if the default virtual unit is > 0
if (_defaultPositionVirtualUnit(component) > 0) {
positions[positionCount] = IBasketToken.Position({
component: component,
module: address(0),
unit: getDefaultPositionRealUnit(component),
positionState: DEFAULT,
data: ""
});
positionCount++;
}
address[] memory externalModules = _externalPositionModules(component);
for (uint256 j = 0; j < externalModules.length; j++) {
address currentModule = externalModules[j];
positions[positionCount] = IBasketToken.Position({
component: component,
module: currentModule,
unit: getExternalPositionRealUnit(component, currentModule),
positionState: EXTERNAL,
data: _externalPositionData(component, currentModule)
});
positionCount++;
}
}
return positions;
}
/**
* Returns the total Real Units for a given component, summing the default and external position units.
*/
function getTotalComponentRealUnits(address _component) external view returns(int256) {
int256 totalUnits = getDefaultPositionRealUnit(_component);
address[] memory externalModules = _externalPositionModules(_component);
for (uint256 i = 0; i < externalModules.length; i++) {
// We will perform the summation no matter what, as an external position virtual unit can be negative
totalUnits = totalUnits.add(getExternalPositionRealUnit(_component, externalModules[i]));
}
return totalUnits;
}
receive() external payable {} // solium-disable-line quotes
/* ============ Internal Functions ============ */
function _defaultPositionVirtualUnit(address _component) internal view returns(int256) {
return componentPositions[_component].virtualUnit;
}
function _externalPositionModules(address _component) internal view returns(address[] memory) {
return componentPositions[_component].externalPositionModules;
}
function _externalPositionVirtualUnit(address _component, address _module) internal view returns(int256) {
return componentPositions[_component].externalPositions[_module].virtualUnit;
}
function _externalPositionData(address _component, address _module) internal view returns(bytes memory) {
return componentPositions[_component].externalPositions[_module].data;
}
/**
* Takes a real unit and divides by the position multiplier to return the virtual unit. Negative units will
* be rounded away from 0 so no need to check that unit will be rounded down to 0 in conversion.
*/
function _convertRealToVirtualUnit(int256 _realUnit) internal view returns(int256) {
int256 virtualUnit = _realUnit.conservativePreciseDiv(positionMultiplier);
// This check ensures that the virtual unit does not return a result that has rounded down to 0
if (_realUnit > 0 && virtualUnit == 0) {
revert("Real to Virtual unit conversion invalid");
}
// This check ensures that when converting back to realUnits the unit won't be rounded down to 0
if (_realUnit > 0 && _convertVirtualToRealUnit(virtualUnit) == 0) {
revert("Virtual to Real unit conversion invalid");
}
return virtualUnit;
}
/**
* Takes a virtual unit and multiplies by the position multiplier to return the real unit
*/
function _convertVirtualToRealUnit(int256 _virtualUnit) internal view returns(int256) {
return _virtualUnit.conservativePreciseMul(positionMultiplier);
}
/**
* To prevent virtual to real unit conversion issues (where real unit may be 0), the
* product of the positionMultiplier and the lowest absolute virtualUnit value (across default and
* external positions) must be greater than 0.
*/
function _validateNewMultiplier(int256 _newMultiplier) internal view {
int256 minVirtualUnit = _getPositionsAbsMinimumVirtualUnit();
require(minVirtualUnit.conservativePreciseMul(_newMultiplier) > 0, "New multiplier too small");
}
/**
* Loops through all of the positions and returns the smallest absolute value of
* the virtualUnit.
*
* @return Min virtual unit across positions denominated as int256
*/
function _getPositionsAbsMinimumVirtualUnit() internal view returns(int256) {
// Additional assignment happens in the loop below
uint256 minimumUnit = uint256(-1);
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
// A default position exists if the default virtual unit is > 0
uint256 defaultUnit = _defaultPositionVirtualUnit(component).toUint256();
if (defaultUnit > 0 && defaultUnit < minimumUnit) {
minimumUnit = defaultUnit;
}
address[] memory externalModules = _externalPositionModules(component);
for (uint256 j = 0; j < externalModules.length; j++) {
address currentModule = externalModules[j];
uint256 virtualUnit = _absoluteValue(
_externalPositionVirtualUnit(component, currentModule)
);
if (virtualUnit > 0 && virtualUnit < minimumUnit) {
minimumUnit = virtualUnit;
}
}
}
return minimumUnit.toInt256();
}
/**
* Gets the total number of positions, defined as the following:
* - Each component has a default position if its virtual unit is > 0
* - Each component's external positions module is counted as a position
*/
function _getPositionCount() internal view returns (uint256) {
uint256 positionCount;
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
// Increment the position count if the default position is > 0
if (_defaultPositionVirtualUnit(component) > 0) {
positionCount++;
}
// Increment the position count by each external position module
address[] memory externalModules = _externalPositionModules(component);
if (externalModules.length > 0) {
positionCount = positionCount.add(externalModules.length);
}
}
return positionCount;
}
/**
* Returns the absolute value of the signed integer value
* @param _a Signed interger value
* @return Returns the absolute value in uint256
*/
function _absoluteValue(int256 _a) internal pure returns(uint256) {
return _a >= 0 ? _a.toUint256() : (-_a).toUint256();
}
function _validateWhenLockedOnlyLocker() internal view {
if (isLocked) {
require(msg.sender == locker, "When locked, only the locker can call");
}
}
} | PRIVELEGED MODULE FUNCTION. Low level function that allows a module to make an arbitrary function call to any contract. _target Address of the smart contract to call _value Quantity of Ether to provide the call (typically 0) _data Encoded function selector and arguments return _returnValue Bytes encoded return value/ | function invoke(
address _target,
uint256 _value,
bytes calldata _data
)
external
whenLockedOnlyLocker
returns (bytes memory _returnValue)
{
_returnValue = _target.functionCallWithValue(_data, _value);
emit Invoked(_target, _value, _data, _returnValue);
return _returnValue;
}
| 5,445,160 |
pragma solidity 0.4.23;
/**
* Helios token http://heliosprotocol.io
*
*/
/**
* @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) {
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;
}
}
/**
* @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;
address public newOwnerTemp;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
newOwnerTemp = newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwnerTemp);
emit OwnershipTransferred(owner, newOwnerTemp);
owner = newOwnerTemp;
newOwnerTemp = address(0x0);
}
}
/**
* @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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract HeliosToken is StandardToken, Ownable {
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customize the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public constant name = "Helios Token";
string public constant symbol = "HLS";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 300000000 * (10 ** uint256(decimals));
uint256 public constant YEAR_TWO_SUPPLY = 30000000 * (10 ** uint256(decimals));
uint256 public constant YEAR_THREE_SUPPLY = 20000000 * (10 ** uint256(decimals));
bool public yearTwoClaimed;
bool public yearThreeClaimed;
//March 1, 2018
uint256 public startTime = 1519862400;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
yearTwoClaimed = false;
yearThreeClaimed = false;
totalSupply_ = INITIAL_SUPPLY + YEAR_TWO_SUPPLY + YEAR_THREE_SUPPLY;
//send 1st year team tokens, exchange tokens, incubator tokens
balances[owner] = INITIAL_SUPPLY;
emit Transfer(0x0, owner, INITIAL_SUPPLY);
}
// ------------------------------------------------------------------------
// Team can claim their tokens after lock up period
// ------------------------------------------------------------------------
function teamClaim(uint256 year) public onlyOwner returns (bool success) {
if(year == 2)
{
require (block.timestamp > (startTime + 31536000) && yearTwoClaimed == false);
balances[owner] = balances[owner].add(YEAR_TWO_SUPPLY);
emit Transfer(0x0, owner, YEAR_TWO_SUPPLY);
yearTwoClaimed = true;
}
if(year == 3)
{
require (block.timestamp > (startTime + 63072000) && yearThreeClaimed == false);
balances[owner] = balances[owner].add(YEAR_THREE_SUPPLY);
emit Transfer(0x0, owner, YEAR_THREE_SUPPLY);
yearThreeClaimed = true;
}
return true;
}
// do not allow deposits
function() public{
revert();
}
} | Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./ | function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
newOwnerTemp = newOwner;
}
| 1,368,259 |
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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;
import "./errors/LibBytesRichErrorsV06.sol";
import "./errors/LibRichErrorsV06.sol";
library LibBytesV06 {
using LibBytesV06 for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// When `from == 0`, the original array will match the slice.
/// In other cases its state will be corrupted.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return equal True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return result bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return result uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return result bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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;
library LibBytesRichErrorsV06 {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @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;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: 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;
}
}
pragma solidity =0.6.6;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "./libraries/TransferHelper.sol";
import "./libraries/PancakeLibrary.sol";
import "./interfaces/IReferralRegistry.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IZerox.sol";
contract FloozMultichainRouter is Ownable, Pausable, ReentrancyGuard {
using SafeMath for uint256;
using LibBytesV06 for bytes;
event SwapFeeUpdated(uint16 swapFee);
event ReferralRegistryUpdated(address referralRegistry);
event ReferralRewardRateUpdated(uint16 referralRewardRate);
event ReferralsActivatedUpdated(bool activated);
event FeeReceiverUpdated(address payable feeReceiver);
event CustomReferralRewardRateUpdated(address indexed account, uint16 referralRate);
event ReferralRewardPaid(address from, address indexed to, address tokenOut, address tokenReward, uint256 amount);
event ForkCreated(address factory);
event ForkUpdated(address factory);
struct SwapData {
address fork;
address referee;
bool fee;
}
// Denominator of fee
uint256 public constant FEE_DENOMINATOR = 10000;
// Numerator of fee
uint16 public swapFee;
// address of WETH
address public immutable WETH;
// address of zeroEx proxy contract to forward swaps
address payable public immutable zeroEx;
// address of referral registry that stores referral anchors
IReferralRegistry public referralRegistry;
// address that receives protocol fees
address payable public feeReceiver;
// percentage of fees that will be paid as rewards
uint16 public referralRewardRate;
// stores if the referral system is turned on or off
bool public referralsActivated;
// stores individual referral rates
mapping(address => uint16) public customReferralRewardRate;
// stores uniswap forks status, index is the factory address
mapping(address => bool) public forkActivated;
// stores uniswap forks initCodes, index is the factory address
mapping(address => bytes) public forkInitCode;
/// @dev construct this contract
/// @param _WETH address of WETH.
/// @param _swapFee nominator for swapFee. Denominator = 10000
/// @param _referralRewardRate percentage of swapFee that are paid out as rewards
/// @param _feeReceiver address that receives protocol fees
/// @param _referralRegistry address of referral registry that stores referral anchors
/// @param _zeroEx address of zeroX proxy contract to forward swaps
constructor(
address _WETH,
uint16 _swapFee,
uint16 _referralRewardRate,
address payable _feeReceiver,
IReferralRegistry _referralRegistry,
address payable _zeroEx
) public {
WETH = _WETH;
swapFee = _swapFee;
referralRewardRate = _referralRewardRate;
feeReceiver = _feeReceiver;
referralRegistry = _referralRegistry;
zeroEx = _zeroEx;
referralsActivated = true;
}
/// @dev execute swap directly on Uniswap/Pancake & simular forks
/// @param swapData stores the swapData information
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @return amounts
function swapExactETHForTokens(
SwapData calldata swapData,
uint256 amountOutMin,
address[] calldata path
)
external
payable
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
msg.value,
referee,
false
);
amounts = _getAmountsOut(swapData.fork, swapAmount, path);
require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), amounts[0]));
_swap(swapData.fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountIn amount of tokensIn
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
function swapExactTokensForETHSupportingFeeOnTransferTokens(
SwapData calldata swapData,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) {
require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amountIn);
_swapSupportingFeeOnTransferTokens(swapData.fork, path, address(this));
uint256 amountOut = IERC20(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(amountOut);
(uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amountOut,
referee,
false
);
require(amountWithdraw >= amountOutMin, "FloozRouter: LOW_SLIPPAGE");
TransferHelper.safeTransferETH(msg.sender, amountWithdraw);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountIn amount if tokens In
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @return amounts
function swapExactTokensForTokens(
SwapData calldata swapData,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
)
external
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
address referee = _getReferee(swapData.referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amountIn,
referee,
false
);
amounts = _getAmountsOut(swapData.fork, swapAmount, path);
require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), swapAmount);
_swap(swapData.fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountIn amount if tokens In
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @return amounts
function swapExactTokensForETH(
SwapData calldata swapData,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
)
external
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
amounts = _getAmountsOut(swapData.fork, amountIn, path);
(uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amounts[amounts.length - 1],
referee,
false
);
require(amountWithdraw >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]);
_swap(swapData.fork, amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(msg.sender, amountWithdraw);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountOut expected amount of tokens out
/// @param path Sell path.
/// @return amounts
function swapETHForExactTokens(
SwapData calldata swapData,
uint256 amountOut,
address[] calldata path
)
external
payable
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
amounts = _getAmountsIn(swapData.fork, amountOut, path);
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amounts[0],
referee,
true
);
require(amounts[0].add(feeAmount).add(referralReward) <= msg.value, "FloozRouter: EXCESSIVE_INPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), amounts[0]));
_swap(swapData.fork, amounts, path, msg.sender);
// refund dust eth, if any
if (msg.value > amounts[0].add(feeAmount).add(referralReward))
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0].add(feeAmount).add(referralReward));
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountIn amount if tokens In
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
SwapData calldata swapData,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) {
address referee = _getReferee(swapData.referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amountIn,
referee,
false
);
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), swapAmount);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender);
_swapSupportingFeeOnTransferTokens(swapData.fork, path, msg.sender);
require(
IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin,
"FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountOut expected tokens to receive
/// @param amountInMax maximum tokens to send
/// @param path Sell path.
/// @return amounts
function swapTokensForExactTokens(
SwapData calldata swapData,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path
)
external
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
address referee = _getReferee(swapData.referee);
amounts = _getAmountsIn(swapData.fork, amountOut, path);
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amounts[0],
referee,
true
);
require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]);
_swap(swapData.fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountOut expected tokens to receive
/// @param amountInMax maximum tokens to send
/// @param path Sell path.
/// @return amounts
function swapTokensForExactETH(
SwapData calldata swapData,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path
)
external
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amountOut,
referee,
true
);
amounts = _getAmountsIn(swapData.fork, amountOut.add(feeAmount).add(referralReward), path);
require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]);
_swap(swapData.fork, amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(msg.sender, amountOut);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountOutMin minimum expected tokens to receive
/// @param path Sell path.
function swapExactETHForTokensSupportingFeeOnTransferTokens(
SwapData calldata swapData,
uint256 amountOutMin,
address[] calldata path
) external payable whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) {
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
msg.value,
referee,
false
);
IWETH(WETH).deposit{value: swapAmount}();
assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), swapAmount));
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender);
_swapSupportingFeeOnTransferTokens(swapData.fork, path, msg.sender);
require(
IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin,
"FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev returns the referee for a given address, if new, registers referee
/// @param referee the address of the referee for msg.sender
/// @return referee address from referral registry
function _getReferee(address referee) internal returns (address) {
address sender = msg.sender;
if (!referralRegistry.hasUserReferee(sender) && referee != address(0)) {
referralRegistry.createReferralAnchor(sender, referee);
}
return referralRegistry.getUserReferee(sender);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(
address fork,
uint256[] memory amounts,
address[] memory path,
address _to
) internal {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = PancakeLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to;
IPancakePair(_pairFor(fork, input, output)).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(
address fork,
address[] memory path,
address _to
) internal {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = PancakeLibrary.sortTokens(input, output);
IPancakePair pair = IPancakePair(_pairFor(fork, input, output));
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) = input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = _getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
/// @dev Fallback function to execute swaps directly on 0x for users that don't pay a fee
/// @dev params as of API documentation from 0x API (https://0x.org/docs/api#response-1)
fallback() external payable {
bytes4 selector = msg.data.readBytes4(0);
address impl = IZerox(zeroEx).getFunctionImplementation(selector);
require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION");
(bool success, ) = impl.delegatecall(msg.data);
require(success, "FloozRouter: REVERTED");
}
/// @dev Executes a swap on 0x API
/// @param data calldata expected by data field on 0x API (https://0x.org/docs/api#response-1)
/// @param tokenOut the address of currency to sell - 0x address for ETH
/// @param tokenIn the address of currency to buy - 0x address for ETH
/// @param referee address of referee for msg.sender, 0x adress if none
/// @param fee boolean if fee should be applied or not
function executeZeroExSwap(
bytes calldata data,
address tokenOut,
address tokenIn,
address referee,
bool fee
) external payable nonReentrant whenNotPaused isValidReferee(referee) {
referee = _getReferee(referee);
bytes4 selector = data.readBytes4(0);
address impl = IZerox(zeroEx).getFunctionImplementation(selector);
require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION");
if (!fee) {
(bool success, ) = impl.delegatecall(data);
require(success, "FloozRouter: REVERTED");
} else {
// if ETH in execute trade as router & distribute funds & fees
if (msg.value > 0) {
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
fee,
msg.value,
referee,
false
);
(bool success, ) = impl.call{value: swapAmount}(data);
require(success, "FloozRouter: REVERTED");
TransferHelper.safeTransfer(tokenIn, msg.sender, IERC20(tokenIn).balanceOf(address(this)));
_withdrawFeesAndRewards(address(0), tokenIn, referee, feeAmount, referralReward);
} else {
uint256 balanceBefore = IERC20(tokenOut).balanceOf(msg.sender);
(bool success, ) = impl.delegatecall(data);
require(success, "FloozRouter: REVERTED");
uint256 balanceAfter = IERC20(tokenOut).balanceOf(msg.sender);
require(balanceBefore > balanceAfter, "INVALID_TOKEN");
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
fee,
balanceBefore.sub(balanceAfter),
referee,
true
);
_withdrawFeesAndRewards(tokenOut, tokenIn, referee, feeAmount, referralReward);
}
}
}
/// @dev calculates swap, fee & reward amounts
/// @param fee boolean if fee will be applied or not
/// @param amount total amount of tokens
/// @param referee the address of the referee for msg.sender
function _calculateFeesAndRewards(
bool fee,
uint256 amount,
address referee,
bool additiveFee
)
internal
view
returns (
uint256 swapAmount,
uint256 feeAmount,
uint256 referralReward
)
{
// no fees for users above threshold
if (!fee) {
swapAmount = amount;
} else {
if (additiveFee) {
swapAmount = amount;
feeAmount = swapAmount.mul(FEE_DENOMINATOR).div(FEE_DENOMINATOR.sub(swapFee)).sub(amount);
} else {
feeAmount = amount.mul(swapFee).div(FEE_DENOMINATOR);
swapAmount = amount.sub(feeAmount);
}
// calculate referral rates, if referee is not 0x
if (referee != address(0) && referralsActivated) {
uint16 referralRate = customReferralRewardRate[referee] > 0
? customReferralRewardRate[referee]
: referralRewardRate;
referralReward = feeAmount.mul(referralRate).div(FEE_DENOMINATOR);
feeAmount = feeAmount.sub(referralReward);
} else {
referralReward = 0;
}
}
}
/// @dev lets the admin register an Uniswap style fork
function registerFork(address _factory, bytes calldata _initCode) external onlyOwner {
require(!forkActivated[_factory], "FloozRouter: ACTIVE_FORK");
forkActivated[_factory] = true;
forkInitCode[_factory] = _initCode;
emit ForkCreated(_factory);
}
/// @dev lets the admin update an Uniswap style fork
function updateFork(
address _factory,
bytes calldata _initCode,
bool _activated
) external onlyOwner {
forkActivated[_factory] = _activated;
forkInitCode[_factory] = _initCode;
emit ForkUpdated(_factory);
}
/// @dev lets the admin update the swapFee nominator
function updateSwapFee(uint16 newSwapFee) external onlyOwner {
swapFee = newSwapFee;
emit SwapFeeUpdated(newSwapFee);
}
/// @dev lets the admin update the referral reward rate
function updateReferralRewardRate(uint16 newReferralRewardRate) external onlyOwner {
require(newReferralRewardRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE");
referralRewardRate = newReferralRewardRate;
emit ReferralRewardRateUpdated(newReferralRewardRate);
}
/// @dev lets the admin update which address receives the protocol fees
function updateFeeReceiver(address payable newFeeReceiver) external onlyOwner {
feeReceiver = newFeeReceiver;
emit FeeReceiverUpdated(newFeeReceiver);
}
/// @dev lets the admin update the status of the referral system
function updateReferralsActivated(bool newReferralsActivated) external onlyOwner {
referralsActivated = newReferralsActivated;
emit ReferralsActivatedUpdated(newReferralsActivated);
}
/// @dev lets the admin set a new referral registry
function updateReferralRegistry(address newReferralRegistry) external onlyOwner {
referralRegistry = IReferralRegistry(newReferralRegistry);
emit ReferralRegistryUpdated(newReferralRegistry);
}
/// @dev lets the admin set a custom referral rate
function updateCustomReferralRewardRate(address account, uint16 referralRate) external onlyOwner returns (uint256) {
require(referralRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE");
customReferralRewardRate[account] = referralRate;
emit CustomReferralRewardRateUpdated(account, referralRate);
}
/// @dev returns the referee for a given user - 0x address if none
function getUserReferee(address user) external view returns (address) {
return referralRegistry.getUserReferee(user);
}
/// @dev returns if the given user has been referred or not
function hasUserReferee(address user) external view returns (bool) {
return referralRegistry.hasUserReferee(user);
}
/// @dev lets the admin withdraw ETH from the contract.
function withdrawETH(address payable to, uint256 amount) external onlyOwner {
TransferHelper.safeTransferETH(to, amount);
}
/// @dev lets the admin withdraw ERC20s from the contract.
function withdrawERC20Token(
address token,
address to,
uint256 amount
) external onlyOwner {
TransferHelper.safeTransfer(token, to, amount);
}
/// @dev distributes fees & referral rewards to users
function _withdrawFeesAndRewards(
address tokenReward,
address tokenOut,
address referee,
uint256 feeAmount,
uint256 referralReward
) internal {
if (tokenReward == address(0)) {
TransferHelper.safeTransferETH(feeReceiver, feeAmount);
if (referralReward > 0) {
TransferHelper.safeTransferETH(referee, referralReward);
emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward);
}
} else {
TransferHelper.safeTransferFrom(tokenReward, msg.sender, feeReceiver, feeAmount);
if (referralReward > 0) {
TransferHelper.safeTransferFrom(tokenReward, msg.sender, referee, referralReward);
emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward);
}
}
}
/// @dev given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function _getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "FloozRouter: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul((9970));
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(10000).add(amountInWithFee);
amountOut = numerator / denominator;
}
/// @dev given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function _getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY");
uint256 numerator = reserveIn.mul(amountOut).mul(10000);
uint256 denominator = reserveOut.sub(amountOut).mul(9970);
amountIn = (numerator / denominator).add(1);
}
/// @dev performs chained getAmountOut calculations on any number of pairs
function _getAmountsOut(
address fork,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "FloozRouter: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = _getReserves(fork, path[i], path[i + 1]);
amounts[i + 1] = _getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
/// @dev performs chained getAmountIn calculations on any number of pairs
function _getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "FloozRouter: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = _getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
/// @dev fetches and sorts the reserves for a pair
function _getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = PancakeLibrary.sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IPancakePair(_pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
/// @dev calculates the CREATE2 address for a pair without making any external calls
function _pairFor(
address factory,
address tokenA,
address tokenB
) internal view returns (address pair) {
(address token0, address token1) = PancakeLibrary.sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
forkInitCode[factory] // init code hash
)
)
)
);
}
/// @dev lets the admin pause this contract
function pause() external onlyOwner {
_pause();
}
/// @dev lets the admin unpause this contract
function unpause() external onlyOwner {
_unpause();
}
/// @dev allows to receive ETH on the contract
receive() external payable {}
modifier isValidFork(address factory) {
require(forkActivated[factory], "FloozRouter: INVALID_FACTORY");
_;
}
modifier isValidReferee(address referee) {
require(msg.sender != referee, "FloozRouter: SELF_REFERRAL");
_;
}
}
pragma solidity >=0.5.0;
interface IReferralRegistry {
function getUserReferee(address _user) external view returns (address);
function hasUserReferee(address _user) external view returns (bool);
function createReferralAnchor(address _user, address _referee) external;
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
function approve(address _spender, uint256 _amount) external returns (bool);
function balanceOf(address _account) external view returns (uint256);
}
pragma solidity ^0.6.5;
interface IZerox {
function getFunctionImplementation(bytes4 selector) external returns (address payable);
}
pragma solidity =0.6.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface IPancakePair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
library PancakeLibrary {
using SafeMath for uint256;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "PancakeLibrary: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "PancakeLibrary: ZERO_ADDRESS");
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "PancakeLibrary: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "PancakeLibrary: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
}
pragma solidity =0.6.6;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED");
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED");
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED");
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
} | Executes a swap on 0x API data calldata expected by data field on 0x API (https://0x.org/docs/apiresponse-1) tokenOut the address of currency to sell - 0x address for ETH tokenIn the address of currency to buy - 0x address for ETH referee address of referee for msg.sender, 0x adress if none fee boolean if fee should be applied or not if ETH in execute trade as router & distribute funds & fees | function executeZeroExSwap(
bytes calldata data,
address tokenOut,
address tokenIn,
address referee,
bool fee
) external payable nonReentrant whenNotPaused isValidReferee(referee) {
referee = _getReferee(referee);
bytes4 selector = data.readBytes4(0);
address impl = IZerox(zeroEx).getFunctionImplementation(selector);
require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION");
if (!fee) {
(bool success, ) = impl.delegatecall(data);
require(success, "FloozRouter: REVERTED");
if (msg.value > 0) {
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
fee,
msg.value,
referee,
false
);
require(success, "FloozRouter: REVERTED");
TransferHelper.safeTransfer(tokenIn, msg.sender, IERC20(tokenIn).balanceOf(address(this)));
_withdrawFeesAndRewards(address(0), tokenIn, referee, feeAmount, referralReward);
uint256 balanceBefore = IERC20(tokenOut).balanceOf(msg.sender);
(bool success, ) = impl.delegatecall(data);
require(success, "FloozRouter: REVERTED");
uint256 balanceAfter = IERC20(tokenOut).balanceOf(msg.sender);
require(balanceBefore > balanceAfter, "INVALID_TOKEN");
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
fee,
balanceBefore.sub(balanceAfter),
referee,
true
);
_withdrawFeesAndRewards(tokenOut, tokenIn, referee, feeAmount, referralReward);
}
}
}
| 10,222,053 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IWETH.sol';
import '@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol';
import './interfaces/IJusDeFi.sol';
import './interfaces/IStakingPool.sol';
import './interfaces/IJDFIStakingPool.sol';
import './FeePool.sol';
import './DevStakingPool.sol';
import './JDFIStakingPool.sol';
import './UNIV2StakingPool.sol';
contract JusDeFi is IJusDeFi, ERC20 {
using FixedPoint for FixedPoint.uq112x112;
using FixedPoint for FixedPoint.uq144x112;
using SafeMath for uint;
// _weth and _uniswapPair cannot be immutable because they are referenced in _beforeTokenTransfer
address private _weth;
address private immutable _uniswapRouter;
address public _uniswapPair;
address payable override public _feePool;
address public immutable _devStakingPool;
address public immutable _jdfiStakingPool;
address public immutable _univ2StakingPool;
uint private constant LIQUIDITY_EVENT_PERIOD = 3 days;
bool public _liquidityEventOpen;
uint public immutable _liquidityEventClosedAt;
mapping (address => bool) private _implicitApprovalWhitelist;
uint private constant RESERVE_TEAM = 1980 ether;
uint private constant RESERVE_JUSTICE = 10020 ether;
uint private constant RESERVE_LIQUIDITY_EVENT = 10000 ether;
uint private constant REWARDS_SEED = 2000 ether;
uint private constant JDFI_PER_ETH = 4;
uint private constant ORACLE_PERIOD = 5 minutes;
FixedPoint.uq112x112 private _priceAverage;
uint private _priceCumulativeLast;
uint32 private _blockTimestampLast;
constructor (
address airdropToken,
address uniswapRouter
)
ERC20('JusDeFi', 'JDFI')
{
address weth = IUniswapV2Router02(uniswapRouter).WETH();
_weth = weth;
address uniswapPair = IUniswapV2Factory(
IUniswapV2Router02(uniswapRouter).factory()
).createPair(weth, address(this));
_uniswapRouter = uniswapRouter;
_uniswapPair = uniswapPair;
address devStakingPool = address(new DevStakingPool(weth));
_devStakingPool = devStakingPool;
address jdfiStakingPool = address(new JDFIStakingPool(airdropToken, RESERVE_LIQUIDITY_EVENT, weth, devStakingPool));
_jdfiStakingPool = jdfiStakingPool;
address univ2StakingPool = address(new UNIV2StakingPool(uniswapPair, uniswapRouter));
_univ2StakingPool = univ2StakingPool;
// mint staked JDFI after-the-fact to match minted JDFI/S
_mint(jdfiStakingPool, RESERVE_LIQUIDITY_EVENT);
// mint JDFI for conversion to locked JDFI/S
_mint(airdropToken, RESERVE_JUSTICE);
// mint team JDFI
_mint(msg.sender, RESERVE_TEAM);
// transfer all minted JDFI/E to sender
IStakingPool(devStakingPool).transfer(msg.sender, IStakingPool(devStakingPool).balanceOf(address(this)));
_liquidityEventClosedAt = block.timestamp + LIQUIDITY_EVENT_PERIOD;
_liquidityEventOpen = true;
// enable trusted addresses to transfer tokens without approval
_implicitApprovalWhitelist[jdfiStakingPool] = true;
_implicitApprovalWhitelist[univ2StakingPool] = true;
_implicitApprovalWhitelist[uniswapRouter] = true;
}
/**
* @notice get average JDFI price over the last ORACLE_PERIOD
* @dev adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol
* @param amount quantity of ETH used for purchase
* @return uint quantity of JDFI purchased, or zero if ORACLE_PERIOD has passed since las tupdate
*/
function consult (uint amount) override external view returns (uint) {
if (block.timestamp - uint(_blockTimestampLast) > ORACLE_PERIOD) {
return 0;
} else {
return _priceAverage.mul(amount).decode144();
}
}
/**
* @notice OpenZeppelin ERC20#transferFrom: enable transfers by staking pools without allowance
* @param from sender
* @param to recipient
* @param amount quantity transferred
*/
function transferFrom (address from, address to, uint amount) override(IERC20, ERC20) public returns (bool) {
if (_implicitApprovalWhitelist[msg.sender]) {
_transfer(from, to, amount);
return true;
} else {
return super.transferFrom(from, to, amount);
}
}
/**
* @notice burn tokens held by sender
* @param amount quantity of tokens to burn
*/
function burn (uint amount) override external {
_burn(msg.sender, amount);
}
/**
* @notice transfer tokens, deducting fee
* @param account recipient of transfer
* @param amount quantity of tokens to transfer, before deduction
*/
function burnAndTransfer (address account, uint amount) override external {
uint withheld = FeePool(_feePool).calculateWithholding(amount);
_transfer(msg.sender, _feePool, withheld);
_burn(_feePool, withheld / 2);
_transfer(msg.sender, account, amount - withheld);
}
/**
* @notice deposit ETH to receive JDFI/S at rate of 1:4
*/
function liquidityEventDeposit () external payable {
require(_liquidityEventOpen, 'JusDeFi: liquidity event has closed');
try IStakingPool(_jdfiStakingPool).transfer(msg.sender, msg.value * JDFI_PER_ETH) returns (bool) {} catch {
revert('JusDeFi: deposit amount surpasses available supply');
}
}
/**
* @notice close liquidity event, add Uniswap liquidity, burn undistributed JDFI
*/
function liquidityEventClose () external {
require(block.timestamp >= _liquidityEventClosedAt, 'JusDeFi: liquidity event still in progress');
require(_liquidityEventOpen, 'JusDeFi: liquidity event has already ended');
_liquidityEventOpen = false;
uint remaining = IStakingPool(_jdfiStakingPool).balanceOf(address(this));
uint distributed = RESERVE_LIQUIDITY_EVENT - remaining;
// require minimum deposit to avoid nonspecific Uniswap error: ds-math-sub-underflow
require(distributed >= 1 ether, 'JusDeFi: insufficient liquidity added');
// prepare Uniswap for minting my FeePool
IUniswapV2Pair pair = IUniswapV2Pair(_uniswapPair);
address weth = _weth;
IWETH(weth).deposit{ value: distributed / JDFI_PER_ETH }();
IWETH(weth).transfer(address(pair), distributed / JDFI_PER_ETH);
_mint(address(pair), distributed);
_feePool = payable(new FeePool(
_jdfiStakingPool,
_univ2StakingPool,
_uniswapRouter,
_uniswapPair
));
// UNI-V2 has been minted, so price is available
_priceCumulativeLast = address(this) > _weth ? pair.price0CumulativeLast() : pair.price1CumulativeLast();
_blockTimestampLast = UniswapV2OracleLibrary.currentBlockTimestamp();
// unstake and burn (including fee accrued on unstaking)
IJDFIStakingPool(_jdfiStakingPool).unstake(remaining);
_burn(address(this), balanceOf(address(this)));
_burn(_feePool, balanceOf(_feePool));
// seed staking pools
_mint(_feePool, REWARDS_SEED);
}
/**
* @notice OpenZeppelin ERC20 hook: prevent transfers during liquidity event, update oracle price
* @dev adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol
* @param from sender
* @param to recipient
* @param amount quantity transferred
*/
function _beforeTokenTransfer (address from, address to, uint amount) override internal {
require(!_liquidityEventOpen, 'JusDeFi: liquidity event still in progress');
super._beforeTokenTransfer(from, to, amount);
address pair = _uniswapPair;
if (from == pair || (to == pair && from != address(0))) {
(
uint price0Cumulative,
uint price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
uint32 timeElapsed = blockTimestamp - _blockTimestampLast; // overflow is desired
// only store the ETH -> JDFI price
uint priceCumulative = address(this) > _weth ? price0Cumulative : price1Cumulative;
if (timeElapsed >= ORACLE_PERIOD) {
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
_priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - _priceCumulativeLast) / timeElapsed));
_priceCumulativeLast = priceCumulative;
_blockTimestampLast = blockTimestamp;
}
}
}
}
| transfer tokens, deducting fee account recipient of transfer amount quantity of tokens to transfer, before deduction/ | function burnAndTransfer (address account, uint amount) override external {
uint withheld = FeePool(_feePool).calculateWithholding(amount);
_transfer(msg.sender, _feePool, withheld);
_burn(_feePool, withheld / 2);
_transfer(msg.sender, account, amount - withheld);
}
| 1,037,054 |
./full_match/73799/0xf4F41dcBB159cc401BB60Ae328bbc4159c776CF6/sources/contracts/trove-factory.sol | returns fee from borrowing the amount/ | function getBorrowingFee(uint256 _amount) public view returns (uint256) {
return (_amount * BONQMath.min(MAX_BORROWING_RATE, (BORROWING_RATE + baseRate))) / DECIMAL_PRECISION;
}
| 16,363,595 |
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OWNERSHIPTRANSFERRED275(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED275(address(0), _owner);
}
function OWNER625() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER263() { //inject NONSTANDARD NAMING
require(ISOWNER221());
_;
}
function ISOWNER221() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP563() public ONLYOWNER263 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED275(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP811(address newOwner) public ONLYOWNER263 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP827(newOwner);
}
function _TRANSFEROWNERSHIP827(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED275(_owner, newOwner);
_owner = newOwner;
}
}
contract Secondary {
address private _primary;
event PRIMARYTRANSFERRED466( //inject NONSTANDARD NAMING
address recipient
);
constructor () internal {
_primary = msg.sender;
emit PRIMARYTRANSFERRED466(_primary);
}
modifier ONLYPRIMARY116() { //inject NONSTANDARD NAMING
require(msg.sender == _primary);
_;
}
function PRIMARY581() public view returns (address) { //inject NONSTANDARD NAMING
return _primary;
}
function TRANSFERPRIMARY630(address recipient) public ONLYPRIMARY116 { //inject NONSTANDARD NAMING
require(recipient != address(0));
_primary = recipient;
emit PRIMARYTRANSFERRED466(_primary);
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol
interface IERC20 {
function TRANSFER568(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE366(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM855(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY96() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF58(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE511(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER836(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL290(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
library SafeMath {
function MUL97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB631(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD445(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD309(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY96() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF58(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE511(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER568(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER261(msg.sender, to, value);
return true;
}
function APPROVE366(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE283(msg.sender, spender, value);
return true;
}
function TRANSFERFROM855(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER261(from, to, value);
_APPROVE283(from, msg.sender, _allowed[from][msg.sender].SUB631(value));
return true;
}
function INCREASEALLOWANCE464(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE283(msg.sender, spender, _allowed[msg.sender][spender].ADD445(addedValue));
return true;
}
function DECREASEALLOWANCE302(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE283(msg.sender, spender, _allowed[msg.sender][spender].SUB631(subtractedValue));
return true;
}
function _TRANSFER261(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB631(value);
_balances[to] = _balances[to].ADD445(value);
emit TRANSFER836(from, to, value);
}
function _MINT945(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD445(value);
_balances[account] = _balances[account].ADD445(value);
emit TRANSFER836(address(0), account, value);
}
function _BURN542(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB631(value);
_balances[account] = _balances[account].SUB631(value);
emit TRANSFER836(account, address(0), value);
}
function _APPROVE283(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit APPROVAL290(owner, spender, value);
}
function _BURNFROM236(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_BURN542(account, value);
_APPROVE283(account, msg.sender, _allowed[account][msg.sender].SUB631(value));
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Burnable.sol
contract ERC20Burnable is ERC20 {
function BURN435(uint256 value) public { //inject NONSTANDARD NAMING
_BURN542(msg.sender, value);
}
function BURNFROM369(address from, uint256 value) public { //inject NONSTANDARD NAMING
_BURNFROM236(from, value);
}
}
// File: node_modules\openzeppelin-solidity\contracts\access\Roles.sol
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function ADD445(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(account != address(0));
require(!HAS23(role, account));
role.bearer[account] = true;
}
function REMOVE600(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(account != address(0));
require(HAS23(role, account));
role.bearer[account] = false;
}
function HAS23(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING
require(account != address(0));
return role.bearer[account];
}
}
// File: node_modules\openzeppelin-solidity\contracts\access\roles\MinterRole.sol
contract MinterRole {
using Roles for Roles.Role;
event MINTERADDED570(address indexed account); //inject NONSTANDARD NAMING
event MINTERREMOVED239(address indexed account); //inject NONSTANDARD NAMING
Roles.Role private _minters;
constructor () internal {
_ADDMINTER827(msg.sender);
}
modifier ONLYMINTER291() { //inject NONSTANDARD NAMING
require(ISMINTER698(msg.sender));
_;
}
function ISMINTER698(address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _minters.HAS23(account);
}
function ADDMINTER239(address account) public ONLYMINTER291 { //inject NONSTANDARD NAMING
_ADDMINTER827(account);
}
function RENOUNCEMINTER237() public { //inject NONSTANDARD NAMING
_REMOVEMINTER650(msg.sender);
}
function _ADDMINTER827(address account) internal { //inject NONSTANDARD NAMING
_minters.ADD445(account);
emit MINTERADDED570(account);
}
function _REMOVEMINTER650(address account) internal { //inject NONSTANDARD NAMING
_minters.REMOVE600(account);
emit MINTERREMOVED239(account);
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Mintable.sol
contract ERC20Mintable is ERC20, MinterRole {
function MINT610(address to, uint256 value) public ONLYMINTER291 returns (bool) { //inject NONSTANDARD NAMING
_MINT945(to, value);
return true;
}
}
// File: contracts\ERC20Frozenable.sol
//truffle-flattener Token.sol
contract ERC20Frozenable is ERC20Burnable, ERC20Mintable, Ownable {
mapping (address => bool) private _frozenAccount;
event FROZENFUNDS807(address target, bool frozen); //inject NONSTANDARD NAMING
function FROZENACCOUNT782(address _address) public view returns(bool isFrozen) { //inject NONSTANDARD NAMING
return _frozenAccount[_address];
}
function FREEZEACCOUNT250(address target, bool freeze) public ONLYOWNER263 { //inject NONSTANDARD NAMING
require(_frozenAccount[target] != freeze, "Same as current");
_frozenAccount[target] = freeze;
emit FROZENFUNDS807(target, freeze);
}
function _TRANSFER261(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(!_frozenAccount[from], "error - frozen");
require(!_frozenAccount[to], "error - frozen");
super._TRANSFER261(from, to, value);
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Detailed.sol
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 NAME858() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL418() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS361() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
contract Escrow is Secondary {
using SafeMath for uint256;
event DEPOSITED6(address indexed payee, uint256 weiAmount); //inject NONSTANDARD NAMING
event WITHDRAWN702(address indexed payee, uint256 weiAmount); //inject NONSTANDARD NAMING
mapping(address => uint256) private _deposits;
function DEPOSITSOF491(address payee) public view returns (uint256) { //inject NONSTANDARD NAMING
return _deposits[payee];
}
function DEPOSIT494(address payee) public ONLYPRIMARY116 payable { //inject NONSTANDARD NAMING
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].ADD445(amount);
emit DEPOSITED6(payee, amount);
}
function WITHDRAW275(address payable payee) public ONLYPRIMARY116 { //inject NONSTANDARD NAMING
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.transfer(payment);
emit WITHDRAWN702(payee, payment);
}
}
contract PullPayment {
Escrow private _escrow;
constructor () internal {
_escrow = new Escrow();
}
function WITHDRAWPAYMENTS729(address payable payee) public { //inject NONSTANDARD NAMING
_escrow.WITHDRAW275(payee);
}
function PAYMENTS838(address dest) public view returns (uint256) { //inject NONSTANDARD NAMING
return _escrow.DEPOSITSOF491(dest);
}
function _ASYNCTRANSFER275(address dest, uint256 amount) internal { //inject NONSTANDARD NAMING
_escrow.DEPOSIT494.value(amount)(dest);
}
}
contract PaymentSplitter {
using SafeMath for uint256;
event PAYEEADDED416(address account, uint256 shares); //inject NONSTANDARD NAMING
event PAYMENTRELEASED38(address to, uint256 amount); //inject NONSTANDARD NAMING
event PAYMENTRECEIVED491(address from, uint256 amount); //inject NONSTANDARD NAMING
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
constructor (address[] memory payees, uint256[] memory shares) public payable {
require(payees.length == shares.length);
require(payees.length > 0);
for (uint256 i = 0; i < payees.length; i++) {
_ADDPAYEE628(payees[i], shares[i]);
}
}
function () external payable {
emit PAYMENTRECEIVED491(msg.sender, msg.value);
}
function TOTALSHARES81() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalShares;
}
function TOTALRELEASED129() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalReleased;
}
function SHARES670(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _shares[account];
}
function RELEASED874(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _released[account];
}
function PAYEE185(uint256 index) public view returns (address) { //inject NONSTANDARD NAMING
return _payees[index];
}
function RELEASE471(address payable account) public { //inject NONSTANDARD NAMING
require(_shares[account] > 0);
uint256 totalReceived = address(this).balance.ADD445(_totalReleased);
uint256 payment = totalReceived.MUL97(_shares[account]).DIV803(_totalShares).SUB631(_released[account]);
require(payment != 0);
_released[account] = _released[account].ADD445(payment);
_totalReleased = _totalReleased.ADD445(payment);
account.transfer(payment);
emit PAYMENTRELEASED38(account, payment);
}
function _ADDPAYEE628(address account, uint256 shares_) private { //inject NONSTANDARD NAMING
require(account != address(0));
require(shares_ > 0);
require(_shares[account] == 0);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares.ADD445(shares_);
emit PAYEEADDED416(account, shares_);
}
}
contract ConditionalEscrow is Escrow {
function WITHDRAWALALLOWED82(address payee) public view returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW275(address payable payee) public { //inject NONSTANDARD NAMING
require(WITHDRAWALALLOWED82(payee));
super.WITHDRAW275(payee);
}
}
contract RefundEscrow is ConditionalEscrow {
enum State { Active, Refunding, Closed }
event REFUNDSCLOSED652(); //inject NONSTANDARD NAMING
event REFUNDSENABLED266(); //inject NONSTANDARD NAMING
State private _state;
address payable private _beneficiary;
constructor (address payable beneficiary) public {
require(beneficiary != address(0));
_beneficiary = beneficiary;
_state = State.Active;
}
function STATE442() public view returns (State) { //inject NONSTANDARD NAMING
return _state;
}
function BENEFICIARY91() public view returns (address) { //inject NONSTANDARD NAMING
return _beneficiary;
}
function DEPOSIT494(address refundee) public payable { //inject NONSTANDARD NAMING
require(_state == State.Active);
super.DEPOSIT494(refundee);
}
function CLOSE124() public ONLYPRIMARY116 { //inject NONSTANDARD NAMING
require(_state == State.Active);
_state = State.Closed;
emit REFUNDSCLOSED652();
}
function ENABLEREFUNDS102() public ONLYPRIMARY116 { //inject NONSTANDARD NAMING
require(_state == State.Active);
_state = State.Refunding;
emit REFUNDSENABLED266();
}
function BENEFICIARYWITHDRAW365() public { //inject NONSTANDARD NAMING
require(_state == State.Closed);
_beneficiary.transfer(address(this).balance);
}
function WITHDRAWALALLOWED82(address) public view returns (bool) { //inject NONSTANDARD NAMING
return _state == State.Refunding;
}
}
// File: contracts\Token.sol
//truffle-flattener Token.sol
contract DeltaBlocks is ERC20Frozenable, ERC20Detailed {
constructor()
ERC20Detailed("Delta Blocks", "DTB", 18)
public {
uint256 supply = 10000000000;
uint256 initialSupply = supply * uint(10) ** DECIMALS361();
_MINT945(msg.sender, initialSupply);
}
} | inject NONSTANDARD NAMING | function WITHDRAWPAYMENTS729(address payable payee) public { | 7,302,980 |
//SPDX-License-Identifier: MIT"
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// This contract is designed to freeze an amount of ether within the contract until a release block.
// per amount frozen and per blocks held, an erc20 token will be granted to the recipient address
contract EtherFreeze is ERC20{
// Variable to hold amount of wei per ether
uint256 weiPerEther = 1000000000000000000;
// Initial supply of Frost token
uint256 initialSupply = 10**12;
// Multiplier of the reward function
uint rewardMultiplier = 100;
/*
*
*/
constructor() ERC20("Frost", "FRST") public {
_mint(address(this), initialSupply);
}
// The following will allow the tracking of balances of the unclaimed stake reward token in an erc20 token
mapping(address => accountInfo) public accounts;
/* Struct to consolidate account details
* rewardsAvailable: Rewards to be given upon withdrawal
* balance: balance of frozen ethereum
* blockDeposited: Record of block deposited
* blockAvailable: Record of block of release
*/
struct accountInfo{
uint256 rewardsAvailable;
uint256 balance;
uint256 blockDeposited;
uint256 blockAvailable;
}
// Deposit function
// Function that deposits the transacted ether into the hold
// If the account has a non 0 balance, release the calculated reward to the user as an incentive, add the additional funds, and update lock date
// Blocks: number of blocks to freeze
// @precondition: blocks > 0
// @postcondition: msg.sender balance -= _wei
// @postcondition: balances[msg.sender] += _wei
// @return: amount deposited
function deposit(uint256 _blocks) public payable {
if(_blocks <= 0){
revert('Blocks frozen must be a positive integer');
}
if(accounts[msg.sender].balance == 0){
uint256 amount = msg.value;
accounts[msg.sender].blockDeposited = block.number;
accounts[msg.sender].blockAvailable = block.number + _blocks;
accounts[msg.sender].balance = amount;
accounts[msg.sender].rewardsAvailable = calculateReward(accounts[msg.sender].balance, accounts[msg.sender].blockAvailable - accounts[msg.sender].blockDeposited);
}
else {
sendRewards();
accounts[msg.sender].blockDeposited = block.number;
accounts[msg.sender].blockAvailable += _blocks;
accounts[msg.sender].rewardsAvailable = calculateReward(accounts[msg.sender].balance, accounts[msg.sender].blockAvailable - accounts[msg.sender].blockDeposited);
}
}
/* Withdrawal function
* Checks if the freeze lock is released. If so, transfers balance to msg.sender, and sends available rewards
*/
function withdraw() public {
if(!checkLock()){
revert('Lock has not yet released');
}
payable(msg.sender).transfer(accounts[msg.sender].balance);
sendRewards();
topUp();
}
/* Interface functions for struct mapping for user interface
*/
function getAccountBalance() public view returns(uint256){
return accounts[msg.sender].balance;
}
function getAccountDepositBlock() public view returns(uint256){
return accounts[msg.sender].blockDeposited;
}
function getAccountAvailableBlock() public view returns(uint256){
return accounts[msg.sender].blockAvailable;
}
function getAccountRewardsAvailable() public view returns(uint256){
return accounts[msg.sender].rewardsAvailable;
}
// Lock Check function
// Checks if the current block is block to release the ethereum deposited by the sender's wallet.
// will be run as a check for the withdraw function
// @precondition: accounts[msg.sender] exists
function checkLock() private returns(bool){
if(block.number >= accounts[msg.sender].blockAvailable){
return true;
}
return false;
}
// Function that takes amount ETH and block delta to calculate ERC20 token reward. Tokens come from
// initial 1,000,000,000 pool for liquidity. 1 token = .1 eth staked per block frozen
// _ethereum: ethereum frozen
// blockDelta: Difference in block height from freeze to release
function calculateReward(uint256 _wei, uint256 blockDelta) private returns (uint256) {
return _wei * rewardMultiplier * blockDelta / weiPerEther ;
}
// Upon successful withdrawal, sends erc20 token to msg.sender
function sendRewards() private {
//TODO: implement erc20 transfer
transfer(msg.sender, accounts[msg.sender].rewardsAvailable);
}
// Top up function
// checks if token reserve in contract wallet is less than 10^9.
// if so, generates initialsupply - 10^9 tokens
function topUp() private {
if(this.balanceOf(address(this)) <= (initialSupply / 10**3)){
_mint(address(this), (initialSupply - 10**9));
}
}
} | Function that takes amount ETH and block delta to calculate ERC20 token reward. Tokens come from initial 1,000,000,000 pool for liquidity. 1 token = .1 eth staked per block frozen _ethereum: ethereum frozen blockDelta: Difference in block height from freeze to release | function calculateReward(uint256 _wei, uint256 blockDelta) private returns (uint256) {
return _wei * rewardMultiplier * blockDelta / weiPerEther ;
}
| 12,749,805 |
pragma solidity ^0.6.0;
contract initializable5 { //inject NONSTANDARD NAMING
bool private initialized;
bool private initializing;
modifier INITIALIZER65() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
}
function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING
}
function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
__OWNABLE_INIT_UNCHAINED84();
}
function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER78();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED52(address(0), msgSender);
}
function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER81() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED52(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED52(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
library safemath14 { //inject NONSTANDARD NAMING
function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB60(a, b, "SafeMath: subtraction overflow");
}
function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV54(a, b, "SafeMath: division by zero");
}
function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD56(a, b, "SafeMath: modulo by zero");
}
function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface ierc2086 { //inject NONSTANDARD NAMING
function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library console87 { //inject NONSTANDARD NAMING
address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address36;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG40() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log()"));
}
function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOG40(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
interface iuniswapv2factory11 { //inject NONSTANDARD NAMING
event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO47() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO7(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING
}
contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING
using safemath14 for uint256;
function INITIALIZE58( //inject NONSTANDARD NAMING
address _NANOCOREAddress,
address _WETHAddress,
address _uniswapFactory
) public INITIALIZER65 {
ownableupgradesafe25.__OWNABLE_INIT13();
nanocoreTokenAddress = _NANOCOREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress);
feePercentX100 = 15;
paused = false; // We start paused until sync post LGE happens.
}
address tokenUniswapPair;
iuniswapv2factory11 public uniswapFactory;
address internal WETHAddress;
address nanocoreTokenAddress;
address nanocoreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
// Pausing transfers of the token
function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING
paused = _pause;
}
function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING
feePercentX100 = _feeMultiplier;
}
function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING
nanocoreVaultAddress = _nanocoreVaultAddress;
}
function SYNC99() public { //inject NONSTANDARD NAMING
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
// console.log("sender is " , sender);
// console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair);
// console.log("Old LP supply", lastTotalSupplyOfLPTokens);
// console.log("Current LP supply", _LPSupplyOfPairTotal);
if(sender == tokenUniswapPair)
require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden");
// console.log('Sender is pair' , sender == tokenUniswapPair);
// console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop
console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console87.LOG40("Normal fee transfer");
transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000);
transferToAmount = amount.SUB60(transferToFeeDistributorAmount);
}
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
} | inject NONSTANDARD NAMING | function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { | 1,019,190 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./ERC2981.sol";
contract ERC721Royalty is ERC721, ERC2981, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
struct Royalty {
address recipient;
uint256 value;
}
mapping(uint256 => Royalty) internal _royalties;
constructor() ERC721("ERC721Royalty", "TEST") {}
function safeMint(address to, uint256 royaltyBps) public onlyOwner {
_tokenIdCounter.increment();
uint256 _tokenId = _tokenIdCounter.current();
_safeMint(to, _tokenId);
_royalties[_tokenId] = Royalty(to, royaltyBps);
}
/// @dev Dumb implementation
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
public
view
override
returns (address receiver, uint256 royaltyAmount)
{
Royalty memory royalty = _royalties[_tokenId];
if (royalty.recipient == address(0)) {
return (address(0), 0);
}
return (royalty.recipient, (_salePrice * royalty.value) / 10000);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| Dumb implementation | function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
public
view
override
returns (address receiver, uint256 royaltyAmount)
{
Royalty memory royalty = _royalties[_tokenId];
if (royalty.recipient == address(0)) {
return (address(0), 0);
}
return (royalty.recipient, (_salePrice * royalty.value) / 10000);
}
| 6,416,536 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "../openzeppelin/access/AccessControl.sol";
import "../openzeppelin/utils/math/SafeMath.sol";
import "../openzeppelin/token/ERC20/SafeERC20.sol";
import "../openzeppelin/token/ERC20/IERC20.sol";
import "../sablierhq/Sablier.sol";
import "./ITokenVesting.sol";
/**
* @title TokenVesting contract for linearly vesting tokens to the respective vesting beneficiary
* @dev This contract receives accepted proposals from the Manager contract, and pass it to sablier contract
* @dev all the tokens to be vested by the vesting beneficiary. It releases these tokens when called
* @dev upon in a continuous-like linear fashion.
* @notice This contract use https://github.com/sablierhq/sablier-smooth-contracts/blob/master/contracts/Sablier.sol
*/
contract TokenVesting is ITokenVesting, AccessControl {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address sablier;
uint256 constant CREATOR_IX = 0;
uint256 constant ROLL_IX = 1;
uint256 constant REFERRAL_IX = 2;
uint256 public constant DAYS_IN_SECONDS = 24 * 60 * 60;
mapping(address => VestingInfo) public vestingInfo;
mapping(address => mapping(uint256 => Beneficiary)) public beneficiaries;
mapping(address => address[]) public beneficiaryTokens;
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"Ownable: caller is not the owner"
);
_;
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
grantRole(DEFAULT_ADMIN_ROLE, newOwner);
revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
constructor(address newOwner) {
_setupRole(DEFAULT_ADMIN_ROLE, newOwner);
}
function setSablier(address _sablier) external onlyOwner {
sablier = _sablier;
}
/**
* @dev Method to add a token into TokenVesting
* @param _token address Address of token
* @param _beneficiaries address[3] memory Address of vesting beneficiary
* @param _proportions uint256[3] memory Proportions of vesting beneficiary
* @param _vestingPeriodInDays uint256 Period of vesting, in units of Days, to be converted
* @notice This emits an Event LogTokenAdded which is indexed by the token address
*/
function addToken(
address _token,
address[3] calldata _beneficiaries,
uint256[3] calldata _proportions,
uint256 _vestingPeriodInDays
) external override onlyOwner {
uint256 duration = uint256(_vestingPeriodInDays).mul(DAYS_IN_SECONDS);
require(duration > 0, "VESTING: period can't be zero");
uint256 stopTime = block.timestamp.add(duration);
uint256 initial = IERC20(_token).balanceOf(address(this));
vestingInfo[_token] = VestingInfo({
vestingBeneficiary: _beneficiaries[0],
totalBalance: initial,
beneficiariesCount: 3, // this is to create a struct compatible with any number but for now is always 3
start: block.timestamp,
stop: stopTime
});
IERC20(_token).approve(sablier, 2**256 - 1);
IERC20(_token).approve(address(this), 2**256 - 1);
for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) {
if (_beneficiaries[i] == address(0)) {
continue;
}
beneficiaries[_token][i].beneficiary = _beneficiaries[i];
beneficiaries[_token][i].proportion = _proportions[i];
uint256 deposit = _proportions[i];
if (deposit == 0) {
continue;
}
// we store the remaing to guarantee deposit be multiple of period. We send that remining at the end of period.
uint256 remaining = deposit % duration;
uint256 streamId =
Sablier(sablier).createStream(
_beneficiaries[i],
deposit.sub(remaining),
_token,
block.timestamp,
stopTime
);
beneficiaries[_token][i].streamId = streamId;
beneficiaries[_token][i].remaining = remaining;
beneficiaryTokens[_beneficiaries[i]].push(_token);
}
emit LogTokenAdded(_token, _beneficiaries[0], _vestingPeriodInDays);
}
function getBeneficiaryId(address _token, address _beneficiary)
internal
view
returns (uint256)
{
for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) {
if (beneficiaries[_token][i].beneficiary == _beneficiary) {
return i;
}
}
revert("VESTING: invalid vesting address");
}
function release(address _token, address _beneficiary) external override {
uint256 ix = getBeneficiaryId(_token, _beneficiary);
uint256 streamId = beneficiaries[_token][ix].streamId;
if (!Sablier(sablier).isEntity(streamId)) {
return;
}
uint256 balance = Sablier(sablier).balanceOf(streamId, _beneficiary);
bool withdrawResult =
Sablier(sablier).withdrawFromStream(streamId, balance);
require(withdrawResult, "VESTING: Error calling withdrawFromStream");
// if vesting duration already finish then release the final dust
if (
vestingInfo[_token].stop < block.timestamp &&
beneficiaries[_token][ix].remaining > 0
) {
IERC20(_token).safeTransferFrom(
address(this),
_beneficiary,
beneficiaries[_token][ix].remaining
);
}
}
function releaseableAmount(address _token)
public
view
override
returns (uint256)
{
uint256 total = 0;
for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) {
if (Sablier(sablier).isEntity(beneficiaries[_token][i].streamId)) {
total =
total +
Sablier(sablier).balanceOf(
beneficiaries[_token][i].streamId,
beneficiaries[_token][i].beneficiary
);
}
}
return total;
}
function releaseableAmountByAddress(address _token, address _beneficiary)
public
view
override
returns (uint256)
{
uint256 ix = getBeneficiaryId(_token, _beneficiary);
uint256 streamId = beneficiaries[_token][ix].streamId;
return Sablier(sablier).balanceOf(streamId, _beneficiary);
}
function vestedAmount(address _token)
public
view
override
returns (uint256)
{
VestingInfo memory info = vestingInfo[_token];
if (block.timestamp >= info.stop) {
return info.totalBalance;
} else {
uint256 duration = info.stop.sub(info.start);
return
info.totalBalance.mul(block.timestamp.sub(info.start)).div(
duration
);
}
}
function getVestingInfo(address _token)
external
view
override
returns (VestingInfo memory)
{
return vestingInfo[_token];
}
function updateVestingAddress(
address _token,
uint256 ix,
address _vestingBeneficiary
) internal {
if (
vestingInfo[_token].vestingBeneficiary ==
beneficiaries[_token][ix].beneficiary
) {
vestingInfo[_token].vestingBeneficiary = _vestingBeneficiary;
}
beneficiaries[_token][ix].beneficiary = _vestingBeneficiary;
uint256 deposit = 0;
uint256 remaining = 0;
{
uint256 streamId = beneficiaries[_token][ix].streamId;
// if there's no pending this will revert and it's ok because has no sense to update the address
uint256 pending =
Sablier(sablier).balanceOf(streamId, address(this));
uint256 duration = vestingInfo[_token].stop.sub(block.timestamp);
deposit = pending.add(beneficiaries[_token][ix].remaining);
remaining = deposit % duration;
bool cancelResult =
Sablier(sablier).cancelStream(
beneficiaries[_token][ix].streamId
);
require(cancelResult, "VESTING: Error calling cancelStream");
}
uint256 streamId =
Sablier(sablier).createStream(
_vestingBeneficiary,
deposit.sub(remaining),
_token,
block.timestamp,
vestingInfo[_token].stop
);
beneficiaries[_token][ix].streamId = streamId;
beneficiaries[_token][ix].remaining = remaining;
emit LogBeneficiaryUpdated(_token, _vestingBeneficiary);
}
function setVestingAddress(
address _vestingBeneficiary,
address _token,
address _newVestingBeneficiary
) external override onlyOwner {
uint256 ix = getBeneficiaryId(_token, _vestingBeneficiary);
updateVestingAddress(_token, ix, _newVestingBeneficiary);
}
function setVestingReferral(
address _vestingBeneficiary,
address _token,
address _vestingReferral
) external override onlyOwner {
require(
_vestingBeneficiary == vestingInfo[_token].vestingBeneficiary,
"VESTING: Only creator"
);
updateVestingAddress(_token, REFERRAL_IX, _vestingReferral);
}
function getAllTokensByBeneficiary(address _beneficiary)
public
view
override
returns (address[] memory)
{
return beneficiaryTokens[_beneficiary];
}
function releaseAll(address _beneficiary) public override {
address[] memory array = beneficiaryTokens[_beneficiary];
for (uint256 i = 0; i < array.length; i++) {
this.release(array[i], _beneficiary);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, 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());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 "./IERC20.sol";
import "../../utils/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.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity =0.7.6;
import "../openzeppelin/utils/Pausable.sol";
import "../openzeppelin/access/Ownable.sol";
import "../openzeppelin/token/ERC20/IERC20.sol";
import "../openzeppelin/utils/ReentrancyGuard.sol";
import "./compound/Exponential.sol";
import "./interfaces/IERC1620.sol";
import "./Types.sol";
/**
* @title Sablier's Money Streaming
* @author Sablier
*/
contract Sablier is IERC1620, Exponential, ReentrancyGuard {
/*** Storage Properties ***/
/**
* @dev The amount of interest has been accrued per token address.
*/
mapping(address => uint256) private earnings;
/**
* @notice The percentage fee charged by the contract on the accrued interest.
*/
Exp public fee;
/**
* @notice Counter for new stream ids.
*/
uint256 public nextStreamId;
/**
* @dev The stream objects identifiable by their unsigned integer ids.
*/
mapping(uint256 => Types.Stream) private streams;
/*** Modifiers ***/
/**
* @dev Throws if the caller is not the sender of the recipient of the stream.
*/
modifier onlySenderOrRecipient(uint256 streamId) {
require(
msg.sender == streams[streamId].sender ||
msg.sender == streams[streamId].recipient,
"caller is not the sender or the recipient of the stream"
);
_;
}
/**
* @dev Throws if the provided id does not point to a valid stream.
*/
modifier streamExists(uint256 streamId) {
require(streams[streamId].isEntity, "stream does not exist");
_;
}
/*** Contract Logic Starts Here */
constructor() public {
nextStreamId = 1;
}
/*** View Functions ***/
function isEntity(uint256 streamId) external view returns (bool) {
return streams[streamId].isEntity;
}
/**
* @dev Returns the compounding stream with all its properties.
* @dev Throws if the id does not point to a valid stream.
* @param streamId The id of the stream to query.
* @dev The stream object.
*/
function getStream(uint256 streamId)
external
view
override
streamExists(streamId)
returns (
address sender,
address recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime,
uint256 remainingBalance,
uint256 ratePerSecond
)
{
sender = streams[streamId].sender;
recipient = streams[streamId].recipient;
deposit = streams[streamId].deposit;
tokenAddress = streams[streamId].tokenAddress;
startTime = streams[streamId].startTime;
stopTime = streams[streamId].stopTime;
remainingBalance = streams[streamId].remainingBalance;
ratePerSecond = streams[streamId].ratePerSecond;
}
/**
* @dev Returns either the delta in seconds between `block.timestamp` and `startTime` or
* between `stopTime` and `startTime, whichever is smaller. If `block.timestamp` is before
* `startTime`, it returns 0.
* @dev Throws if the id does not point to a valid stream.
* @param streamId The id of the stream for which to query the delta.
* @dev The time delta in seconds.
*/
function deltaOf(uint256 streamId)
public
view
streamExists(streamId)
returns (uint256 delta)
{
Types.Stream memory stream = streams[streamId];
if (block.timestamp <= stream.startTime) return 0;
if (block.timestamp < stream.stopTime)
return block.timestamp - stream.startTime;
return stream.stopTime - stream.startTime;
}
struct BalanceOfLocalVars {
MathError mathErr;
uint256 recipientBalance;
uint256 withdrawalAmount;
uint256 senderBalance;
}
/**
* @dev Returns the available funds for the given stream id and address.
* @dev Throws if the id does not point to a valid stream.
* @param streamId The id of the stream for which to query the balance.
* @param who The address for which to query the balance.
* @dev @balance uint256 The total funds allocated to `who` as uint256.
*/
function balanceOf(uint256 streamId, address who)
public
view
override
streamExists(streamId)
returns (uint256 balance)
{
Types.Stream memory stream = streams[streamId];
BalanceOfLocalVars memory vars;
uint256 delta = deltaOf(streamId);
(vars.mathErr, vars.recipientBalance) = mulUInt(
delta,
stream.ratePerSecond
);
require(
vars.mathErr == MathError.NO_ERROR,
"recipient balance calculation error"
);
/*
* If the stream `balance` does not equal `deposit`, it means there have been withdrawals.
* We have to subtract the total amount withdrawn from the amount of money that has been
* streamed until now.
*/
if (stream.deposit > stream.remainingBalance) {
(vars.mathErr, vars.withdrawalAmount) = subUInt(
stream.deposit,
stream.remainingBalance
);
assert(vars.mathErr == MathError.NO_ERROR);
(vars.mathErr, vars.recipientBalance) = subUInt(
vars.recipientBalance,
vars.withdrawalAmount
);
/* `withdrawalAmount` cannot and should not be bigger than `recipientBalance`. */
assert(vars.mathErr == MathError.NO_ERROR);
}
if (who == stream.recipient) return vars.recipientBalance;
if (who == stream.sender) {
(vars.mathErr, vars.senderBalance) = subUInt(
stream.remainingBalance,
vars.recipientBalance
);
/* `recipientBalance` cannot and should not be bigger than `remainingBalance`. */
assert(vars.mathErr == MathError.NO_ERROR);
return vars.senderBalance;
}
return 0;
}
/*** Public Effects & Interactions Functions ***/
struct CreateStreamLocalVars {
MathError mathErr;
uint256 duration;
uint256 ratePerSecond;
}
/**
* @notice Creates a new stream funded by `msg.sender` and paid towards `recipient`.
* @dev Throws if paused.
* Throws if the recipient is the zero address, the contract itself or the caller.
* Throws if the deposit is 0.
* Throws if the start time is before `block.timestamp`.
* Throws if the stop time is before the start time.
* Throws if the duration calculation has a math error.
* Throws if the deposit is smaller than the duration.
* Throws if the deposit is not a multiple of the duration.
* Throws if the rate calculation has a math error.
* Throws if the next stream id calculation has a math error.
* Throws if the contract is not allowed to transfer enough tokens.
* Throws if there is a token transfer failure.
* @param recipient The address towards which the money is streamed.
* @param deposit The amount of money to be streamed.
* @param tokenAddress The ERC20 token to use as streaming currency.
* @param startTime The unix timestamp for when the stream starts.
* @param stopTime The unix timestamp for when the stream stops.
* @return The uint256 id of the newly created stream.
*/
function createStream(
address recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime
) public override returns (uint256) {
require(recipient != address(0x00), "stream to the zero address");
require(recipient != address(this), "stream to the contract itself");
require(recipient != msg.sender, "stream to the caller");
require(deposit > 0, "deposit is zero");
require(
startTime >= block.timestamp,
"start time before block.timestamp"
);
require(stopTime > startTime, "stop time before the start time");
CreateStreamLocalVars memory vars;
(vars.mathErr, vars.duration) = subUInt(stopTime, startTime);
/* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know `stopTime` is higher than `startTime`. */
assert(vars.mathErr == MathError.NO_ERROR);
/* Without this, the rate per second would be zero. */
require(deposit >= vars.duration, "deposit smaller than time delta");
require(
deposit % vars.duration == 0,
"deposit not multiple of time delta"
);
(vars.mathErr, vars.ratePerSecond) = divUInt(deposit, vars.duration);
/* `divUInt` can only return MathError.DIVISION_BY_ZERO but we know `duration` is not zero. */
assert(vars.mathErr == MathError.NO_ERROR);
/* Create and store the stream object. */
uint256 streamId = nextStreamId;
streams[streamId] = Types.Stream({
remainingBalance: deposit,
deposit: deposit,
isEntity: true,
ratePerSecond: vars.ratePerSecond,
recipient: recipient,
sender: msg.sender,
startTime: startTime,
stopTime: stopTime,
tokenAddress: tokenAddress
});
/* Increment the next stream id. */
(vars.mathErr, nextStreamId) = addUInt(nextStreamId, uint256(1));
require(
vars.mathErr == MathError.NO_ERROR,
"next stream id calculation error"
);
require(
IERC20(tokenAddress).transferFrom(
msg.sender,
address(this),
deposit
),
"token transfer failure"
);
emit CreateStream(
streamId,
msg.sender,
recipient,
deposit,
tokenAddress,
startTime,
stopTime
);
return streamId;
}
struct WithdrawFromStreamLocalVars {
MathError mathErr;
}
/**
* @notice Withdraws from the contract to the recipient's account.
* @dev Throws if the id does not point to a valid stream.
* Throws if the caller is not the sender or the recipient of the stream.
* Throws if the amount exceeds the available balance.
* Throws if there is a token transfer failure.
* @param streamId The id of the stream to withdraw tokens from.
* @param amount The amount of tokens to withdraw.
* @return bool true=success, otherwise false.
*/
function withdrawFromStream(uint256 streamId, uint256 amount)
external
override
nonReentrant
streamExists(streamId)
onlySenderOrRecipient(streamId)
returns (bool)
{
require(amount > 0, "amount is zero");
Types.Stream memory stream = streams[streamId];
WithdrawFromStreamLocalVars memory vars;
uint256 balance = balanceOf(streamId, stream.recipient);
require(balance >= amount, "amount exceeds the available balance");
(vars.mathErr, streams[streamId].remainingBalance) = subUInt(
stream.remainingBalance,
amount
);
/**
* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know that `remainingBalance` is at least
* as big as `amount`.
*/
assert(vars.mathErr == MathError.NO_ERROR);
if (streams[streamId].remainingBalance == 0) delete streams[streamId];
require(
IERC20(stream.tokenAddress).transfer(stream.recipient, amount),
"token transfer failure"
);
emit WithdrawFromStream(streamId, stream.recipient, amount);
return true;
}
/**
* @notice Cancels the stream and transfers the tokens back on a pro rata basis.
* @dev Throws if the id does not point to a valid stream.
* Throws if the caller is not the sender or the recipient of the stream.
* Throws if there is a token transfer failure.
* @param streamId The id of the stream to cancel.
* @return bool true=success, otherwise false.
*/
function cancelStream(uint256 streamId)
external
override
nonReentrant
streamExists(streamId)
onlySenderOrRecipient(streamId)
returns (bool)
{
Types.Stream memory stream = streams[streamId];
uint256 senderBalance = balanceOf(streamId, stream.sender);
uint256 recipientBalance = balanceOf(streamId, stream.recipient);
delete streams[streamId];
IERC20 token = IERC20(stream.tokenAddress);
if (recipientBalance > 0)
require(
token.transfer(stream.recipient, recipientBalance),
"recipient token transfer failure"
);
if (senderBalance > 0)
require(
token.transfer(stream.sender, senderBalance),
"sender token transfer failure"
);
emit CancelStream(
streamId,
stream.sender,
stream.recipient,
senderBalance,
recipientBalance
);
return true;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
interface ITokenVesting {
event Released(
address indexed token,
address vestingBeneficiary,
uint256 amount
);
event LogTokenAdded(
address indexed token,
address vestingBeneficiary,
uint256 vestingPeriodInDays
);
event LogBeneficiaryUpdated(
address indexed token,
address vestingBeneficiary
);
struct VestingInfo {
address vestingBeneficiary;
uint256 totalBalance;
uint256 beneficiariesCount;
uint256 start;
uint256 stop;
}
struct Beneficiary {
address beneficiary;
uint256 proportion;
uint256 streamId;
uint256 remaining;
}
function addToken(
address _token,
address[3] calldata _beneficiaries,
uint256[3] calldata _proportions,
uint256 _vestingPeriodInDays
) external;
function release(address _token, address _beneficiary) external;
function releaseableAmount(address _token) external view returns (uint256);
function releaseableAmountByAddress(address _token, address _beneficiary)
external
view
returns (uint256);
function vestedAmount(address _token) external view returns (uint256);
function getVestingInfo(address _token)
external
view
returns (VestingInfo memory);
function setVestingAddress(
address _vestingBeneficiary,
address _token,
address _newVestingBeneficiary
) external;
function setVestingReferral(
address _vestingBeneficiary,
address _token,
address _vestingReferral
) external;
function getAllTokensByBeneficiary(address _beneficiary)
external
view
returns (address[] memory);
function releaseAll(address _beneficiary) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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;
}
}
pragma solidity =0.7.6;
import "./CarefulMath.sol";
/**
* @title Exponential module for storing fixed-decision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint256 constant expScale = 1e18;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 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(uint256 num, uint256 denom)
internal
pure
returns (MathError, Exp memory)
{
(MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
(MathError err1, uint256 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)
internal
pure
returns (MathError, Exp memory)
{
(MathError error, uint256 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)
internal
pure
returns (MathError, Exp memory)
{
(MathError error, uint256 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, uint256 scalar)
internal
pure
returns (MathError, Exp memory)
{
(MathError err0, uint256 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, uint256 scalar)
internal
pure
returns (MathError, uint256)
{
(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,
uint256 scalar,
uint256 addend
) internal pure returns (MathError, uint256) {
(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, uint256 scalar)
internal
pure
returns (MathError, Exp memory)
{
(MathError err0, uint256 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(uint256 scalar, Exp memory divisor)
internal
pure
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, uint256 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(uint256 scalar, Exp memory divisor)
internal
pure
returns (MathError, uint256)
{
(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)
internal
pure
returns (MathError, Exp memory)
{
(MathError err0, uint256 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, uint256 doubleScaledProductWithHalfScale) =
addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({ mantissa: 0 }));
}
(MathError err2, uint256 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(uint256 a, uint256 b)
internal
pure
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
) internal pure 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)
internal
pure
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) internal pure returns (uint256) {
// 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)
internal
pure
returns (bool)
{
return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo.
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
}
pragma solidity =0.7.6;
/**
* @title ERC-1620 Money Streaming Standard
* @author Sablier
* @dev See https://eips.ethereum.org/EIPS/eip-1620
*/
interface IERC1620 {
/**
* @notice Emits when a stream is successfully created.
*/
event CreateStream(
uint256 indexed streamId,
address indexed sender,
address indexed recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime
);
/**
* @notice Emits when the recipient of a stream withdraws a portion or all their pro rata share of the stream.
*/
event WithdrawFromStream(
uint256 indexed streamId,
address indexed recipient,
uint256 amount
);
/**
* @notice Emits when a stream is successfully cancelled and tokens are transferred back on a pro rata basis.
*/
event CancelStream(
uint256 indexed streamId,
address indexed sender,
address indexed recipient,
uint256 senderBalance,
uint256 recipientBalance
);
function balanceOf(uint256 streamId, address who)
external
view
returns (uint256 balance);
function getStream(uint256 streamId)
external
view
returns (
address sender,
address recipient,
uint256 deposit,
address token,
uint256 startTime,
uint256 stopTime,
uint256 remainingBalance,
uint256 ratePerSecond
);
function createStream(
address recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime
) external returns (uint256 streamId);
function withdrawFromStream(uint256 streamId, uint256 funds)
external
returns (bool);
function cancelStream(uint256 streamId) external returns (bool);
}
pragma solidity =0.7.6;
/**
* @title Sablier Types
* @author Sablier
*/
library Types {
struct Stream {
uint256 deposit;
uint256 ratePerSecond;
uint256 remainingBalance;
uint256 startTime;
uint256 stopTime;
address recipient;
address sender;
address tokenAddress;
bool isEntity;
}
}
pragma solidity =0.7.6;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
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(uint256 a, uint256 b)
internal
pure
returns (MathError, uint256)
{
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint256 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(uint256 a, uint256 b)
internal
pure
returns (MathError, uint256)
{
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(uint256 a, uint256 b)
internal
pure
returns (MathError, uint256)
{
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(uint256 a, uint256 b)
internal
pure
returns (MathError, uint256)
{
uint256 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(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (MathError, uint256) {
(MathError err0, uint256 sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
| Divide a scalar by an Exp, returning a new Exp.// | function divScalarByExp(uint256 scalar, Exp memory divisor)
internal
pure
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, uint256 numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
}
return getExp(numerator, divisor.mantissa);
}
| 12,569,873 |
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public 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 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); // 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 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);
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];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* admin manager
*/
contract AdminManager {
event ChangeOwner(address _oldOwner, address _newOwner);
event SetAdmin(address _address, bool _isAdmin);
//constract's owner
address public owner;
//constract's admins. permission less than owner
mapping(address=>bool) public admins;
/**
* constructor
*/
constructor() public {
owner = msg.sender;
}
/**
* modifier for some action only owner can do
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* modifier for some action only admin or owner can do
*/
modifier onlyAdmins() {
require(msg.sender == owner || admins[msg.sender]);
_;
}
/**
* change this constract's owner
*/
function changeOwner(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
emit ChangeOwner(owner, _newOwner);
owner = _newOwner;
}
/**
* add or delete admin
*/
function setAdmin(address _address, bool _isAdmin) public onlyOwner {
emit SetAdmin(_address, _isAdmin);
if(!_isAdmin){
delete admins[_address];
}else{
admins[_address] = true;
}
}
}
/**
* pausable token
*/
contract PausableToken is StandardToken, AdminManager {
event SetPause(bool isPause);
bool public paused = true;
/**
* modifier for pause constract. not contains admin and owner
*/
modifier whenNotPaused() {
if(paused) {
require(msg.sender == owner || admins[msg.sender]);
}
_;
}
/**
* @dev called by the owner to set new pause flags
* pausedPublic can't be false while pausedOwnerAdmin is true
*/
function setPause(bool _isPause) onlyAdmins public {
require(paused != _isPause);
paused = _isPause;
emit SetPause(_isPause);
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* lockadble token
*/
contract LockableToken is PausableToken {
/**
* lock data struct
*/
struct LockData {
uint256 balance;
uint256 releaseTimeS;
}
event SetLock(address _address, uint256 _lockValue, uint256 _releaseTimeS);
mapping (address => LockData) public locks;
/**
* if active balance is not enought. deny transaction
*/
modifier whenNotLocked(address _from, uint256 _value) {
require( activeBalanceOf(_from) >= _value );
_;
}
/**
* active balance of address
*/
function activeBalanceOf(address _owner) public view returns (uint256) {
if( uint256(now) < locks[_owner].releaseTimeS ) {
return balances[_owner].sub(locks[_owner].balance);
}
return balances[_owner];
}
/**
* lock one address
* one address only be locked at the same time.
* because the gas reson, so not support multi lock of one address
*
* @param _lockValue how many tokens locked
* @param _releaseTimeS the lock release unix time
*/
function setLock(address _address, uint256 _lockValue, uint256 _releaseTimeS) onlyAdmins public {
require( uint256(now) > locks[_address].releaseTimeS );
locks[_address].balance = _lockValue;
locks[_address].releaseTimeS = _releaseTimeS;
emit SetLock(_address, _lockValue, _releaseTimeS);
}
function transfer(address _to, uint256 _value) public whenNotLocked(msg.sender, _value) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotLocked(_from, _value) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract EnjoyGameToken is LockableToken {
event Burn(address indexed _burner, uint256 _value);
string public constant name = "EnjoyGameToken";
string public constant symbol = "EGT";
uint8 public constant decimals = 6;
/**
* constructor
*/
constructor() public {
//set totalSupply
totalSupply = 10**16;
//init balances
balances[msg.sender] = totalSupply;
emit Transfer(address(0x0), msg.sender, totalSupply);
}
/**
* transfer and lock this value
* only called by admins (limit when setLock)
*/
function transferAndLock(address _to, uint256 _value, uint256 _releaseTimeS) public returns (bool) {
//at first, try lock address
setLock(_to,_value,_releaseTimeS);
if( !transfer(_to, _value) ){
//revert with lock
revert();
}
return true;
}
} | lock one address one address only be locked at the same time. because the gas reson, so not support multi lock of one address _lockValue how many tokens locked _releaseTimeS the lock release unix time/ | function setLock(address _address, uint256 _lockValue, uint256 _releaseTimeS) onlyAdmins public {
require( uint256(now) > locks[_address].releaseTimeS );
locks[_address].balance = _lockValue;
locks[_address].releaseTimeS = _releaseTimeS;
emit SetLock(_address, _lockValue, _releaseTimeS);
}
| 6,133,416 |
./full_match/44787/0xE872636cca1c141B62bd9f82C745cE6b9113C6bD/sources/project_/contracts/KolorLandToken.sol | increase number of holders set approval for dev or other operator | function newInvestment(
address investor,
uint256 tokenId,
uint256 amount,
uint256 tokenPrice
) public onlyAuthorized {
require(exists(tokenId), "KolorLandToken: land must exists!");
require(
availableTokensOf(tokenId) - amount >= 0,
"KolorLandToken: exceeds max amount"
);
require(isPublished(tokenId), "KolorLandToken: land not published yet");
addInvestment(investor, tokenId, amount, tokenPrice);
addInvestment(tokenId, investor, amount, tokenPrice);
if (balances[tokenId][investor] == 0) {
holders[tokenId]++;
}
if (!operatorApprovals[investor][devAddress]) {
setApprovalForAll(investor, devAddress, true);
setApprovalForAll(investor, address(this), true);
}
totalInvestmentsByAddress[investor]++;
totalInvestmentsByLand[tokenId]++;
totalInvestments++;
landTokensInfo[tokenId].available -= amount;
landTokensInfo[tokenId].sold += amount;
}
| 13,260,551 |
./full_match/1/0x5773681CBeBf0f3fB79Fdb139bDa12eFBc12A7A9/sources/contracts/hacker/LOVELY.sol | Gas consumes testing/ | function testing() external {
uint256 mkpmd = 77 + 2 % 29;
uint256 kizgmy = 71 % 52;
uint256 fupvdgci = 5;
uint256 qsywq = 55 + 8;
uint256 aya = 38 + 88;
if (mkpmd == 57 % 75 + 44 + 91 && kizgmy == 79 * 24 && fupvdgci == 83 + 22 + 50 && qsywq == 82 % 82 && aya == 56 + 39 % 88) return;
emit log("NCN");
emit log("fuzy");
}
| 4,861,854 |
./partial_match/1/0xe14F2e37935A7b500CeF56D2779FFeCa79F0bf65/sources/TokenSale.sol | This lets owner to withdraw any leftover tokens./ | function withdrawLeftoverTokens(address tokenAddress) external onlyOwner{
uint256 balance = IERC20(tokenAddress).balanceOf(address(this));
require(balance > 0, "No token balance to withdraw");
IERC20(tokenAddress).transfer(msg.sender, balance);
}
| 4,079,766 |
pragma solidity ^0.4.21;
/*
* ##### ## ##### ## ### ## ### ###
* ###### /### ###### / #### / /#### #### / ### ###
* /# / / ### /# / / ####/ / ### /####/ ## ##
* / / / ### / / / # # ### / ## ## ##
* / / ## / / # ### / ## ##
* ## ## ## ## ## # ###/ ### /### /### ## ##
* ## ## ## ## ## # ### ###/ #### / / ### / ## ##
* /### ## / ## ######## /### ## ###/ / ###/ ## ##
* / ### ## / ## ## # / ### ## ## ## ## ##
* ## ######/ ## ## ## / ### ## ## ## ## ##
* ## ###### # ## ## / ### ## ## ## ## ##
* ## ## / ## / ### ## ## ## ## ##
* ## ## /##/ ## / ### / ## ## ## ## ##
* ## ## / ##### ## / ####/ ### ###### ### / ### /
* ## ## ## / ## / ### ### #### ##/ ##/
* ### # / #
* ### / ##
* #####/
* ###
*
* ____
* /\' .\ _____
* /: \___\ / . /\
* \' / . / /____/..\
* \/___/ \' '\ /
* \'__'\/
*
* // Probably Unfair //
*
* //*** Developed By:
* _____ _ _ _ ___ _
* |_ _|__ __| |_ _ _ (_)__ __ _| | _ (_)___ ___
* | |/ -_) _| ' \| ' \| / _/ _` | | / (_-</ -_)
* |_|\___\__|_||_|_||_|_\__\__,_|_|_|_\_/__/\___|
*
* © 2018 TechnicalRise. Written in March 2018.
* All rights reserved. Do not copy, adapt, or otherwise use without permission.
* https://www.reddit.com/user/TechnicalRise/
*
*/
contract PHXReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract PHXInterface {
function balanceOf(address who) public view returns (uint);
function transfer(address _to, uint _value) public returns (bool);
function transfer(address _to, uint _value, bytes _data) public returns (bool);
}
contract usingMathLibraries {
function safeAdd(uint a, uint b) internal pure returns (uint) {
require(a + b >= a);
return a + b;
}
function safeSub(uint a, uint b) pure internal returns (uint) {
require(b <= a);
return a - b;
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
}
contract PHXroll is PHXReceivingContract, usingMathLibraries {
/*
* checks player profit, bet size and player number is within range
*/
modifier betIsValid(uint _betSize, uint _playerNumber) {
require(((((_betSize * (100-(safeSub(_playerNumber,1)))) / (safeSub(_playerNumber,1))+_betSize))*houseEdge/houseEdgeDivisor)-_betSize < maxProfit && _betSize > minBet && _playerNumber > minNumber && _playerNumber < maxNumber);
_;
}
/*
* checks game is currently active
*/
modifier gameIsActive {
require(gamePaused == false);
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
require(payoutsPaused == false);
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/*
* checks only treasury address is calling
*/
modifier onlyTreasury {
require(msg.sender == treasury);
_;
}
/*
* game vars
*/
uint constant public maxProfitDivisor = 1000000;
uint constant public houseEdgeDivisor = 1000;
uint constant public maxNumber = 99;
uint constant public minNumber = 2;
bool public gamePaused;
address public owner;
bool public payoutsPaused;
address public treasury;
uint public contractBalance;
uint public houseEdge;
uint public maxProfit;
uint public maxProfitAsPercentOfHouse;
uint public minBet;
//init discontinued contract data
int public totalBets = 0;
//init discontinued contract data
uint public totalTRsWon = 0;
//init discontinued contract data
uint public totalTRsWagered = 0;
/*
* player vars
*/
uint public rngId;
mapping (uint => address) playerAddress;
mapping (uint => uint) playerBetId;
mapping (uint => uint) playerBetValue;
mapping (uint => uint) playerDieResult;
mapping (uint => uint) playerNumber;
mapping (uint => uint) playerProfit;
/*
* events
*/
/* log bets + output to web3 for precise 'payout on win' field in UI */
event LogBet(uint indexed BetID, address indexed PlayerAddress, uint indexed RewardValue, uint ProfitValue, uint BetValue, uint PlayerNumber);
/* output to web3 UI on bet result*/
/* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send*/
event LogResult(uint indexed BetID, address indexed PlayerAddress, uint PlayerNumber, uint DiceResult, uint Value, int Status);
/* log manual refunds */
event LogRefund(uint indexed BetID, address indexed PlayerAddress, uint indexed RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred);
address public constant PHXTKNADDR = 0x14b759A158879B133710f4059d32565b4a66140C;
PHXInterface public PHXTKN;
/*
* init
*/
function PHXroll() public {
owner = msg.sender;
treasury = msg.sender;
// Initialize the PHX Contract
PHXTKN = PHXInterface(PHXTKNADDR);
/* init 990 = 99% (1% houseEdge)*/
ownerSetHouseEdge(990);
/* init 10,000 = 1% */
ownerSetMaxProfitAsPercentOfHouse(10000);
/* init min bet (0.1 PHX) */
ownerSetMinBet(100000000000000000);
}
// This is a supercheap psuedo-random number generator
// that relies on the fact that "who" will mine and "when" they will
// mine is random. This is usually vulnerable to "inside the block"
// attacks where someone writes a contract mined in the same block
// and calls this contract from it -- but we don't accept transactions
// from other contracts, lessening that risk. It seems like someone
// would therefore need to be able to predict the block miner and
// block timestamp in advance to hack this.
//
// ¯\_(ツ)_/¯
//
uint seed3;
function _pRand(uint _modulo) internal view returns (uint) {
require((1 < _modulo) && (_modulo <= 1000));
uint seed1 = uint(block.coinbase); // Get Miner's Address
uint seed2 = now; // Get the timestamp
seed3++; // Make all pRand calls unique
return uint(keccak256(seed1, seed2, seed3)) % _modulo;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid
*/
function _playerRollDice(uint _rollUnder, TKN _tkn) private
gameIsActive
betIsValid(_tkn.value, _rollUnder)
{
// Note that msg.sender is the Token Contract Address
// and "_from" is the sender of the tokens
require(_humanSender(_tkn.sender)); // Check that this is a non-contract sender
require(_phxToken(msg.sender)); // Check that this is a PHX Token Transfer
// Increment rngId
rngId++;
/* map bet id to this wager */
playerBetId[rngId] = rngId;
/* map player lucky number */
playerNumber[rngId] = _rollUnder;
/* map value of wager */
playerBetValue[rngId] = _tkn.value;
/* map player address */
playerAddress[rngId] = _tkn.sender;
/* safely map player profit */
playerProfit[rngId] = 0;
/* provides accurate numbers for web3 and allows for manual refunds */
emit LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId]);
/* map Die result to player */
playerDieResult[rngId] = _pRand(100) + 1;
/* total number of bets */
totalBets += 1;
/* total wagered */
totalTRsWagered += playerBetValue[rngId];
/*
* pay winner
* update contract balance to calculate new max bet
* send reward
*/
if(playerDieResult[rngId] < playerNumber[rngId]){
/* safely map player profit */
playerProfit[rngId] = ((((_tkn.value * (100-(safeSub(_rollUnder,1)))) / (safeSub(_rollUnder,1))+_tkn.value))*houseEdge/houseEdgeDivisor)-_tkn.value;
/* safely reduce contract balance by player profit */
contractBalance = safeSub(contractBalance, playerProfit[rngId]);
/* update total Rises won */
totalTRsWon = safeAdd(totalTRsWon, playerProfit[rngId]);
emit LogResult(playerBetId[rngId], playerAddress[rngId], playerNumber[rngId], playerDieResult[rngId], playerProfit[rngId], 1);
/* update maximum profit */
setMaxProfit();
// Transfer profit plus original bet
PHXTKN.transfer(playerAddress[rngId], playerProfit[rngId] + _tkn.value);
return;
} else {
/*
* no win
* send 1 Rise to a losing bet
* update contract balance to calculate new max bet
*/
emit LogResult(playerBetId[rngId], playerAddress[rngId], playerNumber[rngId], playerDieResult[rngId], playerBetValue[rngId], 0);
/*
* safe adjust contractBalance
* setMaxProfit
* send 1 Rise to losing bet
*/
contractBalance = safeAdd(contractBalance, (playerBetValue[rngId]-1));
/* update maximum profit */
setMaxProfit();
/*
* send 1 Rise
*/
PHXTKN.transfer(playerAddress[rngId], 1);
return;
}
}
// !Important: Note the use of the following struct
struct TKN { address sender; uint value; }
function tokenFallback(address _from, uint _value, bytes _data) public {
if(_from == treasury) {
contractBalance = safeAdd(contractBalance, _value);
/* safely update contract balance */
/* update the maximum profit */
setMaxProfit();
return;
} else {
TKN memory _tkn;
_tkn.sender = _from;
_tkn.value = _value;
_playerRollDice(parseInt(string(_data)), _tkn);
}
}
/*
* internal function
* sets max profit
*/
function setMaxProfit() internal {
maxProfit = (contractBalance*maxProfitAsPercentOfHouse)/maxProfitDivisor;
}
/* only owner adjust contract balance variable (only used for max profit calc) */
function ownerUpdateContractBalance(uint newContractBalanceInTRs) public
onlyOwner
{
contractBalance = newContractBalanceInTRs;
}
/* only owner address can set houseEdge */
function ownerSetHouseEdge(uint newHouseEdge) public
onlyOwner
{
houseEdge = newHouseEdge;
}
/* only owner address can set maxProfitAsPercentOfHouse */
function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public
onlyOwner
{
/* restrict each bet to a maximum profit of 1% contractBalance */
require(newMaxProfitAsPercent <= 10000);
maxProfitAsPercentOfHouse = newMaxProfitAsPercent;
setMaxProfit();
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can transfer PHX */
function ownerTransferPHX(address sendTo, uint amount) public
onlyOwner
{
/* safely update contract balance when sending out funds*/
contractBalance = safeSub(contractBalance, amount);
/* update max profit */
setMaxProfit();
require(!PHXTKN.transfer(sendTo, amount));
emit LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set treasury address */
function ownerSetTreasury(address newTreasury) public
onlyOwner
{
treasury = newTreasury;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can selfdestruct - emergency */
function ownerkill() public
onlyOwner
{
PHXTKN.transfer(owner, contractBalance);
selfdestruct(owner);
}
function _phxToken(address _tokenContract) private pure returns (bool) {
return _tokenContract == PHXTKNADDR; // Returns "true" of this is the PHX Token Contract
}
// Determine if the "_from" address is a contract
function _humanSender(address _from) private view returns (bool) {
uint codeLength;
assembly {
codeLength := extcodesize(_from)
}
return (codeLength == 0); // If this is "true" sender is most likely a Wallet
}
} | Determine if the "_from" address is a contract | function _humanSender(address _from) private view returns (bool) {
uint codeLength;
assembly {
codeLength := extcodesize(_from)
}
}
| 5,812,956 |
./full_match/5/0xCbEDAB3193dc8027cc403a01cE054695a08E2F34/sources/contracts/upgrade_initializers/DiamondInit.sol | initalize the Fee Manager facet _feePerClaim fee per claim to reward the validators _feeManagerBank fee manager bank address _feeManagerOwner fee manager owner address | function initFeeManager(
uint256 _feePerClaim,
address _feeManagerBank,
address _feeManagerOwner
) private {
LibFeeManager.DiamondStorage storage feeManagerDS = LibFeeManager
.diamondStorage();
feeManagerDS.feePerClaim = _feePerClaim;
feeManagerDS.bank = IBank(_feeManagerBank);
feeManagerDS.owner = _feeManagerOwner;
emit FeeManagerInitialized(
_feePerClaim,
_feeManagerBank,
_feeManagerOwner
);
}
| 1,895,336 |
./full_match/80001/0xBB24d7CBade17c26a19B97A1E6204125985f0412/sources/useCases/vehicle-management/vehicleModificationTracker.sol | Function to check if a user is blacklisted | function isBlacklisted(address _user) external view returns (bool) {
return blacklistedUsers[_user];
}
| 9,495,835 |
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @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 private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return 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 OwnershipTransferred(_owner, address(0));
_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;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
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));
return role.bearer[account];
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title PauserRole
* @dev Pausers are responsible for pausing/unpausing transfers.
*/
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed token, address indexed account);
event PauserRemoved(address indexed token, address indexed account);
// Mapping from token to token pausers.
mapping(address => Roles.Role) private _pausers;
constructor () internal {}
modifier onlyPauser(address token) {
require(isPauser(token, msg.sender));
_;
}
function isPauser(address token, address account) public view returns (bool) {
return _pausers[token].has(account);
}
function addPauser(address token, address account) public onlyPauser(token) {
_addPauser(token, account);
}
function renouncePauser(address token) public {
_removePauser(token, msg.sender);
}
function _addPauser(address token, address account) internal {
_pausers[token].add(account);
emit PauserAdded(token, account);
}
function _removePauser(address token, address account) internal {
_pausers[token].remove(account);
emit PauserRemoved(token, account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address indexed token, address account);
event Unpaused(address indexed token, address account);
// Mapping from token to token paused status.
mapping(address => bool) private _paused;
/**
* @return true if the contract is paused, false otherwise.
*/
function paused(address token) public view returns (bool) {
return _paused[token];
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused(address token) {
require(!_paused[token]);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused(address token) {
require(_paused[token]);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause(address token) public onlyPauser(token) whenNotPaused(token) {
_paused[token] = true;
emit Paused(token, msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause(address token) public onlyPauser(token) whenPaused(token) {
_paused[token] = false;
emit Unpaused(token, msg.sender);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title AllowlistAdminRole
* @dev AllowlistAdmins are responsible for assigning and removing Allowlisted accounts.
*/
contract AllowlistAdminRole {
using Roles for Roles.Role;
event AllowlistAdminAdded(address indexed token, address indexed account);
event AllowlistAdminRemoved(address indexed token, address indexed account);
// Mapping from token to token allowlist admins.
mapping(address => Roles.Role) private _allowlistAdmins;
constructor () internal {}
modifier onlyAllowlistAdmin(address token) {
require(isAllowlistAdmin(token, msg.sender));
_;
}
function isAllowlistAdmin(address token, address account) public view returns (bool) {
return _allowlistAdmins[token].has(account);
}
function addAllowlistAdmin(address token, address account) public onlyAllowlistAdmin(token) {
_addAllowlistAdmin(token, account);
}
function renounceAllowlistAdmin(address token) public {
_removeAllowlistAdmin(token, msg.sender);
}
function _addAllowlistAdmin(address token, address account) internal {
_allowlistAdmins[token].add(account);
emit AllowlistAdminAdded(token, account);
}
function _removeAllowlistAdmin(address token, address account) internal {
_allowlistAdmins[token].remove(account);
emit AllowlistAdminRemoved(token, account);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title AllowlistedRole
* @dev Allowlisted accounts have been forbidden by a AllowlistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are AllowlistAdmins (who can also remove
* it), and not Allowlisteds themselves.
*/
contract AllowlistedRole is AllowlistAdminRole {
using Roles for Roles.Role;
event AllowlistedAdded(address indexed token, address indexed account);
event AllowlistedRemoved(address indexed token, address indexed account);
// Mapping from token to token allowlisteds.
mapping(address => Roles.Role) private _allowlisteds;
modifier onlyNotAllowlisted(address token) {
require(!isAllowlisted(token, msg.sender));
_;
}
function isAllowlisted(address token, address account) public view returns (bool) {
return _allowlisteds[token].has(account);
}
function addAllowlisted(address token, address account) public onlyAllowlistAdmin(token) {
_addAllowlisted(token, account);
}
function removeAllowlisted(address token, address account) public onlyAllowlistAdmin(token) {
_removeAllowlisted(token, account);
}
function _addAllowlisted(address token, address account) internal {
_allowlisteds[token].add(account);
emit AllowlistedAdded(token, account);
}
function _removeAllowlisted(address token, address account) internal {
_allowlisteds[token].remove(account);
emit AllowlistedRemoved(token, account);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title BlocklistAdminRole
* @dev BlocklistAdmins are responsible for assigning and removing Blocklisted accounts.
*/
contract BlocklistAdminRole {
using Roles for Roles.Role;
event BlocklistAdminAdded(address indexed token, address indexed account);
event BlocklistAdminRemoved(address indexed token, address indexed account);
// Mapping from token to token blocklist admins.
mapping(address => Roles.Role) private _blocklistAdmins;
constructor () internal {}
modifier onlyBlocklistAdmin(address token) {
require(isBlocklistAdmin(token, msg.sender));
_;
}
function isBlocklistAdmin(address token, address account) public view returns (bool) {
return _blocklistAdmins[token].has(account);
}
function addBlocklistAdmin(address token, address account) public onlyBlocklistAdmin(token) {
_addBlocklistAdmin(token, account);
}
function renounceBlocklistAdmin(address token) public {
_removeBlocklistAdmin(token, msg.sender);
}
function _addBlocklistAdmin(address token, address account) internal {
_blocklistAdmins[token].add(account);
emit BlocklistAdminAdded(token, account);
}
function _removeBlocklistAdmin(address token, address account) internal {
_blocklistAdmins[token].remove(account);
emit BlocklistAdminRemoved(token, account);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title BlocklistedRole
* @dev Blocklisted accounts have been forbidden by a BlocklistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are BlocklistAdmins (who can also remove
* it), and not Blocklisteds themselves.
*/
contract BlocklistedRole is BlocklistAdminRole {
using Roles for Roles.Role;
event BlocklistedAdded(address indexed token, address indexed account);
event BlocklistedRemoved(address indexed token, address indexed account);
// Mapping from token to token blocklisteds.
mapping(address => Roles.Role) private _blocklisteds;
modifier onlyNotBlocklisted(address token) {
require(!isBlocklisted(token, msg.sender));
_;
}
function isBlocklisted(address token, address account) public view returns (bool) {
return _blocklisteds[token].has(account);
}
function addBlocklisted(address token, address account) public onlyBlocklistAdmin(token) {
_addBlocklisted(token, account);
}
function removeBlocklisted(address token, address account) public onlyBlocklistAdmin(token) {
_removeBlocklisted(token, account);
}
function _addBlocklisted(address token, address account) internal {
_blocklisteds[token].add(account);
emit BlocklistedAdded(token, account);
}
function _removeBlocklisted(address token, address account) internal {
_blocklisteds[token].remove(account);
emit BlocklistedRemoved(token, account);
}
}
contract ERC1820Registry {
function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external;
function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address);
function setManager(address _addr, address _newManager) external;
function getManager(address _addr) public view returns (address);
}
/// Base client to interact with the registry.
contract ERC1820Client {
ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal {
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
ERC1820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation);
}
function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) {
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash);
}
function delegateManagement(address _newManager) internal {
ERC1820REGISTRY.setManager(address(this), _newManager);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
contract ERC1820Implementer {
bytes32 constant ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC"));
mapping(bytes32 => bool) internal _interfaceHashes;
function canImplementInterfaceForAddress(bytes32 interfaceHash, address /*addr*/) // Comments to avoid compilation warnings for unused variables.
external
view
returns(bytes32)
{
if(_interfaceHashes[interfaceHash]) {
return ERC1820_ACCEPT_MAGIC;
} else {
return "";
}
}
function _setInterface(string memory interfaceLabel) internal {
_interfaceHashes[keccak256(abi.encodePacked(interfaceLabel))] = true;
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400 security token standard
* @dev See https://github.com/SecurityTokenStandard/EIP-Spec/blob/master/eip/eip-1400.md
*/
interface IERC1400 /*is IERC20*/ { // Interfaces can currently not inherit interfaces, but IERC1400 shall include IERC20
// ****************** Document Management *******************
function getDocument(bytes32 name) external view returns (string memory, bytes32);
function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external;
// ******************* Token Information ********************
function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256);
function partitionsOf(address tokenHolder) external view returns (bytes32[] memory);
// *********************** Transfers ************************
function transferWithData(address to, uint256 value, bytes calldata data) external;
function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external;
// *************** Partition Token Transfers ****************
function transferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external returns (bytes32);
function operatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external returns (bytes32);
// ****************** Controller Operation ******************
function isControllable() external view returns (bool);
// function controllerTransfer(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorTransferByPartition"
// function controllerRedeem(address tokenHolder, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorRedeemByPartition"
// ****************** Operator Management *******************
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function authorizeOperatorByPartition(bytes32 partition, address operator) external;
function revokeOperatorByPartition(bytes32 partition, address operator) external;
// ****************** Operator Information ******************
function isOperator(address operator, address tokenHolder) external view returns (bool);
function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool);
// ********************* Token Issuance *********************
function isIssuable() external view returns (bool);
function issue(address tokenHolder, uint256 value, bytes calldata data) external;
function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external;
// ******************** Token Redemption ********************
function redeem(uint256 value, bytes calldata data) external;
function redeemFrom(address tokenHolder, uint256 value, bytes calldata data) external;
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external;
function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external;
// ******************* Transfer Validity ********************
// We use different transfer validity functions because those described in the interface don't allow to verify the certificate's validity.
// Indeed, verifying the ecrtificate's validity requires to keeps the function's arguments in the exact same order as the transfer function.
//
// function canTransfer(address to, uint256 value, bytes calldata data) external view returns (byte, bytes32);
// function canTransferFrom(address from, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32);
// function canTransferByPartition(address from, address to, bytes32 partition, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32);
// ******************* Controller Events ********************
// We don't use this event as we don't use "controllerTransfer"
// event ControllerTransfer(
// address controller,
// address indexed from,
// address indexed to,
// uint256 value,
// bytes data,
// bytes operatorData
// );
//
// We don't use this event as we don't use "controllerRedeem"
// event ControllerRedemption(
// address controller,
// address indexed tokenHolder,
// uint256 value,
// bytes data,
// bytes operatorData
// );
// ******************** Document Events *********************
event Document(bytes32 indexed name, string uri, bytes32 documentHash);
// ******************** Transfer Events *********************
event TransferByPartition(
bytes32 indexed fromPartition,
address operator,
address indexed from,
address indexed to,
uint256 value,
bytes data,
bytes operatorData
);
event ChangedPartition(
bytes32 indexed fromPartition,
bytes32 indexed toPartition,
uint256 value
);
// ******************** Operator Events *********************
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
event AuthorizedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder);
event RevokedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder);
// ************** Issuance / Redemption Events **************
event Issued(address indexed operator, address indexed to, uint256 value, bytes data);
event Redeemed(address indexed operator, address indexed from, uint256 value, bytes data);
event IssuedByPartition(bytes32 indexed partition, address indexed operator, address indexed to, uint256 value, bytes data, bytes operatorData);
event RedeemedByPartition(bytes32 indexed partition, address indexed operator, address indexed from, uint256 value, bytes operatorData);
}
/**
* Reason codes - ERC-1066
*
* To improve the token holder experience, canTransfer MUST return a reason byte code
* on success or failure based on the ERC-1066 application-specific status codes specified below.
* An implementation can also return arbitrary data as a bytes32 to provide additional
* information not captured by the reason code.
*
* Code Reason
* 0x50 transfer failure
* 0x51 transfer success
* 0x52 insufficient balance
* 0x53 insufficient allowance
* 0x54 transfers halted (contract paused)
* 0x55 funds locked (lockup period)
* 0x56 invalid sender
* 0x57 invalid receiver
* 0x58 invalid operator (transfer agent)
* 0x59
* 0x5a
* 0x5b
* 0x5a
* 0x5b
* 0x5c
* 0x5d
* 0x5e
* 0x5f token meta or info
*
* These codes are being discussed at: https://ethereum-magicians.org/t/erc-1066-ethereum-status-codes-esc/283/24
*/
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensValidator
* @dev ERC1400TokensValidator interface
*/
interface IERC1400TokensValidator {
function canValidate(
address token,
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external view returns(bool);
function tokensToValidate(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @notice Interface to the Minterrole contract
*/
interface IMinterRole {
function isMinter(address account) external view returns (bool);
}
contract ERC1400TokensValidator is IERC1400TokensValidator, Pausable, AllowlistedRole, BlocklistedRole, ERC1820Client, ERC1820Implementer {
using SafeMath for uint256;
string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
bytes4 constant internal ERC20_TRANSFER_FUNCTION_ID = bytes4(keccak256("transfer(address,uint256)"));
bytes4 constant internal ERC20_TRANSFERFROM_FUNCTION_ID = bytes4(keccak256("transferFrom(address,address,uint256)"));
// Mapping from token to allowlist activation status.
mapping(address => bool) internal _allowlistActivated;
// Mapping from token to blocklist activation status.
mapping(address => bool) internal _blocklistActivated;
// Mapping from token to partition granularity activation status.
mapping(address => bool) internal _granularityByPartitionActivated;
// Mapping from token to holds activation status.
mapping(address => bool) internal _holdsActivated;
// Mapping from token to self-holds activation status.
mapping(address => bool) internal _selfHoldsActivated;
// Mapping from token to token controllers.
mapping(address => address[]) internal _tokenControllers;
// Mapping from (token, operator) to token controller status.
mapping(address => mapping(address => bool)) internal _isTokenController;
enum HoldStatusCode {
Nonexistent,
Ordered,
Executed,
ExecutedAndKeptOpen,
ReleasedByNotary,
ReleasedByPayee,
ReleasedOnExpiration
}
struct Hold {
bytes32 partition;
address sender;
address recipient;
address notary;
uint256 value;
uint256 expiration;
bytes32 secretHash;
bytes32 secret;
HoldStatusCode status;
}
// Mapping from (token, partition) to partition granularity.
mapping(address => mapping(bytes32 => uint256)) internal _granularityByPartition;
// Mapping from (token, holdId) to hold.
mapping(address => mapping(bytes32 => Hold)) internal _holds;
// Mapping from (token, tokenHolder) to balance on hold.
mapping(address => mapping(address => uint256)) internal _heldBalance;
// Mapping from (token, tokenHolder, partition) to balance on hold of corresponding partition.
mapping(address => mapping(address => mapping(bytes32 => uint256))) internal _heldBalanceByPartition;
// Mapping from (token, partition) to global balance on hold of corresponding partition.
mapping(address => mapping(bytes32 => uint256)) internal _totalHeldBalanceByPartition;
// Total balance on hold.
mapping(address => uint256) internal _totalHeldBalance;
// Mapping from hold parameter's hash to hold's nonce.
mapping(bytes32 => uint256) internal _hashNonce;
// Mapping from (hash, nonce) to hold ID.
mapping(bytes32 => mapping(uint256 => bytes32)) internal _holdIds;
event HoldCreated(
address indexed token,
bytes32 indexed holdId,
bytes32 partition,
address sender,
address recipient,
address indexed notary,
uint256 value,
uint256 expiration,
bytes32 secretHash
);
event HoldReleased(address indexed token, bytes32 holdId, address indexed notary, HoldStatusCode status);
event HoldRenewed(address indexed token, bytes32 holdId, address indexed notary, uint256 oldExpiration, uint256 newExpiration);
event HoldExecuted(address indexed token, bytes32 holdId, address indexed notary, uint256 heldValue, uint256 transferredValue, bytes32 secret);
event HoldExecutedAndKeptOpen(address indexed token, bytes32 holdId, address indexed notary, uint256 heldValue, uint256 transferredValue, bytes32 secret);
/**
* @dev Modifier to verify if sender is a token controller.
*/
modifier onlyTokenController(address token) {
require(
msg.sender == token ||
msg.sender == Ownable(token).owner() ||
_isTokenController[token][msg.sender],
"Sender is not a token controller."
);
_;
}
/**
* @dev Modifier to verify if sender is a pauser.
*/
modifier onlyPauser(address token) {
require(
msg.sender == Ownable(token).owner() ||
_isTokenController[token][msg.sender] ||
isPauser(token, msg.sender),
"Sender is not a pauser"
);
_;
}
/**
* @dev Modifier to verify if sender is an allowlist admin.
*/
modifier onlyAllowlistAdmin(address token) {
require(
msg.sender == Ownable(token).owner() ||
_isTokenController[token][msg.sender] ||
isAllowlistAdmin(token, msg.sender),
"Sender is not an allowlist admin"
);
_;
}
/**
* @dev Modifier to verify if sender is a blocklist admin.
*/
modifier onlyBlocklistAdmin(address token) {
require(
msg.sender == Ownable(token).owner() ||
_isTokenController[token][msg.sender] ||
isBlocklistAdmin(token, msg.sender),
"Sender is not a blocklist admin"
);
_;
}
constructor() public {
ERC1820Implementer._setInterface(ERC1400_TOKENS_VALIDATOR);
}
/**
* @dev Get the list of token controllers for a given token.
* @return Setup of a given token.
*/
function retrieveTokenSetup(address token) external view returns (bool, bool, bool, bool, bool, address[] memory) {
return (
_allowlistActivated[token],
_blocklistActivated[token],
_granularityByPartitionActivated[token],
_holdsActivated[token],
_selfHoldsActivated[token],
_tokenControllers[token]
);
}
/**
* @dev Register token setup.
*/
function registerTokenSetup(
address token,
bool allowlistActivated,
bool blocklistActivated,
bool granularityByPartitionActivated,
bool holdsActivated,
bool selfHoldsActivated,
address[] calldata operators
) external onlyTokenController(token) {
_allowlistActivated[token] = allowlistActivated;
_blocklistActivated[token] = blocklistActivated;
_granularityByPartitionActivated[token] = granularityByPartitionActivated;
_holdsActivated[token] = holdsActivated;
_selfHoldsActivated[token] = selfHoldsActivated;
_setTokenControllers(token, operators);
}
/**
* @dev Set list of token controllers for a given token.
* @param token Token address.
* @param operators Operators addresses.
*/
function _setTokenControllers(address token, address[] memory operators) internal {
for (uint i = 0; i<_tokenControllers[token].length; i++){
_isTokenController[token][_tokenControllers[token][i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isTokenController[token][operators[j]] = true;
}
_tokenControllers[token] = operators;
}
/**
* @dev Verify if a token transfer can be executed or not, on the validator's perspective.
* @param token Address of the token.
* @param functionSig ID of the function that is called.
* @param partition Name of the partition (left empty for ERC20 transfer).
* @param operator Address which triggered the balance decrease (through transfer or redemption).
* @param from Token holder.
* @param to Token recipient for a transfer and 0x for a redemption.
* @param value Number of tokens the token holder balance is decreased by.
* @param data Extra information.
* @param operatorData Extra information, attached by the operator (if any).
* @return 'true' if the token transfer can be validated, 'false' if not.
*/
function canValidate(
address token,
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) // Comments to avoid compilation warnings for unused variables.
external
view
returns(bool)
{
(bool canValidateToken,) = _canValidate(token, functionSig, partition, operator, from, to, value, data, operatorData);
return canValidateToken;
}
/**
* @dev Function called by the token contract before executing a transfer.
* @param functionSig ID of the function that is called.
* @param partition Name of the partition (left empty for ERC20 transfer).
* @param operator Address which triggered the balance decrease (through transfer or redemption).
* @param from Token holder.
* @param to Token recipient for a transfer and 0x for a redemption.
* @param value Number of tokens the token holder balance is decreased by.
* @param data Extra information.
* @param operatorData Extra information, attached by the operator (if any).
* @return 'true' if the token transfer can be validated, 'false' if not.
*/
function tokensToValidate(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) // Comments to avoid compilation warnings for unused variables.
external
{
(bool canValidateToken, bytes32 holdId) = _canValidate(msg.sender, functionSig, partition, operator, from, to, value, data, operatorData);
require(canValidateToken, "55"); // 0x55 funds locked (lockup period)
if (_holdsActivated[msg.sender] && holdId != "") {
Hold storage executableHold = _holds[msg.sender][holdId];
_setHoldToExecuted(
msg.sender,
executableHold,
holdId,
value,
executableHold.value,
""
);
}
}
/**
* @dev Verify if a token transfer can be executed or not, on the validator's perspective.
* @return 'true' if the token transfer can be validated, 'false' if not.
* @return hold ID in case a hold can be executed for the given parameters.
*/
function _canValidate(
address token,
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes memory /*data*/,
bytes memory /*operatorData*/
) // Comments to avoid compilation warnings for unused variables.
internal
view
whenNotPaused(token)
returns(bool, bytes32)
{
if(_functionRequiresValidation(functionSig)) {
if(_allowlistActivated[token]) {
if(!isAllowlisted(token, from) || !isAllowlisted(token, to)) {
return (false, "");
}
}
if(_blocklistActivated[token]) {
if(isBlocklisted(token, from) || isBlocklisted(token, to)) {
return (false, "");
}
}
}
if(_granularityByPartitionActivated[token]) {
if(
_granularityByPartition[token][partition] > 0 &&
!_isMultiple(_granularityByPartition[token][partition], value)
) {
return (false, "");
}
}
if (_holdsActivated[token]) {
if(functionSig == ERC20_TRANSFERFROM_FUNCTION_ID) {
(,, bytes32 holdId) = _retrieveHoldHashNonceId(token, partition, operator, from, to, value);
Hold storage hold = _holds[token][holdId];
if (_holdCanBeExecutedAsNotary(hold, operator, value) && value <= IERC1400(token).balanceOfByPartition(partition, from)) {
return (true, holdId);
}
}
if(value > _spendableBalanceOfByPartition(token, partition, from)) {
return (false, "");
}
}
return (true, "");
}
/**
* @dev Get granularity for a given partition.
* @param token Address of the token.
* @param partition Name of the partition.
* @return Granularity of the partition.
*/
function granularityByPartition(address token, bytes32 partition) external view returns (uint256) {
return _granularityByPartition[token][partition];
}
/**
* @dev Set partition granularity
*/
function setGranularityByPartition(
address token,
bytes32 partition,
uint256 granularity
)
external
onlyTokenController(token)
{
_granularityByPartition[token][partition] = granularity;
}
/**
* @dev Create a new token pre-hold.
*/
function preHoldFor(
address token,
bytes32 holdId,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 timeToExpiration,
bytes32 secretHash
)
external
returns (bool)
{
return _createHold(
token,
holdId,
address(0),
recipient,
notary,
partition,
value,
_computeExpiration(timeToExpiration),
secretHash
);
}
/**
* @dev Create a new token pre-hold with expiration date.
*/
function preHoldForWithExpirationDate(
address token,
bytes32 holdId,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 expiration,
bytes32 secretHash
)
external
returns (bool)
{
_checkExpiration(expiration);
return _createHold(
token,
holdId,
address(0),
recipient,
notary,
partition,
value,
expiration,
secretHash
);
}
/**
* @dev Create a new token hold.
*/
function hold(
address token,
bytes32 holdId,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 timeToExpiration,
bytes32 secretHash
)
external
returns (bool)
{
return _createHold(
token,
holdId,
msg.sender,
recipient,
notary,
partition,
value,
_computeExpiration(timeToExpiration),
secretHash
);
}
/**
* @dev Create a new token hold on behalf of the token holder.
*/
function holdFrom(
address token,
bytes32 holdId,
address sender,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 timeToExpiration,
bytes32 secretHash
)
external
returns (bool)
{
require(sender != address(0), "Payer address must not be zero address");
return _createHold(
token,
holdId,
sender,
recipient,
notary,
partition,
value,
_computeExpiration(timeToExpiration),
secretHash
);
}
/**
* @dev Create a new token hold with expiration date.
*/
function holdWithExpirationDate(
address token,
bytes32 holdId,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 expiration,
bytes32 secretHash
)
external
returns (bool)
{
_checkExpiration(expiration);
return _createHold(
token,
holdId,
msg.sender,
recipient,
notary,
partition,
value,
expiration,
secretHash
);
}
/**
* @dev Create a new token hold with expiration date on behalf of the token holder.
*/
function holdFromWithExpirationDate(
address token,
bytes32 holdId,
address sender,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 expiration,
bytes32 secretHash
)
external
returns (bool)
{
_checkExpiration(expiration);
require(sender != address(0), "Payer address must not be zero address");
return _createHold(
token,
holdId,
sender,
recipient,
notary,
partition,
value,
expiration,
secretHash
);
}
/**
* @dev Create a new token hold.
*/
function _createHold(
address token,
bytes32 holdId,
address sender,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 expiration,
bytes32 secretHash
) internal returns (bool)
{
Hold storage newHold = _holds[token][holdId];
require(recipient != address(0), "Payee address must not be zero address");
require(value != 0, "Value must be greater than zero");
require(newHold.value == 0, "This holdId already exists");
require(notary != address(0), "Notary address must not be zero address");
if (sender == address(0)) { // pre-hold (tokens do not already exist)
require(
_canPreHold(token, msg.sender),
"The pre-hold can only be created by the minter"
);
} else { // post-hold (tokens already exist)
require(value <= _spendableBalanceOfByPartition(token, partition, sender), "Amount of the hold can't be greater than the spendable balance of the sender");
require(
_canPostHold(token, partition, msg.sender, sender),
"The hold can only be renewed by the issuer or the payer"
);
}
newHold.partition = partition;
newHold.sender = sender;
newHold.recipient = recipient;
newHold.notary = notary;
newHold.value = value;
newHold.expiration = expiration;
newHold.secretHash = secretHash;
newHold.status = HoldStatusCode.Ordered;
if(sender != address(0)) {
// In case tokens already exist, increase held balance
_increaseHeldBalance(token, newHold, holdId);
}
emit HoldCreated(
token,
holdId,
partition,
sender,
recipient,
notary,
value,
expiration,
secretHash
);
return true;
}
/**
* @dev Release token hold.
*/
function releaseHold(address token, bytes32 holdId) external returns (bool) {
return _releaseHold(token, holdId);
}
/**
* @dev Release token hold.
*/
function _releaseHold(address token, bytes32 holdId) internal returns (bool) {
Hold storage releasableHold = _holds[token][holdId];
require(
releasableHold.status == HoldStatusCode.Ordered || releasableHold.status == HoldStatusCode.ExecutedAndKeptOpen,
"A hold can only be released in status Ordered or ExecutedAndKeptOpen"
);
require(
_isExpired(releasableHold.expiration) ||
(msg.sender == releasableHold.notary) ||
(msg.sender == releasableHold.recipient),
"A not expired hold can only be released by the notary or the payee"
);
if (_isExpired(releasableHold.expiration)) {
releasableHold.status = HoldStatusCode.ReleasedOnExpiration;
} else {
if (releasableHold.notary == msg.sender) {
releasableHold.status = HoldStatusCode.ReleasedByNotary;
} else {
releasableHold.status = HoldStatusCode.ReleasedByPayee;
}
}
if(releasableHold.sender != address(0)) { // In case tokens already exist, decrease held balance
_decreaseHeldBalance(token, releasableHold, releasableHold.value);
}
emit HoldReleased(token, holdId, releasableHold.notary, releasableHold.status);
return true;
}
/**
* @dev Renew hold.
*/
function renewHold(address token, bytes32 holdId, uint256 timeToExpiration) external returns (bool) {
return _renewHold(token, holdId, _computeExpiration(timeToExpiration));
}
/**
* @dev Renew hold with expiration time.
*/
function renewHoldWithExpirationDate(address token, bytes32 holdId, uint256 expiration) external returns (bool) {
_checkExpiration(expiration);
return _renewHold(token, holdId, expiration);
}
/**
* @dev Renew hold.
*/
function _renewHold(address token, bytes32 holdId, uint256 expiration) internal returns (bool) {
Hold storage renewableHold = _holds[token][holdId];
require(
renewableHold.status == HoldStatusCode.Ordered
|| renewableHold.status == HoldStatusCode.ExecutedAndKeptOpen,
"A hold can only be renewed in status Ordered or ExecutedAndKeptOpen"
);
require(!_isExpired(renewableHold.expiration), "An expired hold can not be renewed");
if (renewableHold.sender == address(0)) { // pre-hold (tokens do not already exist)
require(
_canPreHold(token, msg.sender),
"The pre-hold can only be renewed by the minter"
);
} else { // post-hold (tokens already exist)
require(
_canPostHold(token, renewableHold.partition, msg.sender, renewableHold.sender),
"The hold can only be renewed by the issuer or the payer"
);
}
uint256 oldExpiration = renewableHold.expiration;
renewableHold.expiration = expiration;
emit HoldRenewed(
token,
holdId,
renewableHold.notary,
oldExpiration,
expiration
);
return true;
}
/**
* @dev Execute hold.
*/
function executeHold(address token, bytes32 holdId, uint256 value, bytes32 secret) external returns (bool) {
return _executeHold(
token,
holdId,
msg.sender,
value,
secret,
false
);
}
/**
* @dev Execute hold and keep open.
*/
function executeHoldAndKeepOpen(address token, bytes32 holdId, uint256 value, bytes32 secret) external returns (bool) {
return _executeHold(
token,
holdId,
msg.sender,
value,
secret,
true
);
}
/**
* @dev Execute hold.
*/
function _executeHold(
address token,
bytes32 holdId,
address operator,
uint256 value,
bytes32 secret,
bool keepOpenIfHoldHasBalance
) internal returns (bool)
{
Hold storage executableHold = _holds[token][holdId];
bool canExecuteHold;
if(secret != "" && _holdCanBeExecutedAsSecretHolder(executableHold, value, secret)) {
executableHold.secret = secret;
canExecuteHold = true;
} else if(_holdCanBeExecutedAsNotary(executableHold, operator, value)) {
canExecuteHold = true;
}
if(canExecuteHold) {
if (keepOpenIfHoldHasBalance && ((executableHold.value - value) > 0)) {
_setHoldToExecutedAndKeptOpen(
token,
executableHold,
holdId,
value,
value,
secret
);
} else {
_setHoldToExecuted(
token,
executableHold,
holdId,
value,
executableHold.value,
secret
);
}
if (executableHold.sender == address(0)) { // pre-hold (tokens do not already exist)
IERC1400(token).issueByPartition(executableHold.partition, executableHold.recipient, value, "");
} else { // post-hold (tokens already exist)
IERC1400(token).operatorTransferByPartition(executableHold.partition, executableHold.sender, executableHold.recipient, value, "", "");
}
} else {
revert("hold can not be executed");
}
}
/**
* @dev Set hold to executed.
*/
function _setHoldToExecuted(
address token,
Hold storage executableHold,
bytes32 holdId,
uint256 value,
uint256 heldBalanceDecrease,
bytes32 secret
) internal
{
if(executableHold.sender != address(0)) { // In case tokens already exist, decrease held balance
_decreaseHeldBalance(token, executableHold, heldBalanceDecrease);
}
executableHold.status = HoldStatusCode.Executed;
emit HoldExecuted(
token,
holdId,
executableHold.notary,
executableHold.value,
value,
secret
);
}
/**
* @dev Set hold to executed and kept open.
*/
function _setHoldToExecutedAndKeptOpen(
address token,
Hold storage executableHold,
bytes32 holdId,
uint256 value,
uint256 heldBalanceDecrease,
bytes32 secret
) internal
{
if(executableHold.sender != address(0)) { // In case tokens already exist, decrease held balance
_decreaseHeldBalance(token, executableHold, heldBalanceDecrease);
}
executableHold.status = HoldStatusCode.ExecutedAndKeptOpen;
executableHold.value = executableHold.value.sub(value);
emit HoldExecutedAndKeptOpen(
token,
holdId,
executableHold.notary,
executableHold.value,
value,
secret
);
}
/**
* @dev Increase held balance.
*/
function _increaseHeldBalance(address token, Hold storage executableHold, bytes32 holdId) private {
_heldBalance[token][executableHold.sender] = _heldBalance[token][executableHold.sender].add(executableHold.value);
_totalHeldBalance[token] = _totalHeldBalance[token].add(executableHold.value);
_heldBalanceByPartition[token][executableHold.sender][executableHold.partition] = _heldBalanceByPartition[token][executableHold.sender][executableHold.partition].add(executableHold.value);
_totalHeldBalanceByPartition[token][executableHold.partition] = _totalHeldBalanceByPartition[token][executableHold.partition].add(executableHold.value);
_increaseNonce(token, executableHold, holdId);
}
/**
* @dev Decrease held balance.
*/
function _decreaseHeldBalance(address token, Hold storage executableHold, uint256 value) private {
_heldBalance[token][executableHold.sender] = _heldBalance[token][executableHold.sender].sub(value);
_totalHeldBalance[token] = _totalHeldBalance[token].sub(value);
_heldBalanceByPartition[token][executableHold.sender][executableHold.partition] = _heldBalanceByPartition[token][executableHold.sender][executableHold.partition].sub(value);
_totalHeldBalanceByPartition[token][executableHold.partition] = _totalHeldBalanceByPartition[token][executableHold.partition].sub(value);
if(executableHold.status == HoldStatusCode.Ordered) {
_decreaseNonce(token, executableHold);
}
}
/**
* @dev Increase nonce.
*/
function _increaseNonce(address token, Hold storage executableHold, bytes32 holdId) private {
(bytes32 holdHash, uint256 nonce,) = _retrieveHoldHashNonceId(
token, executableHold.partition,
executableHold.notary,
executableHold.sender,
executableHold.recipient,
executableHold.value
);
_hashNonce[holdHash] = nonce.add(1);
_holdIds[holdHash][nonce.add(1)] = holdId;
}
/**
* @dev Decrease nonce.
*/
function _decreaseNonce(address token, Hold storage executableHold) private {
(bytes32 holdHash, uint256 nonce,) = _retrieveHoldHashNonceId(
token,
executableHold.partition,
executableHold.notary,
executableHold.sender,
executableHold.recipient,
executableHold.value
);
_holdIds[holdHash][nonce] = "";
_hashNonce[holdHash] = _hashNonce[holdHash].sub(1);
}
/**
* @dev Check secret.
*/
function _checkSecret(Hold storage executableHold, bytes32 secret) internal view returns (bool) {
if(executableHold.secretHash == sha256(abi.encodePacked(secret))) {
return true;
} else {
return false;
}
}
/**
* @dev Compute expiration time.
*/
function _computeExpiration(uint256 timeToExpiration) internal view returns (uint256) {
uint256 expiration = 0;
if (timeToExpiration != 0) {
expiration = now.add(timeToExpiration);
}
return expiration;
}
/**
* @dev Check expiration time.
*/
function _checkExpiration(uint256 expiration) private view {
require(expiration > now || expiration == 0, "Expiration date must be greater than block timestamp or zero");
}
/**
* @dev Check is expiration date is past.
*/
function _isExpired(uint256 expiration) internal view returns (bool) {
return expiration != 0 && (now >= expiration);
}
/**
* @dev Retrieve hold hash, nonce, and ID for given parameters
*/
function _retrieveHoldHashNonceId(address token, bytes32 partition, address notary, address sender, address recipient, uint value) internal view returns (bytes32, uint256, bytes32) {
// Pack and hash hold parameters
bytes32 holdHash = keccak256(abi.encodePacked(
token,
partition,
sender,
recipient,
notary,
value
));
uint256 nonce = _hashNonce[holdHash];
bytes32 holdId = _holdIds[holdHash][nonce];
return (holdHash, nonce, holdId);
}
/**
* @dev Check if hold can be executed
*/
function _holdCanBeExecuted(Hold storage executableHold, uint value) internal view returns (bool) {
if(!(executableHold.status == HoldStatusCode.Ordered || executableHold.status == HoldStatusCode.ExecutedAndKeptOpen)) {
return false; // A hold can only be executed in status Ordered or ExecutedAndKeptOpen
} else if(value == 0) {
return false; // Value must be greater than zero
} else if(_isExpired(executableHold.expiration)) {
return false; // The hold has already expired
} else if(value > executableHold.value) {
return false; // The value should be equal or less than the held amount
} else {
return true;
}
}
/**
* @dev Check if hold can be executed as secret holder
*/
function _holdCanBeExecutedAsSecretHolder(Hold storage executableHold, uint value, bytes32 secret) internal view returns (bool) {
if(
_checkSecret(executableHold, secret)
&& _holdCanBeExecuted(executableHold, value)) {
return true;
} else {
return false;
}
}
/**
* @dev Check if hold can be executed as notary
*/
function _holdCanBeExecutedAsNotary(Hold storage executableHold, address operator, uint value) internal view returns (bool) {
if(
executableHold.notary == operator
&& _holdCanBeExecuted(executableHold, value)) {
return true;
} else {
return false;
}
}
/**
* @dev Retrieve hold data.
*/
function retrieveHoldData(address token, bytes32 holdId) external view returns (
bytes32 partition,
address sender,
address recipient,
address notary,
uint256 value,
uint256 expiration,
bytes32 secretHash,
bytes32 secret,
HoldStatusCode status)
{
Hold storage retrievedHold = _holds[token][holdId];
return (
retrievedHold.partition,
retrievedHold.sender,
retrievedHold.recipient,
retrievedHold.notary,
retrievedHold.value,
retrievedHold.expiration,
retrievedHold.secretHash,
retrievedHold.secret,
retrievedHold.status
);
}
/**
* @dev Total supply on hold.
*/
function totalSupplyOnHold(address token) external view returns (uint256) {
return _totalHeldBalance[token];
}
/**
* @dev Total supply on hold for a specific partition.
*/
function totalSupplyOnHoldByPartition(address token, bytes32 partition) external view returns (uint256) {
return _totalHeldBalanceByPartition[token][partition];
}
/**
* @dev Get balance on hold of a tokenholder.
*/
function balanceOnHold(address token, address account) external view returns (uint256) {
return _heldBalance[token][account];
}
/**
* @dev Get balance on hold of a tokenholder for a specific partition.
*/
function balanceOnHoldByPartition(address token, bytes32 partition, address account) external view returns (uint256) {
return _heldBalanceByPartition[token][account][partition];
}
/**
* @dev Get spendable balance of a tokenholder.
*/
function spendableBalanceOf(address token, address account) external view returns (uint256) {
return _spendableBalanceOf(token, account);
}
/**
* @dev Get spendable balance of a tokenholder for a specific partition.
*/
function spendableBalanceOfByPartition(address token, bytes32 partition, address account) external view returns (uint256) {
return _spendableBalanceOfByPartition(token, partition, account);
}
/**
* @dev Get spendable balance of a tokenholder.
*/
function _spendableBalanceOf(address token, address account) internal view returns (uint256) {
return IERC20(token).balanceOf(account) - _heldBalance[token][account];
}
/**
* @dev Get spendable balance of a tokenholder for a specific partition.
*/
function _spendableBalanceOfByPartition(address token, bytes32 partition, address account) internal view returns (uint256) {
return IERC1400(token).balanceOfByPartition(partition, account) - _heldBalanceByPartition[token][account][partition];
}
/************************** TOKEN CONTROLLERS *******************************/
/**
* @dev Check if operator can create pre-holds.
* @return 'true' if the operator can create pre-holds, 'false' if not.
*/
function _canPreHold(address token, address operator) internal view returns(bool) {
return IMinterRole(token).isMinter(operator);
}
/**
* @dev Check if operator can create/update holds.
* @return 'true' if the operator can create/update holds, 'false' if not.
*/
function _canPostHold(address token, bytes32 partition, address operator, address sender) internal view returns(bool) {
if (_selfHoldsActivated[token]) {
return IERC1400(token).isOperatorForPartition(partition, operator, sender);
} else {
return _isTokenController[token][operator];
}
}
/**
* @dev Check if validator is activated for the function called in the smart contract.
* @param functionSig ID of the function that is called.
* @return 'true' if the function requires validation, 'false' if not.
*/
function _functionRequiresValidation(bytes4 functionSig) internal pure returns(bool) {
if(_areEqual(functionSig, ERC20_TRANSFER_FUNCTION_ID) || _areEqual(functionSig, ERC20_TRANSFERFROM_FUNCTION_ID)) {
return true;
} else {
return false;
}
}
/**
* @dev Check if 2 variables of type bytes4 are identical.
* @return 'true' if 2 variables are identical, 'false' if not.
*/
function _areEqual(bytes4 a, bytes4 b) internal pure returns(bool) {
for (uint256 i = 0; i < a.length; i++) {
if(a[i] != b[i]) {
return false;
}
}
return true;
}
/**
* @dev Check if 'value' is multiple of 'granularity'.
* @param granularity The granularity that want's to be checked.
* @param value The quantity that want's to be checked.
* @return 'true' if 'value' is a multiple of 'granularity'.
*/
function _isMultiple(uint256 granularity, uint256 value) internal pure returns(bool) {
return(value.div(granularity).mul(granularity) == value);
}
} | Decrease held balance./ | function _decreaseHeldBalance(address token, Hold storage executableHold, uint256 value) private {
_heldBalance[token][executableHold.sender] = _heldBalance[token][executableHold.sender].sub(value);
_totalHeldBalance[token] = _totalHeldBalance[token].sub(value);
_heldBalanceByPartition[token][executableHold.sender][executableHold.partition] = _heldBalanceByPartition[token][executableHold.sender][executableHold.partition].sub(value);
_totalHeldBalanceByPartition[token][executableHold.partition] = _totalHeldBalanceByPartition[token][executableHold.partition].sub(value);
function _setHoldToExecuted(
address token,
Hold storage executableHold,
bytes32 holdId,
uint256 value,
uint256 heldBalanceDecrease,
bytes32 secret
) internal
}
executableHold.status = HoldStatusCode.Executed;
emit HoldExecuted(
token,
holdId,
executableHold.notary,
executableHold.value,
value,
secret
);
}
function _setHoldToExecutedAndKeptOpen(
address token,
Hold storage executableHold,
bytes32 holdId,
uint256 value,
uint256 heldBalanceDecrease,
bytes32 secret
) internal
}
executableHold.status = HoldStatusCode.ExecutedAndKeptOpen;
executableHold.value = executableHold.value.sub(value);
emit HoldExecutedAndKeptOpen(
token,
holdId,
executableHold.notary,
executableHold.value,
value,
secret
);
}
}
if(executableHold.status == HoldStatusCode.Ordered) {
_decreaseNonce(token, executableHold);
}
}
| 1,722,074 |
./partial_match/1/0x373ae78a14577682591E088F2E78EF1417612c68/sources/contracts/HomoraBank.sol | Return the borrow balance for given positon and token without trigger interest accrual. positionId The position to query for borrow balance. token The token to query for borrow balance. | function borrowBalanceStored(uint positionId, address token) public view override returns (uint) {
uint totalDebt = banks[token].totalDebt;
uint totalShare = banks[token].totalShare;
uint share = positions[positionId].debtShareOf[token];
if (share == 0 || totalDebt == 0) {
return 0;
return share.mul(totalDebt).div(totalShare);
}
}
| 4,169,084 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: Account
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Storage {
mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
}
// Part: Actions
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
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}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
}
// Part: IAaveIncentivesController
interface IAaveIncentivesController {
/**
* @dev Returns the total of rewards of an user, already accrued + not yet accrued
* @param user The address of the user
* @return The rewards
**/
function getRewardsBalance(address[] calldata assets, address user)
external
view
returns (uint256);
/**
* @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards
* @param amount Amount of rewards to claim
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must
* be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param amount Amount of rewards to claim
* @param user Address to check and claim rewards
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewardsOnBehalf(
address[] calldata assets,
uint256 amount,
address user,
address to
) external returns (uint256);
/**
* @dev returns the unclaimed rewards of the user
* @param user the address of the user
* @return the unclaimed user rewards
*/
function getUserUnclaimedRewards(address user)
external
view
returns (uint256);
/**
* @dev for backward compatibility with previous implementation of the Incentives controller
*/
function REWARD_TOKEN() external view returns (address);
function getDistributionEnd() external view returns (uint256);
function getAssetData(address asset)
external
view
returns (
uint256,
uint256,
uint256
);
}
// Part: ICallee
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
// ============ Public Functions ============
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
// Part: ILendingPoolAddressesProvider
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
// Part: IOptionalERC20
interface IOptionalERC20 {
function decimals() external view returns (uint8);
}
// Part: IPriceOracle
interface IPriceOracle {
function getAssetPrice(address _asset) external view returns (uint256);
function getAssetsPrices(address[] calldata _assets)
external
view
returns (uint256[] memory);
function getSourceOfAsset(address _asset) external view returns (address);
function getFallbackOracle() external view returns (address);
}
// Part: IScaledBalanceToken
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user)
external
view
returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// Part: ISoloMargin
library Decimal {
struct D256 {
uint256 value;
}
}
library Interest {
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
}
library Monetary {
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
}
library Storage {
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
address priceOracle;
// Contract address of the interest setter for this market
address interestSetter;
// Multiplier on the marginRatio for this market
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market
Decimal.D256 spreadPremium;
// Whether additional borrows are allowed for this market
bool isClosing;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
uint64 marginRatioMax;
uint64 liquidationSpreadMax;
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of Solo
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping(uint256 => Market) markets;
// owner => account number => Account
mapping(address => mapping(uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping(address => mapping(address => bool)) operators;
// Addresses that can control all users accounts
mapping(address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
}
interface ISoloMargin {
struct OperatorArg {
address operator1;
bool trusted;
}
function ownerSetSpreadPremium(
uint256 marketId,
Decimal.D256 memory spreadPremium
) external;
function getIsGlobalOperator(address operator1)
external
view
returns (bool);
function getMarketTokenAddress(uint256 marketId)
external
view
returns (address);
function ownerSetInterestSetter(uint256 marketId, address interestSetter)
external;
function getAccountValues(Account.Info memory account)
external
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketPriceOracle(uint256 marketId)
external
view
returns (address);
function getMarketInterestSetter(uint256 marketId)
external
view
returns (address);
function getMarketSpreadPremium(uint256 marketId)
external
view
returns (Decimal.D256 memory);
function getNumMarkets() external view returns (uint256);
function ownerWithdrawUnsupportedTokens(address token, address recipient)
external
returns (uint256);
function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue)
external;
function ownerSetLiquidationSpread(Decimal.D256 memory spread) external;
function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external;
function getIsLocalOperator(address owner, address operator1)
external
view
returns (bool);
function getAccountPar(Account.Info memory account, uint256 marketId)
external
view
returns (Types.Par memory);
function ownerSetMarginPremium(
uint256 marketId,
Decimal.D256 memory marginPremium
) external;
function getMarginRatio() external view returns (Decimal.D256 memory);
function getMarketCurrentIndex(uint256 marketId)
external
view
returns (Interest.Index memory);
function getMarketIsClosing(uint256 marketId) external view returns (bool);
function getRiskParams() external view returns (Storage.RiskParams memory);
function getAccountBalances(Account.Info memory account)
external
view
returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function renounceOwnership() external;
function getMinBorrowedValue()
external
view
returns (Monetary.Value memory);
function setOperators(OperatorArg[] memory args) external;
function getMarketPrice(uint256 marketId) external view returns (address);
function owner() external view returns (address);
function isOwner() external view returns (bool);
function ownerWithdrawExcessTokens(uint256 marketId, address recipient)
external
returns (uint256);
function ownerAddMarket(
address token,
address priceOracle,
address interestSetter,
Decimal.D256 memory marginPremium,
Decimal.D256 memory spreadPremium
) external;
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) external;
function getMarketWithInfo(uint256 marketId)
external
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
function ownerSetMarginRatio(Decimal.D256 memory ratio) external;
function getLiquidationSpread() external view returns (Decimal.D256 memory);
function getAccountWei(Account.Info memory account, uint256 marketId)
external
view
returns (Types.Wei memory);
function getMarketTotalPar(uint256 marketId)
external
view
returns (Types.TotalPar memory);
function getLiquidationSpreadForPair(
uint256 heldMarketId,
uint256 owedMarketId
) external view returns (Decimal.D256 memory);
function getNumExcessTokens(uint256 marketId)
external
view
returns (Types.Wei memory);
function getMarketCachedIndex(uint256 marketId)
external
view
returns (Interest.Index memory);
function getAccountStatus(Account.Info memory account)
external
view
returns (uint8);
function getEarningsRate() external view returns (Decimal.D256 memory);
function ownerSetPriceOracle(uint256 marketId, address priceOracle)
external;
function getRiskLimits() external view returns (Storage.RiskLimits memory);
function getMarket(uint256 marketId)
external
view
returns (Storage.Market memory);
function ownerSetIsClosing(uint256 marketId, bool isClosing) external;
function ownerSetGlobalOperator(address operator1, bool approved) external;
function transferOwnership(address newOwner) external;
function getAdjustedAccountValues(Account.Info memory account)
external
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketMarginPremium(uint256 marketId)
external
view
returns (Decimal.D256 memory);
function getMarketInterestRate(uint256 marketId)
external
view
returns (Interest.Rate memory);
}
// Part: IStakedAave
interface IStakedAave {
function stake(address to, uint256 amount) external;
function redeem(address to, uint256 amount) external;
function cooldown() external;
function claimRewards(address to, uint256 amount) external;
function getTotalRewardsBalance(address) external view returns (uint256);
function COOLDOWN_SECONDS() external view returns (uint256);
function stakersCooldowns(address) external view returns (uint256);
function UNSTAKE_WINDOW() external view returns (uint256);
}
// Part: IUni
interface IUni{
function getAmountsOut(
uint256 amountIn,
address[] calldata path
) external view returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// Part: IUniswapV3SwapCallback
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
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;
}
}
// Part: Types
library Types {
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;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Par {
bool sign; // true if positive
uint128 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
// Part: yearn/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: ILendingPool
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(
address indexed reserve,
address indexed user,
address indexed to,
uint256 amount
);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(
address indexed reserve,
address indexed user
);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(
address indexed reserve,
address indexed user
);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(
address indexed reserve,
address indexed user
);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)
external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(
address reserve,
address rateStrategyAddress
) external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset)
external
view
returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset)
external
view
returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset)
external
view
returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider()
external
view
returns (ILendingPoolAddressesProvider);
function setPause(bool val) external;
function paused() external view returns (bool);
}
// Part: IProtocolDataProvider
interface IProtocolDataProvider {
struct TokenData {
string symbol;
address tokenAddress;
}
function ADDRESSES_PROVIDER()
external
view
returns (ILendingPoolAddressesProvider);
function getAllReservesTokens() external view returns (TokenData[] memory);
function getAllATokens() external view returns (TokenData[] memory);
function getReserveConfigurationData(address asset)
external
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
);
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
function getUserReserveData(address asset, address user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveTokensAddresses(address asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
// Part: ISwapRouter
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params)
external
payable
returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params)
external
payable
returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params)
external
payable
returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params)
external
payable
returns (uint256 amountIn);
}
// Part: IVariableDebtToken
/**
* @title IVariableDebtToken
* @author Aave
* @notice Defines the basic interface for a variable debt token.
**/
interface IVariableDebtToken is IERC20, IScaledBalanceToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(
address indexed from,
address indexed onBehalfOf,
uint256 value,
uint256 index
);
/**
* @dev Mints debt token to the `onBehalfOf` address
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController()
external
view
returns (IAaveIncentivesController);
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @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");
}
}
}
// Part: yearn/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: IInitializableAToken
/**
* @title IInitializableAToken
* @notice Interface for the initialize function on AToken
* @author Aave
**/
interface IInitializableAToken {
/**
* @dev Emitted when an aToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param incentivesController The address of the incentives controller for this aToken
* @param aTokenDecimals the decimals of the underlying
* @param aTokenName the name of the aToken
* @param aTokenSymbol the symbol of the aToken
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
address incentivesController,
uint8 aTokenDecimals,
string aTokenName,
string aTokenSymbol,
bytes params
);
/**
* @dev Initializes the aToken
* @param pool The address of the lending pool where this aToken will be used
* @param treasury The address of the Aave treasury, receiving the fees on this aToken
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param aTokenDecimals The decimals of the aToken, same as the underlying asset's
* @param aTokenName The name of the aToken
* @param aTokenSymbol The symbol of the aToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 aTokenDecimals,
string calldata aTokenName,
string calldata aTokenSymbol,
bytes calldata params
) external;
}
// Part: yearn/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: IAToken
interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` aTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after aTokens are burned
* @param from The owner of the aTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(
address indexed from,
address indexed target,
uint256 value,
uint256 index
);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(
address indexed from,
address indexed to,
uint256 value,
uint256 index
);
/**
* @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the aTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints aTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* @param from The address getting liquidated, current owner of the aTokens
* @param to The recipient
* @param value The amount of tokens getting transferred
**/
function transferOnLiquidation(
address from,
address to,
uint256 value
) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount)
external
returns (uint256);
/**
* @dev Invoked to execute actions on the aToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController()
external
view
returns (IAaveIncentivesController);
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// Part: yearn/[email protected]/BaseStrategyInitializable
abstract contract BaseStrategyInitializable is BaseStrategy {
bool public isOriginal = true;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function clone(address _vault) external returns (address) {
require(isOriginal, "!clone");
return this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
}
// Part: FlashLoanLib
library FlashLoanLib {
using SafeMath for uint256;
event Leverage(
uint256 amountRequested,
uint256 amountGiven,
bool deficit,
address flashLoan
);
address public constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
uint256 private constant collatRatioETH = 0.79 ether;
uint256 private constant COLLAT_RATIO_PRECISION = 1 ether;
address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IAToken public constant aWeth =
IAToken(0x030bA81f1c18d280636F32af80b9AAd02Cf0854e);
IProtocolDataProvider private constant protocolDataProvider =
IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
ILendingPool private constant lendingPool =
ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9);
// Aave's referral code
uint16 private constant referral = 0;
function doDyDxFlashLoan(
bool deficit,
uint256 amountDesired,
address token
) public returns (uint256 amount) {
if (amountDesired == 0) {
return 0;
}
amount = amountDesired;
ISoloMargin solo = ISoloMargin(SOLO);
// calculate amount of ETH we need
uint256 requiredETH;
{
requiredETH = _toETH(amount, token).mul(COLLAT_RATIO_PRECISION).div(
collatRatioETH
);
uint256 dxdyLiquidity = IERC20(weth).balanceOf(address(solo));
if (requiredETH > dxdyLiquidity) {
requiredETH = dxdyLiquidity;
// NOTE: if we cap amountETH, we reduce amountToken we are taking too
amount = _fromETH(requiredETH, token).mul(collatRatioETH).div(
1 ether
);
}
}
// Array of actions to be done during FlashLoan
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
// 1. Take FlashLoan
operations[0] = _getWithdrawAction(0, requiredETH); // hardcoded market ID to 0 (ETH)
// 2. Encode arguments of functions and create action for calling it
bytes memory data = abi.encode(deficit, amount);
// This call will:
// supply ETH to Aave
// borrow desired Token from Aave
// do stuff with Token
// repay desired Token to Aave
// withdraw ETH from Aave
operations[1] = _getCallAction(data);
// 3. Repay FlashLoan
operations[2] = _getDepositAction(0, requiredETH.add(2));
// Create Account Info
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
emit Leverage(amountDesired, requiredETH, deficit, address(solo));
return amount; // we need to return the amount of Token we have changed our position in
}
function loanLogic(
bool deficit,
uint256 amount,
address want
) public {
uint256 wethBal = IERC20(weth).balanceOf(address(this));
ILendingPool lp = lendingPool;
// 1. Deposit WETH in Aave as collateral
lp.deposit(weth, wethBal, address(this), referral);
if (deficit) {
// 2a. if in deficit withdraw amount and repay it
lp.withdraw(want, amount, address(this));
lp.repay(want, amount, 2, address(this));
} else {
// 2b. if levering up borrow and deposit
lp.borrow(want, amount, 2, 0, address(this));
lp.deposit(
want,
IERC20(want).balanceOf(address(this)),
address(this),
referral
);
}
// 3. Withdraw WETH
lp.withdraw(weth, wethBal, address(this));
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint256 marketId, uint256 amount)
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: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data)
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: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount)
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: address(this),
otherAccountId: 0,
data: ""
});
}
function _priceOracle() internal view returns (IPriceOracle) {
return
IPriceOracle(
protocolDataProvider.ADDRESSES_PROVIDER().getPriceOracle()
);
}
function _toETH(uint256 _amount, address asset)
internal
view
returns (uint256)
{
if (
_amount == 0 ||
_amount == type(uint256).max ||
address(asset) == address(weth) // 1:1 change
) {
return _amount;
}
return
_amount.mul(_priceOracle().getAssetPrice(asset)).div(
uint256(10)**uint256(IOptionalERC20(asset).decimals())
);
}
function _fromETH(uint256 _amount, address asset)
internal
view
returns (uint256)
{
if (
_amount == 0 ||
_amount == type(uint256).max ||
address(asset) == address(weth) // 1:1 change
) {
return _amount;
}
return
_amount
.mul(uint256(10)**uint256(IOptionalERC20(asset).decimals()))
.div(_priceOracle().getAssetPrice(asset));
}
}
// File: Strategy.sol
contract Strategy is BaseStrategyInitializable, ICallee {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// AAVE protocol address
IProtocolDataProvider private constant protocolDataProvider =
IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
IAaveIncentivesController private constant incentivesController =
IAaveIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5);
ILendingPool private constant lendingPool =
ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9);
// Token addresses
address private constant aave = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9;
IStakedAave private constant stkAave =
IStakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5);
address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// Supply and borrow tokens
IAToken public aToken;
IVariableDebtToken public debtToken;
// SWAP routers
IUni private constant V2ROUTER =
IUni(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
ISwapRouter private constant V3ROUTER =
ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564);
// OPS State Variables
uint256 private constant DEFAULT_COLLAT_TARGET_MARGIN = 0.02 ether;
uint256 private constant DEFAULT_COLLAT_MAX_MARGIN = 0.005 ether;
uint256 private constant LIQUIDATION_WARNING_THRESHOLD = 0.01 ether;
uint256 public maxBorrowCollatRatio; // The maximum the aave protocol will let us borrow
uint256 public targetCollatRatio; // The LTV we are levering up to
uint256 public maxCollatRatio; // Closest to liquidation we'll risk
uint8 public maxIterations = 6;
bool public isDyDxActive = true;
uint256 public minWant = 100;
uint256 public minRatio = 0.005 ether;
uint256 public minRewardToSell = 1e15;
bool public sellStkAave = true;
bool public cooldownStkAave = false;
bool public useUniV3 = false; // only applied to aave => want, stkAave => aave always uses v3
uint256 public maxStkAavePriceImpactBps = 1000;
uint24 public stkAaveToAaveSwapFee = 10000;
uint24 public aaveToWethSwapFee = 3000;
uint24 public wethToWantSwapFee = 3000;
uint16 private constant referral = 0; // Aave's referral code
bool private alreadyAdjusted = false; // Signal whether a position adjust was done in prepareReturn
uint256 private constant MAX_BPS = 1e4;
uint256 private constant BPS_WAD_RATIO = 1e14;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1 ether;
uint256 private constant PESSIMISM_FACTOR = 1000;
uint256 private DECIMALS;
constructor(address _vault) public BaseStrategyInitializable(_vault) {
_initializeThis();
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external override {
_initialize(_vault, _strategist, _rewards, _keeper);
_initializeThis();
}
function _initializeThis() internal {
require(address(aToken) == address(0));
// initialize operational state
maxIterations = 6;
isDyDxActive = true;
// mins
minWant = 100;
minRatio = 0.005 ether;
minRewardToSell = 1e15;
// reward params
sellStkAave = true;
cooldownStkAave = false;
useUniV3 = false;
maxStkAavePriceImpactBps = 1000;
stkAaveToAaveSwapFee = 10000;
aaveToWethSwapFee = 3000;
wethToWantSwapFee = 3000;
// Set aave tokens
(address _aToken, , address _debtToken) =
protocolDataProvider.getReserveTokensAddresses(address(want));
aToken = IAToken(_aToken);
debtToken = IVariableDebtToken(_debtToken);
// Let collateral targets
(, uint256 ltv, uint256 liquidationThreshold, , , , , , , ) =
protocolDataProvider.getReserveConfigurationData(address(want));
liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO); // convert bps to wad
targetCollatRatio = liquidationThreshold.sub(
DEFAULT_COLLAT_TARGET_MARGIN
);
maxCollatRatio = liquidationThreshold.sub(DEFAULT_COLLAT_MAX_MARGIN);
maxBorrowCollatRatio = ltv.mul(BPS_WAD_RATIO).sub(
DEFAULT_COLLAT_MAX_MARGIN
);
DECIMALS = 10**vault.decimals();
// approve spend aave spend
approveMaxSpend(address(want), address(lendingPool));
approveMaxSpend(address(aToken), address(lendingPool));
// approve flashloan spend
approveMaxSpend(weth, address(lendingPool));
approveMaxSpend(weth, FlashLoanLib.SOLO);
// approve swap router spend
approveMaxSpend(address(stkAave), address(V3ROUTER));
approveMaxSpend(aave, address(V2ROUTER));
approveMaxSpend(aave, address(V3ROUTER));
}
// SETTERS
function setCollateralTargets(
uint256 _targetCollatRatio,
uint256 _maxCollatRatio,
uint256 _maxBorrowCollatRatio
) external onlyVaultManagers {
(, uint256 ltv, uint256 liquidationThreshold, , , , , , , ) =
protocolDataProvider.getReserveConfigurationData(address(want));
// convert bps to wad
ltv = ltv.mul(BPS_WAD_RATIO);
liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO);
require(_targetCollatRatio < liquidationThreshold);
require(_maxCollatRatio < liquidationThreshold);
require(_targetCollatRatio < _maxCollatRatio);
require(_maxBorrowCollatRatio < ltv);
targetCollatRatio = _targetCollatRatio;
maxCollatRatio = _maxCollatRatio;
maxBorrowCollatRatio = _maxBorrowCollatRatio;
}
function setIsDyDxActive(bool _isDyDxActive) external onlyVaultManagers {
isDyDxActive = _isDyDxActive;
}
function setMinsAndMaxs(
uint256 _minWant,
uint256 _minRatio,
uint8 _maxIterations
) external onlyVaultManagers {
require(_minRatio < maxBorrowCollatRatio);
require(_maxIterations > 0 && _maxIterations < 16);
minWant = _minWant;
minRatio = _minRatio;
maxIterations = _maxIterations;
}
function setRewardBehavior(
bool _sellStkAave,
bool _cooldownStkAave,
bool _useUniV3,
uint256 _minRewardToSell,
uint256 _maxStkAavePriceImpactBps,
uint24 _stkAaveToAaveSwapFee,
uint24 _aaveToWethSwapFee,
uint24 _wethToWantSwapFee
) external onlyVaultManagers {
require(_maxStkAavePriceImpactBps <= MAX_BPS);
sellStkAave = _sellStkAave;
cooldownStkAave = _cooldownStkAave;
useUniV3 = _useUniV3;
minRewardToSell = _minRewardToSell;
maxStkAavePriceImpactBps = _maxStkAavePriceImpactBps;
stkAaveToAaveSwapFee = _stkAaveToAaveSwapFee;
aaveToWethSwapFee = _aaveToWethSwapFee;
wethToWantSwapFee = _wethToWantSwapFee;
}
function name() external view override returns (string memory) {
return "StrategyGenLevAAVE";
}
function estimatedTotalAssets() public view override returns (uint256) {
uint256 balanceExcludingRewards =
balanceOfWant().add(getCurrentSupply());
// if we don't have a position, don't worry about rewards
if (balanceExcludingRewards < minWant) {
return balanceExcludingRewards;
}
uint256 rewards =
estimatedRewardsInWant().mul(MAX_BPS.sub(PESSIMISM_FACTOR)).div(
MAX_BPS
);
return balanceExcludingRewards.add(rewards);
}
function estimatedRewardsInWant() public view returns (uint256) {
uint256 aaveBalance = balanceOfAave();
uint256 stkAaveBalance = balanceOfStkAave();
uint256 pendingRewards =
incentivesController.getRewardsBalance(
getAaveAssets(),
address(this)
);
uint256 stkAaveDiscountFactor = MAX_BPS.sub(maxStkAavePriceImpactBps);
uint256 combinedStkAave =
pendingRewards.add(stkAaveBalance).mul(stkAaveDiscountFactor).div(
MAX_BPS
);
return tokenToWant(aave, aaveBalance.add(combinedStkAave));
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// claim & sell rewards
_claimAndSellRewards();
// account for profit / losses
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
// Assets immediately convertable to want only
uint256 supply = getCurrentSupply();
uint256 totalAssets = balanceOfWant().add(supply);
if (totalDebt > totalAssets) {
// we have losses
_loss = totalDebt.sub(totalAssets);
} else {
// we have profit
_profit = totalAssets.sub(totalDebt);
}
// free funds to repay debt + profit to the strategy
uint256 amountAvailable = balanceOfWant();
uint256 amountRequired = _debtOutstanding.add(_profit);
if (amountRequired > amountAvailable) {
// we need to free funds
// we dismiss losses here, they cannot be generated from withdrawal
// but it is possible for the strategy to unwind full position
(amountAvailable, ) = liquidatePosition(amountRequired);
// Don't do a redundant adjustment in adjustPosition
alreadyAdjusted = true;
if (amountAvailable >= amountRequired) {
_debtPayment = _debtOutstanding;
// profit remains unchanged unless there is not enough to pay it
if (amountRequired.sub(_debtPayment) < _profit) {
_profit = amountRequired.sub(_debtPayment);
}
} else {
// we were not able to free enough funds
if (amountAvailable < _debtOutstanding) {
// available funds are lower than the repayment that we need to do
_profit = 0;
_debtPayment = amountAvailable;
// we dont report losses here as the strategy might not be able to return in this harvest
// but it will still be there for the next harvest
} else {
// NOTE: amountRequired is always equal or greater than _debtOutstanding
// important to use amountRequired just in case amountAvailable is > amountAvailable
_debtPayment = _debtOutstanding;
_profit = amountAvailable.sub(_debtPayment);
}
}
} else {
_debtPayment = _debtOutstanding;
// profit remains unchanged unless there is not enough to pay it
if (amountRequired.sub(_debtPayment) < _profit) {
_profit = amountRequired.sub(_debtPayment);
}
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
if (alreadyAdjusted) {
alreadyAdjusted = false; // reset for next time
return;
}
uint256 wantBalance = balanceOfWant();
// deposit available want as collateral
if (
wantBalance > _debtOutstanding &&
wantBalance.sub(_debtOutstanding) > minWant
) {
_depositCollateral(wantBalance.sub(_debtOutstanding));
// we update the value
wantBalance = balanceOfWant();
}
// check current position
uint256 currentCollatRatio = getCurrentCollatRatio();
// Either we need to free some funds OR we want to be max levered
if (_debtOutstanding > wantBalance) {
// we should free funds
uint256 amountRequired = _debtOutstanding.sub(wantBalance);
// NOTE: vault will take free funds during the next harvest
_freeFunds(amountRequired);
} else if (currentCollatRatio < targetCollatRatio) {
// we should lever up
if (targetCollatRatio.sub(currentCollatRatio) > minRatio) {
// we only act on relevant differences
_leverMax();
}
} else if (currentCollatRatio > targetCollatRatio) {
if (currentCollatRatio.sub(targetCollatRatio) > minRatio) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 newBorrow =
getBorrowFromSupply(
deposits.sub(borrows),
targetCollatRatio
);
_leverDownTo(newBorrow, borrows);
}
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
// NOTE: Maintain invariant `want.balanceOf(this) >= _liquidatedAmount`
// NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded`
uint256 wantBalance = balanceOfWant();
if (wantBalance > _amountNeeded) {
// if there is enough free want, let's use it
return (_amountNeeded, 0);
}
// we need to free funds
uint256 amountRequired = _amountNeeded.sub(wantBalance);
_freeFunds(amountRequired);
uint256 freeAssets = balanceOfWant();
if (_amountNeeded > freeAssets) {
_liquidatedAmount = freeAssets;
_loss = _amountNeeded.sub(freeAssets);
} else {
_liquidatedAmount = _amountNeeded;
}
}
function tendTrigger(uint256 gasCost) public view override returns (bool) {
if (harvestTrigger(gasCost)) {
//harvest takes priority
return false;
}
// pull the liquidation liquidationThreshold from aave to be extra safu
(, , uint256 liquidationThreshold, , , , , , , ) =
protocolDataProvider.getReserveConfigurationData(address(want));
// convert bps to wad
liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO);
uint256 currentCollatRatio = getCurrentCollatRatio();
if (currentCollatRatio >= liquidationThreshold) {
return true;
}
return (liquidationThreshold.sub(currentCollatRatio) <=
LIQUIDATION_WARNING_THRESHOLD);
}
function liquidateAllPositions()
internal
override
returns (uint256 _amountFreed)
{
(_amountFreed, ) = liquidatePosition(type(uint256).max);
}
function prepareMigration(address _newStrategy) internal override {
require(getCurrentSupply() < minWant);
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
//emergency function that we can use to deleverage manually if something is broken
function manualDeleverage(uint256 amount) external onlyVaultManagers {
_withdrawCollateral(amount);
_repayWant(amount);
}
//emergency function that we can use to deleverage manually if something is broken
function manualReleaseWant(uint256 amount) external onlyVaultManagers {
_withdrawCollateral(amount);
}
// emergency function that we can use to sell rewards if something is broken
function manualClaimAndSellRewards() external onlyVaultManagers {
_claimAndSellRewards();
}
// INTERNAL ACTIONS
function _claimAndSellRewards() internal returns (uint256) {
uint256 stkAaveBalance = balanceOfStkAave();
uint8 cooldownStatus = stkAaveBalance == 0 ? 0 : _checkCooldown(); // don't check status if we have no stkAave
// If it's the claim period claim
if (stkAaveBalance > 0 && cooldownStatus == 1) {
// redeem AAVE from stkAave
stkAave.claimRewards(address(this), type(uint256).max);
stkAave.redeem(address(this), stkAaveBalance);
}
// claim stkAave from lending and borrowing, this will reset the cooldown
incentivesController.claimRewards(
getAaveAssets(),
type(uint256).max,
address(this)
);
stkAaveBalance = balanceOfStkAave();
// request start of cooldown period, if there's no cooldown in progress
if (cooldownStkAave && stkAaveBalance > 0 && cooldownStatus == 0) {
stkAave.cooldown();
}
// Always keep 1 wei to get around cooldown clear
if (sellStkAave && stkAaveBalance >= minRewardToSell.add(1)) {
uint256 minAAVEOut =
stkAaveBalance.mul(MAX_BPS.sub(maxStkAavePriceImpactBps)).div(
MAX_BPS
);
_sellSTKAAVEToAAVE(stkAaveBalance.sub(1), minAAVEOut);
}
// sell AAVE for want
uint256 aaveBalance = balanceOfAave();
if (aaveBalance >= minRewardToSell) {
_sellAAVEForWant(aaveBalance, 0);
}
}
function _freeFunds(uint256 amountToFree) internal returns (uint256) {
if (amountToFree == 0) return 0;
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 realAssets = deposits.sub(borrows);
uint256 amountRequired = Math.min(amountToFree, realAssets);
uint256 newSupply = realAssets.sub(amountRequired);
uint256 newBorrow = getBorrowFromSupply(newSupply, targetCollatRatio);
// repay required amount
_leverDownTo(newBorrow, borrows);
return balanceOfWant();
}
function _leverMax() internal {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
// NOTE: decimals should cancel out
uint256 realSupply = deposits.sub(borrows);
uint256 newBorrow = getBorrowFromSupply(realSupply, targetCollatRatio);
uint256 totalAmountToBorrow = newBorrow.sub(borrows);
if (isDyDxActive) {
// The best approach is to lever up using regular method, then finish with flash loan
totalAmountToBorrow = totalAmountToBorrow.sub(
_leverUpStep(totalAmountToBorrow)
);
if (totalAmountToBorrow > minWant) {
totalAmountToBorrow = totalAmountToBorrow.sub(
_leverUpFlashLoan(totalAmountToBorrow)
);
}
} else {
for (
uint8 i = 0;
i < maxIterations && totalAmountToBorrow > minWant;
i++
) {
totalAmountToBorrow = totalAmountToBorrow.sub(
_leverUpStep(totalAmountToBorrow)
);
}
}
}
function _leverUpFlashLoan(uint256 amount) internal returns (uint256) {
return FlashLoanLib.doDyDxFlashLoan(false, amount, address(want));
}
function _leverUpStep(uint256 amount) internal returns (uint256) {
if (amount == 0) {
return 0;
}
uint256 wantBalance = balanceOfWant();
// calculate how much borrow can I take
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 canBorrow =
getBorrowFromDeposit(
deposits.add(wantBalance),
maxBorrowCollatRatio
);
if (canBorrow <= borrows) {
return 0;
}
canBorrow = canBorrow.sub(borrows);
if (canBorrow < amount) {
amount = canBorrow;
}
// deposit available want as collateral
_depositCollateral(wantBalance);
// borrow available amount
_borrowWant(amount);
return amount;
}
function _leverDownTo(uint256 newAmountBorrowed, uint256 currentBorrowed)
internal
returns (uint256)
{
if (newAmountBorrowed >= currentBorrowed) {
// we don't need to repay
return 0;
}
uint256 totalRepayAmount = currentBorrowed.sub(newAmountBorrowed);
if (isDyDxActive) {
totalRepayAmount = totalRepayAmount.sub(
_leverDownFlashLoan(totalRepayAmount)
);
_withdrawExcessCollateral();
}
for (
uint8 i = 0;
i < maxIterations && totalRepayAmount > minWant;
i++
) {
uint256 toRepay = totalRepayAmount;
uint256 wantBalance = balanceOfWant();
if (toRepay > wantBalance) {
toRepay = wantBalance;
}
uint256 repaid = _repayWant(toRepay);
totalRepayAmount = totalRepayAmount.sub(repaid);
// withdraw collateral
_withdrawExcessCollateral();
}
// deposit back to get targetCollatRatio (we always need to leave this in this ratio)
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 targetDeposit =
getDepositFromBorrow(borrows, targetCollatRatio);
if (targetDeposit > deposits) {
uint256 toDeposit = targetDeposit.sub(deposits);
if (toDeposit > minWant) {
_depositCollateral(Math.min(toDeposit, balanceOfWant()));
}
}
}
function _leverDownFlashLoan(uint256 amount) internal returns (uint256) {
if (amount <= minWant) return 0;
(, uint256 borrows) = getCurrentPosition();
if (amount > borrows) {
amount = borrows;
}
return FlashLoanLib.doDyDxFlashLoan(true, amount, address(want));
}
function _withdrawExcessCollateral() internal returns (uint256 amount) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 theoDeposits = getDepositFromBorrow(borrows, maxCollatRatio);
if (deposits > theoDeposits) {
uint256 toWithdraw = deposits.sub(theoDeposits);
return _withdrawCollateral(toWithdraw);
}
}
function _depositCollateral(uint256 amount) internal returns (uint256) {
if (amount == 0) return 0;
lendingPool.deposit(address(want), amount, address(this), referral);
return amount;
}
function _withdrawCollateral(uint256 amount) internal returns (uint256) {
if (amount == 0) return 0;
lendingPool.withdraw(address(want), amount, address(this));
return amount;
}
function _repayWant(uint256 amount) internal returns (uint256) {
if (amount == 0) return 0;
return lendingPool.repay(address(want), amount, 2, address(this));
}
function _borrowWant(uint256 amount) internal returns (uint256) {
if (amount == 0) return 0;
lendingPool.borrow(address(want), amount, 2, referral, address(this));
return amount;
}
// INTERNAL VIEWS
function balanceOfWant() internal view returns (uint256) {
return want.balanceOf(address(this));
}
function balanceOfAToken() internal view returns (uint256) {
return aToken.balanceOf(address(this));
}
function balanceOfDebtToken() internal view returns (uint256) {
return debtToken.balanceOf(address(this));
}
function balanceOfAave() internal view returns (uint256) {
return IERC20(aave).balanceOf(address(this));
}
function balanceOfStkAave() internal view returns (uint256) {
return IERC20(address(stkAave)).balanceOf(address(this));
}
// Flashloan callback function
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
(bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));
require(msg.sender == FlashLoanLib.SOLO);
require(sender == address(this));
FlashLoanLib.loanLogic(deficit, amount, address(want));
}
function getCurrentPosition()
public
view
returns (uint256 deposits, uint256 borrows)
{
deposits = balanceOfAToken();
borrows = balanceOfDebtToken();
}
function getCurrentCollatRatio()
public
view
returns (uint256 currentCollatRatio)
{
(uint256 deposits, uint256 borrows) = getCurrentPosition();
if (deposits > 0) {
currentCollatRatio = borrows.mul(COLLATERAL_RATIO_PRECISION).div(
deposits
);
}
}
function getCurrentSupply() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
return deposits.sub(borrows);
}
// conversions
function tokenToWant(address token, uint256 amount)
internal
view
returns (uint256)
{
if (amount == 0 || address(want) == token) {
return amount;
}
uint256[] memory amounts =
IUni(V2ROUTER).getAmountsOut(
amount,
getTokenOutPathV2(token, address(want))
);
return amounts[amounts.length - 1];
}
function ethToWant(uint256 _amtInWei)
public
view
override
returns (uint256)
{
return tokenToWant(weth, _amtInWei);
}
// returns cooldown status
// 0 = no cooldown or past withdraw period
// 1 = claim period
// 2 = cooldown initiated, future claim period
function _checkCooldown() internal view returns (uint8) {
uint256 cooldownStartTimestamp =
IStakedAave(stkAave).stakersCooldowns(address(this));
uint256 COOLDOWN_SECONDS = IStakedAave(stkAave).COOLDOWN_SECONDS();
uint256 UNSTAKE_WINDOW = IStakedAave(stkAave).UNSTAKE_WINDOW();
uint256 nextClaimStartTimestamp =
cooldownStartTimestamp.add(COOLDOWN_SECONDS);
if (cooldownStartTimestamp == 0) {
return 0;
}
if (
block.timestamp > nextClaimStartTimestamp &&
block.timestamp <= nextClaimStartTimestamp.add(UNSTAKE_WINDOW)
) {
return 1;
}
if (block.timestamp < nextClaimStartTimestamp) {
return 2;
}
}
function getTokenOutPathV2(address _token_in, address _token_out)
internal
pure
returns (address[] memory _path)
{
bool is_weth =
_token_in == address(weth) || _token_out == address(weth);
_path = new address[](is_weth ? 2 : 3);
_path[0] = _token_in;
if (is_weth) {
_path[1] = _token_out;
} else {
_path[1] = address(weth);
_path[2] = _token_out;
}
}
function getTokenOutPathV3(address _token_in, address _token_out)
internal
view
returns (bytes memory _path)
{
if (address(want) == weth) {
_path = abi.encodePacked(
address(aave),
aaveToWethSwapFee,
address(weth)
);
} else {
_path = abi.encodePacked(
address(aave),
aaveToWethSwapFee,
address(weth),
wethToWantSwapFee,
address(want)
);
}
}
function _sellAAVEForWant(uint256 amountIn, uint256 minOut) internal {
if (amountIn == 0) {
return;
}
if (useUniV3) {
V3ROUTER.exactInput(
ISwapRouter.ExactInputParams(
getTokenOutPathV3(address(aave), address(want)),
address(this),
now,
amountIn,
minOut
)
);
} else {
V2ROUTER.swapExactTokensForTokens(
amountIn,
minOut,
getTokenOutPathV2(address(aave), address(want)),
address(this),
now
);
}
}
function _sellSTKAAVEToAAVE(uint256 amountIn, uint256 minOut) internal {
// Swap Rewards in UNIV3
// NOTE: Unoptimized, can be frontrun and most importantly this pool is low liquidity
V3ROUTER.exactInputSingle(
ISwapRouter.ExactInputSingleParams(
address(stkAave),
address(aave),
stkAaveToAaveSwapFee,
address(this),
now,
amountIn, // wei
minOut,
0
)
);
}
function getAaveAssets() internal view returns (address[] memory assets) {
assets = new address[](2);
assets[0] = address(aToken);
assets[1] = address(debtToken);
}
function getBorrowFromDeposit(uint256 deposit, uint256 collatRatio)
internal
pure
returns (uint256)
{
return deposit.mul(collatRatio).div(COLLATERAL_RATIO_PRECISION);
}
function getDepositFromBorrow(uint256 borrow, uint256 collatRatio)
internal
pure
returns (uint256)
{
return borrow.mul(COLLATERAL_RATIO_PRECISION).div(collatRatio);
}
function getBorrowFromSupply(uint256 supply, uint256 collatRatio)
internal
pure
returns (uint256)
{
return
supply.mul(collatRatio).div(
COLLATERAL_RATIO_PRECISION.sub(collatRatio)
);
}
function approveMaxSpend(address token, address spender) internal {
IERC20(token).safeApprove(spender, type(uint256).max);
}
} | we don't need to repay | function _leverDownTo(uint256 newAmountBorrowed, uint256 currentBorrowed)
internal
returns (uint256)
{
if (newAmountBorrowed >= currentBorrowed) {
return 0;
}
uint256 totalRepayAmount = currentBorrowed.sub(newAmountBorrowed);
if (isDyDxActive) {
totalRepayAmount = totalRepayAmount.sub(
_leverDownFlashLoan(totalRepayAmount)
);
_withdrawExcessCollateral();
}
for (
uint8 i = 0;
i < maxIterations && totalRepayAmount > minWant;
i++
) {
uint256 toRepay = totalRepayAmount;
uint256 wantBalance = balanceOfWant();
if (toRepay > wantBalance) {
toRepay = wantBalance;
}
uint256 repaid = _repayWant(toRepay);
totalRepayAmount = totalRepayAmount.sub(repaid);
}
uint256 targetDeposit =
getDepositFromBorrow(borrows, targetCollatRatio);
if (targetDeposit > deposits) {
uint256 toDeposit = targetDeposit.sub(deposits);
if (toDeposit > minWant) {
_depositCollateral(Math.min(toDeposit, balanceOfWant()));
}
}
}
| 219,142 |
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {IPoolIO} from "./IPoolIO.sol";
import {PoolSwap} from "./PoolSwap.sol";
import {PoolStorage} from "./PoolStorage.sol";
import {IPremiaMining} from "../mining/IPremiaMining.sol";
/**
* @title Premia option pool
* @dev deployed standalone and referenced by PoolProxy
*/
contract PoolIO is IPoolIO, PoolSwap {
using ABDKMath64x64 for int128;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using PoolStorage for PoolStorage.Layout;
constructor(
address ivolOracle,
address weth,
address premiaMining,
address feeReceiver,
address feeDiscountAddress,
int128 fee64x64,
address uniswapV2Factory,
address sushiswapFactory
)
PoolSwap(
ivolOracle,
weth,
premiaMining,
feeReceiver,
feeDiscountAddress,
fee64x64,
uniswapV2Factory,
sushiswapFactory
)
{}
/**
* @inheritdoc IPoolIO
*/
function setDivestmentTimestamp(uint64 timestamp, bool isCallPool)
external
override
{
PoolStorage.Layout storage l = PoolStorage.layout();
require(
timestamp >= l.depositedAt[msg.sender][isCallPool] + (1 days),
"liq lock 1d"
);
l.divestmentTimestamps[msg.sender][isCallPool] = timestamp;
}
/**
* @inheritdoc IPoolIO
*/
function deposit(uint256 amount, bool isCallPool)
external
payable
override
{
_deposit(amount, isCallPool, false);
}
/**
* @inheritdoc IPoolIO
*/
function swapAndDeposit(
uint256 amount,
bool isCallPool,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
bool isSushi
) external payable override {
// If value is passed, amountInMax must be 0, as the value wont be used
// If amountInMax is not 0, user wants to do a swap from an ERC20, and therefore no value should be attached
require(
msg.value == 0 || amountInMax == 0,
"value and amountInMax passed"
);
// If no amountOut has been passed, we swap the exact deposit amount specified
if (amountOut == 0) {
amountOut = amount;
}
if (msg.value > 0) {
_swapETHForExactTokens(amountOut, path, isSushi);
} else {
_swapTokensForExactTokens(amountOut, amountInMax, path, isSushi);
}
_deposit(amount, isCallPool, true);
}
/**
* @inheritdoc IPoolIO
*/
function withdraw(uint256 amount, bool isCallPool) public override {
PoolStorage.Layout storage l = PoolStorage.layout();
uint256 toWithdraw = amount;
_processPendingDeposits(l, isCallPool);
uint256 depositedAt = l.depositedAt[msg.sender][isCallPool];
require(depositedAt + (1 days) < block.timestamp, "liq lock 1d");
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCallPool);
{
uint256 reservedLiqTokenId = _getReservedLiquidityTokenId(
isCallPool
);
uint256 reservedLiquidity = _balanceOf(
msg.sender,
reservedLiqTokenId
);
if (reservedLiquidity > 0) {
uint256 reservedLiqToWithdraw;
if (reservedLiquidity < toWithdraw) {
reservedLiqToWithdraw = reservedLiquidity;
} else {
reservedLiqToWithdraw = toWithdraw;
}
toWithdraw -= reservedLiqToWithdraw;
// burn reserved liquidity tokens from sender
_burn(msg.sender, reservedLiqTokenId, reservedLiqToWithdraw);
}
}
if (toWithdraw > 0) {
// burn free liquidity tokens from sender
_burn(msg.sender, _getFreeLiquidityTokenId(isCallPool), toWithdraw);
int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(
isCallPool
);
_setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCallPool);
}
_subUserTVL(l, msg.sender, isCallPool, amount);
_pushTo(msg.sender, _getPoolToken(isCallPool), amount);
emit Withdrawal(msg.sender, isCallPool, depositedAt, amount);
}
/**
* @inheritdoc IPoolIO
*/
function reassign(uint256 tokenId, uint256 contractSize)
external
override
returns (
uint256 baseCost,
uint256 feeCost,
uint256 amountOut
)
{
PoolStorage.Layout storage l = PoolStorage.layout();
int128 newPrice64x64 = _update(l);
(
PoolStorage.TokenType tokenType,
uint64 maturity,
int128 strike64x64
) = PoolStorage.parseTokenId(tokenId);
bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL ||
tokenType == PoolStorage.TokenType.LONG_CALL;
(baseCost, feeCost, amountOut) = _reassign(
l,
msg.sender,
maturity,
strike64x64,
isCall,
contractSize,
newPrice64x64
);
_pushTo(msg.sender, _getPoolToken(isCall), amountOut);
}
/**
* @inheritdoc IPoolIO
*/
function reassignBatch(
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
public
override
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
)
{
require(tokenIds.length == contractSizes.length, "diff array length");
PoolStorage.Layout storage l = PoolStorage.layout();
int128 newPrice64x64 = _update(l);
baseCosts = new uint256[](tokenIds.length);
feeCosts = new uint256[](tokenIds.length);
for (uint256 i; i < tokenIds.length; i++) {
(
PoolStorage.TokenType tokenType,
uint64 maturity,
int128 strike64x64
) = PoolStorage.parseTokenId(tokenIds[i]);
bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL ||
tokenType == PoolStorage.TokenType.LONG_CALL;
uint256 amountOut;
uint256 contractSize = contractSizes[i];
(baseCosts[i], feeCosts[i], amountOut) = _reassign(
l,
msg.sender,
maturity,
strike64x64,
isCall,
contractSize,
newPrice64x64
);
if (isCall) {
amountOutCall += amountOut;
} else {
amountOutPut += amountOut;
}
}
_pushTo(msg.sender, _getPoolToken(true), amountOutCall);
_pushTo(msg.sender, _getPoolToken(false), amountOutPut);
}
/**
* @inheritdoc IPoolIO
*/
function withdrawAllAndReassignBatch(
bool isCallPool,
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
external
override
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
)
{
uint256 balance = _balanceOf(
msg.sender,
_getFreeLiquidityTokenId(isCallPool)
);
if (balance > 0) {
withdraw(balance, isCallPool);
}
(baseCosts, feeCosts, amountOutCall, amountOutPut) = reassignBatch(
tokenIds,
contractSizes
);
}
/**
* @inheritdoc IPoolIO
*/
function withdrawFees()
external
override
returns (uint256 amountOutCall, uint256 amountOutPut)
{
amountOutCall = _withdrawFees(true);
amountOutPut = _withdrawFees(false);
_pushTo(FEE_RECEIVER_ADDRESS, _getPoolToken(true), amountOutCall);
_pushTo(FEE_RECEIVER_ADDRESS, _getPoolToken(false), amountOutPut);
}
/**
* @inheritdoc IPoolIO
*/
function annihilate(uint256 tokenId, uint256 contractSize)
external
override
{
(
PoolStorage.TokenType tokenType,
uint64 maturity,
int128 strike64x64
) = PoolStorage.parseTokenId(tokenId);
bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL ||
tokenType == PoolStorage.TokenType.LONG_CALL;
_annihilate(msg.sender, maturity, strike64x64, isCall, contractSize);
_pushTo(
msg.sender,
_getPoolToken(isCall),
isCall
? contractSize
: PoolStorage.layout().fromUnderlyingToBaseDecimals(
strike64x64.mulu(contractSize)
)
);
}
/**
* @inheritdoc IPoolIO
*/
function claimRewards(bool isCallPool) external override {
claimRewards(msg.sender, isCallPool);
}
/**
* @inheritdoc IPoolIO
*/
function claimRewards(address account, bool isCallPool) public override {
PoolStorage.Layout storage l = PoolStorage.layout();
uint256 userTVL = l.userTVL[account][isCallPool];
uint256 totalTVL = l.totalTVL[isCallPool];
IPremiaMining(PREMIA_MINING_ADDRESS).claim(
account,
address(this),
isCallPool,
userTVL,
userTVL,
totalTVL
);
}
/**
* @inheritdoc IPoolIO
*/
function updateMiningPools() external override {
PoolStorage.Layout storage l = PoolStorage.layout();
IPremiaMining(PREMIA_MINING_ADDRESS).updatePool(
address(this),
true,
l.totalTVL[true]
);
IPremiaMining(PREMIA_MINING_ADDRESS).updatePool(
address(this),
false,
l.totalTVL[false]
);
}
/**
* @notice deposit underlying currency, underwriting calls of that currency with respect to base currency
* @param amount quantity of underlying currency to deposit
* @param isCallPool whether to deposit underlying in the call pool or base in the put pool
* @param skipWethDeposit if false, will not try to deposit weth from attach eth
*/
function _deposit(
uint256 amount,
bool isCallPool,
bool skipWethDeposit
) internal {
PoolStorage.Layout storage l = PoolStorage.layout();
// Reset gradual divestment timestamp
delete l.divestmentTimestamps[msg.sender][isCallPool];
uint256 cap = _getPoolCapAmount(l, isCallPool);
require(
l.totalTVL[isCallPool] + amount <= cap,
"pool deposit cap reached"
);
_processPendingDeposits(l, isCallPool);
l.depositedAt[msg.sender][isCallPool] = block.timestamp;
_addUserTVL(l, msg.sender, isCallPool, amount);
_pullFrom(
msg.sender,
_getPoolToken(isCallPool),
amount,
skipWethDeposit
);
_addToDepositQueue(msg.sender, amount, isCallPool);
emit Deposit(msg.sender, isCallPool, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Set implementation with enumeration functions
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license)
*/
library EnumerableSet {
struct Set {
bytes32[] _values;
// 1-indexed to allow 0 to signify nonexistence
mapping(bytes32 => uint256) _indexes;
}
struct Bytes32Set {
Set _inner;
}
struct AddressSet {
Set _inner;
}
struct UintSet {
Set _inner;
}
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
function indexOf(Bytes32Set storage set, bytes32 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, value);
}
function indexOf(AddressSet storage set, address value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(uint256(uint160(value))));
}
function indexOf(UintSet storage set, uint256 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(value));
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
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];
}
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
function _indexOf(Set storage set, bytes32 value)
private
view
returns (uint256)
{
unchecked {
return set._indexes[value] - 1;
}
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 index = valueIndex - 1;
bytes32 last = set._values[set._values.length - 1];
// move last value to now-vacant index
set._values[index] = last;
set._indexes[last] = index + 1;
// clear last index
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
}
// 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.8.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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (int256 (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) {
unchecked {
require (x >= 0);
return uint64 (uint128 (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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (int256 (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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
unchecked {
require (x >= 0);
return int128 (sqrtu (uint256 (int256 (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) {
unchecked {
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 (int256 (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) {
unchecked {
require (x > 0);
return int128 (int256 (
uint256 (int256 (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) {
unchecked {
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 (int256 (63 - (x >> 64)));
require (result <= uint256 (int256 (MAX_64x64)));
return int128 (int256 (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) {
unchecked {
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) {
unchecked {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
unchecked {
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: LGPL-3.0-or-later
pragma solidity ^0.8.0;
/**
* @notice Pool interface for LP position and platform fee management functions
*/
interface IPoolIO {
/**
* @notice set timestamp after which reinvestment is disabled
* @param timestamp timestamp to begin divestment
* @param isCallPool whether we set divestment timestamp for the call pool or put pool
*/
function setDivestmentTimestamp(uint64 timestamp, bool isCallPool) external;
/**
* @notice deposit underlying currency, underwriting calls of that currency with respect to base currency
* @param amount quantity of underlying currency to deposit
* @param isCallPool whether to deposit underlying in the call pool or base in the put pool
*/
function deposit(uint256 amount, bool isCallPool) external payable;
/**
* @notice deposit underlying currency, underwriting calls of that currency with respect to base currency
* @param amount quantity of underlying currency to deposit
* @param isCallPool whether to deposit underlying in the call pool or base in the put pool
* @param amountOut amount out of tokens requested. If 0, we will swap exact amount necessary to pay the quote
* @param amountInMax amount in max of tokens
* @param path swap path
* @param isSushi whether we use sushi or uniV2 for the swap
*/
function swapAndDeposit(
uint256 amount,
bool isCallPool,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
bool isSushi
) external payable;
/**
* @notice redeem pool share tokens for underlying asset
* @param amount quantity of share tokens to redeem
* @param isCallPool whether to deposit underlying in the call pool or base in the put pool
*/
function withdraw(uint256 amount, bool isCallPool) external;
/**
* @notice reassign short position to new underwriter
* @param tokenId ERC1155 token id (long or short)
* @param contractSize quantity of option contract tokens to reassign
* @return baseCost quantity of tokens required to reassign short position
* @return feeCost quantity of tokens required to pay fees
* @return amountOut quantity of liquidity freed and transferred to owner
*/
function reassign(uint256 tokenId, uint256 contractSize)
external
returns (
uint256 baseCost,
uint256 feeCost,
uint256 amountOut
);
/**
* @notice reassign set of short position to new underwriter
* @param tokenIds array of ERC1155 token ids (long or short)
* @param contractSizes array of quantities of option contract tokens to reassign
* @return baseCosts quantities of tokens required to reassign each short position
* @return feeCosts quantities of tokens required to pay fees
* @return amountOutCall quantity of call pool liquidity freed and transferred to owner
* @return amountOutPut quantity of put pool liquidity freed and transferred to owner
*/
function reassignBatch(
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
external
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
);
/**
* @notice withdraw all free liquidity and reassign set of short position to new underwriter
* @param isCallPool true for call, false for put
* @param tokenIds array of ERC1155 token ids (long or short)
* @param contractSizes array of quantities of option contract tokens to reassign
* @return baseCosts quantities of tokens required to reassign each short position
* @return feeCosts quantities of tokens required to pay fees
* @return amountOutCall quantity of call pool liquidity freed and transferred to owner
* @return amountOutPut quantity of put pool liquidity freed and transferred to owner
*/
function withdrawAllAndReassignBatch(
bool isCallPool,
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
external
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
);
/**
* @notice transfer accumulated fees to the fee receiver
* @return amountOutCall quantity of underlying tokens transferred
* @return amountOutPut quantity of base tokens transferred
*/
function withdrawFees()
external
returns (uint256 amountOutCall, uint256 amountOutPut);
/**
* @notice burn corresponding long and short option tokens and withdraw collateral
* @param tokenId ERC1155 token id (long or short)
* @param contractSize quantity of option contract tokens to annihilate
*/
function annihilate(uint256 tokenId, uint256 contractSize) external;
/**
* @notice claim earned PREMIA emissions
* @param isCallPool true for call, false for put
*/
function claimRewards(bool isCallPool) external;
/**
* @notice claim earned PREMIA emissions on behalf of given account
* @param account account on whose behalf to claim rewards
* @param isCallPool true for call, false for put
*/
function claimRewards(address account, bool isCallPool) external;
/**
* @notice TODO
*/
function updateMiningPools() external;
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {PoolStorage} from "./PoolStorage.sol";
import {IWETH} from "@solidstate/contracts/utils/IWETH.sol";
import {IUniswapV2Pair} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import {SafeERC20} from "@solidstate/contracts/utils/SafeERC20.sol";
import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {PoolInternal} from "./PoolInternal.sol";
/**
* @title Premia option pool
* @dev deployed standalone and referenced by PoolProxy
*/
abstract contract PoolSwap is PoolInternal {
using SafeERC20 for IERC20;
using ABDKMath64x64 for int128;
using PoolStorage for PoolStorage.Layout;
address internal immutable UNISWAP_V2_FACTORY;
address internal immutable SUSHISWAP_FACTORY;
constructor(
address ivolOracle,
address weth,
address premiaMining,
address feeReceiver,
address feeDiscountAddress,
int128 fee64x64,
address uniswapV2Factory,
address sushiswapFactory
)
PoolInternal(
ivolOracle,
weth,
premiaMining,
feeReceiver,
feeDiscountAddress,
fee64x64
)
{
UNISWAP_V2_FACTORY = uniswapV2Factory;
SUSHISWAP_FACTORY = sushiswapFactory;
}
// calculates the CREATE2 address for a pair without making any external calls
function _pairFor(
address factory,
address tokenA,
address tokenB,
bool isSushi
) internal pure returns (address pair) {
(address token0, address token1) = _sortTokens(tokenA, tokenB);
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
isSushi
? hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303"
: hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
)
);
}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function _sortTokens(address tokenA, address tokenB)
internal
pure
returns (address token0, address token1)
{
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// performs chained getAmountIn calculations on any number of pairs
function _getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path,
bool isSushi
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = _getReserves(
factory,
path[i - 1],
path[i],
isSushi
);
amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
// fetches and sorts the reserves for a pair
function _getReserves(
address factory,
address tokenA,
address tokenB,
bool isSushi
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = _sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(
_pairFor(factory, tokenA, tokenB, isSushi)
).getReserves();
(reserveA, reserveB) = tokenA == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function _getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn * amountOut * 1000;
uint256 denominator = (reserveOut - amountOut) * 997;
amountIn = (numerator / denominator) + 1;
}
// requires the initial amount to have already been sent to the first pair
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to,
bool isSushi
) internal {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = _sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2
? _pairFor(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
output,
path[i + 2],
isSushi
)
: _to;
IUniswapV2Pair(
_pairFor(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
input,
output,
isSushi
)
).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function _swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
bool isSushi
) internal returns (uint256[] memory amounts) {
amounts = _getAmountsIn(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
amountOut,
path,
isSushi
);
require(
amounts[0] <= amountInMax,
"UniswapV2Router: EXCESSIVE_INPUT_AMOUNT"
);
IERC20(path[0]).safeTransferFrom(
msg.sender,
_pairFor(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
path[0],
path[1],
isSushi
),
amounts[0]
);
_swap(amounts, path, msg.sender, isSushi);
}
function _swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
bool isSushi
) internal returns (uint256[] memory amounts) {
require(path[0] == WETH_ADDRESS, "UniswapV2Router: INVALID_PATH");
amounts = _getAmountsIn(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
amountOut,
path,
isSushi
);
require(
amounts[0] <= msg.value,
"UniswapV2Router: EXCESSIVE_INPUT_AMOUNT"
);
IWETH(WETH_ADDRESS).deposit{value: amounts[0]}();
assert(
IWETH(WETH_ADDRESS).transfer(
_pairFor(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
path[0],
path[1],
isSushi
),
amounts[0]
)
);
_swap(amounts, path, msg.sender, isSushi);
// refund dust eth, if any
if (msg.value > amounts[0]) {
(bool success, ) = payable(msg.sender).call{
value: msg.value - amounts[0]
}(new bytes(0));
require(
success,
"TransferHelper::safeTransferETH: ETH transfer failed"
);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol";
import {OptionMath} from "../libraries/OptionMath.sol";
library PoolStorage {
using ABDKMath64x64 for int128;
using PoolStorage for PoolStorage.Layout;
enum TokenType {
UNDERLYING_FREE_LIQ,
BASE_FREE_LIQ,
UNDERLYING_RESERVED_LIQ,
BASE_RESERVED_LIQ,
LONG_CALL,
SHORT_CALL,
LONG_PUT,
SHORT_PUT
}
struct PoolSettings {
address underlying;
address base;
address underlyingOracle;
address baseOracle;
}
struct QuoteArgsInternal {
address feePayer; // address of the fee payer
uint64 maturity; // timestamp of option maturity
int128 strike64x64; // 64x64 fixed point representation of strike price
int128 spot64x64; // 64x64 fixed point representation of spot price
uint256 contractSize; // size of option contract
bool isCall; // true for call, false for put
}
struct QuoteResultInternal {
int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee)
int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put
int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase
int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size
}
struct BatchData {
uint256 eta;
uint256 totalPendingDeposits;
}
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.Pool");
uint256 private constant C_DECAY_BUFFER = 12 hours;
uint256 private constant C_DECAY_INTERVAL = 4 hours;
struct Layout {
// ERC20 token addresses
address base;
address underlying;
// AggregatorV3Interface oracle addresses
address baseOracle;
address underlyingOracle;
// token metadata
uint8 underlyingDecimals;
uint8 baseDecimals;
// minimum amounts
uint256 baseMinimum;
uint256 underlyingMinimum;
// deposit caps
uint256 basePoolCap;
uint256 underlyingPoolCap;
// market state
int128 _deprecated_steepness64x64;
int128 cLevelBase64x64;
int128 cLevelUnderlying64x64;
uint256 cLevelBaseUpdatedAt;
uint256 cLevelUnderlyingUpdatedAt;
uint256 updatedAt;
// User -> isCall -> depositedAt
mapping(address => mapping(bool => uint256)) depositedAt;
mapping(address => mapping(bool => uint256)) divestmentTimestamps;
// doubly linked list of free liquidity intervals
// isCall -> User -> User
mapping(bool => mapping(address => address)) liquidityQueueAscending;
mapping(bool => mapping(address => address)) liquidityQueueDescending;
// minimum resolution price bucket => price
mapping(uint256 => int128) bucketPrices64x64;
// sequence id (minimum resolution price bucket / 256) => price update sequence
mapping(uint256 => uint256) priceUpdateSequences;
// isCall -> batch data
mapping(bool => BatchData) nextDeposits;
// user -> batch timestamp -> isCall -> pending amount
mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits;
EnumerableSet.UintSet tokenIds;
// user -> isCallPool -> total value locked of user (Used for liquidity mining)
mapping(address => mapping(bool => uint256)) userTVL;
// isCallPool -> total value locked
mapping(bool => uint256) totalTVL;
// steepness values
int128 steepnessBase64x64;
int128 steepnessUnderlying64x64;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
/**
* @notice calculate ERC1155 token id for given option parameters
* @param tokenType TokenType enum
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @return tokenId token id
*/
function formatTokenId(
TokenType tokenType,
uint64 maturity,
int128 strike64x64
) internal pure returns (uint256 tokenId) {
tokenId =
(uint256(tokenType) << 248) +
(uint256(maturity) << 128) +
uint256(int256(strike64x64));
}
/**
* @notice derive option maturity and strike price from ERC1155 token id
* @param tokenId token id
* @return tokenType TokenType enum
* @return maturity timestamp of option maturity
* @return strike64x64 option strike price
*/
function parseTokenId(uint256 tokenId)
internal
pure
returns (
TokenType tokenType,
uint64 maturity,
int128 strike64x64
)
{
assembly {
tokenType := shr(248, tokenId)
maturity := shr(128, tokenId)
strike64x64 := tokenId
}
}
function getTokenDecimals(Layout storage l, bool isCall)
internal
view
returns (uint8 decimals)
{
decimals = isCall ? l.underlyingDecimals : l.baseDecimals;
}
/**
* @notice get the total supply of free liquidity tokens, minus pending deposits
* @param l storage layout struct
* @param isCall whether query is for call or put pool
* @return 64x64 fixed point representation of total free liquidity
*/
function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall)
internal
view
returns (int128)
{
uint256 tokenId = formatTokenId(
isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ,
0,
0
);
return
ABDKMath64x64Token.fromDecimals(
ERC1155EnumerableStorage.layout().totalSupply[tokenId] -
l.nextDeposits[isCall].totalPendingDeposits,
l.getTokenDecimals(isCall)
);
}
function getReinvestmentStatus(
Layout storage l,
address account,
bool isCallPool
) internal view returns (bool) {
uint256 timestamp = l.divestmentTimestamps[account][isCallPool];
return timestamp == 0 || timestamp > block.timestamp;
}
function addUnderwriter(
Layout storage l,
address account,
bool isCallPool
) internal {
require(account != address(0));
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
if (_isInQueue(account, asc, desc)) return;
address last = desc[address(0)];
asc[last] = account;
desc[account] = last;
desc[address(0)] = account;
}
function removeUnderwriter(
Layout storage l,
address account,
bool isCallPool
) internal {
require(account != address(0));
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
if (!_isInQueue(account, asc, desc)) return;
address prev = desc[account];
address next = asc[account];
asc[prev] = next;
desc[next] = prev;
delete asc[account];
delete desc[account];
}
function isInQueue(
Layout storage l,
address account,
bool isCallPool
) internal view returns (bool) {
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
return _isInQueue(account, asc, desc);
}
function _isInQueue(
address account,
mapping(address => address) storage asc,
mapping(address => address) storage desc
) private view returns (bool) {
return asc[account] != address(0) || desc[address(0)] == account;
}
/**
* @notice get current C-Level, without accounting for pending adjustments
* @param l storage layout struct
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function getRawCLevel64x64(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
{
cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64;
}
/**
* @notice get current C-Level, accounting for unrealized decay
* @param l storage layout struct
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function getDecayAdjustedCLevel64x64(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
{
// get raw C-Level from storage
cLevel64x64 = l.getRawCLevel64x64(isCall);
// account for C-Level decay
cLevel64x64 = l.applyCLevelDecayAdjustment(cLevel64x64, isCall);
}
/**
* @notice get updated C-Level and pool liquidity level, accounting for decay and pending deposits
* @param l storage layout struct
* @param isCall whether to update C-Level for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
* @return liquidity64x64 64x64 fixed point representation of new liquidity amount
*/
function getRealPoolState(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64, int128 liquidity64x64)
{
PoolStorage.BatchData storage batchData = l.nextDeposits[isCall];
int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCall);
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
if (
batchData.totalPendingDeposits > 0 &&
batchData.eta != 0 &&
block.timestamp >= batchData.eta
) {
liquidity64x64 = ABDKMath64x64Token
.fromDecimals(
batchData.totalPendingDeposits,
l.getTokenDecimals(isCall)
)
.add(oldLiquidity64x64);
cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment(
oldCLevel64x64,
oldLiquidity64x64,
liquidity64x64,
isCall
);
} else {
cLevel64x64 = oldCLevel64x64;
liquidity64x64 = oldLiquidity64x64;
}
}
/**
* @notice calculate updated C-Level, accounting for unrealized decay
* @param l storage layout struct
* @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for decay
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after accounting for decay
*/
function applyCLevelDecayAdjustment(
Layout storage l,
int128 oldCLevel64x64,
bool isCall
) internal view returns (int128 cLevel64x64) {
uint256 timeElapsed = block.timestamp -
(isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt);
// do not apply C decay if less than 24 hours have elapsed
if (timeElapsed > C_DECAY_BUFFER) {
timeElapsed -= C_DECAY_BUFFER;
} else {
return oldCLevel64x64;
}
int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu(
timeElapsed,
C_DECAY_INTERVAL
);
uint256 tokenId = formatTokenId(
isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ,
0,
0
);
uint256 tvl = l.totalTVL[isCall];
int128 utilization = ABDKMath64x64.divu(
tvl -
(ERC1155EnumerableStorage.layout().totalSupply[tokenId] -
l.nextDeposits[isCall].totalPendingDeposits),
tvl
);
return
OptionMath.calculateCLevelDecay(
OptionMath.CalculateCLevelDecayArgs(
timeIntervalsElapsed64x64,
oldCLevel64x64,
utilization,
0xb333333333333333, // 0.7
0xe666666666666666, // 0.9
0x10000000000000000, // 1.0
0x10000000000000000, // 1.0
0xe666666666666666, // 0.9
0x56fc2a2c515da32ea // 2e
)
);
}
/**
* @notice calculate updated C-Level, accounting for change in liquidity
* @param l storage layout struct
* @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for liquidity change
* @param oldLiquidity64x64 64x64 fixed point representation of previous liquidity
* @param newLiquidity64x64 64x64 fixed point representation of current liquidity
* @param isCallPool whether to update C-Level for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function applyCLevelLiquidityChangeAdjustment(
Layout storage l,
int128 oldCLevel64x64,
int128 oldLiquidity64x64,
int128 newLiquidity64x64,
bool isCallPool
) internal view returns (int128 cLevel64x64) {
int128 steepness64x64 = isCallPool
? l.steepnessUnderlying64x64
: l.steepnessBase64x64;
// fallback to deprecated storage value if side-specific value is not set
if (steepness64x64 == 0) steepness64x64 = l._deprecated_steepness64x64;
cLevel64x64 = OptionMath.calculateCLevel(
oldCLevel64x64,
oldLiquidity64x64,
newLiquidity64x64,
steepness64x64
);
if (cLevel64x64 < 0xb333333333333333) {
cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7
}
}
/**
* @notice set C-Level to arbitrary pre-calculated value
* @param cLevel64x64 new C-Level of pool
* @param isCallPool whether to update C-Level for call or put pool
*/
function setCLevel(
Layout storage l,
int128 cLevel64x64,
bool isCallPool
) internal {
if (isCallPool) {
l.cLevelUnderlying64x64 = cLevel64x64;
l.cLevelUnderlyingUpdatedAt = block.timestamp;
} else {
l.cLevelBase64x64 = cLevel64x64;
l.cLevelBaseUpdatedAt = block.timestamp;
}
}
function setOracles(
Layout storage l,
address baseOracle,
address underlyingOracle
) internal {
require(
AggregatorV3Interface(baseOracle).decimals() ==
AggregatorV3Interface(underlyingOracle).decimals(),
"Pool: oracle decimals must match"
);
l.baseOracle = baseOracle;
l.underlyingOracle = underlyingOracle;
}
function fetchPriceUpdate(Layout storage l)
internal
view
returns (int128 price64x64)
{
int256 priceUnderlying = AggregatorInterface(l.underlyingOracle)
.latestAnswer();
int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer();
return ABDKMath64x64.divi(priceUnderlying, priceBase);
}
/**
* @notice set price update for hourly bucket corresponding to given timestamp
* @param l storage layout struct
* @param timestamp timestamp to update
* @param price64x64 64x64 fixed point representation of price
*/
function setPriceUpdate(
Layout storage l,
uint256 timestamp,
int128 price64x64
) internal {
uint256 bucket = timestamp / (1 hours);
l.bucketPrices64x64[bucket] = price64x64;
l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255));
}
/**
* @notice get price update for hourly bucket corresponding to given timestamp
* @param l storage layout struct
* @param timestamp timestamp to query
* @return 64x64 fixed point representation of price
*/
function getPriceUpdate(Layout storage l, uint256 timestamp)
internal
view
returns (int128)
{
return l.bucketPrices64x64[timestamp / (1 hours)];
}
/**
* @notice get first price update available following given timestamp
* @param l storage layout struct
* @param timestamp timestamp to query
* @return 64x64 fixed point representation of price
*/
function getPriceUpdateAfter(Layout storage l, uint256 timestamp)
internal
view
returns (int128)
{
// price updates are grouped into hourly buckets
uint256 bucket = timestamp / (1 hours);
// divide by 256 to get the index of the relevant price update sequence
uint256 sequenceId = bucket >> 8;
// get position within sequence relevant to current price update
uint256 offset = bucket & 255;
// shift to skip buckets from earlier in sequence
uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >>
offset;
// iterate through future sequences until a price update is found
// sequence corresponding to current timestamp used as upper bound
uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours);
while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) {
sequence = l.priceUpdateSequences[++sequenceId];
}
// if no price update is found (sequence == 0) function will return 0
// this should never occur, as each relevant external function triggers a price update
// the most significant bit of the sequence corresponds to the offset of the relevant bucket
uint256 msb;
for (uint256 i = 128; i > 0; i >>= 1) {
if (sequence >> i > 0) {
msb += i;
sequence >>= i;
}
}
return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1];
}
function fromBaseToUnderlyingDecimals(Layout storage l, uint256 value)
internal
view
returns (uint256)
{
int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals(
value,
l.baseDecimals
);
return
ABDKMath64x64Token.toDecimals(
valueFixed64x64,
l.underlyingDecimals
);
}
function fromUnderlyingToBaseDecimals(Layout storage l, uint256 value)
internal
view
returns (uint256)
{
int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals(
value,
l.underlyingDecimals
);
return ABDKMath64x64Token.toDecimals(valueFixed64x64, l.baseDecimals);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {PremiaMiningStorage} from "./PremiaMiningStorage.sol";
interface IPremiaMining {
function addPremiaRewards(uint256 _amount) external;
function premiaRewardsAvailable() external view returns (uint256);
function getTotalAllocationPoints() external view returns (uint256);
function getPoolInfo(address pool, bool isCallPool)
external
view
returns (PremiaMiningStorage.PoolInfo memory);
function getPremiaPerYear() external view returns (uint256);
function addPool(address _pool, uint256 _allocPoints) external;
function setPoolAllocPoints(
address[] memory _pools,
uint256[] memory _allocPoints
) external;
function pendingPremia(
address _pool,
bool _isCallPool,
address _user
) external view returns (uint256);
function updatePool(
address _pool,
bool _isCallPool,
uint256 _totalTVL
) external;
function allocatePending(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external;
function claim(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20 } from '../token/ERC20/IERC20.sol';
import { IERC20Metadata } from '../token/ERC20/metadata/IERC20Metadata.sol';
/**
* @title WETH (Wrapped ETH) interface
*/
interface IWETH is IERC20, IERC20Metadata {
/**
* @notice convert ETH to WETH
*/
function deposit() external payable;
/**
* @notice convert WETH to ETH
* @dev if caller is a contract, it should have a fallback or receive function
* @param amount quantity of WETH to convert, denominated in wei
*/
function withdraw(uint256 amount) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20 } from '../token/ERC20/IERC20.sol';
import { AddressUtils } from './AddressUtils.sol';
/**
* @title Safe ERC20 interaction library
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
*/
library SafeERC20 {
using AddressUtils 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 safeApprove (like approve) should only be called when setting an initial allowance or when resetting it to zero; otherwise prefer safeIncreaseAllowance and safeDecreaseAllowance
*/
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) + value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(
oldAllowance >= value,
'SafeERC20: decreased allowance below zero'
);
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
}
/**
* @notice send transaction data and check validity of return value, if present
* @param token ERC20 token interface
* @param data transaction data
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
'SafeERC20: low-level call failed'
);
if (returndata.length > 0) {
require(
abi.decode(returndata, (bool)),
'SafeERC20: ERC20 operation did not succeed'
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20Internal } from './IERC20Internal.sol';
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 is IERC20Internal {
/**
* @notice query the total minted token supply
* @return token supply
*/
function totalSupply() external view returns (uint256);
/**
* @notice query the token balance of given account
* @param account address to query
* @return token balance
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice query the allowance granted from given holder to given spender
* @param holder approver of allowance
* @param spender recipient of allowance
* @return token allowance
*/
function allowance(address holder, address spender)
external
view
returns (uint256);
/**
* @notice grant approval to spender to spend tokens
* @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)
* @param spender recipient of allowance
* @param amount quantity of tokens approved for spending
* @return success status (always true; otherwise function should revert)
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @notice transfer tokens to given recipient
* @param recipient beneficiary of token transfer
* @param amount quantity of tokens to transfer
* @return success status (always true; otherwise function should revert)
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @notice transfer tokens to given recipient on behalf of given holder
* @param holder holder of tokens prior to transfer
* @param recipient beneficiary of token transfer
* @param amount quantity of tokens to transfer
* @return success status (always true; otherwise function should revert)
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {IERC173} from "@solidstate/contracts/access/IERC173.sol";
import {OwnableStorage} from "@solidstate/contracts/access/OwnableStorage.sol";
import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol";
import {ERC1155EnumerableInternal, ERC1155EnumerableStorage, EnumerableSet} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol";
import {IWETH} from "@solidstate/contracts/utils/IWETH.sol";
import {PoolStorage} from "./PoolStorage.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol";
import {OptionMath} from "../libraries/OptionMath.sol";
import {IFeeDiscount} from "../staking/IFeeDiscount.sol";
import {IPoolEvents} from "./IPoolEvents.sol";
import {IPremiaMining} from "../mining/IPremiaMining.sol";
import {IVolatilitySurfaceOracle} from "../oracle/IVolatilitySurfaceOracle.sol";
/**
* @title Premia option pool
* @dev deployed standalone and referenced by PoolProxy
*/
contract PoolInternal is IPoolEvents, ERC1155EnumerableInternal {
using ABDKMath64x64 for int128;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using PoolStorage for PoolStorage.Layout;
address internal immutable WETH_ADDRESS;
address internal immutable PREMIA_MINING_ADDRESS;
address internal immutable FEE_RECEIVER_ADDRESS;
address internal immutable FEE_DISCOUNT_ADDRESS;
address internal immutable IVOL_ORACLE_ADDRESS;
int128 internal immutable FEE_64x64;
uint256 internal immutable UNDERLYING_FREE_LIQ_TOKEN_ID;
uint256 internal immutable BASE_FREE_LIQ_TOKEN_ID;
uint256 internal immutable UNDERLYING_RESERVED_LIQ_TOKEN_ID;
uint256 internal immutable BASE_RESERVED_LIQ_TOKEN_ID;
uint256 internal constant INVERSE_BASIS_POINT = 1e4;
uint256 internal constant BATCHING_PERIOD = 260;
// Minimum APY for capital locked up to underwrite options.
// The quote will return a minimum price corresponding to this APY
int128 internal constant MIN_APY_64x64 = 0x4ccccccccccccccd; // 0.3
constructor(
address ivolOracle,
address weth,
address premiaMining,
address feeReceiver,
address feeDiscountAddress,
int128 fee64x64
) {
IVOL_ORACLE_ADDRESS = ivolOracle;
WETH_ADDRESS = weth;
PREMIA_MINING_ADDRESS = premiaMining;
FEE_RECEIVER_ADDRESS = feeReceiver;
// PremiaFeeDiscount contract address
FEE_DISCOUNT_ADDRESS = feeDiscountAddress;
FEE_64x64 = fee64x64;
UNDERLYING_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.UNDERLYING_FREE_LIQ,
0,
0
);
BASE_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.BASE_FREE_LIQ,
0,
0
);
UNDERLYING_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.UNDERLYING_RESERVED_LIQ,
0,
0
);
BASE_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.BASE_RESERVED_LIQ,
0,
0
);
}
modifier onlyProtocolOwner() {
require(
msg.sender == IERC173(OwnableStorage.layout().owner).owner(),
"Not protocol owner"
);
_;
}
function _getFeeDiscount(address feePayer)
internal
view
returns (uint256 discount)
{
if (FEE_DISCOUNT_ADDRESS != address(0)) {
discount = IFeeDiscount(FEE_DISCOUNT_ADDRESS).getDiscount(feePayer);
}
}
function _getFeeWithDiscount(address feePayer, uint256 fee)
internal
view
returns (uint256)
{
uint256 discount = _getFeeDiscount(feePayer);
return fee - ((fee * discount) / INVERSE_BASIS_POINT);
}
function _withdrawFees(bool isCall) internal returns (uint256 amount) {
uint256 tokenId = _getReservedLiquidityTokenId(isCall);
amount = _balanceOf(FEE_RECEIVER_ADDRESS, tokenId);
if (amount > 0) {
_burn(FEE_RECEIVER_ADDRESS, tokenId, amount);
emit FeeWithdrawal(isCall, amount);
}
}
/**
* @notice calculate price of option contract
* @param args structured quote arguments
* @return result quote result
*/
function _quote(PoolStorage.QuoteArgsInternal memory args)
internal
view
returns (PoolStorage.QuoteResultInternal memory result)
{
require(
args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0,
"invalid args"
);
PoolStorage.Layout storage l = PoolStorage.layout();
int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals(
args.contractSize,
l.underlyingDecimals
);
(int128 adjustedCLevel64x64, int128 oldLiquidity64x64) = l
.getRealPoolState(args.isCall);
require(oldLiquidity64x64 > 0, "no liq");
int128 timeToMaturity64x64 = ABDKMath64x64.divu(
args.maturity - block.timestamp,
365 days
);
int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle(
IVOL_ORACLE_ADDRESS
).getAnnualizedVolatility64x64(
l.base,
l.underlying,
args.spot64x64,
args.strike64x64,
timeToMaturity64x64,
args.isCall
);
require(annualizedVolatility64x64 > 0, "vol = 0");
int128 collateral64x64 = args.isCall
? contractSize64x64
: contractSize64x64.mul(args.strike64x64);
(
int128 price64x64,
int128 cLevel64x64,
int128 slippageCoefficient64x64
) = OptionMath.quotePrice(
OptionMath.QuoteArgs(
annualizedVolatility64x64.mul(annualizedVolatility64x64),
args.strike64x64,
args.spot64x64,
timeToMaturity64x64,
adjustedCLevel64x64,
oldLiquidity64x64,
oldLiquidity64x64.sub(collateral64x64),
0x10000000000000000, // 64x64 fixed point representation of 1
MIN_APY_64x64,
args.isCall
)
);
result.baseCost64x64 = args.isCall
? price64x64.mul(contractSize64x64).div(args.spot64x64)
: price64x64.mul(contractSize64x64);
result.feeCost64x64 = result.baseCost64x64.mul(FEE_64x64);
result.cLevel64x64 = cLevel64x64;
result.slippageCoefficient64x64 = slippageCoefficient64x64;
int128 discount = ABDKMath64x64.divu(
_getFeeDiscount(args.feePayer),
INVERSE_BASIS_POINT
);
result.feeCost64x64 -= result.feeCost64x64.mul(discount);
}
/**
* @notice burn corresponding long and short option tokens
* @param account holder of tokens to annihilate
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @param isCall true for call, false for put
* @param contractSize quantity of option contract tokens to annihilate
*/
function _annihilate(
address account,
uint64 maturity,
int128 strike64x64,
bool isCall,
uint256 contractSize
) internal {
uint256 longTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, true),
maturity,
strike64x64
);
uint256 shortTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, false),
maturity,
strike64x64
);
_burn(account, longTokenId, contractSize);
_burn(account, shortTokenId, contractSize);
emit Annihilate(shortTokenId, contractSize);
}
/**
* @notice purchase option
* @param l storage layout struct
* @param account recipient of purchased option
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @param isCall true for call, false for put
* @param contractSize size of option contract
* @param newPrice64x64 64x64 fixed point representation of current spot price
* @return baseCost quantity of tokens required to purchase long position
* @return feeCost quantity of tokens required to pay fees
*/
function _purchase(
PoolStorage.Layout storage l,
address account,
uint64 maturity,
int128 strike64x64,
bool isCall,
uint256 contractSize,
int128 newPrice64x64
) internal returns (uint256 baseCost, uint256 feeCost) {
require(maturity > block.timestamp, "expired");
require(contractSize >= l.underlyingMinimum, "too small");
{
uint256 size = isCall
? contractSize
: l.fromUnderlyingToBaseDecimals(
strike64x64.mulu(contractSize)
);
require(
size <=
ERC1155EnumerableStorage.layout().totalSupply[
_getFreeLiquidityTokenId(isCall)
] -
l.nextDeposits[isCall].totalPendingDeposits,
"insuf liq"
);
}
PoolStorage.QuoteResultInternal memory quote = _quote(
PoolStorage.QuoteArgsInternal(
account,
maturity,
strike64x64,
newPrice64x64,
contractSize,
isCall
)
);
baseCost = ABDKMath64x64Token.toDecimals(
quote.baseCost64x64,
l.getTokenDecimals(isCall)
);
feeCost = ABDKMath64x64Token.toDecimals(
quote.feeCost64x64,
l.getTokenDecimals(isCall)
);
uint256 longTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, true),
maturity,
strike64x64
);
uint256 shortTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, false),
maturity,
strike64x64
);
// mint long option token for buyer
_mint(account, longTokenId, contractSize);
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
// burn free liquidity tokens from other underwriters
_mintShortTokenLoop(
l,
account,
contractSize,
baseCost,
shortTokenId,
isCall
);
int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
_setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCall);
// mint reserved liquidity tokens for fee receiver
_mint(
FEE_RECEIVER_ADDRESS,
_getReservedLiquidityTokenId(isCall),
feeCost
);
emit Purchase(
account,
longTokenId,
contractSize,
baseCost,
feeCost,
newPrice64x64
);
}
/**
* @notice reassign short position to new underwriter
* @param l storage layout struct
* @param account holder of positions to be reassigned
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @param isCall true for call, false for put
* @param contractSize quantity of option contract tokens to reassign
* @param newPrice64x64 64x64 fixed point representation of current spot price
* @return baseCost quantity of tokens required to reassign short position
* @return feeCost quantity of tokens required to pay fees
* @return amountOut quantity of liquidity freed
*/
function _reassign(
PoolStorage.Layout storage l,
address account,
uint64 maturity,
int128 strike64x64,
bool isCall,
uint256 contractSize,
int128 newPrice64x64
)
internal
returns (
uint256 baseCost,
uint256 feeCost,
uint256 amountOut
)
{
(baseCost, feeCost) = _purchase(
l,
account,
maturity,
strike64x64,
isCall,
contractSize,
newPrice64x64
);
_annihilate(account, maturity, strike64x64, isCall, contractSize);
uint256 annihilateAmount = isCall
? contractSize
: l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize));
amountOut = annihilateAmount - baseCost - feeCost;
}
/**
* @notice exercise option on behalf of holder
* @dev used for processing of expired options if passed holder is zero address
* @param holder owner of long option tokens to exercise
* @param longTokenId long option token id
* @param contractSize quantity of tokens to exercise
*/
function _exercise(
address holder,
uint256 longTokenId,
uint256 contractSize
) internal {
uint64 maturity;
int128 strike64x64;
bool isCall;
bool onlyExpired = holder == address(0);
{
PoolStorage.TokenType tokenType;
(tokenType, maturity, strike64x64) = PoolStorage.parseTokenId(
longTokenId
);
require(
tokenType == PoolStorage.TokenType.LONG_CALL ||
tokenType == PoolStorage.TokenType.LONG_PUT,
"invalid type"
);
require(!onlyExpired || maturity < block.timestamp, "not expired");
isCall = tokenType == PoolStorage.TokenType.LONG_CALL;
}
PoolStorage.Layout storage l = PoolStorage.layout();
int128 spot64x64 = _update(l);
if (maturity < block.timestamp) {
spot64x64 = l.getPriceUpdateAfter(maturity);
}
require(
onlyExpired ||
(
isCall
? (spot64x64 > strike64x64)
: (spot64x64 < strike64x64)
),
"not ITM"
);
uint256 exerciseValue;
// option has a non-zero exercise value
if (isCall) {
if (spot64x64 > strike64x64) {
exerciseValue = spot64x64.sub(strike64x64).div(spot64x64).mulu(
contractSize
);
}
} else {
if (spot64x64 < strike64x64) {
exerciseValue = l.fromUnderlyingToBaseDecimals(
strike64x64.sub(spot64x64).mulu(contractSize)
);
}
}
uint256 totalFee;
if (onlyExpired) {
totalFee += _burnLongTokenLoop(
contractSize,
exerciseValue,
longTokenId,
isCall
);
} else {
// burn long option tokens from sender
_burn(holder, longTokenId, contractSize);
uint256 fee;
if (exerciseValue > 0) {
fee = _getFeeWithDiscount(
holder,
FEE_64x64.mulu(exerciseValue)
);
totalFee += fee;
_pushTo(holder, _getPoolToken(isCall), exerciseValue - fee);
}
emit Exercise(
holder,
longTokenId,
contractSize,
exerciseValue,
fee
);
}
totalFee += _burnShortTokenLoop(
contractSize,
exerciseValue,
PoolStorage.formatTokenId(
_getTokenType(isCall, false),
maturity,
strike64x64
),
isCall
);
_mint(
FEE_RECEIVER_ADDRESS,
_getReservedLiquidityTokenId(isCall),
totalFee
);
}
function _mintShortTokenLoop(
PoolStorage.Layout storage l,
address buyer,
uint256 contractSize,
uint256 premium,
uint256 shortTokenId,
bool isCall
) internal {
uint256 freeLiqTokenId = _getFreeLiquidityTokenId(isCall);
(, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId);
uint256 toPay = isCall
? contractSize
: l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize));
while (toPay > 0) {
address underwriter = l.liquidityQueueAscending[isCall][address(0)];
uint256 balance = _balanceOf(underwriter, freeLiqTokenId);
// If dust left, we remove underwriter and skip to next
if (balance < _getMinimumAmount(l, isCall)) {
l.removeUnderwriter(underwriter, isCall);
continue;
}
if (!l.getReinvestmentStatus(underwriter, isCall)) {
_burn(underwriter, freeLiqTokenId, balance);
_mint(
underwriter,
_getReservedLiquidityTokenId(isCall),
balance
);
_subUserTVL(l, underwriter, isCall, balance);
continue;
}
// amount of liquidity provided by underwriter, accounting for reinvested premium
uint256 intervalContractSize = ((balance -
l.pendingDeposits[underwriter][l.nextDeposits[isCall].eta][
isCall
]) * (toPay + premium)) / toPay;
if (intervalContractSize == 0) continue;
if (intervalContractSize > toPay) intervalContractSize = toPay;
// amount of premium paid to underwriter
uint256 intervalPremium = (premium * intervalContractSize) / toPay;
premium -= intervalPremium;
toPay -= intervalContractSize;
_addUserTVL(l, underwriter, isCall, intervalPremium);
// burn free liquidity tokens from underwriter
_burn(
underwriter,
freeLiqTokenId,
intervalContractSize - intervalPremium
);
if (isCall == false) {
// For PUT, conversion to contract amount is done here (Prior to this line, it is token amount)
intervalContractSize = l.fromBaseToUnderlyingDecimals(
strike64x64.inv().mulu(intervalContractSize)
);
}
// mint short option tokens for underwriter
// toPay == 0 ? contractSize : intervalContractSize : To prevent minting less than amount,
// because of rounding (Can happen for put, because of fixed point precision)
_mint(
underwriter,
shortTokenId,
toPay == 0 ? contractSize : intervalContractSize
);
emit Underwrite(
underwriter,
buyer,
shortTokenId,
toPay == 0 ? contractSize : intervalContractSize,
intervalPremium,
false
);
contractSize -= intervalContractSize;
}
}
function _burnLongTokenLoop(
uint256 contractSize,
uint256 exerciseValue,
uint256 longTokenId,
bool isCall
) internal returns (uint256 totalFee) {
EnumerableSet.AddressSet storage holders = ERC1155EnumerableStorage
.layout()
.accountsByToken[longTokenId];
while (contractSize > 0) {
address longTokenHolder = holders.at(holders.length() - 1);
uint256 intervalContractSize = _balanceOf(
longTokenHolder,
longTokenId
);
if (intervalContractSize > contractSize)
intervalContractSize = contractSize;
uint256 intervalExerciseValue;
uint256 fee;
if (exerciseValue > 0) {
intervalExerciseValue =
(exerciseValue * intervalContractSize) /
contractSize;
fee = _getFeeWithDiscount(
longTokenHolder,
FEE_64x64.mulu(intervalExerciseValue)
);
totalFee += fee;
exerciseValue -= intervalExerciseValue;
_pushTo(
longTokenHolder,
_getPoolToken(isCall),
intervalExerciseValue - fee
);
}
contractSize -= intervalContractSize;
emit Exercise(
longTokenHolder,
longTokenId,
intervalContractSize,
intervalExerciseValue - fee,
fee
);
_burn(longTokenHolder, longTokenId, intervalContractSize);
}
}
function _burnShortTokenLoop(
uint256 contractSize,
uint256 exerciseValue,
uint256 shortTokenId,
bool isCall
) internal returns (uint256 totalFee) {
EnumerableSet.AddressSet storage underwriters = ERC1155EnumerableStorage
.layout()
.accountsByToken[shortTokenId];
(, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId);
while (contractSize > 0) {
address underwriter = underwriters.at(underwriters.length() - 1);
// amount of liquidity provided by underwriter
uint256 intervalContractSize = _balanceOf(
underwriter,
shortTokenId
);
if (intervalContractSize > contractSize)
intervalContractSize = contractSize;
// amount of value claimed by buyer
uint256 intervalExerciseValue = (exerciseValue *
intervalContractSize) / contractSize;
exerciseValue -= intervalExerciseValue;
contractSize -= intervalContractSize;
uint256 freeLiq = isCall
? intervalContractSize - intervalExerciseValue
: PoolStorage.layout().fromUnderlyingToBaseDecimals(
strike64x64.mulu(intervalContractSize)
) - intervalExerciseValue;
uint256 fee = _getFeeWithDiscount(
underwriter,
FEE_64x64.mulu(freeLiq)
);
totalFee += fee;
uint256 tvlToSubtract = intervalExerciseValue;
// mint free liquidity tokens for underwriter
if (
PoolStorage.layout().getReinvestmentStatus(underwriter, isCall)
) {
_addToDepositQueue(underwriter, freeLiq - fee, isCall);
tvlToSubtract += fee;
} else {
_mint(
underwriter,
_getReservedLiquidityTokenId(isCall),
freeLiq - fee
);
tvlToSubtract += freeLiq;
}
_subUserTVL(
PoolStorage.layout(),
underwriter,
isCall,
tvlToSubtract
);
// burn short option tokens from underwriter
_burn(underwriter, shortTokenId, intervalContractSize);
emit AssignExercise(
underwriter,
shortTokenId,
freeLiq - fee,
intervalContractSize,
fee
);
}
}
function _addToDepositQueue(
address account,
uint256 amount,
bool isCallPool
) internal {
PoolStorage.Layout storage l = PoolStorage.layout();
_mint(account, _getFreeLiquidityTokenId(isCallPool), amount);
uint256 nextBatch = (block.timestamp / BATCHING_PERIOD) *
BATCHING_PERIOD +
BATCHING_PERIOD;
l.pendingDeposits[account][nextBatch][isCallPool] += amount;
PoolStorage.BatchData storage batchData = l.nextDeposits[isCallPool];
batchData.totalPendingDeposits += amount;
batchData.eta = nextBatch;
}
function _processPendingDeposits(PoolStorage.Layout storage l, bool isCall)
internal
{
PoolStorage.BatchData storage data = l.nextDeposits[isCall];
if (data.eta == 0 || block.timestamp < data.eta) return;
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
_setCLevel(
l,
oldLiquidity64x64,
oldLiquidity64x64.add(
ABDKMath64x64Token.fromDecimals(
data.totalPendingDeposits,
l.getTokenDecimals(isCall)
)
),
isCall
);
delete l.nextDeposits[isCall];
}
function _getFreeLiquidityTokenId(bool isCall)
internal
view
returns (uint256 freeLiqTokenId)
{
freeLiqTokenId = isCall
? UNDERLYING_FREE_LIQ_TOKEN_ID
: BASE_FREE_LIQ_TOKEN_ID;
}
function _getReservedLiquidityTokenId(bool isCall)
internal
view
returns (uint256 reservedLiqTokenId)
{
reservedLiqTokenId = isCall
? UNDERLYING_RESERVED_LIQ_TOKEN_ID
: BASE_RESERVED_LIQ_TOKEN_ID;
}
function _getPoolToken(bool isCall) internal view returns (address token) {
token = isCall
? PoolStorage.layout().underlying
: PoolStorage.layout().base;
}
function _getTokenType(bool isCall, bool isLong)
internal
pure
returns (PoolStorage.TokenType tokenType)
{
if (isCall) {
tokenType = isLong
? PoolStorage.TokenType.LONG_CALL
: PoolStorage.TokenType.SHORT_CALL;
} else {
tokenType = isLong
? PoolStorage.TokenType.LONG_PUT
: PoolStorage.TokenType.SHORT_PUT;
}
}
function _getMinimumAmount(PoolStorage.Layout storage l, bool isCall)
internal
view
returns (uint256 minimumAmount)
{
minimumAmount = isCall ? l.underlyingMinimum : l.baseMinimum;
}
function _getPoolCapAmount(PoolStorage.Layout storage l, bool isCall)
internal
view
returns (uint256 poolCapAmount)
{
poolCapAmount = isCall ? l.underlyingPoolCap : l.basePoolCap;
}
function _setCLevel(
PoolStorage.Layout storage l,
int128 oldLiquidity64x64,
int128 newLiquidity64x64,
bool isCallPool
) internal {
int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCallPool);
int128 cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment(
oldCLevel64x64,
oldLiquidity64x64,
newLiquidity64x64,
isCallPool
);
l.setCLevel(cLevel64x64, isCallPool);
emit UpdateCLevel(
isCallPool,
cLevel64x64,
oldLiquidity64x64,
newLiquidity64x64
);
}
/**
* @notice calculate and store updated market state
* @param l storage layout struct
* @return newPrice64x64 64x64 fixed point representation of current spot price
*/
function _update(PoolStorage.Layout storage l)
internal
returns (int128 newPrice64x64)
{
if (l.updatedAt == block.timestamp) {
return (l.getPriceUpdate(block.timestamp));
}
newPrice64x64 = l.fetchPriceUpdate();
if (l.getPriceUpdate(block.timestamp) == 0) {
l.setPriceUpdate(block.timestamp, newPrice64x64);
}
l.updatedAt = block.timestamp;
_processPendingDeposits(l, true);
_processPendingDeposits(l, false);
}
/**
* @notice transfer ERC20 tokens to message sender
* @param token ERC20 token address
* @param amount quantity of token to transfer
*/
function _pushTo(
address to,
address token,
uint256 amount
) internal {
if (amount == 0) return;
require(IERC20(token).transfer(to, amount), "ERC20 transfer failed");
}
/**
* @notice transfer ERC20 tokens from message sender
* @param from address from which tokens are pulled from
* @param token ERC20 token address
* @param amount quantity of token to transfer
* @param skipWethDeposit if false, will not try to deposit weth from attach eth
*/
function _pullFrom(
address from,
address token,
uint256 amount,
bool skipWethDeposit
) internal {
if (!skipWethDeposit) {
if (token == WETH_ADDRESS) {
if (msg.value > 0) {
if (msg.value > amount) {
IWETH(WETH_ADDRESS).deposit{value: amount}();
(bool success, ) = payable(msg.sender).call{
value: msg.value - amount
}("");
require(success, "ETH refund failed");
amount = 0;
} else {
unchecked {
amount -= msg.value;
}
IWETH(WETH_ADDRESS).deposit{value: msg.value}();
}
}
} else {
require(msg.value == 0, "not WETH deposit");
}
}
if (amount > 0) {
require(
IERC20(token).transferFrom(from, address(this), amount),
"ERC20 transfer failed"
);
}
}
function _mint(
address account,
uint256 tokenId,
uint256 amount
) internal {
_mint(account, tokenId, amount, "");
}
function _addUserTVL(
PoolStorage.Layout storage l,
address user,
bool isCallPool,
uint256 amount
) internal {
uint256 userTVL = l.userTVL[user][isCallPool];
uint256 totalTVL = l.totalTVL[isCallPool];
IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending(
user,
address(this),
isCallPool,
userTVL,
userTVL + amount,
totalTVL
);
l.userTVL[user][isCallPool] = userTVL + amount;
l.totalTVL[isCallPool] = totalTVL + amount;
}
function _subUserTVL(
PoolStorage.Layout storage l,
address user,
bool isCallPool,
uint256 amount
) internal {
uint256 userTVL = l.userTVL[user][isCallPool];
uint256 totalTVL = l.totalTVL[isCallPool];
IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending(
user,
address(this),
isCallPool,
userTVL,
userTVL - amount,
totalTVL
);
l.userTVL[user][isCallPool] = userTVL - amount;
l.totalTVL[isCallPool] = totalTVL - amount;
}
/**
* @notice ERC1155 hook: track eligible underwriters
* @param operator transaction sender
* @param from token sender
* @param to token receiver
* @param ids token ids transferred
* @param amounts token quantities transferred
* @param data data payload
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
PoolStorage.Layout storage l = PoolStorage.layout();
for (uint256 i; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
if (amount == 0) continue;
if (from == address(0)) {
l.tokenIds.add(id);
}
if (
to == address(0) &&
ERC1155EnumerableStorage.layout().totalSupply[id] == 0
) {
l.tokenIds.remove(id);
}
// prevent transfer of free and reserved liquidity during waiting period
if (
id == UNDERLYING_FREE_LIQ_TOKEN_ID ||
id == BASE_FREE_LIQ_TOKEN_ID ||
id == UNDERLYING_RESERVED_LIQ_TOKEN_ID ||
id == BASE_RESERVED_LIQ_TOKEN_ID
) {
if (from != address(0) && to != address(0)) {
bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID ||
id == UNDERLYING_RESERVED_LIQ_TOKEN_ID;
require(
l.depositedAt[from][isCallPool] + (1 days) <
block.timestamp,
"liq lock 1d"
);
}
}
if (
id == UNDERLYING_FREE_LIQ_TOKEN_ID ||
id == BASE_FREE_LIQ_TOKEN_ID
) {
bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID;
uint256 minimum = _getMinimumAmount(l, isCallPool);
if (from != address(0)) {
uint256 balance = _balanceOf(from, id);
if (balance > minimum && balance <= amount + minimum) {
require(
balance -
l.pendingDeposits[from][
l.nextDeposits[isCallPool].eta
][isCallPool] >=
amount,
"Insuf balance"
);
l.removeUnderwriter(from, isCallPool);
}
if (to != address(0)) {
_subUserTVL(l, from, isCallPool, amounts[i]);
_addUserTVL(l, to, isCallPool, amounts[i]);
}
}
if (to != address(0)) {
uint256 balance = _balanceOf(to, id);
if (balance <= minimum && balance + amount > minimum) {
l.addUnderwriter(to, isCallPool);
}
}
}
// Update userTVL on SHORT options transfers
(
PoolStorage.TokenType tokenType,
,
int128 strike64x64
) = PoolStorage.parseTokenId(id);
if (
(from != address(0) && to != address(0)) &&
(tokenType == PoolStorage.TokenType.SHORT_CALL ||
tokenType == PoolStorage.TokenType.SHORT_PUT)
) {
bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL;
uint256 collateral = isCall
? amount
: l.fromUnderlyingToBaseDecimals(strike64x64.mulu(amount));
_subUserTVL(l, from, isCall, collateral);
_addUserTVL(l, to, isCall, collateral);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorInterface {
function latestAnswer()
external
view
returns (
int256
);
function latestTimestamp()
external
view
returns (
uint256
);
function latestRound()
external
view
returns (
uint256
);
function getAnswer(
uint256 roundId
)
external
view
returns (
int256
);
function getTimestamp(
uint256 roundId
)
external
view
returns (
uint256
);
event AnswerUpdated(
int256 indexed current,
uint256 indexed roundId,
uint256 updatedAt
);
event NewRound(
uint256 indexed roundId,
address indexed startedBy,
uint256 startedAt
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
library ERC1155EnumerableStorage {
struct Layout {
mapping(uint256 => uint256) totalSupply;
mapping(uint256 => EnumerableSet.AddressSet) accountsByToken;
mapping(address => EnumerableSet.UintSet) tokensByAccount;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC1155Enumerable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
library ABDKMath64x64Token {
using ABDKMath64x64 for int128;
/**
* @notice convert 64x64 fixed point representation of token amount to decimal
* @param value64x64 64x64 fixed point representation of token amount
* @param decimals token display decimals
* @return value decimal representation of token amount
*/
function toDecimals(int128 value64x64, uint8 decimals)
internal
pure
returns (uint256 value)
{
value = value64x64.mulu(10**decimals);
}
/**
* @notice convert decimal representation of token amount to 64x64 fixed point
* @param value decimal representation of token amount
* @param decimals token display decimals
* @return value64x64 64x64 fixed point representation of token amount
*/
function fromDecimals(uint256 value, uint8 decimals)
internal
pure
returns (int128 value64x64)
{
value64x64 = ABDKMath64x64.divu(value, 10**decimals);
}
/**
* @notice convert 64x64 fixed point representation of token amount to wei (18 decimals)
* @param value64x64 64x64 fixed point representation of token amount
* @return value wei representation of token amount
*/
function toWei(int128 value64x64) internal pure returns (uint256 value) {
value = toDecimals(value64x64, 18);
}
/**
* @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point
* @param value wei representation of token amount
* @return value64x64 64x64 fixed point representation of token amount
*/
function fromWei(uint256 value) internal pure returns (int128 value64x64) {
value64x64 = fromDecimals(value, 18);
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
library OptionMath {
using ABDKMath64x64 for int128;
struct QuoteArgs {
int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance
int128 strike64x64; // 64x64 fixed point representation of strike price
int128 spot64x64; // 64x64 fixed point representation of spot price
int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years)
int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase
int128 oldPoolState; // 64x64 fixed point representation of current state of the pool
int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade
int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier
int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options
bool isCall; // whether to price "call" or "put" option
}
struct CalculateCLevelDecayArgs {
int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update
int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay
int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate
int128 utilizationLowerBound64x64;
int128 utilizationUpperBound64x64;
int128 cLevelLowerBound64x64;
int128 cLevelUpperBound64x64;
int128 cConvergenceULowerBound64x64;
int128 cConvergenceUUpperBound64x64;
}
// 64x64 fixed point integer constants
int128 internal constant ONE_64x64 = 0x10000000000000000;
int128 internal constant THREE_64x64 = 0x30000000000000000;
// 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF
int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989
int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989
int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989
/**
* @notice recalculate C-Level based on change in liquidity
* @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update
* @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update
* @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update
* @param steepness64x64 64x64 fixed point representation of steepness coefficient
* @return 64x64 fixed point representation of new C-Level
*/
function calculateCLevel(
int128 initialCLevel64x64,
int128 oldPoolState64x64,
int128 newPoolState64x64,
int128 steepness64x64
) external pure returns (int128) {
return
newPoolState64x64
.sub(oldPoolState64x64)
.div(
oldPoolState64x64 > newPoolState64x64
? oldPoolState64x64
: newPoolState64x64
)
.mul(steepness64x64)
.neg()
.exp()
.mul(initialCLevel64x64);
}
/**
* @notice calculate the price of an option using the Premia Finance model
* @param args arguments of quotePrice
* @return premiaPrice64x64 64x64 fixed point representation of Premia option price
* @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase
*/
function quotePrice(QuoteArgs memory args)
external
pure
returns (
int128 premiaPrice64x64,
int128 cLevel64x64,
int128 slippageCoefficient64x64
)
{
int128 deltaPoolState64x64 = args
.newPoolState
.sub(args.oldPoolState)
.div(args.oldPoolState)
.mul(args.steepness64x64);
int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp();
int128 blackScholesPrice64x64 = _blackScholesPrice(
args.varianceAnnualized64x64,
args.strike64x64,
args.spot64x64,
args.timeToMaturity64x64,
args.isCall
);
cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64);
slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div(
deltaPoolState64x64
);
premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul(
slippageCoefficient64x64
);
int128 intrinsicValue64x64;
if (args.isCall && args.strike64x64 < args.spot64x64) {
intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64);
} else if (!args.isCall && args.strike64x64 > args.spot64x64) {
intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64);
}
int128 collateralValue64x64 = args.isCall
? args.spot64x64
: args.strike64x64;
int128 minPrice64x64 = intrinsicValue64x64.add(
collateralValue64x64.mul(args.minAPY64x64).mul(
args.timeToMaturity64x64
)
);
if (minPrice64x64 > premiaPrice64x64) {
premiaPrice64x64 = minPrice64x64;
}
}
/**
* @notice calculate the decay of C-Level based on heat diffusion function
* @param args structured CalculateCLevelDecayArgs
* @return cLevelDecayed64x64 C-Level after accounting for decay
*/
function calculateCLevelDecay(CalculateCLevelDecayArgs memory args)
external
pure
returns (int128 cLevelDecayed64x64)
{
int128 convFHighU64x64 = (args.utilization64x64 >=
args.utilizationUpperBound64x64 &&
args.oldCLevel64x64 <= args.cLevelLowerBound64x64)
? ONE_64x64
: int128(0);
int128 convFLowU64x64 = (args.utilization64x64 <=
args.utilizationLowerBound64x64 &&
args.oldCLevel64x64 >= args.cLevelUpperBound64x64)
? ONE_64x64
: int128(0);
cLevelDecayed64x64 = args
.oldCLevel64x64
.sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64))
.sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64))
.mul(
convFLowU64x64
.mul(ONE_64x64.sub(args.utilization64x64))
.add(convFHighU64x64.mul(args.utilization64x64))
.mul(args.timeIntervalsElapsed64x64)
.neg()
.exp()
)
.add(
args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add(
args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)
)
);
}
/**
* @notice calculate the exponential decay coefficient for a given interval
* @param oldTimestamp timestamp of previous update
* @param newTimestamp current timestamp
* @return 64x64 fixed point representation of exponential decay coefficient
*/
function _decay(uint256 oldTimestamp, uint256 newTimestamp)
internal
pure
returns (int128)
{
return
ONE_64x64.sub(
(-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp()
);
}
/**
* @notice calculate Choudhury’s approximation of the Black-Scholes CDF
* @param input64x64 64x64 fixed point representation of random variable
* @return 64x64 fixed point representation of the approximated CDF of x
*/
function _N(int128 input64x64) internal pure returns (int128) {
// squaring via mul is cheaper than via pow
int128 inputSquared64x64 = input64x64.mul(input64x64);
int128 value64x64 = (-inputSquared64x64 >> 1).exp().div(
CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add(
CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt())
)
);
return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64;
}
/**
* @notice calculate the price of an option using the Black-Scholes model
* @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance
* @param strike64x64 64x64 fixed point representation of strike price
* @param spot64x64 64x64 fixed point representation of spot price
* @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years)
* @param isCall whether to price "call" or "put" option
* @return 64x64 fixed point representation of Black-Scholes option price
*/
function _blackScholesPrice(
int128 varianceAnnualized64x64,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) internal pure returns (int128) {
int128 cumulativeVariance64x64 = timeToMaturity64x64.mul(
varianceAnnualized64x64
);
int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt();
int128 d1_64x64 = spot64x64
.div(strike64x64)
.ln()
.add(cumulativeVariance64x64 >> 1)
.div(cumulativeVarianceSqrt64x64);
int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64);
if (isCall) {
return
spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64)));
} else {
return
-spot64x64.mul(_N(-d1_64x64)).sub(
strike64x64.mul(_N(-d2_64x64))
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC20 metadata interface
*/
interface IERC20Metadata {
/**
* @notice return token name
* @return token name
*/
function name() external view returns (string memory);
/**
* @notice return token symbol
* @return token symbol
*/
function symbol() external view returns (string memory);
/**
* @notice return token decimals, generally used only for display purposes
* @return token decimals
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Partial ERC20 interface needed by internal functions
*/
interface IERC20Internal {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library AddressUtils {
function toString(address account) internal pure returns (string memory) {
bytes32 value = bytes32(uint256(uint160(account)));
bytes memory alphabet = '0123456789abcdef';
bytes memory chars = new bytes(42);
chars[0] = '0';
chars[1] = 'x';
for (uint256 i = 0; i < 20; i++) {
chars[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)];
chars[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)];
}
return string(chars);
}
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable account, uint256 amount) internal {
(bool success, ) = account.call{ value: amount }('');
require(success, 'AddressUtils: failed to send value');
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionCall(target, data, 'AddressUtils: failed low-level call');
}
function functionCall(
address target,
bytes memory data,
string memory error
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, error);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'AddressUtils: failed low-level call with value'
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'AddressUtils: insufficient balance for call'
);
return _functionCallWithValue(target, data, value, error);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) private returns (bytes memory) {
require(
isContract(target),
'AddressUtils: function call to non-contract'
);
(bool success, bytes memory returnData) = target.call{ value: value }(
data
);
if (success) {
return returnData;
} else if (returnData.length > 0) {
assembly {
let returnData_size := mload(returnData)
revert(add(32, returnData), returnData_size)
}
} else {
revert(error);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Contract ownership standard interface
* @dev see https://eips.ethereum.org/EIPS/eip-173
*/
interface IERC173 {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @notice get the ERC173 contract owner
* @return conract owner
*/
function owner() external view returns (address);
/**
* @notice transfer contract ownership to new account
* @param account address of new owner
*/
function transferOwnership(address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library OwnableStorage {
struct Layout {
address owner;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.Ownable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function setOwner(Layout storage l, address owner) internal {
l.owner = owner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
import { ERC1155Base, ERC1155BaseInternal } from '../base/ERC1155Base.sol';
import { IERC1155Enumerable } from './IERC1155Enumerable.sol';
import { ERC1155EnumerableInternal, ERC1155EnumerableStorage } from './ERC1155EnumerableInternal.sol';
/**
* @title ERC1155 implementation including enumerable and aggregate functions
*/
abstract contract ERC1155Enumerable is
IERC1155Enumerable,
ERC1155Base,
ERC1155EnumerableInternal
{
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @inheritdoc IERC1155Enumerable
*/
function totalSupply(uint256 id)
public
view
virtual
override
returns (uint256)
{
return ERC1155EnumerableStorage.layout().totalSupply[id];
}
/**
* @inheritdoc IERC1155Enumerable
*/
function totalHolders(uint256 id)
public
view
virtual
override
returns (uint256)
{
return ERC1155EnumerableStorage.layout().accountsByToken[id].length();
}
/**
* @inheritdoc IERC1155Enumerable
*/
function accountsByToken(uint256 id)
public
view
virtual
override
returns (address[] memory)
{
EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage
.layout()
.accountsByToken[id];
address[] memory addresses = new address[](accounts.length());
for (uint256 i; i < accounts.length(); i++) {
addresses[i] = accounts.at(i);
}
return addresses;
}
/**
* @inheritdoc IERC1155Enumerable
*/
function tokensByAccount(address account)
public
view
virtual
override
returns (uint256[] memory)
{
EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage
.layout()
.tokensByAccount[account];
uint256[] memory ids = new uint256[](tokens.length());
for (uint256 i; i < tokens.length(); i++) {
ids[i] = tokens.at(i);
}
return ids;
}
/**
* @notice ERC1155 hook: update aggregate values
* @inheritdoc ERC1155EnumerableInternal
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
override(ERC1155BaseInternal, ERC1155EnumerableInternal)
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {FeeDiscountStorage} from "./FeeDiscountStorage.sol";
interface IFeeDiscount {
event Staked(
address indexed user,
uint256 amount,
uint256 stakePeriod,
uint256 lockedUntil
);
event Unstaked(address indexed user, uint256 amount);
struct StakeLevel {
uint256 amount; // Amount to stake
uint256 discount; // Discount when amount is reached
}
/**
* @notice Stake using IERC2612 permit
* @param amount The amount of xPremia to stake
* @param period The lockup period (in seconds)
* @param deadline Deadline after which permit will fail
* @param v V
* @param r R
* @param s S
*/
function stakeWithPermit(
uint256 amount,
uint256 period,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Lockup xPremia for protocol fee discounts
* Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation
* @param amount The amount of xPremia to stake
* @param period The lockup period (in seconds)
*/
function stake(uint256 amount, uint256 period) external;
/**
* @notice Unstake xPremia (If lockup period has ended)
* @param amount The amount of xPremia to unstake
*/
function unstake(uint256 amount) external;
//////////
// View //
//////////
/**
* Calculate the stake amount of a user, after applying the bonus from the lockup period chosen
* @param user The user from which to query the stake amount
* @return The user stake amount after applying the bonus
*/
function getStakeAmountWithBonus(address user)
external
view
returns (uint256);
/**
* @notice Calculate the % of fee discount for user, based on his stake
* @param user The _user for which the discount is for
* @return Percentage of protocol fee discount (in basis point)
* Ex : 1000 = 10% fee discount
*/
function getDiscount(address user) external view returns (uint256);
/**
* @notice Get stake levels
* @return Stake levels
* Ex : 2500 = -25%
*/
function getStakeLevels() external returns (StakeLevel[] memory);
/**
* @notice Get stake period multiplier
* @param period The duration (in seconds) for which tokens are locked
* @return The multiplier for this staking period
* Ex : 20000 = x2
*/
function getStakePeriodMultiplier(uint256 period)
external
returns (uint256);
/**
* @notice Get staking infos of a user
* @param user The user address for which to get staking infos
* @return The staking infos of the user
*/
function getUserInfo(address user)
external
view
returns (FeeDiscountStorage.UserInfo memory);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
interface IPoolEvents {
event Purchase(
address indexed user,
uint256 longTokenId,
uint256 contractSize,
uint256 baseCost,
uint256 feeCost,
int128 spot64x64
);
event Exercise(
address indexed user,
uint256 longTokenId,
uint256 contractSize,
uint256 exerciseValue,
uint256 fee
);
event Underwrite(
address indexed underwriter,
address indexed longReceiver,
uint256 shortTokenId,
uint256 intervalContractSize,
uint256 intervalPremium,
bool isManualUnderwrite
);
event AssignExercise(
address indexed underwriter,
uint256 shortTokenId,
uint256 freedAmount,
uint256 intervalContractSize,
uint256 fee
);
event Deposit(address indexed user, bool isCallPool, uint256 amount);
event Withdrawal(
address indexed user,
bool isCallPool,
uint256 depositedAt,
uint256 amount
);
event FeeWithdrawal(bool indexed isCallPool, uint256 amount);
event Annihilate(uint256 shortTokenId, uint256 amount);
event UpdateCLevel(
bool indexed isCall,
int128 cLevel64x64,
int128 oldLiquidity64x64,
int128 newLiquidity64x64
);
event UpdateSteepness(int128 steepness64x64, bool isCallPool);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {VolatilitySurfaceOracleStorage} from "./VolatilitySurfaceOracleStorage.sol";
interface IVolatilitySurfaceOracle {
function getWhitelistedRelayers() external view returns (address[] memory);
function getVolatilitySurface(address baseToken, address underlyingToken)
external
view
returns (VolatilitySurfaceOracleStorage.Update memory);
function getVolatilitySurfaceCoefficientsUnpacked(
address baseToken,
address underlyingToken,
bool isCall
) external view returns (int256[] memory);
function getTimeToMaturity64x64(uint64 maturity)
external
view
returns (int128);
function getAnnualizedVolatility64x64(
address baseToken,
address underlyingToken,
int128 spot64x64,
int128 strike64x64,
int128 timeToMaturity64x64,
bool isCall
) external view returns (int128);
function getBlackScholesPrice64x64(
address baseToken,
address underlyingToken,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) external view returns (int128);
function getBlackScholesPrice(
address baseToken,
address underlyingToken,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC1155 } from '../IERC1155.sol';
import { IERC1155Receiver } from '../IERC1155Receiver.sol';
import { ERC1155BaseInternal, ERC1155BaseStorage } from './ERC1155BaseInternal.sol';
/**
* @title Base ERC1155 contract
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
*/
abstract contract ERC1155Base is IERC1155, ERC1155BaseInternal {
/**
* @inheritdoc IERC1155
*/
function balanceOf(address account, uint256 id)
public
view
virtual
override
returns (uint256)
{
return _balanceOf(account, id);
}
/**
* @inheritdoc IERC1155
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(
accounts.length == ids.length,
'ERC1155: accounts and ids length mismatch'
);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
uint256[] memory batchBalances = new uint256[](accounts.length);
unchecked {
for (uint256 i; i < accounts.length; i++) {
require(
accounts[i] != address(0),
'ERC1155: batch balance query for the zero address'
);
batchBalances[i] = balances[ids[i]][accounts[i]];
}
}
return batchBalances;
}
/**
* @inheritdoc IERC1155
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return ERC1155BaseStorage.layout().operatorApprovals[account][operator];
}
/**
* @inheritdoc IERC1155
*/
function setApprovalForAll(address operator, bool status)
public
virtual
override
{
require(
msg.sender != operator,
'ERC1155: setting approval status for self'
);
ERC1155BaseStorage.layout().operatorApprovals[msg.sender][
operator
] = status;
emit ApprovalForAll(msg.sender, operator, status);
}
/**
* @inheritdoc IERC1155
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
'ERC1155: caller is not owner nor approved'
);
_safeTransfer(msg.sender, from, to, id, amount, data);
}
/**
* @inheritdoc IERC1155
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
'ERC1155: caller is not owner nor approved'
);
_safeTransferBatch(msg.sender, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC1155 enumerable and aggregate function interface
*/
interface IERC1155Enumerable {
/**
* @notice query total minted supply of given token
* @param id token id to query
* @return token supply
*/
function totalSupply(uint256 id) external view returns (uint256);
/**
* @notice query total number of holders for given token
* @param id token id to query
* @return quantity of holders
*/
function totalHolders(uint256 id) external view returns (uint256);
/**
* @notice query holders of given token
* @param id token id to query
* @return list of holder addresses
*/
function accountsByToken(uint256 id)
external
view
returns (address[] memory);
/**
* @notice query tokens held by given address
* @param account address to query
* @return list of token ids
*/
function tokensByAccount(address account)
external
view
returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
import { ERC1155BaseInternal, ERC1155BaseStorage } from '../base/ERC1155BaseInternal.sol';
import { ERC1155EnumerableStorage } from './ERC1155EnumerableStorage.sol';
/**
* @title ERC1155Enumerable internal functions
*/
abstract contract ERC1155EnumerableInternal is ERC1155BaseInternal {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice ERC1155 hook: update aggregate values
* @inheritdoc ERC1155BaseInternal
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from != to) {
ERC1155EnumerableStorage.Layout storage l = ERC1155EnumerableStorage
.layout();
mapping(uint256 => EnumerableSet.AddressSet)
storage tokenAccounts = l.accountsByToken;
EnumerableSet.UintSet storage fromTokens = l.tokensByAccount[from];
EnumerableSet.UintSet storage toTokens = l.tokensByAccount[to];
for (uint256 i; i < ids.length; i++) {
uint256 amount = amounts[i];
if (amount > 0) {
uint256 id = ids[i];
if (from == address(0)) {
l.totalSupply[id] += amount;
} else if (_balanceOf(from, id) == amount) {
tokenAccounts[id].remove(from);
fromTokens.remove(id);
}
if (to == address(0)) {
l.totalSupply[id] -= amount;
} else if (_balanceOf(to, id) == 0) {
tokenAccounts[id].add(to);
toTokens.add(id);
}
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC1155Internal } from './IERC1155Internal.sol';
import { IERC165 } from '../../introspection/IERC165.sol';
/**
* @notice ERC1155 interface
* @dev see https://github.com/ethereum/EIPs/issues/1155
*/
interface IERC1155 is IERC1155Internal, IERC165 {
/**
* @notice query the balance of given token held by given address
* @param account address to query
* @param id token to query
* @return token balance
*/
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
/**
* @notice query the balances of given tokens held by given addresses
* @param accounts addresss to query
* @param ids tokens to query
* @return token balances
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @notice query approval status of given operator with respect to given address
* @param account address to query for approval granted
* @param operator address to query for approval received
* @return whether operator is approved to spend tokens held by account
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
/**
* @notice grant approval to or revoke approval from given operator to spend held tokens
* @param operator address whose approval status to update
* @param status whether operator should be considered approved
*/
function setApprovalForAll(address operator, bool status) external;
/**
* @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable
* @param from sender of tokens
* @param to receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable
* @param from sender of tokens
* @param to receiver of tokens
* @param ids list of token IDs
* @param amounts list of quantities of tokens to transfer
* @param data data payload
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC165 } from '../../introspection/IERC165.sol';
/**
* @title ERC1155 transfer receiver interface
*/
interface IERC1155Receiver is IERC165 {
/**
* @notice validate receipt of ERC1155 transfer
* @param operator executor of transfer
* @param from sender of tokens
* @param id token ID received
* @param value quantity of tokens received
* @param data data payload
* @return function's own selector if transfer is accepted
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @notice validate receipt of ERC1155 batch transfer
* @param operator executor of transfer
* @param from sender of tokens
* @param ids token IDs received
* @param values quantities of tokens received
* @param data data payload
* @return function's own selector if transfer is accepted
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { AddressUtils } from '../../../utils/AddressUtils.sol';
import { IERC1155Internal } from '../IERC1155Internal.sol';
import { IERC1155Receiver } from '../IERC1155Receiver.sol';
import { ERC1155BaseStorage } from './ERC1155BaseStorage.sol';
/**
* @title Base ERC1155 internal functions
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
*/
abstract contract ERC1155BaseInternal is IERC1155Internal {
using AddressUtils for address;
/**
* @notice query the balance of given token held by given address
* @param account address to query
* @param id token to query
* @return token balance
*/
function _balanceOf(address account, uint256 id)
internal
view
virtual
returns (uint256)
{
require(
account != address(0),
'ERC1155: balance query for the zero address'
);
return ERC1155BaseStorage.layout().balances[id][account];
}
/**
* @notice mint given quantity of tokens for given address
* @dev ERC1155Receiver implementation is not checked
* @param account beneficiary of minting
* @param id token ID
* @param amount quantity of tokens to mint
* @param data data payload
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), 'ERC1155: mint to the zero address');
_beforeTokenTransfer(
msg.sender,
address(0),
account,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
mapping(address => uint256) storage balances = ERC1155BaseStorage
.layout()
.balances[id];
balances[account] += amount;
emit TransferSingle(msg.sender, address(0), account, id, amount);
}
/**
* @notice mint given quantity of tokens for given address
* @param account beneficiary of minting
* @param id token ID
* @param amount quantity of tokens to mint
* @param data data payload
*/
function _safeMint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
_mint(account, id, amount, data);
_doSafeTransferAcceptanceCheck(
msg.sender,
address(0),
account,
id,
amount,
data
);
}
/**
* @notice mint batch of tokens for given address
* @dev ERC1155Receiver implementation is not checked
* @param account beneficiary of minting
* @param ids list of token IDs
* @param amounts list of quantities of tokens to mint
* @param data data payload
*/
function _mintBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(account != address(0), 'ERC1155: mint to the zero address');
require(
ids.length == amounts.length,
'ERC1155: ids and amounts length mismatch'
);
_beforeTokenTransfer(
msg.sender,
address(0),
account,
ids,
amounts,
data
);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
for (uint256 i; i < ids.length; i++) {
balances[ids[i]][account] += amounts[i];
}
emit TransferBatch(msg.sender, address(0), account, ids, amounts);
}
/**
* @notice mint batch of tokens for given address
* @param account beneficiary of minting
* @param ids list of token IDs
* @param amounts list of quantities of tokens to mint
* @param data data payload
*/
function _safeMintBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
_mintBatch(account, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(
msg.sender,
address(0),
account,
ids,
amounts,
data
);
}
/**
* @notice burn given quantity of tokens held by given address
* @param account holder of tokens to burn
* @param id token ID
* @param amount quantity of tokens to burn
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), 'ERC1155: burn from the zero address');
_beforeTokenTransfer(
msg.sender,
account,
address(0),
_asSingletonArray(id),
_asSingletonArray(amount),
''
);
mapping(address => uint256) storage balances = ERC1155BaseStorage
.layout()
.balances[id];
unchecked {
require(
balances[account] >= amount,
'ERC1155: burn amount exceeds balances'
);
balances[account] -= amount;
}
emit TransferSingle(msg.sender, account, address(0), id, amount);
}
/**
* @notice burn given batch of tokens held by given address
* @param account holder of tokens to burn
* @param ids token IDs
* @param amounts quantities of tokens to burn
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), 'ERC1155: burn from the zero address');
require(
ids.length == amounts.length,
'ERC1155: ids and amounts length mismatch'
);
_beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, '');
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
unchecked {
for (uint256 i; i < ids.length; i++) {
uint256 id = ids[i];
require(
balances[id][account] >= amounts[i],
'ERC1155: burn amount exceeds balance'
);
balances[id][account] -= amounts[i];
}
}
emit TransferBatch(msg.sender, account, address(0), ids, amounts);
}
/**
* @notice transfer tokens between given addresses
* @dev ERC1155Receiver implementation is not checked
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function _transfer(
address operator,
address sender,
address recipient,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(
recipient != address(0),
'ERC1155: transfer to the zero address'
);
_beforeTokenTransfer(
operator,
sender,
recipient,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
unchecked {
uint256 senderBalance = balances[id][sender];
require(
senderBalance >= amount,
'ERC1155: insufficient balances for transfer'
);
balances[id][sender] = senderBalance - amount;
}
balances[id][recipient] += amount;
emit TransferSingle(operator, sender, recipient, id, amount);
}
/**
* @notice transfer tokens between given addresses
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function _safeTransfer(
address operator,
address sender,
address recipient,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
_transfer(operator, sender, recipient, id, amount, data);
_doSafeTransferAcceptanceCheck(
operator,
sender,
recipient,
id,
amount,
data
);
}
/**
* @notice transfer batch of tokens between given addresses
* @dev ERC1155Receiver implementation is not checked
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _transferBatch(
address operator,
address sender,
address recipient,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(
recipient != address(0),
'ERC1155: transfer to the zero address'
);
require(
ids.length == amounts.length,
'ERC1155: ids and amounts length mismatch'
);
_beforeTokenTransfer(operator, sender, recipient, ids, amounts, data);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
for (uint256 i; i < ids.length; i++) {
uint256 token = ids[i];
uint256 amount = amounts[i];
unchecked {
uint256 senderBalance = balances[token][sender];
require(
senderBalance >= amount,
'ERC1155: insufficient balances for transfer'
);
balances[token][sender] = senderBalance - amount;
}
balances[token][recipient] += amount;
}
emit TransferBatch(operator, sender, recipient, ids, amounts);
}
/**
* @notice transfer batch of tokens between given addresses
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _safeTransferBatch(
address operator,
address sender,
address recipient,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
_transferBatch(operator, sender, recipient, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(
operator,
sender,
recipient,
ids,
amounts,
data
);
}
/**
* @notice wrap given element in array of length 1
* @param element element to wrap
* @return singleton array
*/
function _asSingletonArray(uint256 element)
private
pure
returns (uint256[] memory)
{
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
/**
* @notice revert if applicable transfer recipient is not valid ERC1155Receiver
* @param operator executor of transfer
* @param from sender of tokens
* @param to receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155Received(
operator,
from,
id,
amount,
data
)
returns (bytes4 response) {
require(
response == IERC1155Receiver.onERC1155Received.selector,
'ERC1155: ERC1155Receiver rejected tokens'
);
} catch Error(string memory reason) {
revert(reason);
} catch {
revert('ERC1155: transfer to non ERC1155Receiver implementer');
}
}
}
/**
* @notice revert if applicable transfer recipient is not valid ERC1155Receiver
* @param operator executor of transfer
* @param from sender of tokens
* @param to receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
require(
response ==
IERC1155Receiver.onERC1155BatchReceived.selector,
'ERC1155: ERC1155Receiver rejected tokens'
);
} catch Error(string memory reason) {
revert(reason);
} catch {
revert('ERC1155: transfer to non ERC1155Receiver implementer');
}
}
}
/**
* @notice ERC1155 hook, called before all transfers including mint and burn
* @dev function should be overridden and new implementation must call super
* @dev called for both single and batch transfers
* @param operator executor of transfer
* @param from sender of tokens
* @param to receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC165 } from '../../introspection/IERC165.sol';
/**
* @notice Partial ERC1155 interface needed by internal functions
*/
interface IERC1155Internal {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC165 interface registration interface
* @dev see https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice query whether contract has registered support for given interface
* @param interfaceId interface id
* @return bool whether interface is supported
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library ERC1155BaseStorage {
struct Layout {
mapping(uint256 => mapping(address => uint256)) balances;
mapping(address => mapping(address => bool)) operatorApprovals;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC1155Base');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
library FeeDiscountStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.staking.PremiaFeeDiscount");
struct UserInfo {
uint256 balance; // Balance staked by user
uint64 stakePeriod; // Stake period selected by user
uint64 lockedUntil; // Timestamp at which the lock ends
}
struct Layout {
// User data with xPREMIA balance staked and date at which lock ends
mapping(address => UserInfo) userInfo;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
library PremiaMiningStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.PremiaMining");
// Info of each pool.
struct PoolInfo {
uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block.
uint256 lastRewardTimestamp; // Last timestamp that PREMIA distribution occurs
uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below.
}
// Info of each user.
struct UserInfo {
uint256 reward; // Total allocated unclaimed reward
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of PREMIA
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accPremiaPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct Layout {
// Total PREMIA left to distribute
uint256 premiaAvailable;
// Amount of premia distributed per year
uint256 premiaPerYear;
// pool -> isCallPool -> PoolInfo
mapping(address => mapping(bool => PoolInfo)) poolInfo;
// pool -> isCallPool -> user -> UserInfo
mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 totalAllocPoint;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol";
library VolatilitySurfaceOracleStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.VolatilitySurfaceOracle");
uint256 internal constant COEFF_BITS = 51;
uint256 internal constant COEFF_BITS_MINUS_ONE = 50;
uint256 internal constant COEFF_AMOUNT = 5;
// START_BIT = COEFF_BITS * (COEFF_AMOUNT - 1)
uint256 internal constant START_BIT = 204;
struct Update {
uint256 updatedAt;
bytes32 callCoefficients;
bytes32 putCoefficients;
}
struct Layout {
// Base token -> Underlying token -> Update
mapping(address => mapping(address => Update)) volatilitySurfaces;
// Relayer addresses which can be trusted to provide accurate option trades
EnumerableSet.AddressSet whitelistedRelayers;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function getCoefficients(
Layout storage l,
address baseToken,
address underlyingToken,
bool isCall
) internal view returns (bytes32) {
Update storage u = l.volatilitySurfaces[baseToken][underlyingToken];
return isCall ? u.callCoefficients : u.putCoefficients;
}
function parseVolatilitySurfaceCoefficients(bytes32 input)
internal
pure
returns (int256[] memory coefficients)
{
coefficients = new int256[](COEFF_AMOUNT);
// Value to add to negative numbers to cast them to int256
int256 toAdd = (int256(-1) >> COEFF_BITS) << COEFF_BITS;
assembly {
let i := 0
// Value equal to -1
let mid := shl(COEFF_BITS_MINUS_ONE, 1)
for {
} lt(i, COEFF_AMOUNT) {
} {
let offset := sub(START_BIT, mul(COEFF_BITS, i))
let coeff := shr(
offset,
sub(
input,
shl(
add(offset, COEFF_BITS),
shr(add(offset, COEFF_BITS), input)
)
)
)
// Check if value is a negative number and needs casting
if or(eq(coeff, mid), gt(coeff, mid)) {
coeff := add(coeff, toAdd)
}
// Store result in the coefficients array
mstore(add(coefficients, add(0x20, mul(0x20, i))), coeff)
i := add(i, 1)
}
}
}
function formatVolatilitySurfaceCoefficients(int256[5] memory coefficients)
internal
pure
returns (bytes32 result)
{
for (uint256 i = 0; i < COEFF_AMOUNT; i++) {
int256 max = int256(1 << COEFF_BITS_MINUS_ONE);
require(
coefficients[i] < max && coefficients[i] > -max,
"Out of bounds"
);
}
assembly {
let i := 0
for {
} lt(i, COEFF_AMOUNT) {
} {
let offset := sub(START_BIT, mul(COEFF_BITS, i))
let coeff := mload(add(coefficients, mul(0x20, i)))
result := add(
result,
shl(
offset,
sub(coeff, shl(COEFF_BITS, shr(COEFF_BITS, coeff)))
)
)
i := add(i, 1)
}
}
}
} | Calculate x / y rounding towards zero, where x and y are unsigned 256-bit integer numbers. Revert on overflow or when y is zero. x unsigned 256-bit integer number y unsigned 256-bit integer number return unsigned 64.64-bit fixed point number/ | function divuu (uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
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;
lo = hi << 128;
if (xl < lo) xh -= 1;
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
}
| 103,850 |
pragma solidity ^0.4.18;
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) {
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;
}
}
interface ERC20 {
function transfer (address _beneficiary, uint256 _tokenAmount) external returns (bool);
function mint (address _to, uint256 _amount) external returns (bool);
}
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract Crowdsale is Ownable {
using SafeMath for uint256;
modifier onlyWhileOpen {
require(
(now >= preICOStartDate && now < preICOEndDate) ||
(now >= ICOStartDate && now < ICOEndDate)
);
_;
}
modifier onlyWhileICOOpen {
require(now >= ICOStartDate && now < ICOEndDate);
_;
}
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// Сколько токенов покупатель получает за 1 эфир
uint256 public rate = 1000;
// Сколько эфиров привлечено в ходе PreICO, wei
uint256 public preICOWeiRaised;
// Сколько эфиров привлечено в ходе ICO, wei
uint256 public ICOWeiRaised;
// Цена ETH в центах
uint256 public ETHUSD;
// Дата начала PreICO
uint256 public preICOStartDate;
// Дата окончания PreICO
uint256 public preICOEndDate;
// Дата начала ICO
uint256 public ICOStartDate;
// Дата окончания ICO
uint256 public ICOEndDate;
// Минимальный объем привлечения средств в ходе ICO в центах
uint256 public softcap = 300000000;
// Потолок привлечения средств в ходе ICO в центах
uint256 public hardcap = 2500000000;
// Бонус реферала, %
uint8 public referalBonus = 3;
// Бонус приглашенного рефералом, %
uint8 public invitedByReferalBonus = 2;
// Whitelist
mapping(address => bool) public whitelist;
// Инвесторы, которые купили токен
mapping (address => uint256) public investors;
event TokenPurchase(address indexed buyer, uint256 value, uint256 amount);
function Crowdsale(
address _wallet,
uint256 _preICOStartDate,
uint256 _preICOEndDate,
uint256 _ICOStartDate,
uint256 _ICOEndDate,
uint256 _ETHUSD
) public {
require(_preICOEndDate > _preICOStartDate);
require(_ICOStartDate > _preICOEndDate);
require(_ICOEndDate > _ICOStartDate);
wallet = _wallet;
preICOStartDate = _preICOStartDate;
preICOEndDate = _preICOEndDate;
ICOStartDate = _ICOStartDate;
ICOEndDate = _ICOEndDate;
ETHUSD = _ETHUSD;
}
/* Публичные методы */
// Установить стоимость токена
function setRate (uint16 _rate) public onlyOwner {
require(_rate > 0);
rate = _rate;
}
// Установить адрес кошелька для сбора средств
function setWallet (address _wallet) public onlyOwner {
require (_wallet != 0x0);
wallet = _wallet;
}
// Установить торгуемый токен
function setToken (ERC20 _token) public onlyOwner {
token = _token;
}
// Установить дату начала PreICO
function setPreICOStartDate (uint256 _preICOStartDate) public onlyOwner {
require(_preICOStartDate < preICOEndDate);
preICOStartDate = _preICOStartDate;
}
// Установить дату окончания PreICO
function setPreICOEndDate (uint256 _preICOEndDate) public onlyOwner {
require(_preICOEndDate > preICOStartDate);
preICOEndDate = _preICOEndDate;
}
// Установить дату начала ICO
function setICOStartDate (uint256 _ICOStartDate) public onlyOwner {
require(_ICOStartDate < ICOEndDate);
ICOStartDate = _ICOStartDate;
}
// Установить дату окончания PreICO
function setICOEndDate (uint256 _ICOEndDate) public onlyOwner {
require(_ICOEndDate > ICOStartDate);
ICOEndDate = _ICOEndDate;
}
// Установить стоимость эфира в центах
function setETHUSD (uint256 _ETHUSD) public onlyOwner {
ETHUSD = _ETHUSD;
}
function () external payable {
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
uint256 tokens;
if(_isPreICO()){
_preValidatePreICOPurchase(beneficiary, weiAmount);
tokens = weiAmount.mul(rate.add(rate.mul(30).div(100)));
preICOWeiRaised = preICOWeiRaised.add(weiAmount);
wallet.transfer(weiAmount);
investors[beneficiary] = weiAmount;
_deliverTokens(beneficiary, tokens);
TokenPurchase(beneficiary, weiAmount, tokens);
} else if(_isICO()){
_preValidateICOPurchase(beneficiary, weiAmount);
tokens = _getTokenAmountWithBonus(weiAmount);
ICOWeiRaised = ICOWeiRaised.add(weiAmount);
investors[beneficiary] = weiAmount;
_deliverTokens(beneficiary, tokens);
TokenPurchase(beneficiary, weiAmount, tokens);
}
}
/* function buyPreICO() public payable {
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
_preValidatePreICOPurchase(beneficiary, weiAmount);
uint256 tokens = weiAmount.mul(rate.add(rate.mul(30).div(100)));
preICOWeiRaised = preICOWeiRaised.add(weiAmount);
wallet.transfer(weiAmount);
investors[beneficiary] = weiAmount;
_deliverTokens(beneficiary, tokens);
TokenPurchase(beneficiary, weiAmount, tokens);
}
function buyICO() public payable {
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
_preValidateICOPurchase(beneficiary, weiAmount);
uint256 tokens = _getTokenAmountWithBonus(weiAmount);
ICOWeiRaised = ICOWeiRaised.add(weiAmount);
investors[beneficiary] = weiAmount;
_deliverTokens(beneficiary, tokens);
TokenPurchase(beneficiary, weiAmount, tokens);
} */
// Покупка токенов с реферальным бонусом
function buyTokensWithReferal(address _referal) public onlyWhileICOOpen payable {
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
_preValidateICOPurchase(beneficiary, weiAmount);
uint256 tokens = _getTokenAmountWithBonus(weiAmount).add(_getTokenAmountWithReferal(weiAmount, 2));
uint256 referalTokens = _getTokenAmountWithReferal(weiAmount, 3);
ICOWeiRaised = ICOWeiRaised.add(weiAmount);
investors[beneficiary] = weiAmount;
_deliverTokens(beneficiary, tokens);
_deliverTokens(_referal, referalTokens);
TokenPurchase(beneficiary, weiAmount, tokens);
}
// Добавить адрес в whitelist
function addToWhitelist(address _beneficiary) public onlyOwner {
whitelist[_beneficiary] = true;
}
// Добавить несколько адресов в whitelist
function addManyToWhitelist(address[] _beneficiaries) public onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
// Исключить адрес из whitelist
function removeFromWhitelist(address _beneficiary) public onlyOwner {
whitelist[_beneficiary] = false;
}
// Узнать истек ли срок проведения PreICO
function hasPreICOClosed() public view returns (bool) {
return now > preICOEndDate;
}
// Узнать истек ли срок проведения ICO
function hasICOClosed() public view returns (bool) {
return now > ICOEndDate;
}
// Перевести собранные средства на кошелек для сбора
function forwardFunds () public onlyOwner {
require(now > ICOEndDate);
require((preICOWeiRaised.add(ICOWeiRaised)).mul(ETHUSD).div(10**18) >= softcap);
wallet.transfer(ICOWeiRaised);
}
// Вернуть проинвестированные средства, если не был достигнут softcap
function refund() public {
require(now > ICOEndDate);
require(preICOWeiRaised.add(ICOWeiRaised).mul(ETHUSD).div(10**18) < softcap);
require(investors[msg.sender] > 0);
address investor = msg.sender;
investor.transfer(investors[investor]);
}
/* Внутренние методы */
// Проверка актуальности PreICO
function _isPreICO() internal view returns(bool) {
return now >= preICOStartDate && now < preICOEndDate;
}
// Проверка актуальности ICO
function _isICO() internal view returns(bool) {
return now >= ICOStartDate && now < ICOEndDate;
}
// Валидация перед покупкой токенов
function _preValidatePreICOPurchase(address _beneficiary, uint256 _weiAmount) internal view {
require(_weiAmount != 0);
require(whitelist[_beneficiary]);
require(now >= preICOStartDate && now <= preICOEndDate);
}
function _preValidateICOPurchase(address _beneficiary, uint256 _weiAmount) internal view {
require(_weiAmount != 0);
require((preICOWeiRaised + ICOWeiRaised + _weiAmount).mul(ETHUSD).div(10**18) <= hardcap);
require(now >= ICOStartDate && now <= ICOEndDate);
}
// Подсчет бонусов с учетом бонусов за этап ICO и объем инвестиций
function _getTokenAmountWithBonus(uint256 _weiAmount) internal view returns(uint256) {
uint256 baseTokenAmount = _weiAmount.mul(rate);
uint256 tokenAmount = baseTokenAmount;
uint256 usdAmount = _weiAmount.mul(ETHUSD).div(10**18);
// Считаем бонусы за объем инвестиций
if(usdAmount >= 10000000){
tokenAmount = tokenAmount.add(baseTokenAmount.mul(7).div(100));
} else if(usdAmount >= 5000000){
tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100));
} else if(usdAmount >= 1000000){
tokenAmount = tokenAmount.add(baseTokenAmount.mul(3).div(100));
}
// Считаем бонусы за этап ICO
if(now < ICOStartDate + 15 days) {
tokenAmount = tokenAmount.add(baseTokenAmount.mul(20).div(100));
} else if(now < ICOStartDate + 28 days) {
tokenAmount = tokenAmount.add(baseTokenAmount.mul(15).div(100));
} else if(now < ICOStartDate + 42 days) {
tokenAmount = tokenAmount.add(baseTokenAmount.mul(10).div(100));
} else {
tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100));
}
return tokenAmount;
}
// Подсчет бонусов с учетом бонусов реферальной системы
function _getTokenAmountWithReferal(uint256 _weiAmount, uint8 _percent) internal view returns(uint256) {
return _weiAmount.mul(rate).mul(_percent).div(100);
}
// Перевод токенов
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.mint(_beneficiary, _tokenAmount);
}
} | Установить дату окончания PreICO | function setPreICOEndDate (uint256 _preICOEndDate) public onlyOwner {
require(_preICOEndDate > preICOStartDate);
preICOEndDate = _preICOEndDate;
}
| 5,522,672 |
pragma solidity ^0.5.8;
import "./IERC20.sol";
import "./SoraToken.sol";
/**
* Provides functionality of master contract
*/
contract Master {
bool internal initialized_;
address public owner_;
mapping(address => bool) public isPeer;
uint public peersCount;
/** Iroha tx hashes used */
mapping(bytes32 => bool) public used;
mapping(address => bool) public uniqueAddresses;
/** registered client addresses */
mapping(address => bytes) public registeredClients;
SoraToken public xorTokenInstance;
mapping(address => bool) public isToken;
/**
* Emit event on new registration with iroha acountId
*/
event IrohaAccountRegistration(address ethereumAddress, bytes accountId);
/**
* Emit event when master contract does not have enough assets to proceed withdraw
*/
event InsufficientFundsForWithdrawal(address asset, address recipient);
/**
* Constructor. Sets contract owner to contract creator.
*/
constructor(address[] memory initialPeers) public {
initialize(msg.sender, initialPeers);
}
/**
* Initialization of smart contract.
*/
function initialize(address owner, address[] memory initialPeers) public {
require(!initialized_);
owner_ = owner;
for (uint8 i = 0; i < initialPeers.length; i++) {
addPeer(initialPeers[i]);
}
// 0 means ether which is definitely in whitelist
isToken[address(0)] = true;
// Create new instance of Sora token
xorTokenInstance = new SoraToken();
isToken[address(xorTokenInstance)] = true;
initialized_ = true;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == owner_;
}
/**
* A special function-like stub to allow ether accepting
*/
function() external payable {
require(msg.data.length == 0);
}
/**
* Adds new peer to list of signature verifiers. Can be called only by contract owner.
* @param newAddress address of new peer
*/
function addPeer(address newAddress) private returns (uint) {
require(isPeer[newAddress] == false);
isPeer[newAddress] = true;
++peersCount;
return peersCount;
}
function removePeer(address peerAddress) private {
require(isPeer[peerAddress] == true);
isPeer[peerAddress] = false;
--peersCount;
}
function addPeerByPeer(
address newPeerAddress,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s
)
public returns (bool)
{
require(used[txHash] == false);
require(checkSignatures(keccak256(abi.encodePacked(newPeerAddress, txHash)),
v,
r,
s)
);
addPeer(newPeerAddress);
used[txHash] = true;
return true;
}
function removePeerByPeer(
address peerAddress,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s
)
public returns (bool)
{
require(used[txHash] == false);
require(checkSignatures(
keccak256(abi.encodePacked(peerAddress, txHash)),
v,
r,
s)
);
removePeer(peerAddress);
used[txHash] = true;
return true;
}
/**
* Adds new token to whitelist. Token should not been already added.
* @param newToken token to add
*/
function addToken(address newToken) public onlyOwner {
require(isToken[newToken] == false);
isToken[newToken] = true;
}
/**
* Checks is given token inside a whitelist or not
* @param tokenAddress address of token to check
* @return true if token inside whitelist or false otherwise
*/
function checkTokenAddress(address tokenAddress) public view returns (bool) {
return isToken[tokenAddress];
}
/**
* Register a clientIrohaAccountId for the caller clientEthereumAddress
* @param clientEthereumAddress - ethereum address to register
* @param clientIrohaAccountId - iroha account id
* @param txHash - iroha tx hash of registration
* @param v array of signatures of tx_hash (v-component)
* @param r array of signatures of tx_hash (r-component)
* @param s array of signatures of tx_hash (s-component)
*/
function register(
address clientEthereumAddress,
bytes memory clientIrohaAccountId,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s
)
public
{
require(used[txHash] == false);
require(checkSignatures(
keccak256(abi.encodePacked(clientEthereumAddress, clientIrohaAccountId, txHash)),
v,
r,
s)
);
require(clientEthereumAddress == msg.sender);
require(registeredClients[clientEthereumAddress].length == 0);
registeredClients[clientEthereumAddress] = clientIrohaAccountId;
emit IrohaAccountRegistration(clientEthereumAddress, clientIrohaAccountId);
}
/**
* Withdraws specified amount of ether or one of ERC-20 tokens to provided address
* @param tokenAddress address of token to withdraw (0 for ether)
* @param amount amount of tokens or ether to withdraw
* @param to target account address
* @param txHash hash of transaction from Iroha
* @param v array of signatures of tx_hash (v-component)
* @param r array of signatures of tx_hash (r-component)
* @param s array of signatures of tx_hash (s-component)
* @param from relay contract address
*/
function withdraw(
address tokenAddress,
uint256 amount,
address payable to,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s,
address from
)
public
{
require(checkTokenAddress(tokenAddress));
require(used[txHash] == false);
require(checkSignatures(
keccak256(abi.encodePacked(tokenAddress, amount, to, txHash, from)),
v,
r,
s)
);
if (tokenAddress == address (0)) {
if (address(this).balance < amount) {
emit InsufficientFundsForWithdrawal(tokenAddress, to);
} else {
used[txHash] = true;
// untrusted transfer, relies on provided cryptographic proof
to.transfer(amount);
}
} else {
IERC20 coin = IERC20(tokenAddress);
if (coin.balanceOf(address (this)) < amount) {
emit InsufficientFundsForWithdrawal(tokenAddress, to);
} else {
used[txHash] = true;
// untrusted call, relies on provided cryptographic proof
coin.transfer(to, amount);
}
}
}
/**
* Checks given addresses for duplicates and if they are peers signatures
* @param hash unsigned data
* @param v v-component of signature from hash
* @param r r-component of signature from hash
* @param s s-component of signature from hash
* @return true if all given addresses are correct or false otherwise
*/
function checkSignatures(bytes32 hash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s
) private returns (bool) {
require(peersCount >= 1);
require(v.length == r.length);
require(r.length == s.length);
uint needSigs = peersCount - (peersCount - 1) / 3;
require(s.length >= needSigs);
uint count = 0;
address[] memory recoveredAddresses = new address[](s.length);
for (uint i = 0; i < s.length; ++i) {
address recoveredAddress = recoverAddress(
hash,
v[i],
r[i],
s[i]
);
// not a peer address or not unique
if (isPeer[recoveredAddress] != true || uniqueAddresses[recoveredAddress] == true) {
continue;
}
recoveredAddresses[count] = recoveredAddress;
count = count + 1;
uniqueAddresses[recoveredAddress] = true;
}
// restore state for future usages
for (uint i = 0; i < count; ++i) {
uniqueAddresses[recoveredAddresses[i]] = false;
}
return count >= needSigs;
}
/**
* Recovers address from a given single signature
* @param hash unsigned data
* @param v v-component of signature from hash
* @param r r-component of signature from hash
* @param s s-component of signature from hash
* @return address recovered from signature
*/
function recoverAddress(bytes32 hash, uint8 v, bytes32 r, bytes32 s) private pure returns (address) {
bytes32 simple_hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
address res = ecrecover(simple_hash, v, r, s);
return res;
}
/**
* Mint new XORToken
* @param tokenAddress address to mint
* @param amount how much to mint
* @param beneficiary destination address
* @param txHash hash of transaction from Iroha
* @param v array of signatures of tx_hash (v-component)
* @param r array of signatures of tx_hash (r-component)
* @param s array of signatures of tx_hash (s-component)
*/
function mintTokensByPeers(
address tokenAddress,
uint256 amount,
address beneficiary,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s,
address from
)
public
{
require(address(xorTokenInstance) == tokenAddress);
require(used[txHash] == false);
require(checkSignatures(
keccak256(abi.encodePacked(tokenAddress, amount, beneficiary, txHash, from)),
v,
r,
s)
);
xorTokenInstance.mintTokens(beneficiary, amount);
used[txHash] = true;
}
}
| Register a clientIrohaAccountId for the caller clientEthereumAddress clientEthereumAddress - ethereum address to register clientIrohaAccountId - iroha account id txHash - iroha tx hash of registration v array of signatures of tx_hash (v-component) r array of signatures of tx_hash (r-component) s array of signatures of tx_hash (s-component)/ | function register(
address clientEthereumAddress,
bytes memory clientIrohaAccountId,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s
)
public
{
require(used[txHash] == false);
require(checkSignatures(
keccak256(abi.encodePacked(clientEthereumAddress, clientIrohaAccountId, txHash)),
v,
r,
s)
);
require(clientEthereumAddress == msg.sender);
require(registeredClients[clientEthereumAddress].length == 0);
registeredClients[clientEthereumAddress] = clientIrohaAccountId;
emit IrohaAccountRegistration(clientEthereumAddress, clientIrohaAccountId);
}
| 15,831,173 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "../presets/OwnablePausableUpgradeable.sol";
import "../interfaces/IStakedEthToken.sol";
import "../interfaces/IDepositContract.sol";
import "../interfaces/IValidators.sol";
import "../interfaces/IPool.sol";
/**
* @title Pool
*
* @dev Pool contract accumulates deposits from the users, mints tokens and registers validators.
*/
contract Pool is IPool, OwnablePausableUpgradeable {
using SafeMathUpgradeable for uint256;
// @dev Validator deposit amount.
uint256 public constant VALIDATOR_DEPOSIT = 32 ether;
// @dev Total activated validators.
uint256 public override activatedValidators;
// @dev Pool validator withdrawal credentials.
bytes32 public override withdrawalCredentials;
// @dev Address of the ETH2 Deposit Contract (deployed by Ethereum).
IDepositContract public override validatorRegistration;
// @dev Address of the StakedEthToken contract.
IStakedEthToken private stakedEthToken;
// @dev Address of the Validators contract.
IValidators private validators;
// @dev Address of the Oracles contract.
address private oracles;
// @dev Maps senders to the validator index that it will be activated in.
mapping(address => mapping(uint256 => uint256)) public override activations;
// @dev Total pending validators.
uint256 public override pendingValidators;
// @dev Amount of deposited ETH that is not considered for the activation period.
uint256 public override minActivatingDeposit;
// @dev Pending validators percent limit. If it's not exceeded tokens can be minted immediately.
uint256 public override pendingValidatorsLimit;
/**
* @dev See {IPool-upgrade}.
* The `initialize` must be called before upgrading in previous implementation contract:
* https://github.com/stakewise/contracts/blob/v1.0.0/contracts/collectors/Pool.sol#L42
*/
function upgrade(
address _oracles,
uint256 _activatedValidators,
uint256 _pendingValidators,
uint256 _minActivatingDeposit,
uint256 _pendingValidatorsLimit
)
external override onlyAdmin whenPaused
{
require(oracles == address(0), "Pool: already upgraded");
oracles = _oracles;
pendingValidators = _pendingValidators;
activatedValidators = _activatedValidators;
emit ActivatedValidatorsUpdated(_activatedValidators, msg.sender);
minActivatingDeposit = _minActivatingDeposit;
emit MinActivatingDepositUpdated(_minActivatingDeposit, msg.sender);
pendingValidatorsLimit = _pendingValidatorsLimit;
emit PendingValidatorsLimitUpdated(_pendingValidatorsLimit, msg.sender);
}
/**
* @dev See {IPool-setWithdrawalCredentials}.
*/
function setWithdrawalCredentials(bytes32 _withdrawalCredentials) external override onlyAdmin {
withdrawalCredentials = _withdrawalCredentials;
emit WithdrawalCredentialsUpdated(_withdrawalCredentials);
}
/**
* @dev See {IPool-setMinActivatingDeposit}.
*/
function setMinActivatingDeposit(uint256 _minActivatingDeposit) external override onlyAdmin {
minActivatingDeposit = _minActivatingDeposit;
emit MinActivatingDepositUpdated(_minActivatingDeposit, msg.sender);
}
/**
* @dev See {IPool-setPendingValidatorsLimit}.
*/
function setPendingValidatorsLimit(uint256 _pendingValidatorsLimit) external override onlyAdmin {
require(_pendingValidatorsLimit < 10000, "Pool: invalid limit");
pendingValidatorsLimit = _pendingValidatorsLimit;
emit PendingValidatorsLimitUpdated(_pendingValidatorsLimit, msg.sender);
}
/**
* @dev See {IPool-setActivatedValidators}.
*/
function setActivatedValidators(uint256 newActivatedValidators) external override {
require(msg.sender == oracles || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Pool: access denied");
// subtract activated validators from pending validators
pendingValidators = pendingValidators.sub(newActivatedValidators.sub(activatedValidators));
activatedValidators = newActivatedValidators;
emit ActivatedValidatorsUpdated(newActivatedValidators, msg.sender);
}
/**
* @dev See {IPool-addDeposit}.
*/
function addDeposit() external payable override whenNotPaused {
require(msg.value > 0, "Pool: invalid deposit amount");
// mint tokens for small deposits immediately
if (msg.value <= minActivatingDeposit) {
stakedEthToken.mint(msg.sender, msg.value);
return;
}
// mint tokens if current pending validators limit is not exceed
uint256 _pendingValidators = pendingValidators.add((address(this).balance).div(VALIDATOR_DEPOSIT));
uint256 _activatedValidators = activatedValidators; // gas savings
uint256 validatorIndex = _activatedValidators.add(_pendingValidators);
if (validatorIndex.mul(1e4) <= _activatedValidators.mul(pendingValidatorsLimit.add(1e4))) {
stakedEthToken.mint(msg.sender, msg.value);
} else {
// lock deposit amount until validator activated
activations[msg.sender][validatorIndex] = activations[msg.sender][validatorIndex].add(msg.value);
emit ActivationScheduled(msg.sender, validatorIndex, msg.value);
}
}
/**
* @dev See {IPool-canActivate}.
*/
function canActivate(uint256 _validatorIndex) external view override returns (bool) {
return _validatorIndex.mul(1e4) <= activatedValidators.mul(pendingValidatorsLimit.add(1e4));
}
/**
* @dev See {IPool-activate}.
*/
function activate(address _account, uint256 _validatorIndex) external override whenNotPaused {
require(_validatorIndex.mul(1e4) <= activatedValidators.mul(pendingValidatorsLimit.add(1e4)), "Pool: validator is not active yet");
uint256 amount = activations[_account][_validatorIndex];
require(amount > 0, "Pool: invalid validator index");
delete activations[_account][_validatorIndex];
stakedEthToken.mint(_account, amount);
emit Activated(_account, _validatorIndex, amount, msg.sender);
}
/**
* @dev See {IPool-activateMultiple}.
*/
function activateMultiple(address _account, uint256[] calldata _validatorIndexes) external override whenNotPaused {
uint256 toMint;
uint256 _activatedValidators = activatedValidators;
for (uint256 i = 0; i < _validatorIndexes.length; i++) {
uint256 validatorIndex = _validatorIndexes[i];
require(validatorIndex.mul(1e4) <= _activatedValidators.mul(pendingValidatorsLimit.add(1e4)), "Pool: validator is not active yet");
uint256 amount = activations[_account][validatorIndex];
toMint = toMint.add(amount);
delete activations[_account][validatorIndex];
emit Activated(_account, validatorIndex, amount, msg.sender);
}
require(toMint > 0, "Pool: invalid validator index");
stakedEthToken.mint(_account, toMint);
}
/**
* @dev See {IPool-registerValidator}.
*/
function registerValidator(Validator calldata _validator) external override whenNotPaused {
require(validators.isOperator(msg.sender), "Pool: access denied");
// register validator
validators.register(keccak256(abi.encodePacked(_validator.publicKey)));
emit ValidatorRegistered(_validator.publicKey, msg.sender);
// update number of pending validators
pendingValidators = pendingValidators.add(1);
validatorRegistration.deposit{value : VALIDATOR_DEPOSIT}(
_validator.publicKey,
abi.encodePacked(withdrawalCredentials),
_validator.signature,
_validator.depositDataRoot
);
}
}
// 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 SafeMathUpgradeable {
/**
* @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: AGPL-3.0-only
pragma solidity 0.7.5;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "../interfaces/IOwnablePausable.sol";
/**
* @title OwnablePausableUpgradeable
*
* @dev Bundles Access Control, Pausable and Upgradeable contracts in one.
*
*/
abstract contract OwnablePausableUpgradeable is IOwnablePausable, PausableUpgradeable, AccessControlUpgradeable {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Modifier for checking whether the caller is an admin.
*/
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
/**
* @dev Modifier for checking whether the caller is a pauser.
*/
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init(address _admin) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__OwnablePausableUpgradeable_init_unchained(_admin);
}
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `PAUSER_ROLE` to the admin account.
*/
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init_unchained(address _admin) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
}
/**
* @dev See {IOwnablePausable-isAdmin}.
*/
function isAdmin(address _account) external override view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addAdmin}.
*/
function addAdmin(address _account) external override {
grantRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removeAdmin}.
*/
function removeAdmin(address _account) external override {
revokeRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-isPauser}.
*/
function isPauser(address _account) external override view returns (bool) {
return hasRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addPauser}.
*/
function addPauser(address _account) external override {
grantRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removePauser}.
*/
function removePauser(address _account) external override {
revokeRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-pause}.
*/
function pause() external override onlyPauser {
_pause();
}
/**
* @dev See {IOwnablePausable-unpause}.
*/
function unpause() external override onlyPauser {
_unpause();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/**
* @dev Interface of the StakedEthToken contract.
*/
interface IStakedEthToken is IERC20Upgradeable {
/**
* @dev Constructor for initializing the StakedEthToken contract.
* @param _admin - address of the contract admin.
* @param _rewardEthToken - address of the RewardEthToken contract.
* @param _pool - address of the Pool contract.
*/
function initialize(address _admin, address _rewardEthToken, address _pool) external;
/**
* @dev Function for retrieving the total deposits amount.
*/
function totalDeposits() external view returns (uint256);
/**
* @dev Function for creating `amount` tokens and assigning them to `account`.
* Can only be called by Pool contract.
* @param account - address of the account to assign tokens to.
* @param amount - amount of tokens to assign.
*/
function mint(address account, uint256 amount) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
// This interface is designed to be compatible with the Vyper version.
/// @notice This is the Ethereum 2.0 deposit contract interface.
/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
/// https://github.com/ethereum/eth2.0-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol
interface IDepositContract {
/// @notice A processed deposit event.
event DepositEvent(
bytes pubkey,
bytes withdrawal_credentials,
bytes amount,
bytes signature,
bytes index
);
/// @notice Submit a Phase 0 DepositData object.
/// @param pubkey A BLS12-381 public key.
/// @param withdrawal_credentials Commitment to a public key for withdrawals.
/// @param signature A BLS12-381 signature.
/// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
/// Used as a protection against malformed input.
function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) external payable;
/// @notice Query the current deposit root hash.
/// @return The deposit root hash.
function get_deposit_root() external view returns (bytes32);
/// @notice Query the current deposit count.
/// @return The deposit count encoded as a little endian 64-bit number.
function get_deposit_count() external view returns (bytes memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
/**
* @dev Interface of the Validators contract.
*/
interface IValidators {
/**
* @dev Constructor for initializing the Validators contract.
* @param _admin - address of the contract admin.
* @param _pool - address of the Pool contract.
* @param _solos - address of the Solos contract.
*/
function initialize(address _admin, address _pool, address _solos) external;
/**
* @dev Function for checking whether an account has an operator role.
* @param _account - account to check.
*/
function isOperator(address _account) external view returns (bool);
/**
* @dev Function for adding an operator role to the account.
* Can only be called by an account with an admin role.
* @param _account - account to assign an operator role to.
*/
function addOperator(address _account) external;
/**
* @dev Function for removing an operator role from the account.
* Can only be called by an account with an admin role.
* @param _account - account to remove an operator role from.
*/
function removeOperator(address _account) external;
/**
* @dev Function for checking whether public key was already used.
* @param _publicKey - hash of public key to check.
*/
function publicKeys(bytes32 _publicKey) external view returns (bool);
/**
* @dev Function for registering validators. Can only be called by collectors.
* @param _validatorId - ID of the validator.
*/
function register(bytes32 _validatorId) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
pragma abicoder v2;
import "./IDepositContract.sol";
/**
* @dev Interface of the Pool contract.
*/
interface IPool {
/**
* @dev Event for tracking new pool withdrawal credentials.
* @param withdrawalCredentials - new withdrawal credentials for the pool validators.
*/
event WithdrawalCredentialsUpdated(bytes32 withdrawalCredentials);
/**
* @dev Event for tracking registered validators.
* @param publicKey - validator public key.
* @param operator - address of the validator operator.
*/
event ValidatorRegistered(bytes publicKey, address operator);
/**
* @dev Event for tracking scheduled deposit activation.
* @param sender - address of the deposit sender.
* @param validatorIndex - index of the activated validator.
* @param value - deposit amount to be activated.
*/
event ActivationScheduled(address indexed sender, uint256 validatorIndex, uint256 value);
/**
* @dev Event for tracking activated deposits.
* @param account - account the deposit was activated for.
* @param validatorIndex - index of the activated validator.
* @param value - amount activated.
* @param sender - address of the transaction sender.
*/
event Activated(address indexed account, uint256 validatorIndex, uint256 value, address indexed sender);
/**
* @dev Event for tracking activated validators updates.
* @param activatedValidators - new total amount of activated validators.
* @param sender - address of the transaction sender.
*/
event ActivatedValidatorsUpdated(uint256 activatedValidators, address sender);
/**
* @dev Event for tracking updates to the minimal deposit amount considered for the activation period.
* @param minActivatingDeposit - new minimal deposit amount considered for the activation.
* @param sender - address of the transaction sender.
*/
event MinActivatingDepositUpdated(uint256 minActivatingDeposit, address sender);
/**
* @dev Event for tracking pending validators limit.
* When it's exceeded, the deposits will be set for the activation.
* @param pendingValidatorsLimit - pending validators percent limit.
* @param sender - address of the transaction sender.
*/
event PendingValidatorsLimitUpdated(uint256 pendingValidatorsLimit, address sender);
/**
* @dev Structure for passing information about new Validator.
* @param publicKey - BLS public key of the validator, generated by the operator.
* @param signature - BLS signature of the validator, generated by the operator.
* @param depositDataRoot - hash tree root of the deposit data, generated by the operator.
*/
struct Validator {
bytes publicKey;
bytes signature;
bytes32 depositDataRoot;
}
/**
* @dev Function for upgrading the Pools contract.
* @param _oracles - address of the Oracles contract.
* @param _activatedValidators - initial amount of activated validators.
* @param _pendingValidators - initial amount of pending validators.
* @param _minActivatingDeposit - minimal deposit in Wei to be considered for the activation period.
* @param _pendingValidatorsLimit - pending validators percent limit. If it's not exceeded tokens can be minted immediately.
*/
function upgrade(
address _oracles,
uint256 _activatedValidators,
uint256 _pendingValidators,
uint256 _minActivatingDeposit,
uint256 _pendingValidatorsLimit
) external;
/**
* @dev Function for getting the total amount of pending validators.
*/
function pendingValidators() external view returns (uint256);
/**
* @dev Function for retrieving the total amount of activated validators.
*/
function activatedValidators() external view returns (uint256);
/**
* @dev Function for getting the withdrawal credentials used to
* initiate pool validators withdrawal from the beacon chain.
*/
function withdrawalCredentials() external view returns (bytes32);
/**
* @dev Function for getting the minimal deposit amount considered for the activation.
*/
function minActivatingDeposit() external view returns (uint256);
/**
* @dev Function for getting the pending validators percent limit.
* When it's exceeded, the deposits will be set for the activation.
*/
function pendingValidatorsLimit() external view returns (uint256);
/**
* @dev Function for getting the amount of activating deposits.
* @param account - address of the account to get the amount for.
* @param validatorIndex - index of the activated validator.
*/
function activations(address account, uint256 validatorIndex) external view returns (uint256);
/**
* @dev Function for setting minimal deposit amount considered for the activation period.
* @param _minActivatingDeposit - new minimal deposit amount considered for the activation.
*/
function setMinActivatingDeposit(uint256 _minActivatingDeposit) external;
/**
* @dev Function for changing withdrawal credentials.
* @param _withdrawalCredentials - new withdrawal credentials for the pool validators.
*/
function setWithdrawalCredentials(bytes32 _withdrawalCredentials) external;
/**
* @dev Function for changing the total amount of activated validators.
* @param _activatedValidators - new total amount of activated validators.
*/
function setActivatedValidators(uint256 _activatedValidators) external;
/**
* @dev Function for changing pending validators limit.
* @param _pendingValidatorsLimit - new pending validators limit. When it's exceeded, the deposits will be set for the activation.
*/
function setPendingValidatorsLimit(uint256 _pendingValidatorsLimit) external;
/**
* @dev Function for checking whether validator index can be activated.
* @param _validatorIndex - index of the validator to check.
*/
function canActivate(uint256 _validatorIndex) external view returns (bool);
/**
* @dev Function for retrieving the validator registration contract address.
*/
function validatorRegistration() external view returns (IDepositContract);
/**
* @dev Function for adding deposits to the pool.
*/
function addDeposit() external payable;
/**
* @dev Function for minting account's tokens for the specific validator index.
* @param _account - account address to activate the tokens for.
* @param _validatorIndex - index of the activated validator.
*/
function activate(address _account, uint256 _validatorIndex) external;
/**
* @dev Function for minting account's tokens for the specific validator indexes.
* @param _account - account address to activate the tokens for.
* @param _validatorIndexes - list of activated validator indexes.
*/
function activateMultiple(address _account, uint256[] calldata _validatorIndexes) external;
/**
* @dev Function for registering new pool validator.
* @param _validator - validator to register.
*/
function registerValidator(Validator calldata _validator) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, 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 AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @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.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_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());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
/**
* @dev Interface of the OwnablePausableUpgradeable and OwnablePausable contracts.
*/
interface IOwnablePausable {
/**
* @dev Function for checking whether an account has an admin role.
* @param _account - account to check.
*/
function isAdmin(address _account) external view returns (bool);
/**
* @dev Function for assigning an admin role to the account.
* Can only be called by an account with an admin role.
* @param _account - account to assign an admin role to.
*/
function addAdmin(address _account) external;
/**
* @dev Function for removing an admin role from the account.
* Can only be called by an account with an admin role.
* @param _account - account to remove an admin role from.
*/
function removeAdmin(address _account) external;
/**
* @dev Function for checking whether an account has a pauser role.
* @param _account - account to check.
*/
function isPauser(address _account) external view returns (bool);
/**
* @dev Function for adding a pauser role to the account.
* Can only be called by an account with an admin role.
* @param _account - account to assign a pauser role to.
*/
function addPauser(address _account) external;
/**
* @dev Function for removing a pauser role from the account.
* Can only be called by an account with an admin role.
* @param _account - account to remove a pauser role from.
*/
function removePauser(address _account) external;
/**
* @dev Function for pausing the contract.
*/
function pause() external;
/**
* @dev Function for unpausing the contract.
*/
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
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
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
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 payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since 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) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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);
}
| This interface is designed to be compatible with the Vyper version. This is the Ethereum 2.0 deposit contract interface. For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs https://github.com/ethereum/eth2.0-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol | interface IDepositContract {
event DepositEvent(
bytes pubkey,
bytes withdrawal_credentials,
bytes amount,
bytes signature,
bytes index
);
function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) external payable;
function get_deposit_root() external view returns (bytes32);
function get_deposit_count() external view returns (bytes memory);
}
}
| 6,233,599 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "./strategy-alcx-farm-symbiotic.sol";
contract StrategyAlusd3Crv is StrategyAlcxSymbioticFarmBase {
uint256 public alusd_3crv_poolId = 4;
address public alusd_3crv = 0x43b4FdFD4Ff969587185cDB6f0BD875c5Fc83f8c;
constructor(
address _governance,
address _strategist,
address _controller,
address _timelock
) public StrategyAlcxSymbioticFarmBase(alusd_3crv_poolId, alusd_3crv, _governance, _strategist, _controller, _timelock) {}
// **** Views ****
function getName() external pure override returns (string memory) {
return "StrategyAlusd3Crv";
}
function getAlcxFarmHarvestable() public view returns (uint256) {
return IStakingPools(stakingPool).getStakeTotalUnclaimed(address(this), alcxPoolId);
}
// **** State Mutations ****
function harvest() public override onlyBenevolent {
// Collects Alcx tokens
uint256 _alcxHarvestable = getAlcxFarmHarvestable();
if (_alcxHarvestable > 0) IStakingPools(stakingPool).claim(alcxPoolId); //claim from alcx staking pool
uint256 _harvestable = getHarvestable();
if (_harvestable > 0) IStakingPools(stakingPool).claim(poolId); //claim from alusd_3crv staking pool
uint256 _alcx = IERC20(alcx).balanceOf(address(this));
if (_alcx > 0) {
// 10% is locked up for future gov
uint256 _keepAlcx = _alcx.mul(keepAlcx).div(keepAlcxMax);
IERC20(alcx).safeTransfer(IController(controller).treasury(), _keepAlcx);
uint256 _amount = _alcx.sub(_keepAlcx);
IERC20(alcx).safeApprove(stakingPool, 0);
IERC20(alcx).safeApprove(stakingPool, _amount);
IStakingPools(stakingPool).deposit(alcxPoolId, _amount); //stake to alcx farm
}
}
function withdrawReward(uint256 _amount) external {
require(msg.sender == controller, "!controller");
address _jar = IController(controller).jars(address(want));
address reward_token = IJar(_jar).reward();
uint256 _balance = IERC20(alcx).balanceOf(address(this));
uint256 _pendingReward = pendingReward();
require(reward_token != address(0), "Reward token is not set in the pickle jar");
require(reward_token == alcx, "Reward token is invalid");
require(_pendingReward >= _amount, "[withdrawReward] Withdraw amount exceed redeemable amount");
uint256 _alcxHarvestable = getAlcxFarmHarvestable();
uint256 _harvestable = getHarvestable();
_balance = IERC20(alcx).balanceOf(address(this));
if (_balance < _amount && _alcxHarvestable > 0) IStakingPools(stakingPool).claim(alcxPoolId);
_balance = IERC20(alcx).balanceOf(address(this));
if (_balance < _amount && _harvestable > 0) IStakingPools(stakingPool).claim(poolId);
_balance = IERC20(alcx).balanceOf(address(this));
if (_balance < _amount) {
uint256 _r = _amount.sub(_balance);
uint256 _alcxDeposited = getAlcxDeposited();
IStakingPools(stakingPool).withdraw(alcxPoolId, _alcxDeposited >= _r ? _r : _alcxDeposited);
}
_balance = IERC20(alcx).balanceOf(address(this));
require(_balance >= _amount, "[WithdrawReward] Withdraw amount exceed balance"); //double check
IERC20(reward_token).safeTransfer(_jar, _amount);
__redeposit();
}
function getAlcxDeposited() public view override returns (uint256) {
return IStakingPools(stakingPool).getStakeTotalDeposited(address(this), alcxPoolId);
}
function pendingReward() public view returns (uint256) {
return
IERC20(alcx).balanceOf(address(this)).add(IStakingPools(stakingPool).getStakeTotalDeposited(address(this), alcxPoolId).add(
getHarvestable().add(getAlcxFarmHarvestable()))
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "../strategy-base-symbiotic.sol";
import "../../interfaces/alcx-farm.sol";
abstract contract StrategyAlcxSymbioticFarmBase is StrategyBaseSymbiotic {
// How much Alcx tokens to keep?
uint256 public keepAlcx = 0;
uint256 public constant keepAlcxMax = 10000;
uint256 public alcxPoolId = 1;
uint256 public poolId;
constructor(
uint256 _poolId,
address _token,
address _governance,
address _strategist,
address _controller,
address _timelock
) public StrategyBaseSymbiotic(_token, _governance, _strategist, _controller, _timelock) {
poolId = _poolId;
}
function balanceOfPool() public view override returns (uint256) {
uint256 amount = IStakingPools(stakingPool).getStakeTotalDeposited(address(this), poolId);
return amount;
}
function getHarvestable() public view returns (uint256) {
return IStakingPools(stakingPool).getStakeTotalUnclaimed(address(this), poolId);
}
// **** Setters ****
function deposit() public override {
uint256 _want = IERC20(want).balanceOf(address(this));
if (_want > 0) {
IERC20(want).safeApprove(stakingPool, 0);
IERC20(want).safeApprove(stakingPool, _want);
IStakingPools(stakingPool).deposit(poolId, _want);
}
}
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
IStakingPools(stakingPool).withdraw(poolId, _amount);
return _amount;
}
function _withdrawSomeReward(uint256 _amount) internal override returns (uint256) {
IStakingPools(stakingPool).withdraw(alcxPoolId, _amount);
return _amount;
}
function __redeposit() internal override {
uint256 _balance = IERC20(alcx).balanceOf(address(this));
if (_balance > 0) {
IERC20(alcx).safeApprove(stakingPool, 0);
IERC20(alcx).safeApprove(stakingPool, _balance);
IStakingPools(stakingPool).deposit(alcxPoolId, _balance); //stake to alcx farm
}
}
// **** Setters ****
function setKeepAlcx(uint256 _keepAlcx) external {
require(msg.sender == timelock, "!timelock");
keepAlcx = _keepAlcx;
}
// can't have harvest function here
}
pragma solidity ^0.6.7;
import "../lib/erc20.sol";
import "../lib/safe-math.sol";
import "../interfaces/jar.sol";
import "../interfaces/staking-rewards.sol";
import "../interfaces/masterchef.sol";
import "../interfaces/uniswapv2.sol";
import "../interfaces/controller.sol";
// Strategy Contract Basics
abstract contract StrategyBaseSymbiotic {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Perfomance fees - start with 20%
uint256 public performanceTreasuryFee = 2000;
uint256 public constant performanceTreasuryMax = 10000;
uint256 public performanceDevFee = 0;
uint256 public constant performanceDevMax = 10000;
// Withdrawal fee 0%
// - 0% to treasury
// - 0% to dev fund
uint256 public withdrawalTreasuryFee = 0;
uint256 public constant withdrawalTreasuryMax = 100000;
uint256 public withdrawalDevFundFee = 0;
uint256 public constant withdrawalDevFundMax = 100000;
// Tokens
address public want;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// User accounts
address public governance;
address public controller;
address public strategist;
address public timelock;
// Dex
address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
// Token addresses
address public constant alcx = 0xdBdb4d16EdA451D0503b854CF79D55697F90c8DF;
address public constant stakingPool = 0xAB8e74017a8Cc7c15FFcCd726603790d26d7DeCa;
mapping(address => bool) public harvesters;
constructor(
address _want,
address _governance,
address _strategist,
address _controller,
address _timelock
) public {
require(_want != address(0));
require(_governance != address(0));
require(_strategist != address(0));
require(_controller != address(0));
require(_timelock != address(0));
want = _want;
governance = _governance;
strategist = _strategist;
controller = _controller;
timelock = _timelock;
}
// **** Modifiers **** //
modifier onlyBenevolent {
require(harvesters[msg.sender] || msg.sender == governance || msg.sender == strategist);
_;
}
// **** Views **** //
function balanceOfWant() public view returns (uint256) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfPool() public view virtual returns (uint256);
function getAlcxDeposited() public view virtual returns (uint256);
function balanceOf() public view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function getName() external pure virtual returns (string memory);
// **** Setters **** //
function whitelistHarvester(address _harvester) external {
require(msg.sender == governance || msg.sender == strategist, "not authorized");
harvesters[_harvester] = true;
}
function revokeHarvester(address _harvester) external {
require(msg.sender == governance || msg.sender == strategist, "not authorized");
harvesters[_harvester] = false;
}
function setWithdrawalDevFundFee(uint256 _withdrawalDevFundFee) external {
require(msg.sender == timelock, "!timelock");
withdrawalDevFundFee = _withdrawalDevFundFee;
}
function setWithdrawalTreasuryFee(uint256 _withdrawalTreasuryFee) external {
require(msg.sender == timelock, "!timelock");
withdrawalTreasuryFee = _withdrawalTreasuryFee;
}
function setPerformanceDevFee(uint256 _performanceDevFee) external {
require(msg.sender == timelock, "!timelock");
performanceDevFee = _performanceDevFee;
}
function setPerformanceTreasuryFee(uint256 _performanceTreasuryFee) external {
require(msg.sender == timelock, "!timelock");
performanceTreasuryFee = _performanceTreasuryFee;
}
function setStrategist(address _strategist) external {
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setTimelock(address _timelock) external {
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
function setController(address _controller) external {
require(msg.sender == timelock, "!timelock");
controller = _controller;
}
// **** State mutations **** //
function deposit() public virtual;
function __redeposit() internal virtual;
// Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
require(want != address(_asset), "want");
balance = _asset.balanceOf(address(this));
_asset.safeTransfer(controller, balance);
}
// Withdraw partial funds, normally used with a jar withdrawal
function withdraw(uint256 _amount) external {
require(msg.sender == controller, "!controller");
uint256 _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
uint256 _feeDev = _amount.mul(withdrawalDevFundFee).div(withdrawalDevFundMax);
IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev);
uint256 _feeTreasury = _amount.mul(withdrawalTreasuryFee).div(withdrawalTreasuryMax);
IERC20(want).safeTransfer(IController(controller).treasury(), _feeTreasury);
address _jar = IController(controller).jars(address(want));
require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_jar, _amount.sub(_feeDev).sub(_feeTreasury));
__redeposit();
}
// Withdraw funds, used to swap between strategies
function withdrawForSwap(uint256 _amount) external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
_withdrawSome(_amount);
balance = IERC20(want).balanceOf(address(this));
address _jar = IController(controller).jars(address(want));
require(_jar != address(0), "!jar");
IERC20(want).safeTransfer(_jar, balance);
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
_withdrawAll();
_withdrawAllReward();
balance = IERC20(want).balanceOf(address(this));
address _jar = IController(controller).jars(address(want));
require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_jar, balance);
IERC20(alcx).safeTransfer(_jar, IERC20(alcx).balanceOf(address(this)));
}
function _withdrawAll() internal {
_withdrawSome(balanceOfPool());
}
function _withdrawAllReward() internal {
_withdrawSomeReward(getAlcxDeposited());
}
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
function _withdrawSomeReward(uint256 _amount) internal virtual returns (uint256);
function harvest() public virtual;
// **** Emergency functions ****
function execute(address _target, bytes memory _data) public payable returns (bytes memory response) {
require(msg.sender == timelock, "!timelock");
require(_target != address(0), "!target");
// call contract in current context
assembly {
let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0)
let size := returndatasize()
response := mload(0x40)
mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
}
// **** Internal functions ****
function _swapUniswap(
address _from,
address _to,
uint256 _amount
) internal {
require(_to != address(0));
address[] memory path;
if (_from == weth || _to == weth) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = weth;
path[2] = _to;
}
UniswapRouterV2(univ2Router2).swapExactTokensForTokens(_amount, 0, path, address(this), now.add(60));
}
function _swapUniswapWithPath(address[] memory path, uint256 _amount) internal {
require(path[1] != address(0));
UniswapRouterV2(univ2Router2).swapExactTokensForTokens(_amount, 0, path, address(this), now.add(60));
}
function _swapSushiswap(
address _from,
address _to,
uint256 _amount
) internal {
require(_to != address(0));
address[] memory path;
if (_from == weth || _to == weth) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = weth;
path[2] = _to;
}
UniswapRouterV2(sushiRouter).swapExactTokensForTokens(_amount, 0, path, address(this), now.add(60));
}
function _swapSushiswapWithPath(address[] memory path, uint256 _amount) internal {
require(path[1] != address(0));
UniswapRouterV2(sushiRouter).swapExactTokensForTokens(_amount, 0, path, address(this), now.add(60));
}
function _distributePerformanceFeesAndDeposit() internal {
uint256 _want = IERC20(want).balanceOf(address(this));
if (_want > 0) {
// Treasury fees
IERC20(want).safeTransfer(
IController(controller).treasury(),
_want.mul(performanceTreasuryFee).div(performanceTreasuryMax)
);
// Performance fee
IERC20(want).safeTransfer(
IController(controller).devfund(),
_want.mul(performanceDevFee).div(performanceDevMax)
);
deposit();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
// interface for Alchemix farm contract
import "../lib/erc20.sol";
interface IStakingPools {
function createPool(
IERC20 _token
) external returns (uint256);
function setRewardWeights(uint256[] calldata _rewardWeights) external;
function acceptGovernance() external;
function setPendingGovernance(address _pendingGovernance) external;
function setRewardRate(uint256 _rewardRate) external;
function deposit(uint256 _poolId, uint256 _depositAmount) external;
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external;
function claim(uint256 _poolId) external;
function exit(uint256 _poolId) external;
function rewardRate() external view returns (uint256);
function totalRewardWeight() external view returns (uint256);
function poolCount() external view returns (uint256);
function getPoolToken(uint256 _poolId) external view returns (IERC20);
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256);
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256);
function getPoolRewardRate(uint256 _poolId) external view returns (uint256);
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256);
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256);
}
// File: contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./safe-math.sol";
import "./context.sol";
// File: contracts/token/ERC20/IERC20.sol
/**
* @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: 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 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");
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: contracts/token/ERC20/ERC20.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;
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 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 { }
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @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;
import "../lib/erc20.sol";
interface IJar is IERC20 {
function token() external view returns (address);
function reward() external view returns (address);
function claimInsurance() external; // NOTE: Only yDelegatedVault implements this
function getRatio() external view returns (uint256);
function depositAll() external;
function balance() external view returns (uint256);
function deposit(uint256) external;
function withdrawAll() external;
function withdraw(uint256) external;
function earn() external;
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
interface IStakingRewards {
function balanceOf(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function exit() external;
function getReward() external;
function getRewardForDuration() external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function lastUpdateTime() external view returns (uint256);
function notifyRewardAmount(uint256 reward) external;
function periodFinish() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function rewardPerTokenStored() external view returns (uint256);
function rewardRate() external view returns (uint256);
function rewards(address) external view returns (uint256);
function rewardsDistribution() external view returns (address);
function rewardsDuration() external view returns (uint256);
function rewardsToken() external view returns (address);
function stake(uint256 amount) external;
function stakeWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function stakingToken() external view returns (address);
function totalSupply() external view returns (uint256);
function userRewardPerTokenPaid(address) external view returns (uint256);
function withdraw(uint256 amount) external;
}
interface IStakingRewardsFactory {
function deploy(address stakingToken, uint256 rewardAmount) external;
function isOwner() external view returns (bool);
function notifyRewardAmount(address stakingToken) external;
function notifyRewardAmounts() external;
function owner() external view returns (address);
function renounceOwnership() external;
function rewardsToken() external view returns (address);
function stakingRewardsGenesis() external view returns (uint256);
function stakingRewardsInfoByStakingToken(address)
external
view
returns (address stakingRewards, uint256 rewardAmount);
function stakingTokens(uint256) external view returns (address);
function transferOwnership(address newOwner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
interface IMasterchef {
function BONUS_MULTIPLIER() external view returns (uint256);
function add(
uint256 _allocPoint,
address _lpToken,
bool _withUpdate
) external;
function bonusEndBlock() external view returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
function dev(address _devaddr) external;
function devFundDivRate() external view returns (uint256);
function devaddr() external view returns (address);
function emergencyWithdraw(uint256 _pid) external;
function getMultiplier(uint256 _from, uint256 _to)
external
view
returns (uint256);
function massUpdatePools() external;
function owner() external view returns (address);
function pendingPickle(uint256 _pid, address _user)
external
view
returns (uint256);
function pickle() external view returns (address);
function picklePerBlock() external view returns (uint256);
function poolInfo(uint256)
external
view
returns (
address lpToken,
uint256 allocPoint,
uint256 lastRewardBlock,
uint256 accPicklePerShare
);
function poolLength() external view returns (uint256);
function renounceOwnership() external;
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) external;
function setBonusEndBlock(uint256 _bonusEndBlock) external;
function setDevFundDivRate(uint256 _devFundDivRate) external;
function setPicklePerBlock(uint256 _picklePerBlock) external;
function startBlock() external view returns (uint256);
function totalAllocPoint() external view returns (uint256);
function transferOwnership(address newOwner) external;
function updatePool(uint256 _pid) external;
function userInfo(uint256, address)
external
view
returns (uint256 amount, uint256 rewardDebt);
function withdraw(uint256 _pid, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
interface UniswapRouterV2 {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
}
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IController {
function jars(address) external view returns (address);
function rewards() external view returns (address);
function devfund() external view returns (address);
function treasury() external view returns (address);
function balanceOf(address) external view returns (uint256);
function withdraw(address, uint256) external;
function withdrawReward(address, uint256) external;
function earn(address, uint256) external;
function strategies(address) external view returns (address);
}
// 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;
}
}
| Collects Alcx tokens 10% is locked up for future gov | function harvest() public override onlyBenevolent {
uint256 _alcxHarvestable = getAlcxFarmHarvestable();
uint256 _harvestable = getHarvestable();
uint256 _alcx = IERC20(alcx).balanceOf(address(this));
if (_alcx > 0) {
uint256 _keepAlcx = _alcx.mul(keepAlcx).div(keepAlcxMax);
IERC20(alcx).safeTransfer(IController(controller).treasury(), _keepAlcx);
uint256 _amount = _alcx.sub(_keepAlcx);
IERC20(alcx).safeApprove(stakingPool, 0);
IERC20(alcx).safeApprove(stakingPool, _amount);
}
}
| 11,737,595 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IAmp {
function registerCollateralManager() external;
}
/**
* @title Ownable is a contract the provides contract ownership functionality, including a two-
* phase transfer.
*/
contract Ownable {
address private _owner;
address private _authorizedNewOwner;
/**
* @notice Emitted when the owner authorizes ownership transfer to a new address
* @param authorizedAddress New owner address
*/
event OwnershipTransferAuthorization(address indexed authorizedAddress);
/**
* @notice Emitted when the authorized address assumed ownership
* @param oldValue Old owner
* @param newValue New owner
*/
event OwnerUpdate(address indexed oldValue, address indexed newValue);
/**
* @notice Sets the owner to the sender / contract creator
*/
constructor() internal {
_owner = msg.sender;
}
/**
* @notice Retrieves the owner of the contract
* @return The contract owner
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @notice Retrieves the authorized new owner of the contract
* @return The authorized new contract owner
*/
function authorizedNewOwner() public view returns (address) {
return _authorizedNewOwner;
}
/**
* @notice Authorizes the transfer of ownership from owner to the provided address.
* NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership().
* This authorization may be removed by another call to this function authorizing the zero
* address.
* @param _authorizedAddress The address authorized to become the new owner
*/
function authorizeOwnershipTransfer(address _authorizedAddress) external {
require(msg.sender == _owner, "Invalid sender");
_authorizedNewOwner = _authorizedAddress;
emit OwnershipTransferAuthorization(_authorizedNewOwner);
}
/**
* @notice Transfers ownership of this contract to the _authorizedNewOwner
* @dev Error invalid sender.
*/
function assumeOwnership() external {
require(msg.sender == _authorizedNewOwner, "Invalid sender");
address oldValue = _owner;
_owner = _authorizedNewOwner;
_authorizedNewOwner = address(0);
emit OwnerUpdate(oldValue, _owner);
}
}
abstract contract ERC1820Registry {
function setInterfaceImplementer(
address _addr,
bytes32 _interfaceHash,
address _implementer
) external virtual;
function getInterfaceImplementer(address _addr, bytes32 _interfaceHash)
external
virtual
view
returns (address);
function setManager(address _addr, address _newManager) external virtual;
function getManager(address _addr) public virtual view returns (address);
}
/// Base client to interact with the registry.
contract ERC1820Client {
ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry(
0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24
);
function setInterfaceImplementation(
string memory _interfaceLabel,
address _implementation
) internal {
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
ERC1820REGISTRY.setInterfaceImplementer(
address(this),
interfaceHash,
_implementation
);
}
function interfaceAddr(address addr, string memory _interfaceLabel)
internal
view
returns (address)
{
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash);
}
function delegateManagement(address _newManager) internal {
ERC1820REGISTRY.setManager(address(this), _newManager);
}
}
/**
* @title IAmpTokensRecipient
* @dev IAmpTokensRecipient token transfer hook interface
*/
interface IAmpTokensRecipient {
/**
* @dev Report if the recipient will successfully receive the tokens
*/
function canReceive(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
) external view returns (bool);
/**
* @dev Hook executed upon a transfer to the recipient
*/
function tokensReceived(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/**
* @title IAmpTokensSender
* @dev IAmpTokensSender token transfer hook interface
*/
interface IAmpTokensSender {
/**
* @dev Report if the transfer will succeed from the pespective of the
* token sender
*/
function canTransfer(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
) external view returns (bool);
/**
* @dev Hook executed upon a transfer on behalf of the sender
*/
function tokensToTransfer(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/**
* @title PartitionUtils
* @notice Partition related helper functions.
*/
library PartitionUtils {
bytes32 public constant CHANGE_PARTITION_FLAG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/**
* @notice Retrieve the destination partition from the 'data' field.
* A partition change is requested ONLY when 'data' starts with the flag:
*
* 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
*
* When the flag is detected, the destination partition is extracted from the
* 32 bytes following the flag.
* @param _data Information attached to the transfer. Will contain the
* destination partition if a change is requested.
* @param _fallbackPartition Partition value to return if a partition change
* is not requested in the `_data`.
* @return toPartition Destination partition. If the `_data` does not contain
* the prefix and bytes32 partition in the first 64 bytes, the method will
* return the provided `_fromPartition`.
*/
function _getDestinationPartition(bytes memory _data, bytes32 _fallbackPartition)
internal
pure
returns (bytes32)
{
if (_data.length < 64) {
return _fallbackPartition;
}
(bytes32 flag, bytes32 toPartition) = abi.decode(_data, (bytes32, bytes32));
if (flag == CHANGE_PARTITION_FLAG) {
return toPartition;
}
return _fallbackPartition;
}
/**
* @notice Helper to get the strategy identifying prefix from the `_partition`.
* @param _partition Partition to get the prefix for.
* @return 4 byte partition strategy prefix.
*/
function _getPartitionPrefix(bytes32 _partition) internal pure returns (bytes4) {
return bytes4(_partition);
}
/**
* @notice Helper method to split the partition into the prefix, sub partition
* and partition owner components.
* @param _partition The partition to split into parts.
* @return The 4 byte partition prefix, 8 byte sub partition, and final 20
* bytes representing an address.
*/
function _splitPartition(bytes32 _partition)
internal
pure
returns (
bytes4,
bytes8,
address
)
{
bytes4 prefix = bytes4(_partition);
bytes8 subPartition = bytes8(_partition << 32);
address addressPart = address(uint160(uint256(_partition)));
return (prefix, subPartition, addressPart);
}
/**
* @notice Helper method to get a partition strategy ERC1820 interface name
* based on partition prefix.
* @param _prefix 4 byte partition prefix.
* @dev Each 4 byte prefix has a unique interface name so that an individual
* hook implementation can be set for each prefix.
*/
function _getPartitionStrategyValidatorIName(bytes4 _prefix)
internal
pure
returns (string memory)
{
return string(abi.encodePacked("AmpPartitionStrategyValidator", _prefix));
}
}
/**
* @title FlexaCollateralManager is an implementation of IAmpTokensSender and IAmpTokensRecipient
* which serves as the Amp collateral manager for the Flexa Network.
*/
contract FlexaCollateralManager is Ownable, IAmpTokensSender, IAmpTokensRecipient, ERC1820Client {
/**
* @dev AmpTokensSender interface label.
*/
string internal constant AMP_TOKENS_SENDER = "AmpTokensSender";
/**
* @dev AmpTokensRecipient interface label.
*/
string internal constant AMP_TOKENS_RECIPIENT = "AmpTokensRecipient";
/**
* @dev Change Partition Flag used in transfer data parameters to signal which partition
* will receive the tokens.
*/
bytes32
internal constant CHANGE_PARTITION_FLAG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/**
* @dev Required prefix for all registered partitions. Used to ensure the Collateral Pool
* Partition Validator is used within Amp.
*/
bytes4 internal constant PARTITION_PREFIX = 0xCCCCCCCC;
/**********************************************************************************************
* Operator Data Flags
*********************************************************************************************/
/**
* @dev Flag used in operator data parameters to indicate the transfer is a withdrawal
*/
bytes32
internal constant WITHDRAWAL_FLAG = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
/**
* @dev Flag used in operator data parameters to indicate the transfer is a fallback
* withdrawal
*/
bytes32
internal constant FALLBACK_WITHDRAWAL_FLAG = 0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;
/**
* @dev Flag used in operator data parameters to indicate the transfer is a supply refund
*/
bytes32
internal constant REFUND_FLAG = 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc;
/**
* @dev Flag used in operator data parameters to indicate the transfer is a direct transfer
*/
bytes32
internal constant DIRECT_TRANSFER_FLAG = 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd;
/**********************************************************************************************
* Configuration
*********************************************************************************************/
/**
* @notice Address of the Amp contract. Immutable.
*/
address public amp;
/**
* @notice Permitted partitions
*/
mapping(bytes32 => bool) public partitions;
/**********************************************************************************************
* Roles
*********************************************************************************************/
/**
* @notice Address authorized to publish withdrawal roots
*/
address public withdrawalPublisher;
/**
* @notice Address authorized to publish fallback withdrawal roots
*/
address public fallbackPublisher;
/**
* @notice Address authorized to adjust the withdrawal limit
*/
address public withdrawalLimitPublisher;
/**
* @notice Address authorized to directly transfer tokens
*/
address public directTransferer;
/**
* @notice Address authorized to manage permitted partition
*/
address public partitionManager;
/**
* @notice Struct used to record received tokens that can be recovered during the fallback
* withdrawal period
* @param supplier Token supplier
* @param partition Partition which received the tokens
* @param amount Number of tokens received
*/
struct Supply {
address supplier;
bytes32 partition;
uint256 amount;
}
/**********************************************************************************************
* Supply State
*********************************************************************************************/
/**
* @notice Supply nonce used to track incoming token transfers
*/
uint256 public supplyNonce = 0;
/**
* @notice Mapping of all incoming token transfers
*/
mapping(uint256 => Supply) public nonceToSupply;
/**********************************************************************************************
* Withdrawal State
*********************************************************************************************/
/**
* @notice Remaining withdrawal limit. Initially set to 100,000 Amp.
*/
uint256 public withdrawalLimit = 100 * 1000 * (10**18);
/**
* @notice Withdrawal maximum root nonce
*/
uint256 public maxWithdrawalRootNonce = 0;
/**
* @notice Active set of withdrawal roots
*/
mapping(bytes32 => uint256) public withdrawalRootToNonce;
/**
* @notice Last invoked withdrawal root for each account, per partition
*/
mapping(bytes32 => mapping(address => uint256)) public addressToWithdrawalNonce;
/**
* @notice Total amount withdrawn for each account, per partition
*/
mapping(bytes32 => mapping(address => uint256)) public addressToCumulativeAmountWithdrawn;
/**********************************************************************************************
* Fallback Withdrawal State
*********************************************************************************************/
/**
* @notice Withdrawal fallback delay. Initially set to one week.
*/
uint256 public fallbackWithdrawalDelaySeconds = 1 weeks;
/**
* @notice Current fallback withdrawal root
*/
bytes32 public fallbackRoot;
/**
* @notice Timestamp of when the last fallback root was published
*/
uint256 public fallbackSetDate = 2**200; // very far in the future
/**
* @notice Latest supply reflected in the fallback withdrawal authorization tree
*/
uint256 public fallbackMaxIncludedSupplyNonce = 0;
/**********************************************************************************************
* Supplier Events
*********************************************************************************************/
/**
* @notice Indicates a token supply has been received
* @param supplier Token supplier
* @param amount Number of tokens transferred
* @param nonce Nonce of the supply
*/
event SupplyReceipt(
address indexed supplier,
bytes32 indexed partition,
uint256 amount,
uint256 indexed nonce
);
/**
* @notice Indicates that a withdrawal was executed
* @param supplier Address whose withdrawal authorization was executed
* @param partition Partition from which the tokens were transferred
* @param amount Amount of tokens transferred
* @param rootNonce Nonce of the withdrawal root used for authorization
* @param authorizedAccountNonce Maximum previous nonce used by the account
*/
event Withdrawal(
address indexed supplier,
bytes32 indexed partition,
uint256 amount,
uint256 indexed rootNonce,
uint256 authorizedAccountNonce
);
/**
* @notice Indicates a fallback withdrawal was executed
* @param supplier Address whose fallback withdrawal authorization was executed
* @param partition Partition from which the tokens were transferred
* @param amount Amount of tokens transferred
*/
event FallbackWithdrawal(
address indexed supplier,
bytes32 indexed partition,
uint256 indexed amount
);
/**
* @notice Indicates a release of supply is requested
* @param supplier Token supplier
* @param partition Parition from which the tokens should be released
* @param amount Number of tokens requested to be released
* @param data Metadata provided by the requestor
*/
event ReleaseRequest(
address indexed supplier,
bytes32 indexed partition,
uint256 indexed amount,
bytes data
);
/**
* @notice Indicates a supply refund was executed
* @param supplier Address whose refund authorization was executed
* @param partition Partition from which the tokens were transferred
* @param amount Amount of tokens transferred
* @param nonce Nonce of the original supply
*/
event SupplyRefund(
address indexed supplier,
bytes32 indexed partition,
uint256 amount,
uint256 indexed nonce
);
/**********************************************************************************************
* Direct Transfer Events
*********************************************************************************************/
/**
* @notice Emitted when tokens are directly transfered
* @param operator Address that executed the direct transfer
* @param from_partition Partition from which the tokens were transferred
* @param to_address Address to which the tokens were transferred
* @param to_partition Partition to which the tokens were transferred
* @param value Amount of tokens transferred
*/
event DirectTransfer(
address operator,
bytes32 indexed from_partition,
address indexed to_address,
bytes32 indexed to_partition,
uint256 value
);
/**********************************************************************************************
* Admin Configuration Events
*********************************************************************************************/
/**
* @notice Emitted when a partition is permitted for supply
* @param partition Partition added to the permitted set
*/
event PartitionAdded(bytes32 indexed partition);
/**
* @notice Emitted when a partition is removed from the set permitted for supply
* @param partition Partition removed from the permitted set
*/
event PartitionRemoved(bytes32 indexed partition);
/**********************************************************************************************
* Admin Withdrawal Management Events
*********************************************************************************************/
/**
* @notice Emitted when a new withdrawal root hash is added to the active set
* @param rootHash Merkle root hash.
* @param nonce Nonce of the Merkle root hash.
*/
event WithdrawalRootHashAddition(bytes32 indexed rootHash, uint256 indexed nonce);
/**
* @notice Emitted when a withdrawal root hash is removed from the active set
* @param rootHash Merkle root hash.
* @param nonce Nonce of the Merkle root hash.
*/
event WithdrawalRootHashRemoval(bytes32 indexed rootHash, uint256 indexed nonce);
/**
* @notice Emitted when the withdrawal limit is updated
* @param oldValue Old limit.
* @param newValue New limit.
*/
event WithdrawalLimitUpdate(uint256 indexed oldValue, uint256 indexed newValue);
/**********************************************************************************************
* Admin Fallback Management Events
*********************************************************************************************/
/**
* @notice Emitted when a new fallback withdrawal root hash is set
* @param rootHash Merkle root hash
* @param maxSupplyNonceIncluded Nonce of the last supply reflected in the tree data
* @param setDate Timestamp of when the root hash was set
*/
event FallbackRootHashSet(
bytes32 indexed rootHash,
uint256 indexed maxSupplyNonceIncluded,
uint256 setDate
);
/**
* @notice Emitted when the fallback root hash set date is reset
* @param newDate Timestamp of when the fallback reset date was set
*/
event FallbackMechanismDateReset(uint256 indexed newDate);
/**
* @notice Emitted when the fallback delay is updated
* @param oldValue Old delay
* @param newValue New delay
*/
event FallbackWithdrawalDelayUpdate(uint256 indexed oldValue, uint256 indexed newValue);
/**********************************************************************************************
* Role Management Events
*********************************************************************************************/
/**
* @notice Emitted when the Withdrawal Publisher is updated
* @param oldValue Old publisher
* @param newValue New publisher
*/
event WithdrawalPublisherUpdate(address indexed oldValue, address indexed newValue);
/**
* @notice Emitted when the Fallback Publisher is updated
* @param oldValue Old publisher
* @param newValue New publisher
*/
event FallbackPublisherUpdate(address indexed oldValue, address indexed newValue);
/**
* @notice Emitted when Withdrawal Limit Publisher is updated
* @param oldValue Old publisher
* @param newValue New publisher
*/
event WithdrawalLimitPublisherUpdate(address indexed oldValue, address indexed newValue);
/**
* @notice Emitted when the DirectTransferer address is updated
* @param oldValue Old DirectTransferer address
* @param newValue New DirectTransferer address
*/
event DirectTransfererUpdate(address indexed oldValue, address indexed newValue);
/**
* @notice Emitted when the Partition Manager address is updated
* @param oldValue Old Partition Manager address
* @param newValue New Partition Manager address
*/
event PartitionManagerUpdate(address indexed oldValue, address indexed newValue);
/**********************************************************************************************
* Constructor
*********************************************************************************************/
/**
* @notice FlexaCollateralManager constructor
* @param _amp Address of the Amp token contract
*/
constructor(address _amp) public {
amp = _amp;
ERC1820Client.setInterfaceImplementation(AMP_TOKENS_RECIPIENT, address(this));
ERC1820Client.setInterfaceImplementation(AMP_TOKENS_SENDER, address(this));
IAmp(amp).registerCollateralManager();
}
/**********************************************************************************************
* IAmpTokensRecipient Hooks
*********************************************************************************************/
/**
* @notice Validates where the supplied parameters are valid for a transfer of tokens to this
* contract
* @dev Implements IAmpTokensRecipient
* @param _partition Partition from which the tokens were transferred
* @param _to The destination address of the tokens. Must be this.
* @param _data Optional data sent with the transfer. Used to set the destination partition.
* @return true if the tokens can be received, otherwise false
*/
function canReceive(
bytes4, /* functionSig */
bytes32 _partition,
address, /* operator */
address, /* from */
address _to,
uint256, /* value */
bytes calldata _data,
bytes calldata /* operatorData */
) external override view returns (bool) {
if (msg.sender != amp || _to != address(this)) {
return false;
}
bytes32 _destinationPartition = PartitionUtils._getDestinationPartition(_data, _partition);
return partitions[_destinationPartition];
}
/**
* @notice Function called by the token contract after executing a transfer.
* @dev Implements IAmpTokensRecipient
* @param _partition Partition from which the tokens were transferred
* @param _operator Address which triggered the transfer. This address will be credited with
* the supply.
* @param _to The destination address of the tokens. Must be this.
* @param _value Number of tokens the token holder balance is decreased by.
* @param _data Optional data sent with the transfer. Used to set the destination partition.
*/
function tokensReceived(
bytes4, /* functionSig */
bytes32 _partition,
address _operator,
address, /* from */
address _to,
uint256 _value,
bytes calldata _data,
bytes calldata /* operatorData */
) external override {
require(msg.sender == amp, "Invalid sender");
require(_to == address(this), "Invalid to address");
bytes32 _destinationPartition = PartitionUtils._getDestinationPartition(_data, _partition);
require(partitions[_destinationPartition], "Invalid destination partition");
supplyNonce = SafeMath.add(supplyNonce, 1);
nonceToSupply[supplyNonce].supplier = _operator;
nonceToSupply[supplyNonce].partition = _destinationPartition;
nonceToSupply[supplyNonce].amount = _value;
emit SupplyReceipt(_operator, _destinationPartition, _value, supplyNonce);
}
/**********************************************************************************************
* IAmpTokensSender Hooks
*********************************************************************************************/
/**
* @notice Validates where the supplied parameters are valid for a transfer of tokens from this
* contract
* @dev Implements IAmpTokensSender
* @param _partition Source partition of the tokens
* @param _operator Address which triggered the transfer
* @param _from The source address of the tokens. Must be this.
* @param _value Amount of tokens to be transferred
* @param _operatorData Extra information attached by the operator. Must include the transfer
* operation flag and additional authorization data custom for each transfer operation type.
* @return true if the token transfer would succeed, otherwise false
*/
function canTransfer(
bytes4, /*functionSig*/
bytes32 _partition,
address _operator,
address _from,
address, /* to */
uint256 _value,
bytes calldata, /* data */
bytes calldata _operatorData
) external override view returns (bool) {
if (msg.sender != amp || _from != address(this)) {
return false;
}
bytes32 flag = _decodeOperatorDataFlag(_operatorData);
if (flag == WITHDRAWAL_FLAG) {
return _validateWithdrawal(_partition, _operator, _value, _operatorData);
}
if (flag == FALLBACK_WITHDRAWAL_FLAG) {
return _validateFallbackWithdrawal(_partition, _operator, _value, _operatorData);
}
if (flag == REFUND_FLAG) {
return _validateRefund(_partition, _operator, _value, _operatorData);
}
if (flag == DIRECT_TRANSFER_FLAG) {
return _validateDirectTransfer(_operator, _value);
}
return false;
}
/**
* @notice Function called by the token contract when executing a transfer
* @dev Implements IAmpTokensSender
* @param _partition Source partition of the tokens
* @param _operator Address which triggered the transfer
* @param _from The source address of the tokens. Must be this.
* @param _to The target address of the tokens.
* @param _value Amount of tokens to be transferred
* @param _data Data attached to the transfer. Typically includes partition change information.
* @param _operatorData Extra information attached by the operator. Must include the transfer
* operation flag and additional authorization data custom for each transfer operation type.
*/
function tokensToTransfer(
bytes4, /* functionSig */
bytes32 _partition,
address _operator,
address _from,
address _to,
uint256 _value,
bytes calldata _data,
bytes calldata _operatorData
) external override {
require(msg.sender == amp, "Invalid sender");
require(_from == address(this), "Invalid from address");
bytes32 flag = _decodeOperatorDataFlag(_operatorData);
if (flag == WITHDRAWAL_FLAG) {
_executeWithdrawal(_partition, _operator, _value, _operatorData);
} else if (flag == FALLBACK_WITHDRAWAL_FLAG) {
_executeFallbackWithdrawal(_partition, _operator, _value, _operatorData);
} else if (flag == REFUND_FLAG) {
_executeRefund(_partition, _operator, _value, _operatorData);
} else if (flag == DIRECT_TRANSFER_FLAG) {
_executeDirectTransfer(_partition, _operator, _to, _value, _data);
} else {
revert("invalid flag");
}
}
/**********************************************************************************************
* Withdrawals
*********************************************************************************************/
/**
* @notice Validates withdrawal data
* @param _partition Source partition of the withdrawal
* @param _operator Address that is invoking the transfer
* @param _value Number of tokens to be transferred
* @param _operatorData Contains the withdrawal authorization data
* @return true if the withdrawal data is valid, otherwise false
*/
function _validateWithdrawal(
bytes32 _partition,
address _operator,
uint256 _value,
bytes memory _operatorData
) internal view returns (bool) {
(
address supplier,
uint256 maxAuthorizedAccountNonce,
uint256 withdrawalRootNonce
) = _getWithdrawalData(_partition, _value, _operatorData);
return
_validateWithdrawalData(
_partition,
_operator,
_value,
supplier,
maxAuthorizedAccountNonce,
withdrawalRootNonce
);
}
/**
* @notice Validates the withdrawal data and updates state to reflect the transfer
* @param _partition Source partition of the withdrawal
* @param _operator Address that is invoking the transfer
* @param _value Number of tokens to be transferred
* @param _operatorData Contains the withdrawal authorization data
*/
function _executeWithdrawal(
bytes32 _partition,
address _operator,
uint256 _value,
bytes memory _operatorData
) internal {
(
address supplier,
uint256 maxAuthorizedAccountNonce,
uint256 withdrawalRootNonce
) = _getWithdrawalData(_partition, _value, _operatorData);
require(
_validateWithdrawalData(
_partition,
_operator,
_value,
supplier,
maxAuthorizedAccountNonce,
withdrawalRootNonce
),
"Transfer unauthorized"
);
addressToCumulativeAmountWithdrawn[_partition][supplier] = SafeMath.add(
_value,
addressToCumulativeAmountWithdrawn[_partition][supplier]
);
addressToWithdrawalNonce[_partition][supplier] = withdrawalRootNonce;
withdrawalLimit = SafeMath.sub(withdrawalLimit, _value);
emit Withdrawal(
supplier,
_partition,
_value,
withdrawalRootNonce,
maxAuthorizedAccountNonce
);
}
/**
* @notice Extracts withdrawal data from the supplied parameters
* @param _partition Source partition of the withdrawal
* @param _value Number of tokens to be transferred
* @param _operatorData Contains the withdrawal authorization data, including the withdrawal
* operation flag, supplier, maximum authorized account nonce, and Merkle proof.
* @return supplier, the address whose account is authorized
* @return maxAuthorizedAccountNonce, the maximum existing used withdrawal nonce for the
* supplier and partition
* @return withdrawalRootNonce, the active withdrawal root nonce found based on the supplied
* data and Merkle proof
*/
function _getWithdrawalData(
bytes32 _partition,
uint256 _value,
bytes memory _operatorData
)
internal
view
returns (
address, /* supplier */
uint256, /* maxAuthorizedAccountNonce */
uint256 /* withdrawalRootNonce */
)
{
(
address supplier,
uint256 maxAuthorizedAccountNonce,
bytes32[] memory merkleProof
) = _decodeWithdrawalOperatorData(_operatorData);
bytes32 leafDataHash = _calculateWithdrawalLeaf(
supplier,
_partition,
_value,
maxAuthorizedAccountNonce
);
bytes32 calculatedRoot = _calculateMerkleRoot(merkleProof, leafDataHash);
uint256 withdrawalRootNonce = withdrawalRootToNonce[calculatedRoot];
return (supplier, maxAuthorizedAccountNonce, withdrawalRootNonce);
}
/**
* @notice Validates that the parameters are valid for the requested withdrawal
* @param _partition Source partition of the tokens
* @param _operator Address that is executing the withdrawal
* @param _value Number of tokens to be transferred
* @param _supplier The address whose account is authorized
* @param _maxAuthorizedAccountNonce The maximum existing used withdrawal nonce for the
* supplier and partition
* @param _withdrawalRootNonce The active withdrawal root nonce found based on the supplied
* data and Merkle proof
* @return true if the withdrawal data is valid, otherwise false
*/
function _validateWithdrawalData(
bytes32 _partition,
address _operator,
uint256 _value,
address _supplier,
uint256 _maxAuthorizedAccountNonce,
uint256 _withdrawalRootNonce
) internal view returns (bool) {
return
// Only owner, withdrawal publisher or supplier can invoke withdrawals
(_operator == owner() || _operator == withdrawalPublisher || _operator == _supplier) &&
// Ensure maxAuthorizedAccountNonce has not been exceeded
(addressToWithdrawalNonce[_partition][_supplier] <= _maxAuthorizedAccountNonce) &&
// Ensure we are within the global withdrawal limit
(_value <= withdrawalLimit) &&
// Merkle tree proof is valid
(_withdrawalRootNonce > 0) &&
// Ensure the withdrawal root is more recent than the maxAuthorizedAccountNonce
(_withdrawalRootNonce > _maxAuthorizedAccountNonce);
}
/**********************************************************************************************
* Fallback Withdrawals
*********************************************************************************************/
/**
* @notice Validates fallback withdrawal data
* @param _partition Source partition of the withdrawal
* @param _operator Address that is invoking the transfer
* @param _value Number of tokens to be transferred
* @param _operatorData Contains the fallback withdrawal authorization data
* @return true if the fallback withdrawal data is valid, otherwise false
*/
function _validateFallbackWithdrawal(
bytes32 _partition,
address _operator,
uint256 _value,
bytes memory _operatorData
) internal view returns (bool) {
(
address supplier,
uint256 maxCumulativeWithdrawalAmount,
uint256 newCumulativeWithdrawalAmount,
bytes32 calculatedRoot
) = _getFallbackWithdrawalData(_partition, _value, _operatorData);
return
_validateFallbackWithdrawalData(
_operator,
maxCumulativeWithdrawalAmount,
newCumulativeWithdrawalAmount,
supplier,
calculatedRoot
);
}
/**
* @notice Validates the fallback withdrawal data and updates state to reflect the transfer
* @param _partition Source partition of the withdrawal
* @param _operator Address that is invoking the transfer
* @param _value Number of tokens to be transferred
* @param _operatorData Contains the fallback withdrawal authorization data
*/
function _executeFallbackWithdrawal(
bytes32 _partition,
address _operator,
uint256 _value,
bytes memory _operatorData
) internal {
(
address supplier,
uint256 maxCumulativeWithdrawalAmount,
uint256 newCumulativeWithdrawalAmount,
bytes32 calculatedRoot
) = _getFallbackWithdrawalData(_partition, _value, _operatorData);
require(
_validateFallbackWithdrawalData(
_operator,
maxCumulativeWithdrawalAmount,
newCumulativeWithdrawalAmount,
supplier,
calculatedRoot
),
"Transfer unauthorized"
);
addressToCumulativeAmountWithdrawn[_partition][supplier] = newCumulativeWithdrawalAmount;
addressToWithdrawalNonce[_partition][supplier] = maxWithdrawalRootNonce;
emit FallbackWithdrawal(supplier, _partition, _value);
}
/**
* @notice Extracts withdrawal data from the supplied parameters
* @param _partition Source partition of the withdrawal
* @param _value Number of tokens to be transferred
* @param _operatorData Contains the fallback withdrawal authorization data, including the
* fallback withdrawal operation flag, supplier, max cumulative withdrawal amount, and Merkle
* proof.
* @return supplier, the address whose account is authorized
* @return maxCumulativeWithdrawalAmount, the maximum amount of tokens that can be withdrawn
* for the supplier's account, including both withdrawals and fallback withdrawals
* @return newCumulativeWithdrawalAmount, the new total of all withdrawals include the
* current request
* @return calculatedRoot, the Merkle tree root calculated based on the supplied data and proof
*/
function _getFallbackWithdrawalData(
bytes32 _partition,
uint256 _value,
bytes memory _operatorData
)
internal
view
returns (
address, /* supplier */
uint256, /* maxCumulativeWithdrawalAmount */
uint256, /* newCumulativeWithdrawalAmount */
bytes32 /* calculatedRoot */
)
{
(
address supplier,
uint256 maxCumulativeWithdrawalAmount,
bytes32[] memory merkleProof
) = _decodeWithdrawalOperatorData(_operatorData);
uint256 newCumulativeWithdrawalAmount = SafeMath.add(
_value,
addressToCumulativeAmountWithdrawn[_partition][supplier]
);
bytes32 leafDataHash = _calculateFallbackLeaf(
supplier,
_partition,
maxCumulativeWithdrawalAmount
);
bytes32 calculatedRoot = _calculateMerkleRoot(merkleProof, leafDataHash);
return (
supplier,
maxCumulativeWithdrawalAmount,
newCumulativeWithdrawalAmount,
calculatedRoot
);
}
/**
* @notice Validates that the parameters are valid for the requested fallback withdrawal
* @param _operator Address that is executing the withdrawal
* @param _maxCumulativeWithdrawalAmount, the maximum amount of tokens that can be withdrawn
* for the supplier's account, including both withdrawals and fallback withdrawals
* @param _newCumulativeWithdrawalAmount, the new total of all withdrawals include the
* current request
* @param _supplier The address whose account is authorized
* @param _calculatedRoot The Merkle tree root calculated based on the supplied data and proof
* @return true if the fallback withdrawal data is valid, otherwise false
*/
function _validateFallbackWithdrawalData(
address _operator,
uint256 _maxCumulativeWithdrawalAmount,
uint256 _newCumulativeWithdrawalAmount,
address _supplier,
bytes32 _calculatedRoot
) internal view returns (bool) {
return
// Only owner or supplier can invoke the fallback withdrawal
(_operator == owner() || _operator == _supplier) &&
// Ensure we have entered fallback mode
(SafeMath.add(fallbackSetDate, fallbackWithdrawalDelaySeconds) <= block.timestamp) &&
// Check that the maximum allowable withdrawal for the supplier has not been exceeded
(_newCumulativeWithdrawalAmount <= _maxCumulativeWithdrawalAmount) &&
// Merkle tree proof is valid
(fallbackRoot == _calculatedRoot);
}
/**********************************************************************************************
* Supply Refunds
*********************************************************************************************/
/**
* @notice Validates refund data
* @param _partition Source partition of the refund
* @param _operator Address that is invoking the transfer
* @param _value Number of tokens to be transferred
* @param _operatorData Contains the refund authorization data
* @return true if the refund data is valid, otherwise false
*/
function _validateRefund(
bytes32 _partition,
address _operator,
uint256 _value,
bytes memory _operatorData
) internal view returns (bool) {
(uint256 _supplyNonce, Supply memory supply) = _getRefundData(_operatorData);
return _verifyRefundData(_partition, _operator, _value, _supplyNonce, supply);
}
/**
* @notice Validates the refund data and updates state to reflect the transfer
* @param _partition Source partition of the refund
* @param _operator Address that is invoking the transfer
* @param _value Number of tokens to be transferred
* @param _operatorData Contains the refund authorization data
*/
function _executeRefund(
bytes32 _partition,
address _operator,
uint256 _value,
bytes memory _operatorData
) internal {
(uint256 nonce, Supply memory supply) = _getRefundData(_operatorData);
require(
_verifyRefundData(_partition, _operator, _value, nonce, supply),
"Transfer unauthorized"
);
delete nonceToSupply[nonce];
emit SupplyRefund(supply.supplier, _partition, supply.amount, nonce);
}
/**
* @notice Extracts refund data from the supplied parameters
* @param _operatorData Contains the refund authorization data, including the refund
* operation flag and supply nonce.
* @return supplyNonce, nonce of the recorded supply
* @return supply, The supplier, partition and amount of tokens in the original supply
*/
function _getRefundData(bytes memory _operatorData)
internal
view
returns (uint256, Supply memory)
{
uint256 _supplyNonce = _decodeRefundOperatorData(_operatorData);
Supply memory supply = nonceToSupply[_supplyNonce];
return (_supplyNonce, supply);
}
/**
* @notice Validates that the parameters are valid for the requested refund
* @param _partition Source partition of the tokens
* @param _operator Address that is executing the refund
* @param _value Number of tokens to be transferred
* @param _supplyNonce nonce of the recorded supply
* @param _supply The supplier, partition and amount of tokens in the original supply
* @return true if the refund data is valid, otherwise false
*/
function _verifyRefundData(
bytes32 _partition,
address _operator,
uint256 _value,
uint256 _supplyNonce,
Supply memory _supply
) internal view returns (bool) {
return
// Supply record exists
(_supply.amount > 0) &&
// Only owner or supplier can invoke the refund
(_operator == owner() || _operator == _supply.supplier) &&
// Requested partition matches the Supply record
(_partition == _supply.partition) &&
// Requested value matches the Supply record
(_value == _supply.amount) &&
// Ensure we have entered fallback mode
(SafeMath.add(fallbackSetDate, fallbackWithdrawalDelaySeconds) <= block.timestamp) &&
// Supply has not already been included in the fallback withdrawal data
(_supplyNonce > fallbackMaxIncludedSupplyNonce);
}
/**********************************************************************************************
* Direct Transfers
*********************************************************************************************/
/**
* @notice Validates direct transfer data
* @param _operator Address that is invoking the transfer
* @param _value Number of tokens to be transferred
* @return true if the direct transfer data is valid, otherwise false
*/
function _validateDirectTransfer(address _operator, uint256 _value)
internal
view
returns (bool)
{
return
// Only owner and directTransferer can invoke withdrawals
(_operator == owner() || _operator == directTransferer) &&
// Ensure we are within the global withdrawal limit
(_value <= withdrawalLimit);
}
/**
* @notice Validates the direct transfer data and updates state to reflect the transfer
* @param _partition Source partition of the direct transfer
* @param _operator Address that is invoking the transfer
* @param _to The target address of the tokens.
* @param _value Number of tokens to be transferred
* @param _data Data attached to the transfer. Typically includes partition change information.
*/
function _executeDirectTransfer(
bytes32 _partition,
address _operator,
address _to,
uint256 _value,
bytes memory _data
) internal {
require(_validateDirectTransfer(_operator, _value), "Transfer unauthorized");
withdrawalLimit = SafeMath.sub(withdrawalLimit, _value);
bytes32 to_partition = PartitionUtils._getDestinationPartition(_data, _partition);
emit DirectTransfer(_operator, _partition, _to, to_partition, _value);
}
/**********************************************************************************************
* Release Request
*********************************************************************************************/
/**
* @notice Emits a release request event that can be used to trigger the release of tokens
* @param _partition Parition from which the tokens should be released
* @param _amount Number of tokens requested to be released
* @param _data Metadata to include with the release request
*/
function requestRelease(
bytes32 _partition,
uint256 _amount,
bytes memory _data
) external {
emit ReleaseRequest(msg.sender, _partition, _amount, _data);
}
/**********************************************************************************************
* Partition Management
*********************************************************************************************/
/**
* @notice Adds a partition to the set allowed to receive tokens
* @param _partition Parition to be permitted for incoming transfers
*/
function addPartition(bytes32 _partition) external {
require(msg.sender == owner() || msg.sender == partitionManager, "Invalid sender");
require(partitions[_partition] == false, "Partition already permitted");
(bytes4 prefix, , address partitionOwner) = PartitionUtils._splitPartition(_partition);
require(prefix == PARTITION_PREFIX, "Invalid partition prefix");
require(partitionOwner == address(this), "Invalid partition owner");
partitions[_partition] = true;
emit PartitionAdded(_partition);
}
/**
* @notice Removes a partition from the set allowed to receive tokens
* @param _partition Parition to be disallowed from incoming transfers
*/
function removePartition(bytes32 _partition) external {
require(msg.sender == owner() || msg.sender == partitionManager, "Invalid sender");
require(partitions[_partition], "Partition not permitted");
delete partitions[_partition];
emit PartitionRemoved(_partition);
}
/**********************************************************************************************
* Withdrawal Management
*********************************************************************************************/
/**
* @notice Modifies the withdrawal limit by the provided amount.
* @param _amount Limit delta
*/
function modifyWithdrawalLimit(int256 _amount) external {
require(msg.sender == owner() || msg.sender == withdrawalLimitPublisher, "Invalid sender");
uint256 oldLimit = withdrawalLimit;
if (_amount < 0) {
uint256 unsignedAmount = uint256(-_amount);
withdrawalLimit = SafeMath.sub(withdrawalLimit, unsignedAmount);
} else {
uint256 unsignedAmount = uint256(_amount);
withdrawalLimit = SafeMath.add(withdrawalLimit, unsignedAmount);
}
emit WithdrawalLimitUpdate(oldLimit, withdrawalLimit);
}
/**
* @notice Adds the root hash of a Merkle tree containing authorized token withdrawals to the
* active set
* @param _root The root hash to be added to the active set
* @param _nonce The nonce of the new root hash. Must be exactly one higher than the existing
* max nonce.
* @param _replacedRoots The root hashes to be removed from the repository.
*/
function addWithdrawalRoot(
bytes32 _root,
uint256 _nonce,
bytes32[] calldata _replacedRoots
) external {
require(msg.sender == owner() || msg.sender == withdrawalPublisher, "Invalid sender");
require(_root != 0, "Invalid root");
require(maxWithdrawalRootNonce + 1 == _nonce, "Nonce not current max plus one");
require(withdrawalRootToNonce[_root] == 0, "Nonce already used");
withdrawalRootToNonce[_root] = _nonce;
maxWithdrawalRootNonce = _nonce;
emit WithdrawalRootHashAddition(_root, _nonce);
for (uint256 i = 0; i < _replacedRoots.length; i++) {
deleteWithdrawalRoot(_replacedRoots[i]);
}
}
/**
* @notice Removes withdrawal root hashes from active set
* @param _roots The root hashes to be removed from the active set
*/
function removeWithdrawalRoots(bytes32[] calldata _roots) external {
require(msg.sender == owner() || msg.sender == withdrawalPublisher, "Invalid sender");
for (uint256 i = 0; i < _roots.length; i++) {
deleteWithdrawalRoot(_roots[i]);
}
}
/**
* @notice Removes a withdrawal root hash from active set
* @param _root The root hash to be removed from the active set
*/
function deleteWithdrawalRoot(bytes32 _root) private {
uint256 nonce = withdrawalRootToNonce[_root];
require(nonce > 0, "Root not found");
delete withdrawalRootToNonce[_root];
emit WithdrawalRootHashRemoval(_root, nonce);
}
/**********************************************************************************************
* Fallback Management
*********************************************************************************************/
/**
* @notice Sets the root hash of the Merkle tree containing fallback
* withdrawal authorizations.
* @param _root The root hash of a Merkle tree containing the fallback withdrawal
* authorizations
* @param _maxSupplyNonce The nonce of the latest supply whose value is reflected in the
* fallback withdrawal authorizations.
*/
function setFallbackRoot(bytes32 _root, uint256 _maxSupplyNonce) external {
require(msg.sender == owner() || msg.sender == fallbackPublisher, "Invalid sender");
require(_root != 0, "Invalid root");
require(
SafeMath.add(fallbackSetDate, fallbackWithdrawalDelaySeconds) > block.timestamp,
"Fallback is active"
);
require(
_maxSupplyNonce >= fallbackMaxIncludedSupplyNonce,
"Included supply nonce decreased"
);
require(_maxSupplyNonce <= supplyNonce, "Included supply nonce exceeds latest supply");
fallbackRoot = _root;
fallbackMaxIncludedSupplyNonce = _maxSupplyNonce;
fallbackSetDate = block.timestamp;
emit FallbackRootHashSet(_root, fallbackMaxIncludedSupplyNonce, block.timestamp);
}
/**
* @notice Resets the fallback set date to the current block's timestamp. This can be used to
* delay the start of the fallback period without publishing a new root, or to deactivate the
* fallback mechanism so a new fallback root may be published.
*/
function resetFallbackMechanismDate() external {
require(msg.sender == owner() || msg.sender == fallbackPublisher, "Invalid sender");
fallbackSetDate = block.timestamp;
emit FallbackMechanismDateReset(fallbackSetDate);
}
/**
* @notice Updates the time-lock period before the fallback mechanism is activated after the
* last fallback root was published.
* @param _newFallbackDelaySeconds The new delay period in seconds
*/
function setFallbackWithdrawalDelay(uint256 _newFallbackDelaySeconds) external {
require(msg.sender == owner(), "Invalid sender");
require(_newFallbackDelaySeconds != 0, "Invalid zero delay seconds");
require(_newFallbackDelaySeconds < 10 * 365 days, "Invalid delay over 10 years");
uint256 oldDelay = fallbackWithdrawalDelaySeconds;
fallbackWithdrawalDelaySeconds = _newFallbackDelaySeconds;
emit FallbackWithdrawalDelayUpdate(oldDelay, _newFallbackDelaySeconds);
}
/**********************************************************************************************
* Role Management
*********************************************************************************************/
/**
* @notice Updates the Withdrawal Publisher address, the only address other than the owner that
* can publish / remove withdrawal Merkle tree roots.
* @param _newWithdrawalPublisher The address of the new Withdrawal Publisher
* @dev Error invalid sender.
*/
function setWithdrawalPublisher(address _newWithdrawalPublisher) external {
require(msg.sender == owner(), "Invalid sender");
address oldValue = withdrawalPublisher;
withdrawalPublisher = _newWithdrawalPublisher;
emit WithdrawalPublisherUpdate(oldValue, withdrawalPublisher);
}
/**
* @notice Updates the Fallback Publisher address, the only address other than the owner that
* can publish / remove fallback withdrawal Merkle tree roots.
* @param _newFallbackPublisher The address of the new Fallback Publisher
* @dev Error invalid sender.
*/
function setFallbackPublisher(address _newFallbackPublisher) external {
require(msg.sender == owner(), "Invalid sender");
address oldValue = fallbackPublisher;
fallbackPublisher = _newFallbackPublisher;
emit FallbackPublisherUpdate(oldValue, fallbackPublisher);
}
/**
* @notice Updates the Withdrawal Limit Publisher address, the only address other than the
* owner that can set the withdrawal limit.
* @param _newWithdrawalLimitPublisher The address of the new Withdrawal Limit Publisher
* @dev Error invalid sender.
*/
function setWithdrawalLimitPublisher(address _newWithdrawalLimitPublisher) external {
require(msg.sender == owner(), "Invalid sender");
address oldValue = withdrawalLimitPublisher;
withdrawalLimitPublisher = _newWithdrawalLimitPublisher;
emit WithdrawalLimitPublisherUpdate(oldValue, withdrawalLimitPublisher);
}
/**
* @notice Updates the DirectTransferer address, the only address other than the owner that
* can execute direct transfers
* @param _newDirectTransferer The address of the new DirectTransferer
*/
function setDirectTransferer(address _newDirectTransferer) external {
require(msg.sender == owner(), "Invalid sender");
address oldValue = directTransferer;
directTransferer = _newDirectTransferer;
emit DirectTransfererUpdate(oldValue, directTransferer);
}
/**
* @notice Updates the Partition Manager address, the only address other than the owner that
* can add and remove permitted partitions
* @param _newPartitionManager The address of the new PartitionManager
*/
function setPartitionManager(address _newPartitionManager) external {
require(msg.sender == owner(), "Invalid sender");
address oldValue = partitionManager;
partitionManager = _newPartitionManager;
emit PartitionManagerUpdate(oldValue, partitionManager);
}
/**********************************************************************************************
* Operator Data Decoders
*********************************************************************************************/
/**
* @notice Extract flag from operatorData
* @param _operatorData The operator data to be decoded
* @return flag, the transfer operation type
*/
function _decodeOperatorDataFlag(bytes memory _operatorData) internal pure returns (bytes32) {
return abi.decode(_operatorData, (bytes32));
}
/**
* @notice Extracts the supplier, max authorized nonce, and Merkle proof from the operator data
* @param _operatorData The operator data to be decoded
* @return supplier, the address whose account is authorized
* @return For withdrawals: max authorized nonce, the last used withdrawal root nonce for the
* supplier and partition. For fallback withdrawals: max cumulative withdrawal amount, the
* maximum amount of tokens that can be withdrawn for the supplier's account, including both
* withdrawals and fallback withdrawals
* @return proof, the Merkle proof to be used for the authorization
*/
function _decodeWithdrawalOperatorData(bytes memory _operatorData)
internal
pure
returns (
address,
uint256,
bytes32[] memory
)
{
(, address supplier, uint256 nonce, bytes32[] memory proof) = abi.decode(
_operatorData,
(bytes32, address, uint256, bytes32[])
);
return (supplier, nonce, proof);
}
/**
* @notice Extracts the supply nonce from the operator data
* @param _operatorData The operator data to be decoded
* @return nonce, the nonce of the supply to be refunded
*/
function _decodeRefundOperatorData(bytes memory _operatorData) internal pure returns (uint256) {
(, uint256 nonce) = abi.decode(_operatorData, (bytes32, uint256));
return nonce;
}
/**********************************************************************************************
* Merkle Tree Verification
*********************************************************************************************/
/**
* @notice Hashes the supplied data and returns the hash to be used in conjunction with a proof
* to calculate the Merkle tree root
* @param _supplier The address whose account is authorized
* @param _partition Source partition of the tokens
* @param _value Number of tokens to be transferred
* @param _maxAuthorizedAccountNonce The maximum existing used withdrawal nonce for the
* supplier and partition
* @return leaf, the hash of the supplied data
*/
function _calculateWithdrawalLeaf(
address _supplier,
bytes32 _partition,
uint256 _value,
uint256 _maxAuthorizedAccountNonce
) internal pure returns (bytes32) {
return
keccak256(abi.encodePacked(_supplier, _partition, _value, _maxAuthorizedAccountNonce));
}
/**
* @notice Hashes the supplied data and returns the hash to be used in conjunction with a proof
* to calculate the Merkle tree root
* @param _supplier The address whose account is authorized
* @param _partition Source partition of the tokens
* @param _maxCumulativeWithdrawalAmount, the maximum amount of tokens that can be withdrawn
* for the supplier's account, including both withdrawals and fallback withdrawals
* @return leaf, the hash of the supplied data
*/
function _calculateFallbackLeaf(
address _supplier,
bytes32 _partition,
uint256 _maxCumulativeWithdrawalAmount
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_supplier, _partition, _maxCumulativeWithdrawalAmount));
}
/**
* @notice Calculates the Merkle root for the unique Merkle tree described by the provided
Merkle proof and leaf hash.
* @param _merkleProof The sibling node hashes at each level of the tree.
* @param _leafHash The hash of the leaf data for which merkleProof is an inclusion proof.
* @return The calculated Merkle root.
*/
function _calculateMerkleRoot(bytes32[] memory _merkleProof, bytes32 _leafHash)
private
pure
returns (bytes32)
{
bytes32 computedHash = _leafHash;
for (uint256 i = 0; i < _merkleProof.length; i++) {
bytes32 proofElement = _merkleProof[i];
if (computedHash < proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
} | Resets the fallback set date to the current block's timestamp. This can be used to delay the start of the fallback period without publishing a new root, or to deactivate the fallback mechanism so a new fallback root may be published./ | function resetFallbackMechanismDate() external {
require(msg.sender == owner() || msg.sender == fallbackPublisher, "Invalid sender");
fallbackSetDate = block.timestamp;
emit FallbackMechanismDateReset(fallbackSetDate);
}
| 6,532,346 |
pragma solidity 0.6.12;
//
/**
* @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;
}
}
//
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* 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 {
/**
* @dev Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/**
* @dev 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), uint256 (x) + uint256 (y) >> 1));
}
/**
* 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, 0x10000000000000000));
}
/**
* 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) << 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 >>= 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 >>= xe;
else x <<= -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 <<= re;
else if (re < 0) result >>= -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, uint256 r) private pure returns (uint128) {
if (x == 0) return 0;
else {
require (r > 0);
while (true) {
uint256 rr = x / r;
if (r == rr || r + 1 == rr) return uint128 (r);
else if (r == rr + 1) return uint128 (rr);
r = r + rr + 1 >> 1;
}
}
}
}
//
interface INest_3_OfferPrice {
function transfer(address to, uint value) external returns (bool);
/**
* @dev Update and check the latest price
* @param tokenAddress Token address
* @return ethAmount ETH amount
* @return erc20Amount Erc20 amount
* @return blockNum Price block
*/
function updateAndCheckPriceNow(address tokenAddress) external payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum);
/**
* @dev Update and check the effective price list
* @param tokenAddress Token address
* @param num Number of prices to check
* @return uint256[] price list
*/
function updateAndCheckPriceList(address tokenAddress, uint256 num) external payable returns (uint256[] memory);
// Activate the price checking function
function activation() external;
// Check the minimum ETH cost of obtaining the price
function checkPriceCostLeast(address tokenAddress) external view returns(uint256);
// Check the maximum ETH cost of obtaining the price
function checkPriceCostMost(address tokenAddress) external view returns(uint256);
// Check the cost of a single price data
function checkPriceCostSingle(address tokenAddress) external view returns(uint256);
// Check whether the price-checking functions can be called
function checkUseNestPrice(address target) external view returns (bool);
// Check whether the address is in the blocklist
function checkBlocklist(address add) external view returns(bool);
// Check the amount of NEST to destroy to call prices
function checkDestructionAmount() external view returns(uint256);
// Check the waiting time to start calling prices
function checkEffectTime() external view returns (uint256);
}
//
interface ICoFiXKTable {
function setK0(uint256 tIdx, uint256 sigmaIdx, int128 k0) external;
function setK0InBatch(uint256[] memory tIdxs, uint256[] memory sigmaIdxs, int128[] memory k0s) external;
function getK0(uint256 tIdx, uint256 sigmaIdx) external view returns (int128);
}
//
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
//
interface ICoFiXController {
event NewK(address token, int128 K, int128 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 tIdx, uint256 sigmaIdx, int128 K0);
event NewGovernance(address _new);
event NewOracle(address _priceOracle);
event NewKTable(address _kTable);
event NewTimespan(uint256 _timeSpan);
event NewKRefreshInterval(uint256 _interval);
event NewKLimit(int128 maxK0);
event NewGamma(int128 _gamma);
event NewTheta(address token, uint32 theta);
function addCaller(address caller) external;
function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta);
}
//
interface INest_3_VoteFactory {
// 查询地址
function checkAddress(string calldata name) external view returns (address contractAddress);
// _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
}
//
interface ICoFiXERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
// function name() external pure returns (string memory);
// function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
//
interface ICoFiXPair is ICoFiXERC20 {
struct OraclePrice {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 theta;
}
// All pairs: {ETH <-> ERC20 Token}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function mint(address to) external payable returns (uint liquidity, uint oracleFeeChange);
function burn(address outToken, address to) external payable returns (uint amountOut, uint oracleFeeChange);
function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function skim(address to) external;
function sync() external;
function initialize(address, address, string memory, string memory) external;
/// @dev get Net Asset Value Per Share
/// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token}
/// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token}
/// @return navps The Net Asset Value Per Share (liquidity) represents
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps);
}
//
// Controller contract to call NEST Oracle for prices, managed by governance
// Governance role of this contract should be the `Timelock` contract, which is further managed by a multisig contract
contract CoFiXController is ICoFiXController {
using SafeMath for uint256;
enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX
uint256 constant public AONE = 1 ether;
uint256 constant public K_BASE = 1E8;
uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy
uint256 constant internal TIMESTAMP_MODULUS = 2**32;
int128 constant internal SIGMA_STEP = 0x346DC5D638865; // (0.00005*2**64).toString(16), 0.00005 as 64.64-bit fixed point
int128 constant internal ZERO_POINT_FIVE = 0x8000000000000000; // (0.5*2**64).toString(16)
uint256 constant internal K_EXPECTED_VALUE = 0.0025*1E8;
// impact cost params
uint256 constant internal C_BUYIN_ALPHA = 25700000000000; // α=2.570e-05*1e18
uint256 constant internal C_BUYIN_BETA = 854200000000; // β=8.542e-07*1e18
uint256 constant internal C_SELLOUT_ALPHA = 117100000000000; // α=-1.171e-04*1e18
uint256 constant internal C_SELLOUT_BETA = 838600000000; // β=8.386e-07*1e18
mapping(address => uint32[3]) internal KInfoMap; // gas saving, index [0] is k vlaue, index [1] is updatedAt, index [2] is theta
mapping(address => bool) public callerAllowed;
INest_3_VoteFactory public immutable voteFactory;
// managed by governance
address public governance;
address public immutable nestToken;
address public immutable factory;
address public kTable;
uint256 public timespan = 14;
uint256 public kRefreshInterval = 5 minutes;
uint256 public DESTRUCTION_AMOUNT = 0 ether; // from nest oracle
int128 public MAX_K0 = 0xCCCCCCCCCCCCD00; // (0.05*2**64).toString(16)
int128 public GAMMA = 0x8000000000000000; // (0.5*2**64).toString(16)
modifier onlyGovernance() {
require(msg.sender == governance, "CoFiXCtrl: !governance");
_;
}
constructor(address _voteFactory, address _nest, address _factory, address _kTable) public {
governance = msg.sender;
voteFactory = INest_3_VoteFactory(address(_voteFactory));
nestToken = _nest;
factory = _factory;
kTable = _kTable;
}
receive() external payable {}
/* setters for protocol governance */
function setGovernance(address _new) external onlyGovernance {
governance = _new;
emit NewGovernance(_new);
}
function setKTable(address _kTable) external onlyGovernance {
kTable = _kTable;
emit NewKTable(_kTable);
}
function setTimespan(uint256 _timeSpan) external onlyGovernance {
timespan = _timeSpan;
emit NewTimespan(_timeSpan);
}
function setKRefreshInterval(uint256 _interval) external onlyGovernance {
kRefreshInterval = _interval;
emit NewKRefreshInterval(_interval);
}
function setOracleDestructionAmount(uint256 _amount) external onlyGovernance {
DESTRUCTION_AMOUNT = _amount;
}
function setKLimit(int128 maxK0) external onlyGovernance {
MAX_K0 = maxK0;
emit NewKLimit(maxK0);
}
function setGamma(int128 _gamma) external onlyGovernance {
GAMMA = _gamma;
emit NewGamma(_gamma);
}
function setTheta(address token, uint32 theta) external onlyGovernance {
KInfoMap[token][2] = theta;
emit NewTheta(token, theta);
}
// Activate on NEST Oracle, should not be called twice for the same nest oracle
function activate() external onlyGovernance {
// address token, address from, address to, uint value
TransferHelper.safeTransferFrom(nestToken, msg.sender, address(this), DESTRUCTION_AMOUNT);
address oracle = voteFactory.checkAddress("nest.v3.offerPrice");
// address token, address to, uint value
TransferHelper.safeApprove(nestToken, oracle, DESTRUCTION_AMOUNT);
INest_3_OfferPrice(oracle).activation(); // nest.transferFrom will be called
TransferHelper.safeApprove(nestToken, oracle, 0); // ensure safety
}
function addCaller(address caller) external override {
require(msg.sender == factory || msg.sender == governance, "CoFiXCtrl: only factory or gov");
callerAllowed[caller] = true;
}
// Calc variance of price and K in CoFiX is very expensive
// We use expected value of K based on statistical calculations here to save gas
// In the near future, NEST could provide the variance of price directly. We will adopt it then.
// We can make use of `data` bytes in the future
function queryOracle(address token, uint8 op, bytes memory data) external override payable returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum, uint256 _theta) {
require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed");
(_ethAmount, _erc20Amount, _blockNum) = getLatestPrice(token);
CoFiX_OP cop = CoFiX_OP(op);
uint256 impactCost;
if (cop == CoFiX_OP.SWAP_WITH_EXACT) {
impactCost = calcImpactCostFor_SWAP_WITH_EXACT(token, data, _ethAmount, _erc20Amount);
} else if (cop == CoFiX_OP.SWAP_FOR_EXACT) {
impactCost = calcImpactCostFor_SWAP_FOR_EXACT(token, data, _ethAmount, _erc20Amount);
} else if (cop == CoFiX_OP.BURN) {
impactCost = calcImpactCostFor_BURN(token, data, _ethAmount, _erc20Amount);
}
return (K_EXPECTED_VALUE.add(impactCost), _ethAmount, _erc20Amount, _blockNum, KInfoMap[token][2]);
}
function calcImpactCostFor_BURN(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) {
// bytes memory data = abi.encode(msg.sender, outToken, to, liquidity);
(, address outToken, , uint256 liquidity) = abi.decode(data, (address, address, address, uint256));
// calc real vol by liquidity * np
uint256 navps = ICoFiXPair(msg.sender).getNAVPerShare(ethAmount, erc20Amount); // pair call controller, msg.sender is pair
uint256 vol = liquidity.mul(navps).div(NAVPS_BASE);
if (outToken != token) {
// buy in ETH, outToken is ETH
return impactCostForBuyInETH(vol);
}
// sell out liquidity, outToken is token, take this as sell out ETH and get token
return impactCostForSellOutETH(vol);
}
function calcImpactCostFor_SWAP_WITH_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, , uint256 amountIn) = abi.decode(data, (address, address, address, uint256));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountIn is token
// convert to amountIn in ETH
uint256 vol = uint256(amountIn).mul(ethAmount).div(erc20Amount);
return impactCostForBuyInETH(vol);
}
// sell out ETH, amountIn is ETH
return impactCostForSellOutETH(amountIn);
}
function calcImpactCostFor_SWAP_FOR_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, uint256 amountOutExact,) = abi.decode(data, (address, address, uint256, address));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountOutExact is ETH
return impactCostForBuyInETH(amountOutExact);
}
// sell out ETH, amountIn is ETH, amountOutExact is token
// convert to amountOutExact in ETH
uint256 vol = uint256(amountOutExact).mul(ethAmount).div(erc20Amount);
return impactCostForSellOutETH(vol);
}
// impact cost
// - C = 0, if VOL < 500
// - C = α + β * VOL, if VOL >= 500
// α=2.570e-05,β=8.542e-07
function impactCostForBuyInETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).mul(1e8).div(1e18);
return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).div(1e10); // combine mul div
}
// α=-1.171e-04,β=8.386e-07
function impactCostForSellOutETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).mul(1e8).div(1e18);
return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).div(1e10); // combine mul div
}
// // We can make use of `data` bytes in the future
// function queryOracle(address token, bytes memory /*data*/) external override payable returns (uint256 _k, uint256, uint256, uint256, uint256) {
// require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed");
// uint256 _now = block.timestamp % TIMESTAMP_MODULUS; // 2106
// {
// uint256 _lastUpdate = KInfoMap[token][1];
// if (_now >= _lastUpdate && _now.sub(_lastUpdate) <= kRefreshInterval) { // lastUpdate (2105) | 2106 | now (1)
// return getLatestPrice(token);
// }
// }
// uint256 _balanceBefore = address(this).balance;
// // int128 K0; // K0AndK[0]
// // int128 K; // K0AndK[1]
// int128[2] memory K0AndK;
// // OraclePrice memory _op;
// uint256[7] memory _op;
// int128 _variance;
// // (_variance, _op.T, _op.ethAmount, _op.erc20Amount, _op.blockNum) = calcVariance(token);
// (_variance, _op[0], _op[1], _op[2], _op[3]) = calcVariance(token);
// {
// // int128 _volatility = ABDKMath64x64.sqrt(_variance);
// // int128 _sigma = ABDKMath64x64.div(_volatility, ABDKMath64x64.sqrt(ABDKMath64x64.fromUInt(timespan)));
// int128 _sigma = ABDKMath64x64.sqrt(ABDKMath64x64.div(_variance, ABDKMath64x64.fromUInt(timespan))); // combined into one sqrt
// // tIdx is _op[4]
// // sigmaIdx is _op[5]
// _op[4] = (_op[0].add(5)).div(10); // rounding to the nearest
// _op[5] = ABDKMath64x64.toUInt(
// ABDKMath64x64.add(
// ABDKMath64x64.div(_sigma, SIGMA_STEP), // _sigma / 0.0001, e.g. (0.00098/0.0001)=9.799 => 9
// ZERO_POINT_FIVE // e.g. (0.00098/0.0001)+0.5=10.299 => 10
// )
// );
// if (_op[5] > 0) {
// _op[5] = _op[5].sub(1);
// }
// // getK0(uint256 tIdx, uint256 sigmaIdx)
// // K0 is K0AndK[0]
// K0AndK[0] = ICoFiXKTable(kTable).getK0(
// _op[4],
// _op[5]
// );
// // K = gamma * K0
// K0AndK[1] = ABDKMath64x64.mul(GAMMA, K0AndK[0]);
// emit NewK(token, K0AndK[1], _sigma, _op[0], _op[1], _op[2], _op[3], _op[4], _op[5], K0AndK[0]);
// }
// require(K0AndK[0] <= MAX_K0, "CoFiXCtrl: K0");
// {
// // we could decode data in the future to pay the fee change and mining award token directly to reduce call cost
// // TransferHelper.safeTransferETH(payback, msg.value.sub(_balanceBefore.sub(address(this).balance)));
// uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance));
// if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
// _k = ABDKMath64x64.toUInt(ABDKMath64x64.mul(K0AndK[1], ABDKMath64x64.fromUInt(K_BASE)));
// _op[6] = KInfoMap[token][2]; // theta
// KInfoMap[token][0] = uint32(_k); // k < MAX_K << uint32(-1)
// KInfoMap[token][1] = uint32(_now); // 2106
// return (_k, _op[1], _op[2], _op[3], _op[6]);
// }
// }
// function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) {
// k = KInfoMap[token][0];
// updatedAt = KInfoMap[token][1];
// theta = KInfoMap[token][2];
// }
function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) {
k = uint32(K_EXPECTED_VALUE);
updatedAt = uint32(block.timestamp);
theta = KInfoMap[token][2];
}
function getLatestPrice(address token) internal returns (uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum) {
uint256 _balanceBefore = address(this).balance;
address oracle = voteFactory.checkAddress("nest.v3.offerPrice");
uint256[] memory _rawPriceList = INest_3_OfferPrice(oracle).updateAndCheckPriceList{value: msg.value}(token, 1);
require(_rawPriceList.length == 3, "CoFiXCtrl: bad price len");
// validate T
uint256 _T = block.number.sub(_rawPriceList[2]).mul(timespan);
require(_T < 900, "CoFiXCtrl: oralce price outdated");
uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance));
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
return (_rawPriceList[0], _rawPriceList[1], _rawPriceList[2]);
// return (K_EXPECTED_VALUE, _rawPriceList[0], _rawPriceList[1], _rawPriceList[2], KInfoMap[token][2]);
}
// calc Variance, a.k.a. sigma squared
function calcVariance(address token) internal returns (
int128 _variance,
uint256 _T,
uint256 _ethAmount,
uint256 _erc20Amount,
uint256 _blockNum
) // keep these variables to make return values more clear
{
address oracle = voteFactory.checkAddress("nest.v3.offerPrice");
// query raw price list from nest oracle (newest to oldest)
uint256[] memory _rawPriceList = INest_3_OfferPrice(oracle).updateAndCheckPriceList{value: msg.value}(token, 50);
require(_rawPriceList.length == 150, "CoFiXCtrl: bad price len");
// calc P a.k.a. price from the raw price data (ethAmount, erc20Amount, blockNum)
uint256[] memory _prices = new uint256[](50);
for (uint256 i = 0; i < 50; i++) {
// 0..50 (newest to oldest), so _prices[0] is p49 (latest price), _prices[49] is p0 (base price)
_prices[i] = calcPrice(_rawPriceList[i*3], _rawPriceList[i*3+1]);
}
// calc x a.k.a. standardized sequence of differences (newest to oldest)
int128[] memory _stdSeq = new int128[](49);
for (uint256 i = 0; i < 49; i++) {
_stdSeq[i] = calcStdSeq(_prices[i], _prices[i+1], _prices[49], _rawPriceList[i*3+2], _rawPriceList[(i+1)*3+2]);
}
// Option 1: calc variance of x
// Option 2: calc mean value first and then calc variance
// Use option 1 for gas saving
int128 _sumSq; // sum of squares of x
int128 _sum; // sum of x
for (uint256 i = 0; i < 49; i++) {
_sumSq = ABDKMath64x64.add(ABDKMath64x64.pow(_stdSeq[i], 2), _sumSq);
_sum = ABDKMath64x64.add(_stdSeq[i], _sum);
}
_variance = ABDKMath64x64.sub(
ABDKMath64x64.div(
_sumSq,
ABDKMath64x64.fromUInt(49)
),
ABDKMath64x64.div(
ABDKMath64x64.pow(_sum, 2),
ABDKMath64x64.fromUInt(49*49)
)
);
_T = block.number.sub(_rawPriceList[2]).mul(timespan);
return (_variance, _T, _rawPriceList[0], _rawPriceList[1], _rawPriceList[2]);
}
function calcPrice(uint256 _ethAmount, uint256 _erc20Amount) internal pure returns (uint256) {
return AONE.mul(_erc20Amount).div(_ethAmount);
}
// diff ratio could be negative
// p2: P_{i}
// p1: P_{i-1}
// p0: P_{0}
function calcDiffRatio(uint256 p2, uint256 p1, uint256 p0) internal pure returns (int128) {
int128 _p2 = ABDKMath64x64.fromUInt(p2);
int128 _p1 = ABDKMath64x64.fromUInt(p1);
int128 _p0 = ABDKMath64x64.fromUInt(p0);
return ABDKMath64x64.div(ABDKMath64x64.sub(_p2, _p1), _p0);
}
// p2: P_{i}
// p1: P_{i-1}
// p0: P_{0}
// bn2: blocknum_{i}
// bn1: blocknum_{i-1}
function calcStdSeq(uint256 p2, uint256 p1, uint256 p0, uint256 bn2, uint256 bn1) internal pure returns (int128) {
return ABDKMath64x64.div(
calcDiffRatio(p2, p1, p0),
ABDKMath64x64.sqrt(
ABDKMath64x64.fromUInt(bn2.sub(bn1)) // c must be larger than d
)
);
}
} | α=2.570e-05,β=8.542e-07 | function impactCostForBuyInETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
| 14,965,909 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Contracts
import { RolesMods } from "../contexts2/access-control/roles/RolesMods.sol";
import { PausableMods } from "../settings/pausable/PausableMods.sol";
import {
ReentryMods
} from "../contexts2/access-control/reentry/ReentryMods.sol";
import { AUTHORIZED } from "../shared/roles.sol";
import { LoanDataFacet } from "./LoanDataFacet.sol";
// Libraries
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {
EnumerableSet
} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { LibLoans } from "./libraries/LibLoans.sol";
import { LibCollateral } from "./libraries/LibCollateral.sol";
import { LibDapps } from "../escrow/dapps/libraries/LibDapps.sol";
import { LibEscrow } from "../escrow/libraries/LibEscrow.sol";
import {
PlatformSettingsLib
} from "../settings/platform/libraries/PlatformSettingsLib.sol";
import { NumbersLib } from "../shared/libraries/NumbersLib.sol";
import { PriceAggLib } from "../price-aggregator/PriceAggLib.sol";
import { NFTLib } from "../nft/libraries/NFTLib.sol";
// Interfaces
import { ITToken } from "../lending/ttoken/ITToken.sol";
import { ILoansEscrow } from "../escrow/escrow/ILoansEscrow.sol";
// Storage
import {
MarketStorageLib,
MarketStorage,
Loan,
LoanStatus
} from "../storage/market.sol";
contract RepayFacet is RolesMods, ReentryMods, PausableMods {
/**
@notice This event is emitted when a loan has been successfully repaid
@param loanID ID of loan from which collateral was withdrawn
@param borrower Account address of the borrower
@param amountPaid Amount of the loan paid back
@param payer Account address of the payer
@param totalOwed Total amount of the loan to be repaid
*/
event LoanRepaid(
uint256 indexed loanID,
address indexed borrower,
uint256 amountPaid,
address payer,
uint256 totalOwed
);
/**
* @notice This event is emitted when a loan has been successfully cd
* @param loanID ID of loan from which collateral was withdrawn
* @param borrower Account address of the borrower
* @param liquidator Account address of the liquidator
* @param reward Value in lending token paid out to liquidator
* @param tokensIn Percentage of the collateral price paid by the liquidator to the lending pool
*/
event LoanLiquidated(
uint256 indexed loanID,
address indexed borrower,
address liquidator,
uint256 reward,
uint256 tokensIn
);
/**
* @notice Repay this Escrow's loan.
* @dev If the Escrow's balance of the borrowed token is less than the amount to repay, transfer tokens from the sender's wallet.
* @dev Only the owner of the Escrow can call this. If someone else wants to make a payment, they should call the loan manager directly.
* @param loanID The id of the loan being used.
* @param amount The amount being repaid.
*/
function escrowRepay(uint256 loanID, uint256 amount)
external
paused("", false)
authorized(AUTHORIZED, msg.sender)
nonReentry("")
{
uint256 balance =
LibEscrow.balanceOf(loanID, LibLoans.loan(loanID).lendingToken);
uint256 totalOwed = LibLoans.getTotalOwed(loanID);
if (balance < totalOwed && amount > balance) {
uint256 amountNeeded =
amount > totalOwed ? totalOwed - (balance) : amount - (balance);
SafeERC20.safeTransferFrom(
IERC20(LibLoans.loan(loanID).lendingToken),
msg.sender,
address(LibEscrow.e(loanID)),
amountNeeded
);
}
__repayLoan(loanID, amount, address(LibEscrow.e(loanID)), false);
}
/**
* @notice Make a payment to a loan
* @param loanID The ID of the loan the payment is for
* @param amount The amount of tokens to pay back to the loan
*/
function repayLoan(uint256 loanID, uint256 amount)
external
nonReentry("")
paused("", false)
authorized(AUTHORIZED, msg.sender)
{
__repayLoan(loanID, amount, msg.sender, false);
}
function __repayLoan(
uint256 loanID,
uint256 amount,
address sender,
bool isLiquidation
) private returns (uint256 leftToPay_) {
require(amount > 0, "Teller: zero repay");
// calculate the actual amount to repay
leftToPay_ =
LibLoans.debt(loanID).principalOwed +
LibLoans.debt(loanID).interestOwed;
if (leftToPay_ < amount) {
amount = leftToPay_;
leftToPay_ = 0;
} else {
leftToPay_ -= amount;
}
// Get the Teller token for the loan
ITToken tToken =
MarketStorageLib.store().tTokens[
LibLoans.loan(loanID).lendingToken
];
// Transfer funds from account
if (address(LibEscrow.e(loanID)) == sender) {
LibEscrow.e(loanID).claimToken(
LibLoans.loan(loanID).lendingToken,
address(tToken),
amount
);
} else {
SafeERC20.safeTransferFrom(
IERC20(LibLoans.loan(loanID).lendingToken),
sender,
address(tToken),
amount
);
}
// Deduct the interest and principal owed
uint256 principalPaid;
uint256 interestPaid;
if (amount < LibLoans.debt(loanID).interestOwed) {
interestPaid = amount;
LibLoans.debt(loanID).interestOwed -= amount;
} else {
if (LibLoans.debt(loanID).interestOwed > 0) {
interestPaid = LibLoans.debt(loanID).interestOwed;
amount -= interestPaid;
LibLoans.debt(loanID).interestOwed = 0;
}
if (amount > 0) {
principalPaid = amount;
LibLoans.debt(loanID).principalOwed -= amount;
}
}
// Tell the Teller Token value has been deposited back into the pool.
tToken.repayLoan(principalPaid, interestPaid);
if (isLiquidation) {
// Make sure there is nothing left to repay on the loan
require(leftToPay_ == 0, "Teller: liquidate partial repay");
// Set loan status
LibLoans.loan(loanID).status = LoanStatus.Liquidated;
// Transfer NFT if linked
NFTLib.liquidateNFT(loanID);
} else {
// if the loan is now fully paid, close it and withdraw borrower collateral
if (leftToPay_ == 0) {
LibLoans.loan(loanID).status = LoanStatus.Closed;
LibCollateral.withdrawAll(
loanID,
LibLoans.loan(loanID).borrower
);
// Restake any NFTs linked to loan for borrower
NFTLib.restakeLinked(loanID, LibLoans.loan(loanID).borrower);
}
emit LoanRepaid(
loanID,
LibLoans.loan(loanID).borrower,
amount,
msg.sender,
leftToPay_
);
}
}
/**
* @notice Liquidate a loan if it is expired or under collateralized
* @param loanID The ID of the loan to be liquidated
*/
function liquidateLoan(uint256 loanID)
external
nonReentry("")
paused("", false)
authorized(AUTHORIZED, msg.sender)
{
Loan storage loan = LibLoans.loan(loanID);
uint256 collateralAmount = LibCollateral.e(loanID).loanSupply(loanID);
require(
RepayLib.isLiquidable(loanID, collateralAmount),
"Teller: does not need liquidation"
);
// Calculate the reward before repaying the loan
(uint256 rewardInLending, uint256 collateralInLending) =
RepayLib.getLiquidationReward(loanID, collateralAmount);
// The liquidator pays the amount still owed on the loan
uint256 amountToLiquidate =
LibLoans.debt(loanID).principalOwed +
LibLoans.debt(loanID).interestOwed;
__repayLoan(loanID, amountToLiquidate, msg.sender, true);
// Payout the liquidator reward owed
if (rewardInLending > 0) {
RepayLib.payOutLiquidator(
loanID,
rewardInLending,
collateralInLending,
collateralAmount,
payable(msg.sender)
);
}
emit LoanLiquidated(
loanID,
loan.borrower,
msg.sender,
rewardInLending,
amountToLiquidate
);
}
/**
* @notice It gets the current liquidation reward for a given loan.
* @param loanID The loan ID to get the info.
* @return inLending_ The value the liquidator will receive denoted in lending tokens.
* @return inCollateral_ The value the liquidator will receive denoted in collateral tokens.
*/
function getLiquidationReward(uint256 loanID)
external
view
returns (uint256 inLending_, uint256 inCollateral_)
{
(inLending_, ) = RepayLib.getLiquidationReward(
loanID,
LibCollateral.e(loanID).loanSupply(loanID)
);
inCollateral_ = PriceAggLib.valueFor(
LibLoans.loan(loanID).lendingToken,
LibLoans.loan(loanID).collateralToken,
inLending_
);
}
}
library RepayLib {
/**
* @notice It checks if a loan can be liquidated.
* @param loanID The loan ID to check.
* @return true if the loan is liquidable.
*/
function isLiquidable(uint256 loanID, uint256 collateralAmount)
internal
view
returns (bool)
{
Loan storage loan = LibLoans.loan(loanID);
// Check if loan can be liquidated
if (loan.status != LoanStatus.Active) {
return false;
}
if (loan.collateralRatio > 0) {
// If loan has a collateral ratio, check how much is needed
(, uint256 neededInCollateral, ) =
LoanDataFacet(address(this)).getCollateralNeededInfo(loanID);
if (neededInCollateral > collateralAmount) {
return true;
}
}
// Otherwise, check if the loan has expired
return block.timestamp >= loan.loanStartTime + loan.duration;
}
/**
* @notice It gets the current liquidation reward for a given loan.
* @param loanID The loan ID to get the info.
* @param collateralAmount The amount of collateral for the {loanID}. Passed in to save gas calling the collateral escrow multiple times.
* @return reward_ The value the liquidator will receive denoted in lending tokens.
*/
function getLiquidationReward(uint256 loanID, uint256 collateralAmount)
internal
view
returns (uint256 reward_, uint256 collateralValue_)
{
uint256 amountToLiquidate =
LibLoans.debt(loanID).principalOwed +
LibLoans.debt(loanID).interestOwed;
// Max reward is amount repaid on loan plus extra percentage
uint256 maxReward =
amountToLiquidate +
NumbersLib.percent(
amountToLiquidate,
uint16(PlatformSettingsLib.getLiquidateRewardPercent())
);
// Calculate available collateral for reward
if (collateralAmount > 0) {
collateralValue_ = PriceAggLib.valueFor(
LibLoans.loan(loanID).collateralToken,
LibLoans.loan(loanID).lendingToken,
collateralAmount
);
reward_ += collateralValue_;
}
// Calculate loan escrow value if collateral not enough to cover reward
if (reward_ < maxReward) {
reward_ += LibEscrow.calculateTotalValue(loanID);
}
// Cap the reward to max
if (reward_ > maxReward) {
reward_ = maxReward;
}
}
/**
* @notice Checks if the loan has an Escrow and claims any tokens then pays out the loan collateral.
* @dev See Escrow.claimTokens for more info.
* @param loanID The loan ID which is being liquidated
* @param rewardInLending The total amount of reward based in the lending token to pay the liquidator
* @param collateralInLending The amount of collateral that is available for the loan denoted in lending tokens
* @param collateralAmount The amount of collateral that is available for the loan
* @param liquidator The address of the liquidator where the liquidation reward will be sent to
*/
function payOutLiquidator(
uint256 loanID,
uint256 rewardInLending,
uint256 collateralInLending,
uint256 collateralAmount,
address payable liquidator
) internal {
require(
LibLoans.loan(loanID).status == LoanStatus.Liquidated,
"Teller: loan not liquidated"
);
if (rewardInLending <= collateralInLending) {
uint256 rewardInCollateral =
PriceAggLib.valueFor(
LibLoans.loan(loanID).lendingToken,
LibLoans.loan(loanID).collateralToken,
rewardInLending
);
LibCollateral.withdraw(loanID, rewardInCollateral, liquidator);
} else {
// Payout whats available in the collateral token
LibCollateral.withdraw(loanID, collateralAmount, liquidator);
// Claim remaining reward value from the loan escrow
claimEscrowTokensByValue(
loanID,
liquidator,
rewardInLending - collateralInLending
);
}
}
/**
* @dev Send the equivalent of tokens owned by the loan escrow (in lending value) to the recipient,
* @param loanID The loan ID to clam tokens from
* @param recipient address to send the tokens to
* @param value The value of escrow held tokens to be claimed based in lending value
*/
function claimEscrowTokensByValue(
uint256 loanID,
address recipient,
uint256 value
) private {
EnumerableSet.AddressSet storage tokens =
MarketStorageLib.store().escrowTokens[loanID];
uint256 valueLeftToTransfer = value;
// Start with the lending token
valueLeftToTransfer = claimEscrowToken(
loanID,
LibLoans.loan(loanID).lendingToken,
recipient,
valueLeftToTransfer
);
// Cycle through remaining tokens
for (uint256 i = 0; i < EnumerableSet.length(tokens); i++) {
if (valueLeftToTransfer == 0) {
return;
}
valueLeftToTransfer = claimEscrowToken(
loanID,
EnumerableSet.at(tokens, i),
recipient,
valueLeftToTransfer
);
}
}
function claimEscrowToken(
uint256 loanID,
address token,
address recipient,
uint256 valueLeftToTransfer
) private returns (uint256) {
uint256 balance = LibEscrow.balanceOf(loanID, token);
// get value of token balance in lending value
if (balance > 0) {
// If token not the lending token, get value of token
uint256 balanceInLending;
if (token == LibLoans.loan(loanID).lendingToken) {
balanceInLending = balance;
} else {
balanceInLending = PriceAggLib.valueFor(
token,
LibLoans.loan(loanID).lendingToken,
balance
);
}
if (balanceInLending <= valueLeftToTransfer) {
LibEscrow.e(loanID).claimToken(token, recipient, balance);
valueLeftToTransfer -= balanceInLending;
} else {
// Token balance is more than enough so calculate ratio of balance to transfer
uint256 valueToTransfer;
if (token == LibLoans.loan(loanID).lendingToken) {
valueToTransfer = valueLeftToTransfer;
} else {
valueToTransfer = NumbersLib.percent(
balance,
NumbersLib.ratioOf(
valueLeftToTransfer,
balanceInLending
)
);
}
LibEscrow.e(loanID).claimToken(
token,
recipient,
valueToTransfer
);
valueLeftToTransfer = 0;
}
}
return valueLeftToTransfer;
}
}
| It gets the current liquidation reward for a given loan. loanID The loan ID to get the info. return inLending_ The value the liquidator will receive denoted in lending tokens. return inCollateral_ The value the liquidator will receive denoted in collateral tokens./ | function getLiquidationReward(uint256 loanID)
external
view
returns (uint256 inLending_, uint256 inCollateral_)
{
(inLending_, ) = RepayLib.getLiquidationReward(
loanID,
LibCollateral.e(loanID).loanSupply(loanID)
);
inCollateral_ = PriceAggLib.valueFor(
LibLoans.loan(loanID).lendingToken,
LibLoans.loan(loanID).collateralToken,
inLending_
);
}
| 6,395,457 |
./full_match/420/0x3de80F2f5610d2cA96534cf560357fD2db5bBb3B/sources/contracts/thirdweb-wallet/WalletEntrypoint.sol | Calls an account with transaction data. solhint-disable-next-line avoid-low-level-calls Next 5 lines from https:ethereum.stackexchange.com/a/83577 | function execute(TransactionRequest calldata req, bytes memory signature)
public
payable
onlyValidTimeWindow(req.validityStartTimestamp, req.validityEndTimestamp)
returns (bool, bytes memory)
{
require(req.value == msg.value, "WalletEntrypoint: incorrect value sent.");
bytes32 messageHash = keccak256(
abi.encode(
TRANSACTION_TYPEHASH,
req.signer,
req.credentials,
req.value,
req.gas,
req.data,
req.validityStartTimestamp,
req.validityEndTimestamp
)
);
_validateSignature(messageHash, signature, req.signer);
(bool success, bytes memory result) = accountOf[keccak256(abi.encode(req.signer, req.credentials))].call{
gas: req.gas,
value: req.value
}(req.data);
if (!success) {
if (result.length < 68) revert("Transaction reverted silently");
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
emit CallResult(success, result);
return (success, result);
}
| 13,226,228 |
./full_match/1/0x8430Be7B8fd28Cc58EA70A25C9c7A624F26f5D09/sources/src/core/processors/RollupProcessorV2.sol | Returns true if deposits are capped, false otherwise return capped - True if deposits are capped, false otherwise/ | function getCapped() public view override (IRollupProcessorV2) returns (bool capped) {
return rollupState.capped;
}
| 4,874,851 |
./partial_match/1/0x43eA73168B8f192dBDEC088DA29F2C5E517f6fcB/sources/contracts-verify/KUMASwap.sol | Visibility function that calculates the face value of a bond at the current timestamp tokenId Bond tokenId. return Bond value e.g. principal value + accrued interests./ | function getBondValue(uint256 tokenId) external view returns (uint256) {
if (!_bondReserve.contains(tokenId)) {
revert Errors.INVALID_TOKEN_ID();
}
IKUMABondToken.Bond memory bond = IKUMABondToken(_KUMAAddressProvider.getKUMABondToken()).getBond(tokenId);
return _getBondValue(bond.issuance, bond.maturity - bond.issuance, bond.coupon, bond.principal);
}
| 15,921,125 |
./full_match/43114/0x7766E37357598FeF21007E689f07b89788c56a9b/sources/production-contracts/BlizzVault.sol | Withdraw full unlocked balance and claim pending rewards | function withdrawAll() external updateReward(msg.sender) {
(uint256 amount, uint256 penaltyAmount) = withdrawableBalance(msg.sender);
delete userEarnings[msg.sender];
Balances storage bal = balances[msg.sender];
bal.total = bal.total.sub(bal.unlocked).sub(bal.earned);
bal.unlocked = 0;
bal.earned = 0;
totalSupply = totalSupply.sub(amount.add(penaltyAmount));
stakingToken.safeTransfer(msg.sender, amount);
if (penaltyAmount > 0) {
_notifyReward(address(stakingToken), penaltyAmount);
}
claim();
}
| 4,571,027 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./TransferHelper.sol";
import "./INFTWEscrow.sol";
import "./INFTWRental.sol";
import "./INFTW_ERC721.sol";
contract NFTWRental is Context, ERC165, INFTWRental, Ownable, ReentrancyGuard {
using SafeCast for uint;
address immutable WRLD_ERC20_ADDR;
INFTWEscrow immutable NFTWEscrow;
WorldRentInfo[10001] public worldRentInfo; // NFTW tokenId is in N [1,10000]
mapping (address => uint) public rentCount; // count of rented worlds per tenant
mapping (address => mapping(uint => uint)) private _rentedWorlds; // enumerate rented worlds per tenant
mapping (uint => uint) private _rentedWorldsIndex; // tokenId to index in _rentedWorlds[tenant]
// ======== Admin functions ========
constructor(address wrld, INFTWEscrow escrow) {
require(wrld != address(0), "E0"); // E0: addr err
require(escrow.supportsInterface(type(INFTWEscrow).interfaceId),"E0");
WRLD_ERC20_ADDR = wrld;
NFTWEscrow = escrow;
}
// Rescue ERC20 tokens sent directly to this contract
function rescueERC20(address token, uint amount) external onlyOwner {
TransferHelper.safeTransfer(token, _msgSender(), amount);
}
// ======== Public functions ========
// Can be used by tenant to initiate rent
// Can be used on a world where rental payment has expired
// paymentAlert is the number of seconds before an alert can be rentalPerDay
// payment unit in ether
function rentWorld(uint tokenId, uint32 _paymentAlert, uint32 initialPayment) external virtual override nonReentrant {
INFTWEscrow.WorldInfo memory worldInfo_ = NFTWEscrow.getWorldInfo(tokenId);
WorldRentInfo memory worldRentInfo_ = worldRentInfo[tokenId];
require(worldInfo_.owner != address(0), "EN"); // EN: Not staked
require(uint(worldInfo_.rentableUntil) >= block.timestamp + worldInfo_.minRentDays * 86400, "EC"); // EC: Not available
if (worldRentInfo_.tenant != address(0)) { // if previously rented
uint paidUntil = rentalPaidUntil(tokenId);
require(paidUntil < block.timestamp, "EB"); // EB: Ongoing rent
worldRentInfo_.rentalPaid = 0; // reset payment amount
}
// should pay at least deposit + 1 day of rent
require(uint(initialPayment) >= uint(worldInfo_.deposit + worldInfo_.rentalPerDay), "ED"); // ED: Payment insufficient
// prevent the user from paying too much
// block.timestamp casts it into uint256 which is desired
// if the rentable time left is less than minRentDays then the tenant just has to pay up until the time limit
uint paymentAmount = Math.min((worldInfo_.rentableUntil - block.timestamp) * worldInfo_.rentalPerDay / 86400,
uint(initialPayment));
worldRentInfo_.tenant = _msgSender();
worldRentInfo_.rentStartTime = block.timestamp.toUint32();
worldRentInfo_.rentalPaid += paymentAmount.toUint32();
worldRentInfo_.paymentAlert = _paymentAlert;
TransferHelper.safeTransferFrom(WRLD_ERC20_ADDR, _msgSender(), worldInfo_.owner, paymentAmount * 1e18);
worldRentInfo[tokenId] = worldRentInfo_;
uint count = rentCount[_msgSender()];
_rentedWorlds[_msgSender()][count] = tokenId;
_rentedWorldsIndex[tokenId] = count;
rentCount[_msgSender()] ++;
emit WorldRented(tokenId, _msgSender(), paymentAmount * 1e18);
}
// Used by tenant to pay rent in advance. As soon as the tenant defaults the renter can vacate the tenant
// The rental period can be extended as long as rent is prepaid, up to rentableUntil timestamp.
// payment unit in ether
function payRent(uint tokenId, uint32 payment) external virtual override nonReentrant {
INFTWEscrow.WorldInfo memory worldInfo_ = NFTWEscrow.getWorldInfo(tokenId);
WorldRentInfo memory worldRentInfo_ = worldRentInfo[tokenId];
require(worldRentInfo_.tenant == _msgSender(), "EE"); // EE: Not rented
// prevent the user from paying too much
uint paymentAmount = Math.min(uint(worldInfo_.rentableUntil - worldRentInfo_.rentStartTime) * worldInfo_.rentalPerDay / 86400
- worldRentInfo_.rentalPaid,
uint(payment));
worldRentInfo_.rentalPaid += paymentAmount.toUint32();
TransferHelper.safeTransferFrom(WRLD_ERC20_ADDR, _msgSender(), worldInfo_.owner, paymentAmount * 1e18);
worldRentInfo[tokenId] = worldRentInfo_;
emit RentalPaid(tokenId, _msgSender(), paymentAmount * 1e18);
}
// Used by renter to vacate tenant in case of default, or when rental period expires.
// If payment + deposit covers minRentDays then deposit can be used as rent. Otherwise rent has to be provided in addition to the deposit.
// If rental period is shorter than minRentDays then deposit will be forfeited.
function terminateRental(uint tokenId) external override virtual {
require(NFTWEscrow.getWorldInfo(tokenId).owner == _msgSender(), "E9"); // E9: Not your world
uint paidUntil = rentalPaidUntil(tokenId);
require(paidUntil < block.timestamp, "EB"); // EB: Ongoing rent
address tenant = worldRentInfo[tokenId].tenant;
emit RentalTerminated(tokenId, tenant);
rentCount[tenant]--;
uint lastIndex = rentCount[tenant];
uint tokenIndex = _rentedWorldsIndex[tokenId];
// swap and purge if not the last one
if (tokenIndex != lastIndex) {
uint lastTokenId = _rentedWorlds[tenant][lastIndex];
_rentedWorlds[tenant][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_rentedWorldsIndex[lastTokenId] = tokenIndex;
}
delete _rentedWorldsIndex[tokenId];
delete _rentedWorlds[tenant][tokenIndex];
worldRentInfo[tokenId] = WorldRentInfo(address(0),0,0,0);
}
// ======== View only functions ========
function isRentActive(uint tokenId) public view override returns(bool) {
return worldRentInfo[tokenId].tenant != address(0);
}
function getTenant(uint tokenId) public view override returns(address) {
return worldRentInfo[tokenId].tenant;
}
function rentedByIndex(address tenant, uint index) public view virtual override returns(uint) {
require(index < rentCount[tenant], "EI"); // EI: index out of bounds
return _rentedWorlds[tenant][index];
}
function isRentable(uint tokenId) external view virtual override returns(bool state) {
INFTWEscrow.WorldInfo memory worldInfo_ = NFTWEscrow.getWorldInfo(tokenId);
WorldRentInfo memory worldRentInfo_ = worldRentInfo[tokenId];
state = (worldInfo_.owner != address(0)) &&
(uint(worldInfo_.rentableUntil) >= block.timestamp + worldInfo_.minRentDays * 86400);
if (worldRentInfo_.tenant != address(0)) { // if previously rented
uint paidUntil = rentalPaidUntil(tokenId);
state = state && (paidUntil < block.timestamp);
}
}
function rentalPaidUntil(uint tokenId) public view virtual override returns(uint paidUntil) {
INFTWEscrow.WorldInfo memory worldInfo_ = NFTWEscrow.getWorldInfo(tokenId);
WorldRentInfo memory worldRentInfo_ = worldRentInfo[tokenId];
if (worldInfo_.rentalPerDay == 0) {
paidUntil = worldInfo_.rentableUntil;
}
else {
uint rentalPaidSeconds = uint(worldRentInfo_.rentalPaid) * 86400 / worldInfo_.rentalPerDay;
bool fundExceedsMin = rentalPaidSeconds >= Math.max(worldInfo_.minRentDays * 86400, block.timestamp - worldRentInfo_.rentStartTime);
paidUntil = uint(worldRentInfo_.rentStartTime) + rentalPaidSeconds
- (fundExceedsMin ? 0 : uint(worldInfo_.deposit) * 86400 / worldInfo_.rentalPerDay);
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(INFTWRental).interfaceId || super.supportsInterface(interfaceId);
}
}
| Used by renter to vacate tenant in case of default, or when rental period expires. If payment + deposit covers minRentDays then deposit can be used as rent. Otherwise rent has to be provided in addition to the deposit. If rental period is shorter than minRentDays then deposit will be forfeited. swap and purge if not the last one | function terminateRental(uint tokenId) external override virtual {
uint paidUntil = rentalPaidUntil(tokenId);
address tenant = worldRentInfo[tokenId].tenant;
emit RentalTerminated(tokenId, tenant);
rentCount[tenant]--;
uint lastIndex = rentCount[tenant];
uint tokenIndex = _rentedWorldsIndex[tokenId];
if (tokenIndex != lastIndex) {
uint lastTokenId = _rentedWorlds[tenant][lastIndex];
_rentedWorldsIndex[lastTokenId] = tokenIndex;
}
delete _rentedWorldsIndex[tokenId];
delete _rentedWorlds[tenant][tokenIndex];
worldRentInfo[tokenId] = WorldRentInfo(address(0),0,0,0);
}
| 12,991,668 |
./full_match/4/0x0199C6242d1ca20E05b88Da441C43F771498d8FB/sources/browser/Comptroller.sol | Checks if the account should be allowed to repay a borrow in the given market cToken The market to verify the repay against payer The account which would repay the asset borrower The account which would borrowed the asset repayAmount The amount of the underlying asset the account would repay return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/ Shh - currently unused | function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
| 760,692 |
./full_match/1/0x7D576dE740e290bC3c279C8A879442c4108b9398/sources/contracts/feiotherarb.sol | use rai to get fei out | function rai_curve_best_out(uint256 lowerbound, uint256 higherbound , uint256 step) public returns(uint256 bestin, uint256 bestprofit, uint256 bestraiout){
uint256 curve_out;
uint256 amountin;
uint256 v3_raiout;
uint256 v3_usdc_out;
uint256 v3_dai_out;
while(lowerbound < higherbound){
amountin = lowerbound;
v3_raiout = v3out(address(0x6B175474E89094C44Da98b954EedeAC495271d0F), address(0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919), 500, amountin);
curve_out = ethbondingcurve(address(0x25d60212D47Dd8F6Ff0469367E4c6C98Cd3411A5)).getAmountOut(v3_raiout);
v3_usdc_out = v3out(address(0x956F47F50A910163D8BF957Cf5846D573E7f87CA), address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48), 500, curve_out);
v3_dai_out = v3out(address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48), address(0x6B175474E89094C44Da98b954EedeAC495271d0F), 500, v3_usdc_out);
if(v3_dai_out < amountin){
break;
}
if((v3_dai_out - amountin) > bestprofit){
bestprofit = v3_dai_out - amountin;
bestin = amountin;
lowerbound = lowerbound + step;
bestraiout = v3_raiout;
break;
}
}
}
| 9,698,281 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./libraries/Utils.sol";
import "./libraries/Signature.sol";
import "./Domain.sol";
import "./TLD.sol";
import "./Settings.sol";
contract Ordering is Ownable {
using SafeMath for uint256;
bool public initialized;
Settings settings;
struct AcquisitionOrder {
address payable custodianAddress;
address requester;
uint256 acquisitionType;
uint256 acquisitionFee;
uint256 paidAcquisitionFee;
uint256 transferInitiated;
uint256 acquisitionSuccessful;
uint256 acquisitionFail;
uint256 acquisitionYears;
uint256 validUntil;
uint256 custodianNonce;
uint256 reservedId;
}
mapping(bytes32=>AcquisitionOrder) acquisitionOrders;
event AcquisitionOrderCreated(address custodianAddress,
address requesterAddress,
bytes32 domainHash,
uint256 acquisitionType,
uint256 custodianNonce,
bytes acquisitionCustodianEncryptedData);
event TransferInitiated( bytes32 domainHash );
event DomainAcquisitionPaid(bytes32 domainHash,
uint256 acquisitionFeePaid);
event AcquisitionSuccessful(bytes32 domainHash,
string domainName,
uint256 acquisitionType);
event AcquisitionFailed(bytes32 domainHash);
event AcquisitionPaid(bytes32 domainHash,
string domainName,
uint256 amount);
event RefundPaid(bytes32 domainHash,
address requester,
uint256 amount);
event OrderCancel(bytes32 domainHash);
event TokenExpirationExtension(bytes32 domainHash,
uint256 tokenId,
uint256 extensionTime);
enum OrderStatus {
UNDEFINED, // 0
OPEN, // 1
ACQUISITION_CONFIRMED, // 2
ACQUISITION_FAILED, // 3
EXPIRED, // 4
TRANSFER_INITIATED // 5
}
enum OrderType {
UNKNOWN, // should not be used
REGISTRATION, // 1
TRANSFER, // 2
EXTENSION // 3
}
constructor(){
}
function initialize(Settings _settings) public onlyOwner {
require(!initialized, "Contract instance has already been initialized");
initialized = true;
settings = _settings;
}
function user() public view returns(User){
return User(settings.getNamedAddress("USER"));
}
function getAcquisitionOrder(bytes32 domainHash) public view returns(AcquisitionOrder memory){
return acquisitionOrders[domainHash];
}
function getAcquisitionOrderByDomainName(string memory domainName) public view returns(AcquisitionOrder memory){
bytes32 domainHash = Utils.hashString(domainName);
return acquisitionOrders[domainHash];
}
function setSettingsAddress(Settings _settings) public onlyOwner {
settings = _settings;
}
function tld() public view returns(TLD){
return TLD(payable(settings.getNamedAddress("TLD")));
}
function tokenCreationFee(bytes32 domainHash)
public
view
returns(uint256){
return tld().rprice(acquisitionOrders[domainHash].reservedId);
}
function minimumOrderValidityTime(uint256 orderType)
public
view
returns (uint256) {
if(orderType == uint256(OrderType.REGISTRATION)){
return settings.getNamedUint("ORDER_MINIMUM_VALIDITY_TIME_REGISTRATION");
}
if(orderType == uint256(OrderType.TRANSFER)){
return settings.getNamedUint("ORDER_MINIMUM_VALIDITY_TIME_TRANSFER");
}
if(orderType == uint256(OrderType.EXTENSION)){
return settings.getNamedUint("ORDER_MINIMUM_VALIDITY_TIME_EXTENSION");
}
return 0;
}
function orderStatus(bytes32 domainHash)
public
view
returns (uint256) {
if(isOrderConfirmed(domainHash)){
return uint256(OrderStatus.ACQUISITION_CONFIRMED);
}
if(isOrderFailed(domainHash)){
return uint256(OrderStatus.ACQUISITION_FAILED);
}
if(isTransferInitiated(domainHash)){
return uint256(OrderStatus.TRANSFER_INITIATED);
}
if(isOrderExpired(domainHash)){
return uint256(OrderStatus.EXPIRED);
}
if(isOrderOpen(domainHash)){
return uint256(OrderStatus.OPEN);
}
return uint256(OrderStatus.UNDEFINED);
}
function orderExists(bytes32 domainHash)
public
view
returns (bool){
return acquisitionOrders[domainHash].validUntil > 0;
}
function isOrderExpired(bytes32 domainHash)
public
view
returns (bool){
return acquisitionOrders[domainHash].validUntil > 0
&& acquisitionOrders[domainHash].validUntil < block.timestamp
&& acquisitionOrders[domainHash].transferInitiated == 0
&& acquisitionOrders[domainHash].acquisitionSuccessful == 0
&& acquisitionOrders[domainHash].acquisitionFail == 0;
}
function isOrderOpen(bytes32 domainHash)
public
view
returns (bool){
return acquisitionOrders[domainHash].validUntil > block.timestamp
|| isOrderConfirmed(domainHash)
|| isTransferInitiated(domainHash);
}
function isOrderConfirmed(bytes32 domainHash)
public
view
returns (bool){
return acquisitionOrders[domainHash].acquisitionSuccessful > 0;
}
function isOrderFailed(bytes32 domainHash)
public
view
returns (bool){
return acquisitionOrders[domainHash].acquisitionFail > 0;
}
function isTransferInitiated(bytes32 domainHash)
public
view
returns(bool){
return acquisitionOrders[domainHash].transferInitiated > 0;
}
function canCancelOrder(bytes32 domainHash)
public
view
returns (bool){
return orderExists(domainHash)
&& acquisitionOrders[domainHash].validUntil > block.timestamp
&& !isOrderConfirmed(domainHash)
&& !isOrderFailed(domainHash)
&& !isTransferInitiated(domainHash);
}
function orderDomainAcquisition(bytes32 domainHash,
address requester,
uint256 acquisitionType,
uint256 acquisitionYears,
uint256 acquisitionFee,
uint256 acquisitionOrderTimestamp,
uint256 custodianNonce,
bytes memory signature,
bytes memory acquisitionCustodianEncryptedData)
public
payable {
require(user().isActive(requester), "Requester must be an active user");
require(acquisitionOrderTimestamp > block.timestamp.sub(settings.getNamedUint("ACQUISITION_ORDER_TIME_WINDOW")),
"Try again with a fresh acquisition order");
bytes32 message = keccak256(abi.encode(requester,
acquisitionType,
acquisitionYears,
acquisitionFee,
acquisitionOrderTimestamp,
custodianNonce,
domainHash));
address custodianAddress = Signature.recoverSigner(message,signature);
require(settings.hasNamedRole("CUSTODIAN", custodianAddress),
"Signer is not a registered custodian");
if(isOrderOpen(domainHash)){
revert("An order for this domain is already active");
}
if(acquisitionType == uint256(OrderType.EXTENSION)){
require(domainToken().tokenForHashExists(domainHash), "Token for domain does not exist");
}
require(msg.value >= acquisitionFee,
"Acquisition fee must be paid upfront");
uint256 reservedId = 0;
acquisitionOrders[domainHash] = AcquisitionOrder(
payable(custodianAddress),
requester,
acquisitionType,
acquisitionFee,
0, // paidAcquisitionFee
0, // transferInitiated
0, // acquisitionSuccessful flag,
0, // acquisitionFail flag,
acquisitionYears,
block.timestamp.add(minimumOrderValidityTime(acquisitionType)), //validUntil,
custodianNonce,
reservedId
);
emit AcquisitionOrderCreated(custodianAddress,
requester,
domainHash,
acquisitionType,
custodianNonce,
acquisitionCustodianEncryptedData);
}
modifier onlyCustodian() {
require(settings.hasNamedRole("CUSTODIAN", _msgSender())
|| _msgSender() == owner(),
"Must be a custodian");
_;
}
function transferInitiated(bytes32 domainHash)
public onlyCustodian {
require(acquisitionOrders[domainHash].validUntil > 0,
"Order does not exist");
require(acquisitionOrders[domainHash].acquisitionType == uint256(OrderType.TRANSFER),
"Order is not Transfer");
require(acquisitionOrders[domainHash].transferInitiated == 0,
"Already marked");
acquisitionOrders[domainHash].transferInitiated = block.timestamp;
if(acquisitionOrders[domainHash].paidAcquisitionFee == 0
&& acquisitionOrders[domainHash].acquisitionFee > 0){
uint256 communityFee = Utils.calculatePercentageCents(acquisitionOrders[domainHash].acquisitionFee,
settings.getNamedUint("COMMUNITY_FEE"));
address payable custodianAddress = acquisitionOrders[domainHash].custodianAddress;
uint256 custodianFee = acquisitionOrders[domainHash].acquisitionFee.sub(communityFee);
acquisitionOrders[domainHash].paidAcquisitionFee = acquisitionOrders[domainHash].acquisitionFee;
custodianAddress.transfer(custodianFee);
payable(address(tld())).transfer(communityFee);
}
emit TransferInitiated(domainHash);
}
function domainToken() public view returns(Domain){
return Domain(settings.getNamedAddress("DOMAIN"));
}
function acquisitionSuccessful(string memory domainName)
public onlyCustodian {
bytes32 domainHash = domainToken().registryDiscover(domainName);
require(acquisitionOrders[domainHash].validUntil > 0,
"Order does not exist");
require(acquisitionOrders[domainHash].acquisitionSuccessful == 0,
"Already marked");
if(acquisitionOrders[domainHash].acquisitionType == uint256(OrderType.TRANSFER)
&& acquisitionOrders[domainHash].transferInitiated == 0){
revert("Transfer was not initiated");
}
acquisitionOrders[domainHash].acquisitionSuccessful = block.timestamp;
acquisitionOrders[domainHash].acquisitionFail = 0;
if(acquisitionOrders[domainHash].paidAcquisitionFee == 0
&& acquisitionOrders[domainHash].acquisitionFee > 0){
uint256 communityFee = Utils.calculatePercentageCents(acquisitionOrders[domainHash].acquisitionFee,
settings.getNamedUint("COMMUNITY_FEE"));
address payable custodianAddress = acquisitionOrders[domainHash].custodianAddress;
uint256 custodianFee = acquisitionOrders[domainHash].acquisitionFee.sub(communityFee);
acquisitionOrders[domainHash].paidAcquisitionFee = acquisitionOrders[domainHash].acquisitionFee;
custodianAddress.transfer(custodianFee);
payable(address(tld())).transfer(communityFee);
}
uint256 acquisitionType = acquisitionOrders[domainHash].acquisitionType;
if(acquisitionOrders[domainHash].acquisitionType == uint256(OrderType.EXTENSION)){
emit TokenExpirationExtension(domainHash,
domainToken().tokenIdForHash(domainHash),
acquisitionOrders[domainHash].acquisitionYears.mul(365 days));
delete acquisitionOrders[domainHash];
}
emit AcquisitionSuccessful(domainHash, domainName, acquisitionType);
}
function getAcquisitionYears(bytes32 domainHash) public view returns(uint256){
return acquisitionOrders[domainHash].acquisitionYears;
}
function acquisitionFail(bytes32 domainHash)
public onlyCustodian {
require(acquisitionOrders[domainHash].validUntil > 0,
"Order does not exist");
require(acquisitionOrders[domainHash].acquisitionFail == 0,
"Already marked");
acquisitionOrders[domainHash].transferInitiated = 0;
acquisitionOrders[domainHash].acquisitionSuccessful = 0;
acquisitionOrders[domainHash].acquisitionFail = block.timestamp;
if( acquisitionOrders[domainHash].paidAcquisitionFee == 0
&& acquisitionOrders[domainHash].acquisitionFee > 0){
address payable requester = payable(acquisitionOrders[domainHash].requester);
uint256 refundAmount = acquisitionOrders[domainHash].acquisitionFee;
requester.transfer(refundAmount);
}
delete acquisitionOrders[domainHash];
emit AcquisitionFailed(domainHash);
}
function cancelOrder(bytes32 domainHash)
public {
require(canCancelOrder(domainHash),
"Can not cancel order");
if(acquisitionOrders[domainHash].paidAcquisitionFee == 0
&& acquisitionOrders[domainHash].acquisitionFee > 0){
address payable requester = payable(acquisitionOrders[domainHash].requester);
acquisitionOrders[domainHash].paidAcquisitionFee = acquisitionOrders[domainHash].acquisitionFee;
if(requester.send(acquisitionOrders[domainHash].acquisitionFee)){
emit RefundPaid(domainHash, requester, acquisitionOrders[domainHash].acquisitionFee);
}
}
delete acquisitionOrders[domainHash];
emit OrderCancel(domainHash);
}
function canClaim(bytes32 domainHash)
public view returns(bool){
return (acquisitionOrders[domainHash].validUntil > 0 &&
acquisitionOrders[domainHash].acquisitionFail == 0 &&
acquisitionOrders[domainHash].acquisitionSuccessful > 0 &&
!domainToken().tokenForHashExists(domainHash));
}
function orderRequester(bytes32 domainHash)
public view returns(address){
return acquisitionOrders[domainHash].requester;
}
function computedExpirationDate(bytes32 domainHash)
public view returns(uint256){
return acquisitionOrders[domainHash].acquisitionSuccessful
.add(acquisitionOrders[domainHash].acquisitionYears
.mul(365 days));
}
function tldOrderReservedId(bytes32 domainHash)
public view returns(uint256){
return acquisitionOrders[domainHash].reservedId;
}
function finishOrder(bytes32 domainHash)
public onlyOwner {
delete acquisitionOrders[domainHash];
}
}
// 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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
library Utils {
using SafeMath for uint256;
function hashString(string memory domainName)
internal
pure
returns (bytes32) {
return keccak256(abi.encode(domainName));
}
function calculatePercentage(uint256 amount,
uint256 percentagePoints,
uint256 maxPercentagePoints)
internal
pure
returns (uint256){
return amount.mul(percentagePoints).div(maxPercentagePoints);
}
function percentageCentsMax()
internal
pure
returns (uint256){
return 10000;
}
function calculatePercentageCents(uint256 amount,
uint256 percentagePoints)
internal
pure
returns (uint256){
return calculatePercentage(amount, percentagePoints, percentageCentsMax());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Signature {
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address){
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
function splitSignature(bytes memory sig)
internal
pure
returns (uint8, bytes32, bytes32){
require(sig.length == 65, "Invalid Signature");
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./libraries/Utils.sol";
import "./libraries/Signature.sol";
import "./User.sol";
import "./Registry.sol";
import "./Settings.sol";
contract Domain is ERC721Enumerable {
using SafeMath for uint256;
using Counters for Counters.Counter;
Settings settings;
Counters.Counter private _tokenIds;
struct DomainInfo {
bytes32 domainHash;
uint256 expireTimestamp;
uint256 transferCooloffTime;
bool active;
uint256 canBurnAfter;
bool burnRequest;
bool burnRequestCancel;
bool burnInit;
}
address private _owner;
mapping(uint256=>DomainInfo) public domains;
mapping(bytes32=>uint256) public domainHashToToken;
mapping(address=>mapping(address=>mapping(uint256=>uint256))) public offchainTransferConfirmations;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event DomainDeactivated(uint256 tokenId);
event DomainActivated(uint256 tokenId);
event InitBurnRequest(uint256 tokenId);
event BurnInitiated(uint256 tokenId);
event InitCancelBurn(uint256 tokenId);
event BurnCancel(uint256 tokenId);
event Burned(uint256 tokenId, bytes32 domainHash);
string public _custodianBaseUri;
constructor(string memory baseUri, Settings _settings) ERC721("Domain Name Token", "DOMAIN") {
_owner = msg.sender;
_custodianBaseUri = baseUri;
settings = _settings;
}
function _baseURI()
internal
view
virtual
override
returns (string memory) {
return _custodianBaseUri;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
string memory domainName = getDomainName(tokenId);
return string(abi.encodePacked(baseURI, "/", "api" "/","info","/","domain","/",domainName,".json"));
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
function setSettingsAddress(Settings _settings) public onlyOwner {
settings = _settings;
}
function burnRestrictionWindow() public view returns(uint256){
return settings.getNamedUint("BURN_RESTRICTION_WINDOW");
}
function changeOwner(address nextOwner) public onlyOwner {
address previousOwner = _owner;
_owner = nextOwner;
emit OwnershipTransferred(previousOwner, nextOwner);
}
function user() public view returns(User){
return User(settings.getNamedAddress("USER"));
}
function registry() public view returns(Registry){
return Registry(settings.getNamedAddress("REGISTRY"));
}
function isDomainActive(uint256 tokenId)
public
view
returns (bool){
return _exists(tokenId) && domains[tokenId].active && domains[tokenId].expireTimestamp > block.timestamp;
}
function isDomainNameActive(string memory domainName)
public
view
returns (bool){
return isDomainActive(tokenOfDomain(domainName));
}
function getDomainName(uint256 tokenId)
public
view
returns (string memory){
return registry().reveal(domains[tokenId].domainHash);
}
function getHashOfTokenId(uint256 tokenId) public view returns(bytes32){
return domains[tokenId].domainHash;
}
function registryDiscover(string memory name) public returns(bytes32){
return registry().discover(name);
}
function registryReveal(bytes32 key) public view returns(string memory){
return registry().reveal(key);
}
function tokenOfDomain(string memory domainName)
public
view
returns (uint256){
bytes32 domainHash = Utils.hashString(domainName);
return domainHashToToken[domainHash];
}
function getTokenId(string memory domainName)
public
view
returns (uint256){
return tokenOfDomain(domainName);
}
function getExpirationDate(uint256 tokenId)
public
view
returns(uint256){
return domains[tokenId].expireTimestamp;
}
function extendExpirationDate(uint256 tokenId, uint256 interval) public onlyOwner {
require(_exists(tokenId), "Token id does not exist");
domains[tokenId].expireTimestamp = domains[tokenId].expireTimestamp.add(interval);
}
function extendExpirationDateDomainHash(bytes32 domainHash, uint256 interval) public onlyOwner {
extendExpirationDate(domainHashToToken[domainHash], interval);
}
function getTokenInfo(uint256 tokenId)
public
view
returns(uint256, // tokenId
address, // ownerOf tokenId
uint256, // expireTimestamp
bytes32, // domainHash
string memory // domainName
){
return (tokenId,
ownerOf(tokenId),
domains[tokenId].expireTimestamp,
domains[tokenId].domainHash,
registry().reveal(domains[tokenId].domainHash));
}
function getTokenInfoByDomainHash(bytes32 domainHash)
public
view
returns (
uint256, // tokenId
address, // ownerOf tokenId
uint256, // expireTimestamp
bytes32, // domainHash
string memory // domainName
){
if(_exists(domainHashToToken[domainHash])){
return getTokenInfo(domainHashToToken[domainHash]);
}else{
return (
0,
address(0x0),
0,
bytes32(0x00),
""
);
}
}
function claim(address domainOwner, bytes32 domainHash, uint256 expireTimestamp) public onlyOwner returns (uint256){
require(domainHashToToken[domainHash] == 0, "Token already exists");
require(user().isActive(domainOwner), "Domain Owner is not an active user");
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
domains[tokenId] = DomainInfo(domainHash,
expireTimestamp,
0,
true,
block.timestamp.add(burnRestrictionWindow()),
false,
false,
false);
domainHashToToken[domainHash] = tokenId;
_mint(domainOwner, tokenId);
return tokenId;
}
function transferCooloffTime() public view returns (uint256){
return settings.getNamedUint("TRANSFER_COOLOFF_WINDOW");
}
function _deactivate(uint256 tokenId) internal {
domains[tokenId].active = false;
emit DomainDeactivated(tokenId);
}
function _activate(uint256 tokenId) internal {
domains[tokenId].active = true;
emit DomainActivated(tokenId);
}
function deactivate(uint256 tokenId) public onlyOwner {
require(_exists(tokenId), "Token does not exist");
require(domains[tokenId].active, "Token is already deactivated");
_deactivate(tokenId);
}
function activate(uint256 tokenId) public onlyOwner {
require(_exists(tokenId), "Token does not exist");
require(!domains[tokenId].active, "Token is already activated");
_activate(tokenId);
}
function isInBurnCycle(uint256 tokenId) public view returns(bool){
return _exists(tokenId)
&&
(
domains[tokenId].burnRequest
|| domains[tokenId].burnRequestCancel
|| domains[tokenId].burnInit
);
}
function canBeTransferred(uint256 tokenId) public view returns(bool){
return user().isActive(ownerOf(tokenId))
&& domains[tokenId].active
&& domains[tokenId].transferCooloffTime <= block.timestamp
&& domains[tokenId].expireTimestamp > block.timestamp
&& !isInBurnCycle(tokenId);
}
function canBeBurned(uint256 tokenId) public view returns(bool){
return domains[tokenId].canBurnAfter < block.timestamp;
}
function canTransferTo(address _receiver) public view returns(bool){
return user().isActive(_receiver);
}
function extendCooloffTimeForToken(uint256 tokenId, uint256 window) public onlyOwner {
if(_exists(tokenId)){
domains[tokenId].transferCooloffTime = block.timestamp.add(window);
}
}
function extendCooloffTimeForHash(bytes32 hash, uint256 window) public onlyOwner {
uint256 tokenId = tokenIdForHash(hash);
if(_exists(tokenId)){
domains[tokenId].transferCooloffTime = block.timestamp.add(window);
}
}
function offchainConfirmTransfer(address from, address to, uint256 tokenId, uint256 validUntil, uint256 custodianNonce, bytes memory signature) public {
bytes32 message = keccak256(abi.encode(from,
to,
tokenId,
validUntil,
custodianNonce));
address signer = Signature.recoverSigner(message, signature);
require(settings.hasNamedRole("CUSTODIAN", signer), "Signer is not a registered custodian");
require(_exists(tokenId), "Token does not exist");
require(_isApprovedOrOwner(from, tokenId), "Is not token owner");
require(isDomainActive(tokenId), "Token is not active");
require(user().isActive(to), "Destination address is not an active user");
offchainTransferConfirmations[from][to][tokenId] = validUntil;
}
function transferFrom(address from, address to, uint256 tokenId) public virtual override(ERC721){
require(canBeTransferred(tokenId), "Token can not be transfered now");
require(user().isActive(to), "Destination address is not an active user");
if(settings.getNamedUint("OFFCHAIN_TRANSFER_CONFIRMATION_ENABLED") > 0){
require(offchainTransferConfirmations[from][to][tokenId] > block.timestamp, "Transfer requires offchain confirmation");
}
domains[tokenId].transferCooloffTime = block.timestamp.add(transferCooloffTime());
super.transferFrom(from, to, tokenId);
}
function adminTransferFrom(address from, address to, uint256 tokenId) public onlyOwner {
require(_exists(tokenId), "Token does not exist");
require(_isApprovedOrOwner(from, tokenId), "Can not transfer");
require(user().isActive(to), "Destination address is not an active user");
_transfer(from, to, tokenId);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function tokenExists(uint256 tokenId) public view returns(bool){
return _exists(tokenId);
}
function tokenForHashExists(bytes32 hash) public view returns(bool){
return tokenExists(tokenIdForHash(hash));
}
function tokenIdForHash(bytes32 hash) public view returns(uint256){
return domainHashToToken[hash];
}
function initBurn(uint256 tokenId) public {
require(canBeBurned(tokenId), "Domain is in burn restriction period");
require(!isInBurnCycle(tokenId), "Domain already in burn cycle");
require(_exists(tokenId), "Domain does not exist");
require(ownerOf(tokenId) == msg.sender, "Must be owner of domain");
domains[tokenId].burnRequest = true;
_deactivate(tokenId);
emit InitBurnRequest(tokenId);
}
function cancelBurn(uint256 tokenId) public {
require(_exists(tokenId), "Domain does not exist");
require(ownerOf(tokenId) == msg.sender, "Must be owner of domain");
require(domains[tokenId].burnRequest, "No burn initiated");
domains[tokenId].burnRequestCancel = true;
emit InitCancelBurn(tokenId);
}
function burnInit(uint256 tokenId) public onlyOwner {
require(_exists(tokenId), "Token does not exist");
domains[tokenId].burnRequest = true;
domains[tokenId].burnRequestCancel = false;
domains[tokenId].burnInit = true;
_deactivate(tokenId);
emit BurnInitiated(tokenId);
}
function burnCancel(uint256 tokenId) public onlyOwner {
require(_exists(tokenId), "Token does not exist");
domains[tokenId].burnRequest = false;
domains[tokenId].burnRequestCancel = false;
domains[tokenId].burnInit = false;
_activate(tokenId);
emit BurnCancel(tokenId);
}
function burn(uint256 tokenId) public onlyOwner {
require(_exists(tokenId), "Token does not exist");
bytes32 domainHash = domains[tokenId].domainHash;
delete domainHashToToken[domainHash];
delete domains[tokenId];
_burn(tokenId);
emit Burned(tokenId, domainHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./ERC20Changeable.sol";
contract TLD is ERC20Changeable {
using SafeMath for uint256;
using Counters for Counters.Counter;
address private _owner;
uint256 private AVERAGE_LENGTH;
uint256 private MINT_UNIT = 1;
uint256 private gasUnitsHistory;
uint256 private gasPriceHistory;
uint256 private MINTED_ETH = 0;
uint256 private MINTED_TLD = 0;
uint256 private MINTED_CONSTANT = 0;
uint256 private REIMBURSEMENT_TX_GAS_HISTORY;
uint256 private DEFAULT_REIMBURSEMENT_TX_GAS = 90000;
uint256 private BASE_PRICE_MULTIPLIER = 3;
uint256 private _basePrice;
Counters.Counter private _reservedIds;
mapping(uint256=>uint256) reservedPrice;
event Skimmed(address destinationAddress, uint256 amount);
constructor() ERC20Changeable("Domain Name Community Token", ".TLD") {
_owner = msg.sender;
}
function changeSymbol(string memory symbol_) public onlyOwner{
_symbol = symbol_;
}
function changeName(string memory name_) public onlyOwner{
_name = name_;
}
function init(uint256 initialGasEstimation, uint256 averageLength, uint256 basePriceMultiplier) public payable onlyOwner returns(uint256){
if(MINTED_CONSTANT != 0){
revert("Already initialized");
}
AVERAGE_LENGTH = averageLength;
BASE_PRICE_MULTIPLIER = basePriceMultiplier;
trackGasReimburses(initialGasEstimation);
trackGasPrice(tx.gasprice.add(1));
uint256 toMint = msg.value.mul(unit()).div(basePrice());
MINTED_ETH = msg.value;
MINTED_TLD = toMint;
MINTED_CONSTANT = MINTED_ETH.mul(MINTED_TLD);
_mint(msg.sender, toMint);
return toMint;
}
function setBasePriceMultiplier(uint256 basePriceMultiplier) public onlyOwner {
BASE_PRICE_MULTIPLIER = basePriceMultiplier;
}
function setAverageLength(uint256 averageLength) public onlyOwner {
require(averageLength > 1, "Average length must be greater than one.");
AVERAGE_LENGTH = averageLength;
}
function mintedEth() public view returns(uint256){
return MINTED_ETH;
}
function mintedTld() public view returns(uint256){
return MINTED_TLD;
}
function unit() public view returns (uint256) {
return MINT_UNIT.mul(10 ** decimals());
}
function owner() public view virtual returns (address) {
return _owner;
}
function payableOwner() public view virtual returns(address payable){
return payable(_owner);
}
modifier onlyOwner() {
require(owner() == msg.sender, "Caller is not the owner");
_;
}
function decimals() public view virtual override returns (uint8) {
return 8;
}
function totalAvailableEther() public view returns (uint256) {
return address(this).balance;
}
function basePrice() public view returns (uint256){
return averageGasUnits().mul(averageGasPrice()).mul(BASE_PRICE_MULTIPLIER);
}
function mintPrice(uint256 numberOfTokensToMint) public view returns (uint256){
if(numberOfTokensToMint >= MINTED_TLD){
return basePrice()
.add(uncovered()
.div(AVERAGE_LENGTH));
}
uint256 computedPrice = MINTED_CONSTANT
.div( MINTED_TLD
.sub(numberOfTokensToMint))
.add(uncovered()
.div(AVERAGE_LENGTH))
.add(basePrice());
if(computedPrice <= MINTED_ETH){
return uncovered().add(basePrice());
}
return computedPrice
.sub(MINTED_ETH);
}
function burnPrice(uint256 numberOfTokensToBurn) public view returns (uint256) {
if(MINTED_CONSTANT == 0){
return 0;
}
if(uncovered() > 0){
return 0;
}
return MINTED_ETH.sub(MINTED_CONSTANT.div( MINTED_TLD.add(numberOfTokensToBurn)));
}
function isCovered() public view returns (bool){
return MINTED_ETH > 0 && MINTED_ETH <= address(this).balance;
}
function uncovered() public view returns (uint256){
if(isCovered()){
return 0;
}
return MINTED_ETH.sub(address(this).balance);
}
function overflow() public view returns (uint256){
if(!isCovered()){
return 0;
}
return address(this).balance.sub(MINTED_ETH);
}
function transferOwnership(address newOwner) public onlyOwner returns(address){
require(newOwner != address(0), "New owner is the zero address");
_owner = newOwner;
return _owner;
}
function mintUpdateMintedStats(uint256 unitsAmount, uint256 ethAmount) internal {
MINTED_TLD = MINTED_TLD.add(unitsAmount);
MINTED_ETH = MINTED_ETH.add(ethAmount);
MINTED_CONSTANT = MINTED_TLD.mul(MINTED_ETH);
}
function rprice(uint256 reservedId) public view returns(uint256){
return reservedPrice[reservedId];
}
function reserveMint() public returns (uint256) {
_reservedIds.increment();
uint256 reservedId = _reservedIds.current();
reservedPrice[reservedId] = mintPrice(unit());
return reservedId;
}
function mint(uint256 reservedId) payable public onlyOwner returns (uint256){
require(msg.value >= reservedPrice[reservedId], "Minimum payment is not met.");
mintUpdateMintedStats(unit(), basePrice());
_mint(msg.sender, unit());
return unit();
}
function unitsToBurn(uint256 ethAmount) public view returns (uint256){
if(MINTED_CONSTANT == 0){
return totalSupply();
}
if(ethAmount > MINTED_ETH){
return totalSupply();
}
return MINTED_CONSTANT.div( MINTED_ETH.sub(ethAmount) ).sub(MINTED_TLD);
}
function trackGasReimburses(uint256 gasUnits) internal {
gasUnitsHistory = gasUnitsHistory.mul(AVERAGE_LENGTH-1).add(gasUnits).div(AVERAGE_LENGTH);
}
function trackGasPrice(uint256 gasPrice) internal {
gasPriceHistory = gasPriceHistory.mul(AVERAGE_LENGTH-1).add(gasPrice).div(AVERAGE_LENGTH);
}
function averageGasPrice() public view returns(uint256){
return gasPriceHistory;
}
function averageGasUnits() public view returns(uint256){
return gasUnitsHistory;
}
function reimbursementValue() public view returns(uint256){
return averageGasUnits().mul(averageGasPrice()).mul(2);
}
function burn(uint256 unitsAmount) public returns(uint256){
require(balanceOf(msg.sender) >= unitsAmount, "Insuficient funds to burn");
uint256 value = burnPrice(unitsAmount);
if(value > 0 && value <= address(this).balance){
_burn(msg.sender, unitsAmount);
payable(msg.sender).transfer(value);
}
return 0;
}
function skim(address destination) public onlyOwner returns (uint256){
uint256 amountToSkim = overflow();
if(amountToSkim > 0){
if(payable(destination).send(amountToSkim)){
emit Skimmed(destination, amountToSkim);
}
}
return amountToSkim;
}
function reimburse(uint256 gasUnits, address payable toAddress) public onlyOwner returns (bool){
uint256 gasStart = gasleft();
uint256 value = reimbursementValue();
if(value > MINTED_ETH){
return false;
}
uint256 reimbursementUnits = unitsToBurn(value);
trackGasPrice(tx.gasprice.add(1));
if(balanceOf(msg.sender) >= reimbursementUnits && address(this).balance > value){
_burn(msg.sender, reimbursementUnits);
payable(toAddress).transfer(value);
}else{
mintUpdateMintedStats(0, value);
}
trackGasReimburses(gasUnits.add(gasStart.sub(gasleft())));
return false;
}
receive() external payable {
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
contract Settings is AccessControlEnumerable {
mapping(bytes32=>uint256) uintSetting;
mapping(bytes32=>address) addressSetting;
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Must be admin");
_;
}
constructor(){
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function isAdmin(address _address) public view returns(bool){
return hasRole(DEFAULT_ADMIN_ROLE, _address);
}
function changeAdmin(address adminAddress)
public onlyAdmin {
require(adminAddress != address(0), "New admin must be a valid address");
_setupRole(DEFAULT_ADMIN_ROLE, adminAddress);
revokeRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function registerNamedRole(string memory _name, address _address) public onlyAdmin {
bytes32 role = toKey(_name);
require(!hasRole(role, _address), "Address already has role");
_setupRole(role, _address);
}
function unregisterNamedRole(string memory _name, address _address) public onlyAdmin {
bytes32 role = toKey(_name);
require(hasRole(role, _address), "Address already has role");
revokeRole(role, _address);
}
function hasNamedRole(string memory _name, address _address) public view returns(bool){
return hasRole(toKey(_name), _address);
}
function toKey(string memory _name) public pure returns(bytes32){
return keccak256(abi.encode(_name));
}
function ownerSetNamedUint(string memory _name, uint256 _value) public onlyAdmin{
ownerSetUint(toKey(_name), _value);
}
function ownerSetUint(bytes32 _key, uint256 _value) public onlyAdmin {
uintSetting[_key] = _value;
}
function ownerSetAddress(bytes32 _key, address _value) public onlyAdmin {
addressSetting[_key] = _value;
}
function ownerSetNamedAddress(string memory _name, address _value) public onlyAdmin{
ownerSetAddress(toKey(_name), _value);
}
function getUint(bytes32 _key) public view returns(uint256){
return uintSetting[_key];
}
function getAddress(bytes32 _key) public view returns(address){
return addressSetting[_key];
}
function getNamedUint(string memory _name) public view returns(uint256){
return getUint(toKey(_name));
}
function getNamedAddress(string memory _name) public view returns(address){
return getAddress(toKey(_name));
}
function removeNamedUint(string memory _name) public onlyAdmin {
delete uintSetting[toKey(_name)];
}
function removeNamedAddress(string memory _name) public onlyAdmin {
delete addressSetting[toKey(_name)];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "./extensions/IERC721Enumerable.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. 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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.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();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Settings.sol";
contract User is Ownable{
bool public initialized;
Settings settings;
struct Account {
uint256 registered;
uint256 active;
}
mapping (address=>Account) users;
mapping (address=>address) subaccounts;
mapping (address=>address[]) userSubaccounts;
constructor() {
}
function initialize(Settings _settings) public onlyOwner {
require(!initialized, "Contract instance has already been initialized");
initialized = true;
settings = _settings;
}
function setSettingsAddress(Settings _settings) public onlyOwner {
settings = _settings;
}
function isRegistered(address userAddress) public view returns(bool){
return users[userAddress].registered > 0;
}
function isSubaccount(address anAddress) public view returns(bool){
return subaccounts[anAddress] != address(0x0);
}
function parentUser(address anAddress) public view returns(address){
if(isSubaccount(anAddress) ){
return subaccounts[anAddress];
}
if(isRegistered(anAddress)){
return anAddress;
}
return address(0x0);
}
function isActive(address anAddress) public view returns(bool){
address checkAddress = parentUser(anAddress);
return (isRegistered(checkAddress) && users[checkAddress].active > 0);
}
function register(address registerAddress) public onlyOwner {
require(!isRegistered(registerAddress),"Address already registered");
require(!isSubaccount(registerAddress), "Address is a subaccount of another address");
users[registerAddress] = Account(block.timestamp, 0);
}
function activateUser(address userAddress) public onlyOwner {
require(isRegistered(userAddress), "Address is not a registered user");
users[userAddress].active = block.timestamp;
}
function deactivateUser(address userAddress) public onlyOwner {
require(isRegistered(userAddress), "Address is not a registered user");
users[userAddress].active = 0;
}
function addSubaccount(address anAddress) public {
require(isActive(_msgSender()),"Must be a registered active user");
require(!isRegistered(anAddress), "Address is already registered");
require(!isSubaccount(anAddress), "Address is already a subaccount");
require(settings.getNamedUint("SUBACCOUNTS_ENABLED") > 0, "Subaccounts are not enabled");
subaccounts[anAddress] = _msgSender();
userSubaccounts[_msgSender()].push(anAddress);
}
function removeSubaccount(address anAddress) public {
//require(isActive(_msgSender()),"Must be a registered active user");
if(anAddress == _msgSender()){
require(subaccounts[anAddress] != address(0x0), "Address is not a subaccount");
}else{
require(subaccounts[anAddress] == _msgSender(), "Subaccount doesnt belong to caller");
}
address parent = parentUser(anAddress);
require(parent != address(0x0), "Address has no parent");
delete subaccounts[anAddress];
for(uint256 i = 0; i < userSubaccounts[parent].length; i++){
if(userSubaccounts[parent][i] == anAddress){
userSubaccounts[parent][i] = userSubaccounts[parent][userSubaccounts[parent].length-1];
userSubaccounts[parent].pop();
}
}
}
function listSubaccounts(address anAddress) public view returns(address[] memory){
return userSubaccounts[anAddress];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./libraries/Utils.sol";
contract Registry {
mapping(bytes32=>string) registry;
bytes32[] private index;
constructor(){
}
function count() public view returns(uint256){
return index.length;
}
function atIndex(uint256 _i) public view returns(string memory){
return registry[index[_i]];
}
function discover(string memory _name) public returns(bytes32){
if(bytes(_name).length == 0){
revert("Revert due to empty name");
}
bytes32 hash = Utils.hashString(_name);
if(bytes(registry[hash]).length == 0){
registry[hash] = _name;
}
return hash;
}
function reveal(bytes32 hash) public view returns(string memory){
return registry[hash];
}
function isDiscovered(string memory _name) public view returns(bool) {
bytes32 hash = Utils.hashString(_name);
return bytes(registry[hash]).length > 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: 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 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
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/introspection/ERC165.sol";
/**
* @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 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 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 {
require(hasRole(getRoleAdmin(role), _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 override {
require(hasRole(getRoleAdmin(role), _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 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());
}
}
}
// SPDX-License-Identifier: MIT
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 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.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 ERC20Changeable is Context, IERC20 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string public _name;
string public _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @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 this function is
* overloaded;
*
* 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 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(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");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// 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);
}
| See {IERC165-supportsInterface}./ | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
| 8,802 |
./full_match/1/0x2fC246149B4B8d7bcEF6188A10AF1791380227f1/sources/src/Estate/EstateBaseToken.sol | add a single land to an existing estate sender address perforing the operation that will add the quad to its Estate estateId the estate that is going to be modified id land id to be added to the estate junction this need to be the index (in the estate) of a quad/land part of the estate that is adjacent to the newly added quad | function addSingleLand(
address sender,
uint256 estateId,
uint256 id,
uint256 junction
) external {
_addLand(sender, estateId, id, junction);
}
| 8,434,832 |
pragma solidity ^0.4.18;
/**
* Math operations with safety checks that throw on error
*/
contract SafeMath {
function safeMul(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) public pure returns (uint256) {
//assert(a > 0);// Solidity automatically throws when dividing by 0
//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;
}
function safeSub(uint256 a, uint256 b) public pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
}
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public constant returns (uint256);
function balanceOf(address _owner) public constant returns (uint256);
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 constant returns (uint256);
/* ERC20 Events */
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ContractReceiver {
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
contract ERC223 is ERC20 {
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public returns (bool success);
/* ERC223 Events */
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
}
contract BankeraToken is ERC223, SafeMath {
string public constant name = "Banker Token"; // Set the name for display purposes
string public constant symbol = "BNK"; // Set the symbol for display purposes
uint8 public constant decimals = 8; // Amount of decimals for display purposes
uint256 private issued = 0; // tokens count issued to addresses
uint256 private totalTokens = 25000000000 * 100000000; //25,000,000,000.0000 0000 BNK
address private contractOwner;
address private rewardManager;
address private roundManager;
address private issueManager;
uint64 public currentRound = 0;
bool public paused = false;
mapping (uint64 => Reward) public reward; //key - round, value - reward in round
mapping (address => AddressBalanceInfoStructure) public accountBalances; //key - address, value - address balance info
mapping (uint64 => uint256) public issuedTokensInRound; //key - round, value - issued tokens
mapping (address => mapping (address => uint256)) internal allowed;
uint256 public blocksPerRound; // blocks per round
uint256 public lastBlockNumberInRound;
struct Reward {
uint64 roundNumber;
uint256 rewardInWei;
uint256 rewardRate; //reward rate in wei. 1 sBNK - xxx wei
bool isConfigured;
}
struct AddressBalanceInfoStructure {
uint256 addressBalance;
mapping (uint256 => uint256) roundBalanceMap; //key - round number, value - total token amount in round
mapping (uint64 => bool) wasModifiedInRoundMap; //key - round number, value - is modified in round
uint64[] mapKeys; //round balance map keys
uint64 claimedRewardTillRound;
uint256 totalClaimedReward;
}
/* Initializes contract with initial blocks per round number*/
function BankeraToken(uint256 _blocksPerRound, uint64 _round) public {
contractOwner = msg.sender;
lastBlockNumberInRound = block.number;
blocksPerRound = _blocksPerRound;
currentRound = _round;
}
function() public whenNotPaused payable {
}
// Public functions
/**
* @dev Reject all ERC223 compatible tokens
* @param _from address The address that is transferring the tokens
* @param _value uint256 the amount of the specified token
* @param _data Bytes The data passed from the caller.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) public whenNotPaused view {
revert();
}
function setReward(uint64 _roundNumber, uint256 _roundRewardInWei) public whenNotPaused onlyRewardManager {
isNewRound();
Reward storage rewardInfo = reward[_roundNumber];
//validations
assert(rewardInfo.roundNumber == _roundNumber);
assert(!rewardInfo.isConfigured); //allow just not configured reward configuration
rewardInfo.rewardInWei = _roundRewardInWei;
if(_roundRewardInWei > 0){
rewardInfo.rewardRate = safeDiv(_roundRewardInWei, issuedTokensInRound[_roundNumber]);
}
rewardInfo.isConfigured = true;
}
/* Change contract owner */
function changeContractOwner(address _newContractOwner) public onlyContractOwner {
isNewRound();
if (_newContractOwner != contractOwner) {
contractOwner = _newContractOwner;
} else {
revert();
}
}
/* Change reward contract owner */
function changeRewardManager(address _newRewardManager) public onlyContractOwner {
isNewRound();
if (_newRewardManager != rewardManager) {
rewardManager = _newRewardManager;
} else {
revert();
}
}
/* Change round contract owner */
function changeRoundManager(address _newRoundManager) public onlyContractOwner {
isNewRound();
if (_newRoundManager != roundManager) {
roundManager = _newRoundManager;
} else {
revert();
}
}
/* Change issue contract owner */
function changeIssueManager(address _newIssueManager) public onlyContractOwner {
isNewRound();
if (_newIssueManager != issueManager) {
issueManager = _newIssueManager;
} else {
revert();
}
}
function setBlocksPerRound(uint64 _newBlocksPerRound) public whenNotPaused onlyRoundManager {
blocksPerRound = _newBlocksPerRound;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyContractOwner whenNotPaused public {
paused = true;
}
/**
* @dev called by the owner to resume, returns to normal state
*/
function resume() onlyContractOwner whenPaused public {
paused = false;
}
/**
*
* permission checker
*/
modifier onlyContractOwner() {
if(msg.sender != contractOwner){
revert();
}
_;
}
/**
* set reward for round (reward admin)
*/
modifier onlyRewardManager() {
if(msg.sender != rewardManager && msg.sender != contractOwner){
revert();
}
_;
}
/**
* adjust round length (round admin)
*/
modifier onlyRoundManager() {
if(msg.sender != roundManager && msg.sender != contractOwner){
revert();
}
_;
}
/**
* issue tokens to ETH addresses (issue admin)
*/
modifier onlyIssueManager() {
if(msg.sender != issueManager && msg.sender != contractOwner){
revert();
}
_;
}
modifier notSelf(address _to) {
if(msg.sender == _to){
revert();
}
_;
}
/**
* @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);
_;
}
function getRoundBalance(address _address, uint256 _round) public view returns (uint256) {
return accountBalances[_address].roundBalanceMap[_round];
}
function isModifiedInRound(address _address, uint64 _round) public view returns (bool) {
return accountBalances[_address].wasModifiedInRoundMap[_round];
}
function getBalanceModificationRounds(address _address) public view returns (uint64[]) {
return accountBalances[_address].mapKeys;
}
//action for issue tokens
function issueTokens(address _receiver, uint256 _tokenAmount) public whenNotPaused onlyIssueManager {
isNewRound();
issue(_receiver, _tokenAmount);
}
function withdrawEther() public onlyContractOwner {
isNewRound();
if(this.balance > 0) {
contractOwner.transfer(this.balance);
} else {
revert();
}
}
/* Send coins from owner to other address */
/*Override*/
function transfer(address _to, uint256 _value) public notSelf(_to) whenNotPaused returns (bool success){
require(_to != address(0));
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(msg.sender, _to, _value, empty);
}
else {
return transferToAddress(msg.sender, _to, _value, empty);
}
}
/*Override*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return accountBalances[_owner].addressBalance;
}
/*Override*/
function totalSupply() public constant returns (uint256){
return totalTokens;
}
/**
* @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
*/
/*Override*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= allowed[_from][msg.sender]);
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
require(transferToContract(_from, _to, _value, empty));
}
else {
require(transferToAddress(_from, _to, _value, empty));
}
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _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.
*/
/*Override*/
function approve(address _spender, uint256 _value) public whenNotPaused 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.
*/
/*Override*/
function allowance(address _owner, address _spender) public view whenNotPaused returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender], _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] = safeSub(oldValue, _subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// Function that is called when a user or another contract wants to transfer funds .
/*Override*/
function transfer(address _to, uint256 _value, bytes _data) public whenNotPaused notSelf(_to) returns (bool success){
require(_to != address(0));
if(isContract(_to)) {
return transferToContract(msg.sender, _to, _value, _data);
}
else {
return transferToAddress(msg.sender, _to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds.
/*Override*/
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public whenNotPaused notSelf(_to) returns (bool success){
require(_to != address(0));
if(isContract(_to)) {
if(accountBalances[msg.sender].addressBalance < _value){ // Check if the sender has enough
revert();
}
if(safeAdd(accountBalances[_to].addressBalance, _value) < accountBalances[_to].addressBalance){ // Check for overflows
revert();
}
isNewRound();
subFromAddressBalancesInfo(msg.sender, _value); // Subtract from the sender
addToAddressBalancesInfo(_to, _value); // Add the same to the recipient
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
/* Notify anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
else {
return transferToAddress(msg.sender, _to, _value, _data);
}
}
function claimReward() public whenNotPaused returns (uint256 rewardAmountInWei) {
isNewRound();
return claimRewardTillRound(currentRound);
}
function claimRewardTillRound(uint64 _claimTillRound) public whenNotPaused returns (uint256 rewardAmountInWei) {
isNewRound();
rewardAmountInWei = calculateClaimableRewardTillRound(msg.sender, _claimTillRound);
accountBalances[msg.sender].claimedRewardTillRound = _claimTillRound;
if (rewardAmountInWei > 0){
accountBalances[msg.sender].totalClaimedReward = safeAdd(accountBalances[msg.sender].totalClaimedReward, rewardAmountInWei);
msg.sender.transfer(rewardAmountInWei);
}
return rewardAmountInWei;
}
function calculateClaimableReward(address _address) public constant returns (uint256 rewardAmountInWei) {
return calculateClaimableRewardTillRound(_address, currentRound);
}
function calculateClaimableRewardTillRound(address _address, uint64 _claimTillRound) public constant returns (uint256) {
uint256 rewardAmountInWei = 0;
if (_claimTillRound > currentRound) { revert(); }
if (currentRound < 1) { revert(); }
AddressBalanceInfoStructure storage accountBalanceInfo = accountBalances[_address];
if(accountBalanceInfo.mapKeys.length == 0){ revert(); }
uint64 userLastClaimedRewardRound = accountBalanceInfo.claimedRewardTillRound;
if (_claimTillRound < userLastClaimedRewardRound) { revert(); }
for (uint64 workRound = userLastClaimedRewardRound; workRound < _claimTillRound; workRound++) {
Reward storage rewardInfo = reward[workRound];
assert(rewardInfo.isConfigured); //don't allow to withdraw reward if affected reward is not configured
if(accountBalanceInfo.wasModifiedInRoundMap[workRound]){
rewardAmountInWei = safeAdd(rewardAmountInWei, safeMul(accountBalanceInfo.roundBalanceMap[workRound], rewardInfo.rewardRate));
} else {
uint64 lastBalanceModifiedRound = 0;
for (uint256 i = accountBalanceInfo.mapKeys.length; i > 0; i--) {
uint64 modificationInRound = accountBalanceInfo.mapKeys[i-1];
if (modificationInRound <= workRound) {
lastBalanceModifiedRound = modificationInRound;
break;
}
}
rewardAmountInWei = safeAdd(rewardAmountInWei, safeMul(accountBalanceInfo.roundBalanceMap[lastBalanceModifiedRound], rewardInfo.rewardRate));
}
}
return rewardAmountInWei;
}
function createRounds(uint256 maxRounds) public {
uint256 blocksAfterLastRound = safeSub(block.number, lastBlockNumberInRound); //current block number - last round block number = blocks after last round
if(blocksAfterLastRound >= blocksPerRound){ // need to increase reward round if blocks after last round is greater or equal blocks per round
uint256 roundsNeedToCreate = safeDiv(blocksAfterLastRound, blocksPerRound); //calculate how many rounds need to create
if(roundsNeedToCreate > maxRounds){
roundsNeedToCreate = maxRounds;
}
lastBlockNumberInRound = safeAdd(lastBlockNumberInRound, safeMul(roundsNeedToCreate, blocksPerRound));
for (uint256 i = 0; i < roundsNeedToCreate; i++) {
updateRoundInformation();
}
}
}
// Private functions
//assemble the given address bytecode. If bytecode exists then the _address is a contract.
function isContract(address _address) private view returns (bool is_contract) {
uint256 length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_address)
}
return (length > 0);
}
function isNewRound() private {
uint256 blocksAfterLastRound = safeSub(block.number, lastBlockNumberInRound); //current block number - last round block number = blocks after last round
if(blocksAfterLastRound >= blocksPerRound){ // need to increase reward round if blocks after last round is greater or equal blocks per round
updateRoundsInformation(blocksAfterLastRound);
}
}
function updateRoundsInformation(uint256 _blocksAfterLastRound) private {
uint256 roundsNeedToCreate = safeDiv(_blocksAfterLastRound, blocksPerRound); //calculate how many rounds need to create
lastBlockNumberInRound = safeAdd(lastBlockNumberInRound, safeMul(roundsNeedToCreate, blocksPerRound)); //calculate last round creation block number
for (uint256 i = 0; i < roundsNeedToCreate; i++) {
updateRoundInformation();
}
}
function updateRoundInformation() private {
issuedTokensInRound[currentRound] = issued;
Reward storage rewardInfo = reward[currentRound];
rewardInfo.roundNumber = currentRound;
currentRound = currentRound + 1;
}
function issue(address _receiver, uint256 _tokenAmount) private {
if(_tokenAmount == 0){
revert();
}
uint256 newIssuedAmount = safeAdd(_tokenAmount, issued);
if(newIssuedAmount > totalTokens){
revert();
}
addToAddressBalancesInfo(_receiver, _tokenAmount);
issued = newIssuedAmount;
bytes memory empty;
if(isContract(_receiver)) {
ContractReceiver receiverContract = ContractReceiver(_receiver);
receiverContract.tokenFallback(msg.sender, _tokenAmount, empty);
}
/* Notify anyone listening that this transfer took place */
Transfer(msg.sender, _receiver, _tokenAmount, empty);
Transfer(msg.sender, _receiver, _tokenAmount);
}
function addToAddressBalancesInfo(address _receiver, uint256 _tokenAmount) private {
AddressBalanceInfoStructure storage accountBalance = accountBalances[_receiver];
if(!accountBalance.wasModifiedInRoundMap[currentRound]){ //allow just push one time per round
// If user first time get update balance set user claimed reward round to round before.
if(accountBalance.mapKeys.length == 0 && currentRound > 0){
accountBalance.claimedRewardTillRound = currentRound;
}
accountBalance.mapKeys.push(currentRound);
accountBalance.wasModifiedInRoundMap[currentRound] = true;
}
accountBalance.addressBalance = safeAdd(accountBalance.addressBalance, _tokenAmount);
accountBalance.roundBalanceMap[currentRound] = accountBalance.addressBalance;
}
function subFromAddressBalancesInfo(address _adr, uint256 _tokenAmount) private {
AddressBalanceInfoStructure storage accountBalance = accountBalances[_adr];
if(!accountBalance.wasModifiedInRoundMap[currentRound]){ //allow just push one time per round
accountBalance.mapKeys.push(currentRound);
accountBalance.wasModifiedInRoundMap[currentRound] = true;
}
accountBalance.addressBalance = safeSub(accountBalance.addressBalance, _tokenAmount);
accountBalance.roundBalanceMap[currentRound] = accountBalance.addressBalance;
}
//function that is called when transaction target is an address
function transferToAddress(address _from, address _to, uint256 _value, bytes _data) private returns (bool success) {
if(accountBalances[_from].addressBalance < _value){ // Check if the sender has enough
revert();
}
if(safeAdd(accountBalances[_to].addressBalance, _value) < accountBalances[_to].addressBalance){ // Check for overflows
revert();
}
isNewRound();
subFromAddressBalancesInfo(_from, _value); // Subtract from the sender
addToAddressBalancesInfo(_to, _value); // Add the same to the recipient
/* Notify anyone listening that this transfer took place */
Transfer(_from, _to, _value, _data);
Transfer(_from, _to, _value);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _from, address _to, uint256 _value, bytes _data) private returns (bool success) {
if(accountBalances[_from].addressBalance < _value){ // Check if the sender has enough
revert();
}
if(safeAdd(accountBalances[_to].addressBalance, _value) < accountBalances[_to].addressBalance){ // Check for overflows
revert();
}
isNewRound();
subFromAddressBalancesInfo(_from, _value); // Subtract from the sender
addToAddressBalancesInfo(_to, _value); // Add the same to the recipient
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(_from, _value, _data);
/* Notify anyone listening that this transfer took place */
Transfer(_from, _to, _value, _data);
Transfer(_from, _to, _value);
return true;
}
} | Function that is called when a user or another contract wants to transfer funds .Override/ | function transfer(address _to, uint256 _value, bytes _data) public whenNotPaused notSelf(_to) returns (bool success){
require(_to != address(0));
if(isContract(_to)) {
return transferToContract(msg.sender, _to, _value, _data);
}
else {
return transferToAddress(msg.sender, _to, _value, _data);
}
}
| 6,212,654 |
pragma solidity >=0.5.4 <0.6.0;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; }
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
/**
* @dev Checks if msg.sender is in whitelist.
*/
modifier inWhitelist() {
require (whitelist[msg.sender] == true);
_;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public {
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public {
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
/**
* @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;
}
}
interface INameAccountRecovery {
function isCompromised(address _id) external view returns (bool);
}
interface INamePublicKey {
function initialize(address _id, address _defaultKey, address _writerKey) external returns (bool);
function isKeyExist(address _id, address _key) external view returns (bool);
function getDefaultKey(address _id) external view returns (address);
function whitelistAddKey(address _id, address _key) external returns (bool);
}
interface INameTAOPosition {
function senderIsAdvocate(address _sender, address _id) external view returns (bool);
function senderIsListener(address _sender, address _id) external view returns (bool);
function senderIsSpeaker(address _sender, address _id) external view returns (bool);
function senderIsPosition(address _sender, address _id) external view returns (bool);
function getAdvocate(address _id) external view returns (address);
function nameIsAdvocate(address _nameId, address _id) external view returns (bool);
function nameIsPosition(address _nameId, address _id) external view returns (bool);
function initialize(address _id, address _advocateId, address _listenerId, address _speakerId) external returns (bool);
function determinePosition(address _sender, address _id) external view returns (uint256);
}
interface IAOSetting {
function getSettingValuesByTAOName(address _taoId, string calldata _settingName) external view returns (uint256, bool, address, bytes32, string memory);
function getSettingTypes() external view returns (uint8, uint8, uint8, uint8, uint8);
function settingTypeLookup(uint256 _settingId) external view returns (uint8);
}
interface IAOIonLot {
function createPrimordialLot(address _account, uint256 _primordialAmount, uint256 _multiplier, uint256 _networkBonusAmount) external returns (bytes32);
function createWeightedMultiplierLot(address _account, uint256 _amount, uint256 _weightedMultiplier) external returns (bytes32);
function lotById(bytes32 _lotId) external view returns (bytes32, address, uint256, uint256);
function totalLotsByAddress(address _lotOwner) external view returns (uint256);
function createBurnLot(address _account, uint256 _amount, uint256 _multiplierAfterBurn) external returns (bool);
function createConvertLot(address _account, uint256 _amount, uint256 _multiplierAfterConversion) external returns (bool);
}
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string memory tokenName, string memory tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/**
* @title TAO
*/
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
/**
* 0 = TAO
* 1 = Name
*/
uint8 public typeId;
/**
* @dev Constructor function
*/
constructor (string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
/**
* @dev Checks if calling address is Vault contract
*/
modifier onlyVault {
require (msg.sender == vaultAddress);
_;
}
/**
* Will receive any ETH sent
*/
function () external payable {
}
/**
* @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferEth(address payable _recipient, uint256 _amount) public onlyVault returns (bool) {
_recipient.transfer(_amount);
return true;
}
/**
* @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.transfer(_recipient, _amount);
return true;
}
}
/**
* @title Name
*/
contract Name is TAO {
/**
* @dev Constructor function
*/
constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
/**
* @title AOLibrary
*/
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1
uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000
/**
* @dev Check whether or not the given TAO ID is a TAO
* @param _taoId The ID of the TAO
* @return true if yes. false otherwise
*/
function isTAO(address _taoId) public view returns (bool) {
return (_taoId != address(0) && bytes(TAO(address(uint160(_taoId))).name()).length > 0 && TAO(address(uint160(_taoId))).originId() != address(0) && TAO(address(uint160(_taoId))).typeId() == 0);
}
/**
* @dev Check whether or not the given Name ID is a Name
* @param _nameId The ID of the Name
* @return true if yes. false otherwise
*/
function isName(address _nameId) public view returns (bool) {
return (_nameId != address(0) && bytes(TAO(address(uint160(_nameId))).name()).length > 0 && Name(address(uint160(_nameId))).originId() != address(0) && Name(address(uint160(_nameId))).typeId() == 1);
}
/**
* @dev Check if `_tokenAddress` is a valid ERC20 Token address
* @param _tokenAddress The ERC20 Token address to check
*/
function isValidERC20TokenAddress(address _tokenAddress) public view returns (bool) {
if (_tokenAddress == address(0)) {
return false;
}
TokenERC20 _erc20 = TokenERC20(_tokenAddress);
return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
* @param _sender The address to check
* @param _theAO The AO address
* @param _nameTAOPositionAddress The address of NameTAOPosition
* @return true if yes, false otherwise
*/
function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {
return (_sender == _theAO ||
(
(isTAO(_theAO) || isName(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
INameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)
)
);
}
/**
* @dev Return the divisor used to correctly calculate percentage.
* Percentage stored throughout AO contracts covers 4 decimals,
* so 1% is 10000, 1.25% is 12500, etc
*/
function PERCENTAGE_DIVISOR() public pure returns (uint256) {
return _PERCENTAGE_DIVISOR;
}
/**
* @dev Return the divisor used to correctly calculate multiplier.
* Multiplier stored throughout AO contracts covers 6 decimals,
* so 1 is 1000000, 0.023 is 23000, etc
*/
function MULTIPLIER_DIVISOR() public pure returns (uint256) {
return _MULTIPLIER_DIVISOR;
}
/**
* @dev deploy a TAO
* @param _name The name of the TAO
* @param _originId The Name ID the creates the TAO
* @param _datHash The datHash of this TAO
* @param _database The database for this TAO
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this TAO
* @param _nameTAOVaultAddress The address of NameTAOVault
*/
function deployTAO(string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (TAO _tao) {
_tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
/**
* @dev deploy a Name
* @param _name The name of the Name
* @param _originId The eth address the creates the Name
* @param _datHash The datHash of this Name
* @param _database The database for this Name
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this Name
* @param _nameTAOVaultAddress The address of NameTAOVault
*/
function deployName(string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (Name _myName) {
_myName = new Name(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
/**
* @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier`
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _currentPrimordialBalance Account's current primordial ion balance
* @param _additionalWeightedMultiplier The weighted multiplier to be added
* @param _additionalPrimordialAmount The primordial ion amount to be added
* @return the new primordial weighted multiplier
*/
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedIons = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));
uint256 _totalIons = _currentPrimordialBalance.add(_additionalPrimordialAmount);
return _totalWeightedIons.div(_totalIons);
} else {
return _additionalWeightedMultiplier;
}
}
/**
* @dev Calculate the primordial ion multiplier on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Multiplier = S
* Ending Multiplier = E
* To Purchase = P
* Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E)
*
* @param _purchaseAmount The amount of primordial ion intended to be purchased
* @param _totalPrimordialMintable Total Primordial ion mintable
* @param _totalPrimordialMinted Total Primordial ion minted so far
* @param _startingMultiplier The starting multiplier in (10 ** 6)
* @param _endingMultiplier The ending multiplier in (10 ** 6)
* @return The multiplier in (10 ** 6)
*/
function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* Multiplier = (1 - (temp / T)) x (S-E)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals
* so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E)
* Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR
* Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR
* Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation
* Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)
*/
uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier));
/**
* Since _startingMultiplier and _endingMultiplier are in 6 decimals
* Need to divide multiplier by _MULTIPLIER_DIVISOR
*/
return multiplier.div(_MULTIPLIER_DIVISOR);
} else {
return 0;
}
}
/**
* @dev Calculate the bonus percentage of network ion on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Network Bonus Multiplier = Bs
* Ending Network Bonus Multiplier = Be
* To Purchase = P
* AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be)
*
* @param _purchaseAmount The amount of primordial ion intended to be purchased
* @param _totalPrimordialMintable Total Primordial ion intable
* @param _totalPrimordialMinted Total Primordial ion minted so far
* @param _startingMultiplier The starting Network ion bonus multiplier
* @param _endingMultiplier The ending Network ion bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* B% = (1 - (temp / T)) x (Bs-Be)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals
* so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be)
* B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)
* But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR
*/
uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR);
return bonusPercentage;
} else {
return 0;
}
}
/**
* @dev Calculate the bonus amount of network ion on a given lot
* AO Bonus Amount = B% x P
*
* @param _purchaseAmount The amount of primordial ion intended to be purchased
* @param _totalPrimordialMintable Total Primordial ion intable
* @param _totalPrimordialMinted Total Primordial ion minted so far
* @param _startingMultiplier The starting Network ion bonus multiplier
* @param _endingMultiplier The ending Network ion bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
/**
* Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
* when calculating the network ion bonus amount
*/
uint256 networkBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkBonus;
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _maximumMultiplier = S
* _amountToBurn = B
* B = ((S x P) - (P x M)) / S
*
* @param _primordialBalance Account's primordial ion balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _maximumMultiplier The maximum multiplier of this account
* @return The maximum burn amount
*/
function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) {
return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier);
}
/**
* @dev Calculate the new multiplier after burning primordial ion
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToBurn = B
* _newMultiplier = E
* E = (P x M) / (P - B)
*
* @param _primordialBalance Account's primordial ion balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToBurn The amount of primordial ion to burn
* @return The new multiplier
*/
function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn));
}
/**
* @dev Calculate the new multiplier after converting network ion to primordial ion
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToConvert = C
* _newMultiplier = E
* E = (P x M) / (P + C)
*
* @param _primordialBalance Account's primordial ion balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToConvert The amount of network ion to convert
* @return The new multiplier
*/
function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert));
}
/**
* @dev count num of digits
* @param number uint256 of the nuumber to be checked
* @return uint8 num of digits
*/
function numDigits(uint256 number) public pure returns (uint8) {
uint8 digits = 0;
while(number != 0) {
number = number.div(10);
digits++;
}
return digits;
}
}
interface ionRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external;
}
/**
* @title AOIonInterface
*/
contract AOIonInterface is TheAO {
using SafeMath for uint256;
address public namePublicKeyAddress;
address public nameAccountRecoveryAddress;
INameTAOPosition internal _nameTAOPosition;
INamePublicKey internal _namePublicKey;
INameAccountRecovery internal _nameAccountRecovery;
// Public variables of the contract
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// To differentiate denomination of AO
uint256 public powerOfTen;
/***** NETWORK ION VARIABLES *****/
uint256 public sellPrice;
uint256 public buyPrice;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public stakedBalance;
mapping (address => uint256) public escrowedBalance;
// This generates a public event on the blockchain that will notify clients
event FrozenFunds(address target, bool frozen);
event Stake(address indexed from, uint256 value);
event Unstake(address indexed from, uint256 value);
event Escrow(address indexed from, address indexed to, uint256 value);
event Unescrow(address indexed from, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* @dev Constructor function
*/
constructor(string memory _name, string memory _symbol, address _nameTAOPositionAddress, address _namePublicKeyAddress, address _nameAccountRecoveryAddress) public {
setNameTAOPositionAddress(_nameTAOPositionAddress);
setNamePublicKeyAddress(_namePublicKeyAddress);
setNameAccountRecoveryAddress(_nameAccountRecoveryAddress);
name = _name; // Set the name for display purposes
symbol = _symbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = INameTAOPosition(nameTAOPositionAddress);
}
/**
* @dev The AO set the NamePublicKey Address
* @param _namePublicKeyAddress The address of NamePublicKey
*/
function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO {
require (_namePublicKeyAddress != address(0));
namePublicKeyAddress = _namePublicKeyAddress;
_namePublicKey = INamePublicKey(namePublicKeyAddress);
}
/**
* @dev The AO set the NameAccountRecovery Address
* @param _nameAccountRecoveryAddress The address of NameAccountRecovery
*/
function setNameAccountRecoveryAddress(address _nameAccountRecoveryAddress) public onlyTheAO {
require (_nameAccountRecoveryAddress != address(0));
nameAccountRecoveryAddress = _nameAccountRecoveryAddress;
_nameAccountRecovery = INameAccountRecovery(nameAccountRecoveryAddress);
}
/**
* @dev Allows TheAO to transfer `_amount` of ETH from this address to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
*/
function transferEth(address payable _recipient, uint256 _amount) public onlyTheAO {
require (_recipient != address(0));
_recipient.transfer(_amount);
}
/**
* @dev Prevent/Allow target from sending & receiving ions
* @param target Address to be frozen
* @param freeze Either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyTheAO {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/**
* @dev Allow users to buy ions for `newBuyPrice` eth and sell ions for `newSellPrice` eth
* @param newSellPrice Price users can sell to the contract
* @param newBuyPrice Price users can buy from the contract
*/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/***** NETWORK ION WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Create `mintedAmount` ions and send it to `target`
* @param target Address to receive the ions
* @param mintedAmount The amount of ions it will receive
* @return true on success
*/
function mint(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
_mint(target, mintedAmount);
return true;
}
/**
* @dev Stake `_value` ions on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to stake
* @return true on success
*/
function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance
emit Stake(_from, _value);
return true;
}
/**
* @dev Unstake `_value` ions on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @return true on success
*/
function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough
stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unstake(_from, _value);
return true;
}
/**
* @dev Store `_value` from `_from` to `_to` in escrow
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network ions to put in escrow
* @return true on success
*/
function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance
emit Escrow(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` ions and send it to `target` escrow balance
* @param target Address to receive ions
* @param mintedAmount The amount of ions it will receive in escrow
*/
function mintEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
escrowedBalance[target] = escrowedBalance[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Escrow(address(this), target, mintedAmount);
return true;
}
/**
* @dev Release escrowed `_value` from `_from`
* @param _from The address of the sender
* @param _value The amount of escrowed network ions to be released
* @return true on success
*/
function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough
escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unescrow(_from, _value);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` ions from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Whitelisted address transfer ions from other address
*
* Send `_value` ions to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) {
_transfer(_from, _to, _value);
return true;
}
/***** PUBLIC METHODS *****/
/**
* Transfer ions
*
* Send `_value` ions to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer ions from other address
*
* Send `_value` ions to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Transfer ions between public key addresses in a Name
* @param _nameId The ID of the Name
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool success) {
require (AOLibrary.isName(_nameId));
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId));
require (!_nameAccountRecovery.isCompromised(_nameId));
// Make sure _from exist in the Name's Public Keys
require (_namePublicKey.isKeyExist(_nameId, _from));
// Make sure _to exist in the Name's Public Keys
require (_namePublicKey.isKeyExist(_nameId, _to));
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` ions in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` ions in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {
ionRecipient spender = ionRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* Destroy ions
*
* Remove `_value` ions from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy ions from other account
*
* Remove `_value` ions from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Buy ions from contract by sending ether
*/
function buy() public payable {
require (buyPrice > 0);
uint256 amount = msg.value.div(buyPrice);
_transfer(address(this), msg.sender, amount);
}
/**
* @dev Sell `amount` ions to contract
* @param amount The amount of ions to be sold
*/
function sell(uint256 amount) public {
require (sellPrice > 0);
address myAddress = address(this);
require (myAddress.balance >= amount.mul(sellPrice));
_transfer(msg.sender, address(this), amount);
msg.sender.transfer(amount.mul(sellPrice));
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` ions from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` ions and send it to `target`
* @param target Address to receive the ions
* @param mintedAmount The amount of ions it will receive
*/
function _mint(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(address(0), address(this), mintedAmount);
emit Transfer(address(this), target, mintedAmount);
}
}
/**
* @title AOETH
*/
contract AOETH is TheAO, TokenERC20, tokenRecipient {
using SafeMath for uint256;
address public aoIonAddress;
AOIon internal _aoIon;
uint256 public totalERC20Tokens;
uint256 public totalTokenExchanges;
struct ERC20Token {
address tokenAddress;
uint256 price; // price of this ERC20 Token to AOETH
uint256 maxQuantity; // To prevent too much exposure to a given asset
uint256 exchangedQuantity; // Running total (total AOETH exchanged from this specific ERC20 Token)
bool active;
}
struct TokenExchange {
bytes32 exchangeId;
address buyer; // The buyer address
address tokenAddress; // The address of ERC20 Token
uint256 price; // price of ERC20 Token to AOETH
uint256 sentAmount; // Amount of ERC20 Token sent
uint256 receivedAmount; // Amount of AOETH received
bytes extraData; // Extra data
}
// Mapping from id to ERC20Token object
mapping (uint256 => ERC20Token) internal erc20Tokens;
mapping (address => uint256) internal erc20TokenIdLookup;
// Mapping from id to TokenExchange object
mapping (uint256 => TokenExchange) internal tokenExchanges;
mapping (bytes32 => uint256) internal tokenExchangeIdLookup;
mapping (address => uint256) public totalAddressTokenExchanges;
// Event to be broadcasted to public when TheAO adds an ERC20 Token
event AddERC20Token(address indexed tokenAddress, uint256 price, uint256 maxQuantity);
// Event to be broadcasted to public when TheAO sets price for ERC20 Token
event SetPrice(address indexed tokenAddress, uint256 price);
// Event to be broadcasted to public when TheAO sets max quantity for ERC20 Token
event SetMaxQuantity(address indexed tokenAddress, uint256 maxQuantity);
// Event to be broadcasted to public when TheAO sets active status for ERC20 Token
event SetActive(address indexed tokenAddress, bool active);
// Event to be broadcasted to public when user exchanges ERC20 Token for AOETH
event ExchangeToken(bytes32 indexed exchangeId, address indexed from, address tokenAddress, string tokenName, string tokenSymbol, uint256 sentTokenAmount, uint256 receivedAOETHAmount, bytes extraData);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string memory tokenName, string memory tokenSymbol, address _aoIonAddress, address _nameTAOPositionAddress)
TokenERC20(initialSupply, tokenName, tokenSymbol) public {
setAOIonAddress(_aoIonAddress);
setNameTAOPositionAddress(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the AOIon Address
* @param _aoIonAddress The address of AOIon
*/
function setAOIonAddress(address _aoIonAddress) public onlyTheAO {
require (_aoIonAddress != address(0));
aoIonAddress = _aoIonAddress;
_aoIon = AOIon(_aoIonAddress);
}
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Allows TheAO to transfer `_amount` of ERC20 Token from this address to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyTheAO {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
require (_erc20.transfer(_recipient, _amount));
}
/**
* @dev Add an ERC20 Token to the list
* @param _tokenAddress The address of the ERC20 Token
* @param _price The price of this token to AOETH
* @param _maxQuantity Maximum quantity allowed for exchange
*/
function addERC20Token(address _tokenAddress, uint256 _price, uint256 _maxQuantity) public onlyTheAO {
require (_tokenAddress != address(0) && _price > 0 && _maxQuantity > 0);
require (AOLibrary.isValidERC20TokenAddress(_tokenAddress));
require (erc20TokenIdLookup[_tokenAddress] == 0);
totalERC20Tokens++;
erc20TokenIdLookup[_tokenAddress] = totalERC20Tokens;
ERC20Token storage _erc20Token = erc20Tokens[totalERC20Tokens];
_erc20Token.tokenAddress = _tokenAddress;
_erc20Token.price = _price;
_erc20Token.maxQuantity = _maxQuantity;
_erc20Token.active = true;
emit AddERC20Token(_erc20Token.tokenAddress, _erc20Token.price, _erc20Token.maxQuantity);
}
/**
* @dev Set price for existing ERC20 Token
* @param _tokenAddress The address of the ERC20 Token
* @param _price The price of this token to AOETH
*/
function setPrice(address _tokenAddress, uint256 _price) public onlyTheAO {
require (erc20TokenIdLookup[_tokenAddress] > 0);
require (_price > 0);
ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_tokenAddress]];
_erc20Token.price = _price;
emit SetPrice(_erc20Token.tokenAddress, _erc20Token.price);
}
/**
* @dev Set max quantity for existing ERC20 Token
* @param _tokenAddress The address of the ERC20 Token
* @param _maxQuantity The max exchange quantity for this token
*/
function setMaxQuantity(address _tokenAddress, uint256 _maxQuantity) public onlyTheAO {
require (erc20TokenIdLookup[_tokenAddress] > 0);
ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_tokenAddress]];
require (_maxQuantity > _erc20Token.exchangedQuantity);
_erc20Token.maxQuantity = _maxQuantity;
emit SetMaxQuantity(_erc20Token.tokenAddress, _erc20Token.maxQuantity);
}
/**
* @dev Set active status for existing ERC20 Token
* @param _tokenAddress The address of the ERC20 Token
* @param _active The active status for this token
*/
function setActive(address _tokenAddress, bool _active) public onlyTheAO {
require (erc20TokenIdLookup[_tokenAddress] > 0);
ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_tokenAddress]];
_erc20Token.active = _active;
emit SetActive(_erc20Token.tokenAddress, _erc20Token.active);
}
/**
* @dev Whitelisted address transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) {
_transfer(_from, _to, _value);
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get an ERC20 Token information given an ID
* @param _id The internal ID of the ERC20 Token
* @return The ERC20 Token address
* @return The name of the token
* @return The symbol of the token
* @return The price of this token to AOETH
* @return The max quantity for exchange
* @return The total AOETH exchanged from this token
* @return The status of this token
*/
function getById(uint256 _id) public view returns (address, string memory, string memory, uint256, uint256, uint256, bool) {
require (erc20Tokens[_id].tokenAddress != address(0));
ERC20Token memory _erc20Token = erc20Tokens[_id];
return (
_erc20Token.tokenAddress,
TokenERC20(_erc20Token.tokenAddress).name(),
TokenERC20(_erc20Token.tokenAddress).symbol(),
_erc20Token.price,
_erc20Token.maxQuantity,
_erc20Token.exchangedQuantity,
_erc20Token.active
);
}
/**
* @dev Get an ERC20 Token information given an address
* @param _tokenAddress The address of the ERC20 Token
* @return The ERC20 Token address
* @return The name of the token
* @return The symbol of the token
* @return The price of this token to AOETH
* @return The max quantity for exchange
* @return The total AOETH exchanged from this token
* @return The status of this token
*/
function getByAddress(address _tokenAddress) public view returns (address, string memory, string memory, uint256, uint256, uint256, bool) {
require (erc20TokenIdLookup[_tokenAddress] > 0);
return getById(erc20TokenIdLookup[_tokenAddress]);
}
/**
* @dev When a user approves AOETH to spend on his/her behalf (i.e exchange to AOETH)
* @param _from The user address that approved AOETH
* @param _value The amount that the user approved
* @param _token The address of the ERC20 Token
* @param _extraData The extra data sent during the approval
*/
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external {
require (_from != address(0));
require (AOLibrary.isValidERC20TokenAddress(_token));
// Check if the token is supported
require (erc20TokenIdLookup[_token] > 0);
ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_token]];
require (_erc20Token.active && _erc20Token.price > 0 && _erc20Token.exchangedQuantity < _erc20Token.maxQuantity);
uint256 amountToTransfer = _value.div(_erc20Token.price);
require (_erc20Token.maxQuantity.sub(_erc20Token.exchangedQuantity) >= amountToTransfer);
require (_aoIon.availableETH() >= amountToTransfer);
// Transfer the ERC20 Token from the `_from` address to here
require (TokenERC20(_token).transferFrom(_from, address(this), _value));
_erc20Token.exchangedQuantity = _erc20Token.exchangedQuantity.add(amountToTransfer);
balanceOf[_from] = balanceOf[_from].add(amountToTransfer);
totalSupply = totalSupply.add(amountToTransfer);
// Store the TokenExchange information
totalTokenExchanges++;
totalAddressTokenExchanges[_from]++;
bytes32 _exchangeId = keccak256(abi.encodePacked(this, _from, totalTokenExchanges));
tokenExchangeIdLookup[_exchangeId] = totalTokenExchanges;
TokenExchange storage _tokenExchange = tokenExchanges[totalTokenExchanges];
_tokenExchange.exchangeId = _exchangeId;
_tokenExchange.buyer = _from;
_tokenExchange.tokenAddress = _token;
_tokenExchange.price = _erc20Token.price;
_tokenExchange.sentAmount = _value;
_tokenExchange.receivedAmount = amountToTransfer;
_tokenExchange.extraData = _extraData;
emit ExchangeToken(_tokenExchange.exchangeId, _tokenExchange.buyer, _tokenExchange.tokenAddress, TokenERC20(_token).name(), TokenERC20(_token).symbol(), _tokenExchange.sentAmount, _tokenExchange.receivedAmount, _tokenExchange.extraData);
}
/**
* @dev Get TokenExchange information given an exchange ID
* @param _exchangeId The exchange ID to query
* @return The buyer address
* @return The sent ERC20 Token address
* @return The ERC20 Token name
* @return The ERC20 Token symbol
* @return The price of ERC20 Token to AOETH
* @return The amount of ERC20 Token sent
* @return The amount of AOETH received
* @return Extra data during the transaction
*/
function getTokenExchangeById(bytes32 _exchangeId) public view returns (address, address, string memory, string memory, uint256, uint256, uint256, bytes memory) {
require (tokenExchangeIdLookup[_exchangeId] > 0);
TokenExchange memory _tokenExchange = tokenExchanges[tokenExchangeIdLookup[_exchangeId]];
return (
_tokenExchange.buyer,
_tokenExchange.tokenAddress,
TokenERC20(_tokenExchange.tokenAddress).name(),
TokenERC20(_tokenExchange.tokenAddress).symbol(),
_tokenExchange.price,
_tokenExchange.sentAmount,
_tokenExchange.receivedAmount,
_tokenExchange.extraData
);
}
}
/**
* @title AOIon
*/
contract AOIon is AOIonInterface {
using SafeMath for uint256;
address public aoIonLotAddress;
address public settingTAOId;
address public aoSettingAddress;
address public aoethAddress;
// AO Dev Team addresses to receive Primordial/Network Ions
address public aoDevTeam1 = 0x146CbD9821e6A42c8ff6DC903fe91CB69625A105;
address public aoDevTeam2 = 0x4810aF1dA3aC827259eEa72ef845F4206C703E8D;
IAOIonLot internal _aoIonLot;
IAOSetting internal _aoSetting;
AOETH internal _aoeth;
/***** PRIMORDIAL ION VARIABLES *****/
uint256 public primordialTotalSupply;
uint256 public primordialTotalBought;
uint256 public primordialSellPrice;
uint256 public primordialBuyPrice;
uint256 public totalEthForPrimordial; // Total ETH sent for Primordial AO+
uint256 public totalRedeemedAOETH; // Total AOETH redeemed for Primordial AO+
// Total available primordial ion for sale 3,377,699,720,527,872 AO+
uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 3377699720527872;
mapping (address => uint256) public primordialBalanceOf;
mapping (address => mapping (address => uint256)) public primordialAllowance;
// Mapping from owner's lot weighted multiplier to the amount of staked ions
mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance;
event PrimordialTransfer(address indexed from, address indexed to, uint256 value);
event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value);
event PrimordialBurn(address indexed from, uint256 value);
event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier);
event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier);
event NetworkExchangeEnded();
bool public networkExchangeEnded;
// Mapping from owner to his/her current weighted multiplier
mapping (address => uint256) internal ownerWeightedMultiplier;
// Mapping from owner to his/her max multiplier (multiplier of account's first Lot)
mapping (address => uint256) internal ownerMaxMultiplier;
// Event to be broadcasted to public when user buys primordial ion
// payWith 1 == with Ethereum
// payWith 2 == with AOETH
event BuyPrimordial(address indexed lotOwner, bytes32 indexed lotId, uint8 payWith, uint256 sentAmount, uint256 refundedAmount);
/**
* @dev Constructor function
*/
constructor(string memory _name, string memory _symbol, address _settingTAOId, address _aoSettingAddress, address _nameTAOPositionAddress, address _namePublicKeyAddress, address _nameAccountRecoveryAddress)
AOIonInterface(_name, _symbol, _nameTAOPositionAddress, _namePublicKeyAddress, _nameAccountRecoveryAddress) public {
setSettingTAOId(_settingTAOId);
setAOSettingAddress(_aoSettingAddress);
powerOfTen = 0;
decimals = 0;
setPrimordialPrices(0, 10 ** 8); // Set Primordial buy price to 0.1 gwei/ion
}
/**
* @dev Checks if buyer can buy primordial ion
*/
modifier canBuyPrimordial(uint256 _sentAmount, bool _withETH) {
require (networkExchangeEnded == false &&
primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE &&
primordialBuyPrice > 0 &&
_sentAmount > 0 &&
availablePrimordialForSaleInETH() > 0 &&
(
(_withETH && availableETH() > 0) ||
(!_withETH && totalRedeemedAOETH < _aoeth.totalSupply())
)
);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO sets AOIonLot address
* @param _aoIonLotAddress The address of AOIonLot
*/
function setAOIonLotAddress(address _aoIonLotAddress) public onlyTheAO {
require (_aoIonLotAddress != address(0));
aoIonLotAddress = _aoIonLotAddress;
_aoIonLot = IAOIonLot(_aoIonLotAddress);
}
/**
* @dev The AO sets setting TAO ID
* @param _settingTAOId The new setting TAO ID to set
*/
function setSettingTAOId(address _settingTAOId) public onlyTheAO {
require (AOLibrary.isTAO(_settingTAOId));
settingTAOId = _settingTAOId;
}
/**
* @dev The AO sets AO Setting address
* @param _aoSettingAddress The address of AOSetting
*/
function setAOSettingAddress(address _aoSettingAddress) public onlyTheAO {
require (_aoSettingAddress != address(0));
aoSettingAddress = _aoSettingAddress;
_aoSetting = IAOSetting(_aoSettingAddress);
}
/**
* @dev Set AO Dev team addresses to receive Primordial/Network ions during network exchange
* @param _aoDevTeam1 The first AO dev team address
* @param _aoDevTeam2 The second AO dev team address
*/
function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO {
aoDevTeam1 = _aoDevTeam1;
aoDevTeam2 = _aoDevTeam2;
}
/**
* @dev Set AOETH address
* @param _aoethAddress The address of AOETH
*/
function setAOETHAddress(address _aoethAddress) public onlyTheAO {
require (_aoethAddress != address(0));
aoethAddress = _aoethAddress;
_aoeth = AOETH(_aoethAddress);
}
/***** PRIMORDIAL ION THE AO ONLY METHODS *****/
/**
* @dev Allow users to buy Primordial ions for `newBuyPrice` eth and sell Primordial ions for `newSellPrice` eth
* @param newPrimordialSellPrice Price users can sell to the contract
* @param newPrimordialBuyPrice Price users can buy from the contract
*/
function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO {
primordialSellPrice = newPrimordialSellPrice;
primordialBuyPrice = newPrimordialBuyPrice;
}
/**
* @dev Only the AO can force end network exchange
*/
function endNetworkExchange() public onlyTheAO {
require (!networkExchangeEnded);
networkExchangeEnded = true;
emit NetworkExchangeEnded();
}
/***** PRIMORDIAL ION WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Stake `_value` Primordial ions at `_weightedMultiplier ` multiplier on behalf of `_from`
* @param _from The address of the target
* @param _value The amount of Primordial ions to stake
* @param _weightedMultiplier The weighted multiplier of the Primordial ions
* @return true on success
*/
function stakePrimordialFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted balance is enough
require (primordialBalanceOf[_from] >= _value);
// Make sure the weighted multiplier is the same as account's current weighted multiplier
require (_weightedMultiplier == ownerWeightedMultiplier[_from]);
// Subtract from the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
// Add to the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value);
emit PrimordialStake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Unstake `_value` Primordial ions at `_weightedMultiplier` on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @param _weightedMultiplier The weighted multiplier of the Primordial ions
* @return true on success
*/
function unstakePrimordialFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted staked balance is enough
require (primordialStakedBalance[_from][_weightedMultiplier] >= _value);
// Subtract from the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value);
// Add to the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value);
emit PrimordialUnstake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Send `_value` primordial ions to `_to` on behalf of `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function whitelistTransferPrimordialFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
return _createLotAndTransferPrimordial(_from, _to, _value);
}
/***** PUBLIC METHODS *****/
/***** PRIMORDIAL ION PUBLIC METHODS *****/
/**
* @dev Buy Primordial ions from contract by sending ether
*/
function buyPrimordial() public payable canBuyPrimordial(msg.value, true) {
(uint256 amount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateAmountAndRemainderBudget(msg.value, true);
require (amount > 0);
// Ends network exchange if necessary
if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
emit NetworkExchangeEnded();
}
// Update totalEthForPrimordial
totalEthForPrimordial = totalEthForPrimordial.add(msg.value.sub(remainderBudget));
// Send the primordial ion to buyer and reward AO devs
bytes32 _lotId = _sendPrimordialAndRewardDev(amount, msg.sender);
emit BuyPrimordial(msg.sender, _lotId, 1, msg.value, remainderBudget);
// Send remainder budget back to buyer if exist
if (remainderBudget > 0) {
msg.sender.transfer(remainderBudget);
}
}
/**
* @dev Buy Primordial ion from contract by sending AOETH
*/
function buyPrimordialWithAOETH(uint256 _aoethAmount) public canBuyPrimordial(_aoethAmount, false) {
(uint256 amount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateAmountAndRemainderBudget(_aoethAmount, false);
require (amount > 0);
// Ends network exchange if necessary
if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
emit NetworkExchangeEnded();
}
// Calculate the actual AOETH that was charged for this transaction
uint256 actualCharge = _aoethAmount.sub(remainderBudget);
// Update totalRedeemedAOETH
totalRedeemedAOETH = totalRedeemedAOETH.add(actualCharge);
// Transfer AOETH from buyer to here
require (_aoeth.whitelistTransferFrom(msg.sender, address(this), actualCharge));
// Send the primordial ion to buyer and reward AO devs
bytes32 _lotId = _sendPrimordialAndRewardDev(amount, msg.sender);
emit BuyPrimordial(msg.sender, _lotId, 2, _aoethAmount, remainderBudget);
}
/**
* @dev Send `_value` Primordial ions to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordial(address _to, uint256 _value) public returns (bool) {
return _createLotAndTransferPrimordial(msg.sender, _to, _value);
}
/**
* @dev Send `_value` Primordial ions to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialFrom(address _from, address _to, uint256 _value) public returns (bool) {
require (_value <= primordialAllowance[_from][msg.sender]);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
return _createLotAndTransferPrimordial(_from, _to, _value);
}
/**
* Transfer primordial ions between public key addresses in a Name
* @param _nameId The ID of the Name
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferPrimordialBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool) {
require (AOLibrary.isName(_nameId));
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId));
require (!_nameAccountRecovery.isCompromised(_nameId));
// Make sure _from exist in the Name's Public Keys
require (_namePublicKey.isKeyExist(_nameId, _from));
// Make sure _to exist in the Name's Public Keys
require (_namePublicKey.isKeyExist(_nameId, _to));
return _createLotAndTransferPrimordial(_from, _to, _value);
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial ions in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @return true on success
*/
function approvePrimordial(address _spender, uint256 _value) public returns (bool) {
primordialAllowance[msg.sender][_spender] = _value;
emit PrimordialApproval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial ions in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approvePrimordialAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool) {
tokenRecipient spender = tokenRecipient(_spender);
if (approvePrimordial(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* @dev Remove `_value` Primordial ions from the system irreversibly
* and re-weight the account's multiplier after burn
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordial(uint256 _value) public returns (bool) {
require (primordialBalanceOf[msg.sender] >= _value);
require (calculateMaximumBurnAmount(msg.sender) >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value);
primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
require (_aoIonLot.createBurnLot(msg.sender, _value, ownerWeightedMultiplier[msg.sender]));
emit PrimordialBurn(msg.sender, _value);
return true;
}
/**
* @dev Remove `_value` Primordial ions from the system irreversibly on behalf of `_from`
* and re-weight `_from`'s multiplier after burn
* @param _from The address of sender
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialFrom(address _from, uint256 _value) public returns (bool) {
require (primordialBalanceOf[_from] >= _value);
require (primordialAllowance[_from][msg.sender] >= _value);
require (calculateMaximumBurnAmount(_from) >= _value);
// Update `_from`'s multiplier
ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
require (_aoIonLot.createBurnLot(_from, _value, ownerWeightedMultiplier[_from]));
emit PrimordialBurn(_from, _value);
return true;
}
/**
* @dev Return the average weighted multiplier of all lots owned by an address
* @param _lotOwner The address of the lot owner
* @return the weighted multiplier of the address (in 10 ** 6)
*/
function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) {
return ownerWeightedMultiplier[_lotOwner];
}
/**
* @dev Return the max multiplier of an address
* @param _target The address to query
* @return the max multiplier of the address (in 10 ** 6)
*/
function maxMultiplierByAddress(address _target) public view returns (uint256) {
return (_aoIonLot.totalLotsByAddress(_target) > 0) ? ownerMaxMultiplier[_target] : 0;
}
/**
* @dev Calculate the primordial ion multiplier, bonus network ion percentage, and the
* bonus network ion amount on a given lot when someone purchases primordial ion
* during network exchange
* @param _purchaseAmount The amount of primordial ion intended to be purchased
* @return The multiplier in (10 ** 6)
* @return The bonus percentage
* @return The amount of network ion as bonus
*/
function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkBonusMultiplier, uint256 endingNetworkBonusMultiplier) = _getSettingVariables();
return (
AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier),
AOLibrary.calculateNetworkBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkBonusMultiplier, endingNetworkBonusMultiplier),
AOLibrary.calculateNetworkBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkBonusMultiplier, endingNetworkBonusMultiplier)
);
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* @param _account The address of the account
* @return The maximum primordial ion amount to burn
*/
function calculateMaximumBurnAmount(address _account) public view returns (uint256) {
return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]);
}
/**
* @dev Calculate account's new multiplier after burn `_amountToBurn` primordial ions
* @param _account The address of the account
* @param _amountToBurn The amount of primordial ion to burn
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) {
require (calculateMaximumBurnAmount(_account) >= _amountToBurn);
return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn);
}
/**
* @dev Calculate account's new multiplier after converting `amountToConvert` network ion to primordial ion
* @param _account The address of the account
* @param _amountToConvert The amount of network ion to convert
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) {
return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert);
}
/**
* @dev Convert `_value` of network ions to primordial ions
* and re-weight the account's multiplier after conversion
* @param _value The amount to convert
* @return true on success
*/
function convertToPrimordial(uint256 _value) public returns (bool) {
require (balanceOf[msg.sender] >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value);
// Burn network ion
burn(_value);
// mint primordial ion
_mintPrimordial(msg.sender, _value);
require (_aoIonLot.createConvertLot(msg.sender, _value, ownerWeightedMultiplier[msg.sender]));
return true;
}
/**
* @dev Get quantity of AO+ left in Network Exchange
* @return The quantity of AO+ left in Network Exchange
*/
function availablePrimordialForSale() public view returns (uint256) {
return TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought);
}
/**
* @dev Get quantity of AO+ in ETH left in Network Exchange (i.e How much ETH is there total that can be
* exchanged for AO+
* @return The quantity of AO+ in ETH left in Network Exchange
*/
function availablePrimordialForSaleInETH() public view returns (uint256) {
return availablePrimordialForSale().mul(primordialBuyPrice);
}
/**
* @dev Get maximum quantity of AOETH or ETH that can still be sold
* @return The maximum quantity of AOETH or ETH that can still be sold
*/
function availableETH() public view returns (uint256) {
if (availablePrimordialForSaleInETH() > 0) {
uint256 _availableETH = availablePrimordialForSaleInETH().sub(_aoeth.totalSupply().sub(totalRedeemedAOETH));
if (availablePrimordialForSale() == 1 && _availableETH < primordialBuyPrice) {
return primordialBuyPrice;
} else {
return _availableETH;
}
} else {
return 0;
}
}
/***** INTERNAL METHODS *****/
/***** PRIMORDIAL ION INTERNAL METHODS *****/
/**
* @dev Calculate the amount of ion the buyer will receive and remaining budget if exist
* when he/she buys primordial ion
* @param _budget The amount of ETH sent by buyer
* @param _withETH Whether or not buyer is paying with ETH
* @return uint256 of the amount the buyer will receiver
* @return uint256 of the remaining budget, if exist
* @return bool whether or not the network exchange should end
*/
function _calculateAmountAndRemainderBudget(uint256 _budget, bool _withETH) internal view returns (uint256, uint256, bool) {
// Calculate the amount of ion
uint256 amount = _budget.div(primordialBuyPrice);
// If we need to return ETH to the buyer, in the case
// where the buyer sends more ETH than available primordial ion to be purchased
uint256 remainderEth = _budget.sub(amount.mul(primordialBuyPrice));
uint256 _availableETH = availableETH();
// If paying with ETH, it can't exceed availableETH
if (_withETH && _budget > availableETH()) {
// Calculate the amount of ions
amount = _availableETH.div(primordialBuyPrice);
remainderEth = _budget.sub(amount.mul(primordialBuyPrice));
}
// Make sure primordialTotalBought is not overflowing
bool shouldEndNetworkExchange = false;
if (primordialTotalBought.add(amount) >= TOTAL_PRIMORDIAL_FOR_SALE) {
amount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought);
shouldEndNetworkExchange = true;
remainderEth = _budget.sub(amount.mul(primordialBuyPrice));
}
return (amount, remainderEth, shouldEndNetworkExchange);
}
/**
* @dev Actually sending the primordial ion to buyer and reward AO devs accordingly
* @param amount The amount of primordial ion to be sent to buyer
* @param to The recipient of ion
* @return the lot Id of the buyer
*/
function _sendPrimordialAndRewardDev(uint256 amount, address to) internal returns (bytes32) {
(uint256 startingPrimordialMultiplier,, uint256 startingNetworkBonusMultiplier, uint256 endingNetworkBonusMultiplier) = _getSettingVariables();
// Update primordialTotalBought
(uint256 multiplier, uint256 networkBonusPercentage, uint256 networkBonusAmount) = calculateMultiplierAndBonus(amount);
primordialTotalBought = primordialTotalBought.add(amount);
bytes32 _lotId = _createPrimordialLot(to, amount, multiplier, networkBonusAmount);
// Calculate The AO and AO Dev Team's portion of Primordial and Network ion Bonus
uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier
uint256 theAONetworkBonusAmount = (startingNetworkBonusMultiplier.sub(networkBonusPercentage).add(endingNetworkBonusMultiplier)).mul(amount).div(AOLibrary.PERCENTAGE_DIVISOR());
if (aoDevTeam1 != address(0)) {
_createPrimordialLot(aoDevTeam1, amount.div(2), inverseMultiplier, theAONetworkBonusAmount.div(2));
}
if (aoDevTeam2 != address(0)) {
_createPrimordialLot(aoDevTeam2, amount.div(2), inverseMultiplier, theAONetworkBonusAmount.div(2));
}
_mint(theAO, theAONetworkBonusAmount);
return _lotId;
}
/**
* @dev Create a lot with `primordialAmount` of primordial ions with `_multiplier` for an `account`
* during network exchange, and reward `_networkBonusAmount` if exist
* @param _account Address of the lot owner
* @param _primordialAmount The amount of primordial ions to be stored in the lot
* @param _multiplier The multiplier for this lot in (10 ** 6)
* @param _networkBonusAmount The network ion bonus amount
* @return Created lot Id
*/
function _createPrimordialLot(address _account, uint256 _primordialAmount, uint256 _multiplier, uint256 _networkBonusAmount) internal returns (bytes32) {
bytes32 lotId = _aoIonLot.createPrimordialLot(_account, _primordialAmount, _multiplier, _networkBonusAmount);
ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], _multiplier, _primordialAmount);
// If this is the first lot, set this as the max multiplier of the account
if (_aoIonLot.totalLotsByAddress(_account) == 1) {
ownerMaxMultiplier[_account] = _multiplier;
}
_mintPrimordial(_account, _primordialAmount);
_mint(_account, _networkBonusAmount);
return lotId;
}
/**
* @dev Create `mintedAmount` Primordial ions and send it to `target`
* @param target Address to receive the Primordial ions
* @param mintedAmount The amount of Primordial ions it will receive
*/
function _mintPrimordial(address target, uint256 mintedAmount) internal {
primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount);
primordialTotalSupply = primordialTotalSupply.add(mintedAmount);
emit PrimordialTransfer(address(0), address(this), mintedAmount);
emit PrimordialTransfer(address(this), target, mintedAmount);
}
/**
* @dev Create a lot with `amount` of ions at `weightedMultiplier` for an `account`
* @param _account Address of lot owner
* @param _amount The amount of ions
* @param _weightedMultiplier The multiplier of the lot (in 10^6)
* @return bytes32 of new created lot ID
*/
function _createWeightedMultiplierLot(address _account, uint256 _amount, uint256 _weightedMultiplier) internal returns (bytes32) {
require (_account != address(0));
require (_amount > 0);
bytes32 lotId = _aoIonLot.createWeightedMultiplierLot(_account, _amount, _weightedMultiplier);
// If this is the first lot, set this as the max multiplier of the account
if (_aoIonLot.totalLotsByAddress(_account) == 1) {
ownerMaxMultiplier[_account] = _weightedMultiplier;
}
return lotId;
}
/**
* @dev Create Lot and send `_value` Primordial ions from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function _createLotAndTransferPrimordial(address _from, address _to, uint256 _value) internal returns (bool) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
(, address _lotOwner,,) = _aoIonLot.lotById(_createdLotId);
// Make sure the new lot is created successfully
require (_lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial ions
require (_transferPrimordial(_from, _to, _value));
return true;
}
/**
* @dev Send `_value` Primordial ions from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transferPrimordial(address _from, address _to, uint256 _value) internal returns (bool) {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough
require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender
primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient
emit PrimordialTransfer(_from, _to, _value);
assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances);
return true;
}
/**
* @dev Get setting variables
* @return startingPrimordialMultiplier The starting multiplier used to calculate primordial ion
* @return endingPrimordialMultiplier The ending multiplier used to calculate primordial ion
* @return startingNetworkBonusMultiplier The starting multiplier used to calculate network ion bonus
* @return endingNetworkBonusMultiplier The ending multiplier used to calculate network ion bonus
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier');
(uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier');
(uint256 startingNetworkBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkBonusMultiplier');
(uint256 endingNetworkBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkBonusMultiplier');
return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkBonusMultiplier, endingNetworkBonusMultiplier);
}
}
/**
* @title AOPool
*
* This contract acts as the exchange between AO and ETH/ERC-20 compatible tokens
*/
contract AOPool is TheAO {
using SafeMath for uint256;
address public aoIonAddress;
AOIon internal _aoIon;
struct Pool {
uint256 price; // Flat price of AO
/**
* If true, Pool is live and can be sold into.
* Otherwise, Pool cannot be sold into.
*/
bool status;
/**
* If true, has sell cap. Otherwise, no sell cap.
*/
bool sellCapStatus;
/**
* Denominated in AO, creates a cap for the amount of AO that can be
* put up for sale in this pool at `price`
*/
uint256 sellCapAmount;
/**
* If true, has quantity cap. Otherwise, no quantity cap.
*/
bool quantityCapStatus;
/**
* Denominated in AO, creates a cap for the amount of AO at any given time
* that can be available for sale in this pool
*/
uint256 quantityCapAmount;
/**
* If true, the Pool is priced in an ERC20 compatible token.
* Otherwise, the Pool is priced in Ethereum
*/
bool erc20CounterAsset;
address erc20TokenAddress; // The address of the ERC20 Token
/**
* Used if ERC20 token needs to deviate from Ethereum in multiplication/division
*/
uint256 erc20TokenMultiplier;
address adminAddress; // defaults to TheAO address, but can be modified
}
struct Lot {
bytes32 lotId; // The ID of this Lot
address seller; // Ethereum address of the seller
uint256 lotQuantity; // Amount of AO being added to the Pool from this Lot
uint256 poolId; // Identifier for the Pool this Lot is adding to
uint256 poolPreSellSnapshot; // Amount of contributed to the Pool prior to this Lot Number
uint256 poolSellLotSnapshot; // poolPreSellSnapshot + lotQuantity
uint256 lotValueInCounterAsset; // Amount of AO x Pool Price
uint256 counterAssetWithdrawn; // Amount of Counter-Asset withdrawn from this Lot
uint256 ionWithdrawn; // Amount of AO withdrawn from this Lot
uint256 timestamp;
}
// Contract variables
uint256 public totalPool;
uint256 public contractTotalLot; // Total lot from all pools
uint256 public contractTotalSell; // Quantity of AO that has been contributed to all Pools
uint256 public contractTotalBuy; // Quantity of AO that has been bought from all Pools
uint256 public contractTotalQuantity; // Quantity of AO available to buy from all Pools
uint256 public contractTotalWithdrawn; // Quantity of AO that has been withdrawn from all Pools
uint256 public contractEthereumBalance; // Total Ethereum in contract
uint256 public contractTotalEthereumWithdrawn; // Total Ethereum withdrawn from selling AO in contract
// Mapping from Pool ID to Pool
mapping (uint256 => Pool) public pools;
// Mapping from Lot ID to Lot
mapping (bytes32 => Lot) public lots;
// Mapping from Pool ID to total Lots in the Pool
mapping (uint256 => uint256) public poolTotalLot;
// Mapping from Pool ID to quantity of AO available to buy at `price`
mapping (uint256 => uint256) public poolTotalQuantity;
// Mapping from Pool ID to quantity of AO that has been contributed to the Pool
mapping (uint256 => uint256) public poolTotalSell;
// Mapping from Pool ID to quantity of AO that has been bought from the Pool
mapping (uint256 => uint256) public poolTotalBuy;
// Mapping from Pool ID to quantity of AO that has been withdrawn from the Pool
mapping (uint256 => uint256) public poolTotalWithdrawn;
// Mapping from Pool ID to total Ethereum available to withdraw
mapping (uint256 => uint256) public poolEthereumBalance;
// Mapping from Pool ID to quantity of ERC20 token available to withdraw
mapping (uint256 => uint256) public poolERC20TokenBalance;
// Mapping from Pool ID to amount of Ethereum withdrawn from selling AO
mapping (uint256 => uint256) public poolTotalEthereumWithdrawn;
// Mapping from an address to quantity of AO put on sale from all sell lots
mapping (address => uint256) public totalPutOnSale;
// Mapping from an address to quantity of AO sold and redeemed from all sell lots
mapping (address => uint256) public totalSold;
// Mapping from an address to quantity of AO bought from all pool
mapping (address => uint256) public totalBought;
// Mapping from an address to amount of Ethereum withdrawn from selling AO
mapping (address => uint256) public totalEthereumWithdrawn;
// Mapping from an address to its Lots
mapping (address => bytes32[]) internal ownerLots;
// Mapping from Pool's Lot ID to Lot internal ID
mapping (uint256 => mapping (bytes32 => uint256)) internal poolLotInternalIdLookup;
// Mapping from Pool's Lot internal ID to total ion withdrawn
mapping (uint256 => mapping (uint256 => uint256)) internal poolLotIonWithdrawn;
// Mapping from Pool's tenth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolTenthLotIonWithdrawnSnapshot;
// Mapping from Pool's hundredth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolHundredthLotIonWithdrawnSnapshot;
// Mapping from Pool's thousandth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolThousandthLotIonWithdrawnSnapshot;
// Mapping from Pool's ten thousandth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolTenThousandthLotIonWithdrawnSnapshot;
// Mapping from Pool's hundred thousandth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolHundredThousandthLotIonWithdrawnSnapshot;
// Mapping from Pool's millionth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolMillionthLotIonWithdrawnSnapshot;
// Event to be broadcasted to public when Pool is created
event CreatePool(uint256 indexed poolId, address indexed adminAddress, uint256 price, bool status, bool sellCapStatus, uint256 sellCapAmount, bool quantityCapStatus, uint256 quantityCapAmount, bool erc20CounterAsset, address erc20TokenAddress, uint256 erc20TokenMultiplier);
// Event to be broadcasted to public when Pool's status is updated
// If status == true, start Pool
// Otherwise, stop Pool
event UpdatePoolStatus(uint256 indexed poolId, bool status);
// Event to be broadcasted to public when Pool's admin address is changed
event ChangeAdminAddress(uint256 indexed poolId, address newAdminAddress);
/**
* Event to be broadcasted to public when a seller sells AO
*
* If erc20CounterAsset is true, the Lot is priced in an ERC20 compatible token.
* Otherwise, the Lot is priced in Ethereum
*/
event LotCreation(uint256 indexed poolId, bytes32 indexed lotId, address indexed seller, uint256 lotQuantity, uint256 price, uint256 poolPreSellSnapshot, uint256 poolSellLotSnapshot, uint256 lotValueInCounterAsset, bool erc20CounterAsset, uint256 timestamp);
// Event to be broadcasted to public when a buyer buys AO
event BuyWithEth(uint256 indexed poolId, address indexed buyer, uint256 buyQuantity, uint256 price, uint256 currentPoolTotalBuy);
// Event to be broadcasted to public when a buyer withdraw ETH from Lot
event WithdrawEth(address indexed seller, bytes32 indexed lotId, uint256 indexed poolId, uint256 withdrawnAmount, uint256 currentLotValueInCounterAsset, uint256 currentLotCounterAssetWithdrawn);
// Event to be broadcasted to public when a seller withdraw ion from Lot
event WithdrawIon(address indexed seller, bytes32 indexed lotId, uint256 indexed poolId, uint256 withdrawnAmount, uint256 currentlotValueInCounterAsset, uint256 currentLotIonWithdrawn);
/**
* @dev Constructor function
*/
constructor(address _aoIonAddress, address _nameTAOPositionAddress) public {
setAOIonAddress(_aoIonAddress);
setNameTAOPositionAddress(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** THE AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the AOIonAddress Address
* @param _aoIonAddress The address of AOIonAddress
*/
function setAOIonAddress(address _aoIonAddress) public onlyTheAO {
require (_aoIonAddress != address(0));
aoIonAddress = _aoIonAddress;
_aoIon = AOIon(_aoIonAddress);
}
/**
* @dev The AO sets NameTAOPosition address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Allows TheAO to transfer `_amount` of ETH from this address to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
*/
function transferEth(address payable _recipient, uint256 _amount) public onlyTheAO {
_recipient.transfer(_amount);
}
/**
* @dev Allows TheAO to transfer `_amount` of ERC20 Token from this address to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyTheAO {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
require (_erc20.transfer(_recipient, _amount));
}
/**
* @dev TheAO creates a Pool
* @param _price The flat price of AO
* @param _status The status of the Pool
* true = Pool is live and can be sold into
* false = Pool cannot be sold into
* @param _sellCapStatus Whether or not the Pool has sell cap
* true = has sell cap
* false = no sell cap
* @param _sellCapAmount Cap for the amount of AO that can be put up for sale in this Pool at `_price`
* @param _quantityCapStatus Whether or not the Pool has quantity cap
* true = has quantity cap
* false = no quantity cap
* @param _quantityCapAmount Cap for the amount of AO at any given time that can be available for sale in this Pool
* @param _erc20CounterAsset Type of the Counter-Asset
* true = Pool is priced in ERC20 compatible Token
* false = Pool is priced in Ethereum
* @param _erc20TokenAddress The address of the ERC20 Token
* @param _erc20TokenMultiplier Used if ERC20 Token needs to deviate from Ethereum in multiplication/division
*/
function createPool(
uint256 _price,
bool _status,
bool _sellCapStatus,
uint256 _sellCapAmount,
bool _quantityCapStatus,
uint256 _quantityCapAmount,
bool _erc20CounterAsset,
address _erc20TokenAddress,
uint256 _erc20TokenMultiplier) public onlyTheAO {
require (_price > 0);
// Make sure sell cap amount is provided if sell cap is enabled
if (_sellCapStatus == true) {
require (_sellCapAmount > 0);
}
// Make sure quantity cap amount is provided if quantity cap is enabled
if (_quantityCapStatus == true) {
require (_quantityCapAmount > 0);
}
// Make sure the ERC20 token address and multiplier are provided
// if this Pool is priced in ERC20 compatible Token
if (_erc20CounterAsset == true) {
require (AOLibrary.isValidERC20TokenAddress(_erc20TokenAddress));
require (_erc20TokenMultiplier > 0);
}
totalPool++;
Pool storage _pool = pools[totalPool];
_pool.price = _price;
_pool.status = _status;
_pool.sellCapStatus = _sellCapStatus;
if (_sellCapStatus) {
_pool.sellCapAmount = _sellCapAmount;
}
_pool.quantityCapStatus = _quantityCapStatus;
if (_quantityCapStatus) {
_pool.quantityCapAmount = _quantityCapAmount;
}
_pool.erc20CounterAsset = _erc20CounterAsset;
if (_erc20CounterAsset) {
_pool.erc20TokenAddress = _erc20TokenAddress;
_pool.erc20TokenMultiplier = _erc20TokenMultiplier;
}
_pool.adminAddress = msg.sender;
emit CreatePool(totalPool, _pool.adminAddress, _pool.price, _pool.status, _pool.sellCapStatus, _pool.sellCapAmount, _pool.quantityCapStatus, _pool.quantityCapAmount, _pool.erc20CounterAsset, _pool.erc20TokenAddress, _pool.erc20TokenMultiplier);
}
/***** Pool's Admin Only Methods *****/
/**
* @dev Start/Stop a Pool
* @param _poolId The ID of the Pool
* @param _status The status to set. true = start. false = stop
*/
function updatePoolStatus(uint256 _poolId, bool _status) public {
// Check pool existence by requiring price > 0
require (pools[_poolId].price > 0 && (pools[_poolId].adminAddress == msg.sender || AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)));
pools[_poolId].status = _status;
emit UpdatePoolStatus(_poolId, _status);
}
/**
* @dev Change Admin Address
* @param _poolId The ID of the Pool
* @param _adminAddress The new admin address to set
*/
function changeAdminAddress(uint256 _poolId, address _adminAddress) public {
// Check pool existence by requiring price > 0
require (pools[_poolId].price > 0 && (pools[_poolId].adminAddress == msg.sender || AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)));
require (_adminAddress != address(0));
pools[_poolId].adminAddress = _adminAddress;
emit ChangeAdminAddress(_poolId, _adminAddress);
}
/***** Public Methods *****/
/**
* @dev Seller sells AO in Pool `_poolId` - create a Lot to be added to a Pool for a seller.
* @param _poolId The ID of the Pool
* @param _quantity The amount of AO to be sold
* @param _price The price supplied by seller
*/
function sell(uint256 _poolId, uint256 _quantity, uint256 _price) public {
Pool memory _pool = pools[_poolId];
require (_pool.status == true && _pool.price == _price && _quantity > 0 && _aoIon.balanceOf(msg.sender) >= _quantity);
// If there is a sell cap
if (_pool.sellCapStatus == true) {
require (poolTotalSell[_poolId].add(_quantity) <= _pool.sellCapAmount);
}
// If there is a quantity cap
if (_pool.quantityCapStatus == true) {
require (poolTotalQuantity[_poolId].add(_quantity) <= _pool.quantityCapAmount);
}
// Create Lot for this sell transaction
contractTotalLot++;
poolTotalLot[_poolId]++;
// Generate Lot ID
bytes32 _lotId = keccak256(abi.encodePacked(this, msg.sender, contractTotalLot));
Lot storage _lot = lots[_lotId];
_lot.lotId = _lotId;
_lot.seller = msg.sender;
_lot.lotQuantity = _quantity;
_lot.poolId = _poolId;
_lot.poolPreSellSnapshot = poolTotalSell[_poolId];
_lot.poolSellLotSnapshot = poolTotalSell[_poolId].add(_quantity);
_lot.lotValueInCounterAsset = _quantity.mul(_pool.price);
_lot.timestamp = now;
poolLotInternalIdLookup[_poolId][_lotId] = poolTotalLot[_poolId];
ownerLots[msg.sender].push(_lotId);
// Update contract variables
poolTotalQuantity[_poolId] = poolTotalQuantity[_poolId].add(_quantity);
poolTotalSell[_poolId] = poolTotalSell[_poolId].add(_quantity);
totalPutOnSale[msg.sender] = totalPutOnSale[msg.sender].add(_quantity);
contractTotalQuantity = contractTotalQuantity.add(_quantity);
contractTotalSell = contractTotalSell.add(_quantity);
require (_aoIon.whitelistTransferFrom(msg.sender, address(this), _quantity));
emit LotCreation(_lot.poolId, _lot.lotId, _lot.seller, _lot.lotQuantity, _pool.price, _lot.poolPreSellSnapshot, _lot.poolSellLotSnapshot, _lot.lotValueInCounterAsset, _pool.erc20CounterAsset, _lot.timestamp);
}
/**
* @dev Retrieve number of Lots an `_account` has
* @param _account The address of the Lot's owner
* @return Total Lots the owner has
*/
function ownerTotalLot(address _account) public view returns (uint256) {
return ownerLots[_account].length;
}
/**
* @dev Get list of owner's Lot IDs from `_from` to `_to` index
* @param _account The address of the Lot's owner
* @param _from The starting index, (i.e 0)
* @param _to The ending index, (i.e total - 1)
* @return list of owner's Lot IDs
*/
function ownerLotIds(address _account, uint256 _from, uint256 _to) public view returns (bytes32[] memory) {
require (_from >= 0 && _to >= _from && ownerLots[_account].length > _to);
bytes32[] memory _lotIds = new bytes32[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_lotIds[i.sub(_from)] = ownerLots[_account][i];
}
return _lotIds;
}
/**
* @dev Buyer buys AO from Pool `_poolId` with Ethereum
* @param _poolId The ID of the Pool
* @param _quantity The amount of AO to be bought
* @param _price The price supplied by buyer
*/
function buyWithEth(uint256 _poolId, uint256 _quantity, uint256 _price) public payable {
Pool memory _pool = pools[_poolId];
require (_pool.status == true && _pool.price == _price && _pool.erc20CounterAsset == false);
require (_quantity > 0 && _quantity <= poolTotalQuantity[_poolId]);
require (msg.value > 0 && msg.value.div(_pool.price) == _quantity);
// Update contract variables
poolTotalQuantity[_poolId] = poolTotalQuantity[_poolId].sub(_quantity);
poolTotalBuy[_poolId] = poolTotalBuy[_poolId].add(_quantity);
poolEthereumBalance[_poolId] = poolEthereumBalance[_poolId].add(msg.value);
contractTotalQuantity = contractTotalQuantity.sub(_quantity);
contractTotalBuy = contractTotalBuy.add(_quantity);
contractEthereumBalance = contractEthereumBalance.add(msg.value);
totalBought[msg.sender] = totalBought[msg.sender].add(_quantity);
require (_aoIon.whitelistTransferFrom(address(this), msg.sender, _quantity));
emit BuyWithEth(_poolId, msg.sender, _quantity, _price, poolTotalBuy[_poolId]);
}
/**
* @dev Seller withdraw Ethereum from Lot `_lotId`
* @param _lotId The ID of the Lot
*/
function withdrawEth(bytes32 _lotId) public {
Lot storage _lot = lots[_lotId];
require (_lot.seller == msg.sender && _lot.lotValueInCounterAsset > 0);
(uint256 soldQuantity, uint256 ethAvailableToWithdraw,) = lotEthAvailableToWithdraw(_lotId);
require (ethAvailableToWithdraw > 0 && ethAvailableToWithdraw <= _lot.lotValueInCounterAsset && ethAvailableToWithdraw <= poolEthereumBalance[_lot.poolId] && ethAvailableToWithdraw <= contractEthereumBalance && soldQuantity <= _lot.lotQuantity.sub(_lot.ionWithdrawn));
// Update lot variables
_lot.counterAssetWithdrawn = _lot.counterAssetWithdrawn.add(ethAvailableToWithdraw);
_lot.lotValueInCounterAsset = _lot.lotValueInCounterAsset.sub(ethAvailableToWithdraw);
// Update contract variables
poolEthereumBalance[_lot.poolId] = poolEthereumBalance[_lot.poolId].sub(ethAvailableToWithdraw);
poolTotalEthereumWithdrawn[_lot.poolId] = poolTotalEthereumWithdrawn[_lot.poolId].add(ethAvailableToWithdraw);
contractEthereumBalance = contractEthereumBalance.sub(ethAvailableToWithdraw);
contractTotalEthereumWithdrawn = contractTotalEthereumWithdrawn.add(ethAvailableToWithdraw);
totalSold[msg.sender] = totalSold[msg.sender].add(soldQuantity);
totalEthereumWithdrawn[msg.sender] = totalEthereumWithdrawn[msg.sender].add(ethAvailableToWithdraw);
// Send eth to seller
address(uint160(_lot.seller)).transfer(ethAvailableToWithdraw);
//_lot.seller.transfer(ethAvailableToWithdraw);
emit WithdrawEth(_lot.seller, _lot.lotId, _lot.poolId, ethAvailableToWithdraw, _lot.lotValueInCounterAsset, _lot.counterAssetWithdrawn);
}
/**
* @dev Seller gets Lot `_lotId` (priced in ETH) available to withdraw info
* @param _lotId The ID of the Lot
* @return The amount of ion sold
* @return Ethereum available to withdraw from the Lot
* @return Current Ethereum withdrawn from the Lot
*/
function lotEthAvailableToWithdraw(bytes32 _lotId) public view returns (uint256, uint256, uint256) {
Lot memory _lot = lots[_lotId];
require (_lot.seller != address(0));
Pool memory _pool = pools[_lot.poolId];
require (_pool.erc20CounterAsset == false);
uint256 soldQuantity = 0;
uint256 ethAvailableToWithdraw = 0;
// Check whether or not there are ions withdrawn from Lots before this Lot
uint256 lotAdjustment = totalIonWithdrawnBeforeLot(_lotId);
if (poolTotalBuy[_lot.poolId] > _lot.poolPreSellSnapshot.sub(lotAdjustment) && _lot.lotValueInCounterAsset > 0) {
soldQuantity = (poolTotalBuy[_lot.poolId] >= _lot.poolSellLotSnapshot.sub(lotAdjustment)) ? _lot.lotQuantity : poolTotalBuy[_lot.poolId].sub(_lot.poolPreSellSnapshot.sub(lotAdjustment));
if (soldQuantity > 0) {
if (soldQuantity > _lot.ionWithdrawn) {
soldQuantity = soldQuantity.sub(_lot.ionWithdrawn);
}
soldQuantity = soldQuantity.sub(_lot.counterAssetWithdrawn.div(_pool.price));
ethAvailableToWithdraw = soldQuantity.mul(_pool.price);
assert (soldQuantity <= _lot.lotValueInCounterAsset.div(_pool.price));
assert (soldQuantity.add(_lot.ionWithdrawn) <= _lot.lotQuantity);
assert (ethAvailableToWithdraw <= _lot.lotValueInCounterAsset);
}
}
return (soldQuantity, ethAvailableToWithdraw, _lot.counterAssetWithdrawn);
}
/**
* @dev Seller withdraw ion from Lot `_lotId`
* @param _lotId The ID of the Lot
* @param _quantity The amount of ion to withdraw
*/
function withdrawIon(bytes32 _lotId, uint256 _quantity) public {
Lot storage _lot = lots[_lotId];
require (_lot.seller == msg.sender && _lot.lotValueInCounterAsset > 0);
Pool memory _pool = pools[_lot.poolId];
require (_quantity > 0 && _quantity <= _lot.lotValueInCounterAsset.div(_pool.price));
// Update lot variables
_lot.ionWithdrawn = _lot.ionWithdrawn.add(_quantity);
_lot.lotValueInCounterAsset = _lot.lotValueInCounterAsset.sub(_quantity.mul(_pool.price));
poolLotIonWithdrawn[_lot.poolId][poolLotInternalIdLookup[_lot.poolId][_lotId]] = poolLotIonWithdrawn[_lot.poolId][poolLotInternalIdLookup[_lot.poolId][_lotId]].add(_quantity);
// Store Pool's millionth Lot snapshot
uint256 millionth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(1000000);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(millionth.mul(1000000)) != 0) {
millionth++;
}
poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][millionth] = poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][millionth].add(_quantity);
// Store Pool's hundred thousandth Lot snapshot
uint256 hundredThousandth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(100000);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(hundredThousandth.mul(100000)) != 0) {
hundredThousandth++;
}
poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][hundredThousandth] = poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][hundredThousandth].add(_quantity);
// Store Pool's ten thousandth Lot snapshot
uint256 tenThousandth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(10000);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(tenThousandth.mul(10000)) != 0) {
tenThousandth++;
}
poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][tenThousandth] = poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][tenThousandth].add(_quantity);
// Store Pool's thousandth Lot snapshot
uint256 thousandth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(1000);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(thousandth.mul(1000)) != 0) {
thousandth++;
}
poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][thousandth] = poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][thousandth].add(_quantity);
// Store Pool's hundredth Lot snapshot
uint256 hundredth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(100);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(hundredth.mul(100)) != 0) {
hundredth++;
}
poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][hundredth] = poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][hundredth].add(_quantity);
// Store Pool's tenth Lot snapshot
uint256 tenth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(10);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(tenth.mul(10)) != 0) {
tenth++;
}
poolTenthLotIonWithdrawnSnapshot[_lot.poolId][tenth] = poolTenthLotIonWithdrawnSnapshot[_lot.poolId][tenth].add(_quantity);
// Update contract variables
poolTotalQuantity[_lot.poolId] = poolTotalQuantity[_lot.poolId].sub(_quantity);
contractTotalQuantity = contractTotalQuantity.sub(_quantity);
poolTotalWithdrawn[_lot.poolId] = poolTotalWithdrawn[_lot.poolId].add(_quantity);
contractTotalWithdrawn = contractTotalWithdrawn.add(_quantity);
totalPutOnSale[msg.sender] = totalPutOnSale[msg.sender].sub(_quantity);
assert (_lot.ionWithdrawn.add(_lot.lotValueInCounterAsset.div(_pool.price)).add(_lot.counterAssetWithdrawn.div(_pool.price)) == _lot.lotQuantity);
require (_aoIon.whitelistTransferFrom(address(this), msg.sender, _quantity));
emit WithdrawIon(_lot.seller, _lot.lotId, _lot.poolId, _quantity, _lot.lotValueInCounterAsset, _lot.ionWithdrawn);
}
/**
* @dev Get total ion withdrawn from all Lots before Lot `_lotId`
* @param _lotId The ID of the Lot
* @return Total ion withdrawn from all Lots before Lot `_lotId`
*/
function totalIonWithdrawnBeforeLot(bytes32 _lotId) public view returns (uint256) {
Lot memory _lot = lots[_lotId];
require (_lot.seller != address(0) && poolLotInternalIdLookup[_lot.poolId][_lotId] > 0);
uint256 totalIonWithdrawn = 0;
uint256 lotInternalId = poolLotInternalIdLookup[_lot.poolId][_lotId];
uint256 lowerBound = 0;
uint256 millionth = lotInternalId.div(1000000);
if (millionth > 0) {
for (uint256 i=1; i<=millionth; i++) {
if (poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = millionth.mul(1000000);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(100000);
}
}
uint256 hundredThousandth = lotInternalId.div(100000);
if (hundredThousandth > 0) {
for (uint256 i=lowerBound.add(1); i<=hundredThousandth; i++) {
if (poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = hundredThousandth.mul(100000);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(10000);
}
}
uint256 tenThousandth = lotInternalId.div(10000);
if (tenThousandth > 0) {
for (uint256 i=lowerBound.add(1); i<=tenThousandth; i++) {
if (poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = tenThousandth.mul(10000);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(1000);
}
}
uint256 thousandth = lotInternalId.div(1000);
if (thousandth > 0) {
for (uint256 i=lowerBound.add(1); i<=thousandth; i++) {
if (poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = thousandth.mul(1000);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(100);
}
}
uint256 hundredth = lotInternalId.div(100);
if (hundredth > 0) {
for (uint256 i=lowerBound.add(1); i<=hundredth; i++) {
if (poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = hundredth.mul(100);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(10);
}
}
uint256 tenth = lotInternalId.div(10);
if (tenth > 0) {
for (uint256 i=lowerBound.add(1); i<=tenth; i++) {
if (poolTenthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolTenthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = tenth.mul(10);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
}
}
for (uint256 i=lowerBound.add(1); i<lotInternalId; i++) {
if (poolLotIonWithdrawn[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolLotIonWithdrawn[_lot.poolId][i]);
}
}
return totalIonWithdrawn;
}
} | Send `_value` Primordial ions to `_to` from `_from` _from The address of the sender _to The address of the recipient _value The amount to send return true on success/ | function transferPrimordialFrom(address _from, address _to, uint256 _value) public returns (bool) {
require (_value <= primordialAllowance[_from][msg.sender]);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
return _createLotAndTransferPrimordial(_from, _to, _value);
}
| 985,635 |
// File: @openzeppelin/contracts/utils/Counters.sol
// 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 Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @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/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: NiftyApeNation.sol
// __ __ __ ______ __ ______
// / \ / |/ | / \ / | / \
// $$ \ $$ |$$/ /$$$$$$ |_$$ |_ __ __ /$$$$$$ | ______ ______
// $$$ \$$ |/ |$$ |_ $$// $$ | / | / | $$ |__$$ | / \ / \
// $$$$ $$ |$$ |$$ | $$$$$$/ $$ | $$ | $$ $$ |/$$$$$$ |/$$$$$$ |
// $$ $$ $$ |$$ |$$$$/ $$ | __ $$ | $$ | $$$$$$$$ |$$ | $$ |$$ $$ |
// $$ |$$$$ |$$ |$$ | $$ |/ |$$ \__$$ | $$ | $$ |$$ |__$$ |$$$$$$$$/
// $$ | $$$ |$$ |$$ | $$ $$/ $$ $$ | $$ | $$ |$$ $$/ $$ |
// $$/ $$/ $$/ $$/ $$$$/ $$$$$$$ | $$/ $$/ $$$$$$$/ $$$$$$$/
// / \__$$ | $$ |
// $$ $$/ $$ |
// $$$$$$/ $$/
// __ __ __ __
// / \ / | / | / |
// $$ \ $$ | ______ _$$ |_ $$/ ______ _______
// $$$ \$$ | / \ / $$ | / | / \ / \
// $$$$ $$ | $$$$$$ |$$$$$$/ $$ |/$$$$$$ |$$$$$$$ |
// $$ $$ $$ | / $$ | $$ | __ $$ |$$ | $$ |$$ | $$ |
// $$ |$$$$ |/$$$$$$$ | $$ |/ |$$ |$$ \__$$ |$$ | $$ |
// $$ | $$$ |$$ $$ | $$ $$/ $$ |$$ $$/ $$ | $$ |
// $$/ $$/ $$$$$$$/ $$$$/ $$/ $$$$$$/ $$/ $$/
//
pragma solidity 0.8.9;
contract NiftyApeNation is ERC721Enumerable, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private _publicMintCounter;
Counters.Counter private _privateMintCounter;
uint8 public constant PUBLIC_MINT = 1;
uint8 public constant PRIVATE_MINT = 2;
string public baseURI;
string public _contractURI;
string public baseExtension = '.json';
uint256 public maxSupply = 8888;
uint256 public maxPublicSupply = 7904;//maximum allowed for public mint
uint256 public privateMintCounterStart = 7904;//token Ids 7905-8888 is reserved for auctions
uint256 public publicSaleDropSize = 888;//public sale drop batch size
uint256 public publicSaleDropPhase = 1;//there will be 9 drops.
uint256 public maxMintAmount = 3;
uint256 public pricePerPublicToken = 0.0888 ether;
bool public paused = true;
bool public whitelistAllowed = false;
mapping(address => uint8) private _whitelist;
//withdraw addresses
address actWallet = 0x4043806F2d2bd98DcdfAB0a4477528EbE1c4c0c8;
address aiWallet = 0x54BfF4ED1b1D677c3A3b738516DFbe7A8EaC1e8A;
address devWallet = 0xdD2f3cfC6310F0365E83Dd964D38a06e10Cca69E;
address afWallet = 0x33FB4D418943C6AAF85f808EdC901fEcF1Cb51F8;
constructor(string memory _initBaseURI, string memory _initContractURI) ERC721("Nifty Ape Nation", "NAN") {
setBaseURI(_initBaseURI);
setContractURI(_initContractURI);
}
//modifiers
modifier publicMintCheck(uint8 numberOfTokens) {
require(!paused, "Sales is not active");
require(getCurrentCounterValue(PUBLIC_MINT) + numberOfTokens <= maxPublicSupply, "Purchase would exceed max public tokens!");
require(getCurrentCounterValue(PUBLIC_MINT) + numberOfTokens <= publicSaleDropPhase * publicSaleDropSize, "Purchase would exceed this Drop's max amount!");
require(numberOfTokens > 0 && numberOfTokens <= maxMintAmount, "Invalid amount or maximum token mint amount reached!");
require(pricePerPublicToken * numberOfTokens <= msg.value, "Ether value sent is not correct!");
_;
}
modifier whitelistCheck(uint8 numberOfTokens){
if(whitelistAllowed){
require(_whitelist[msg.sender] > 0, "Address is not whitelisted or not enough quota!");
require(numberOfTokens <= _whitelist[msg.sender], "Exceeded max available to purchase");
}
_;
}
modifier privateMintCheck(uint8 numberOfTokens) {
require(!paused, "Contract is not active!");
require(numberOfTokens > 0, "Invalid token amount!");
require(totalSupply() <= maxSupply, "Max supply reached!");
require(getCurrentCounterValue(PRIVATE_MINT) + numberOfTokens <= maxSupply, "Purchase would exceed max tokens!");
_;
}
//we override the _baseURI() method of ERC721 to return our own baseURI
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : "";
}
function setContractURI(string memory newuri) public onlyOwner {
_contractURI = newuri;
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
//public
//Public minting
function mintPublic(uint8 numberOfTokens) public payable whitelistCheck(numberOfTokens) publicMintCheck(numberOfTokens) {
//whitelist checks
if(whitelistAllowed){
_whitelist[msg.sender] -= numberOfTokens;
}
for (uint256 i = 0; i < numberOfTokens; i++) {
incrementCurrentCounterValue(PUBLIC_MINT);
_safeMint(msg.sender, getCurrentCounterValue(PUBLIC_MINT));
}
}
//Token Ids from 7905-8888 is reserved for auctions)
function mintPrivate(uint8 numberOfTokens) public onlyOwner privateMintCheck(numberOfTokens) {
for (uint256 i = 0; i < numberOfTokens; i++) {
incrementCurrentCounterValue(PRIVATE_MINT);
_safeMint(msg.sender, getCurrentCounterValue(PRIVATE_MINT));
}
}
//change states
//set BaseURI
function setBaseURI(string memory uri) public onlyOwner {
baseURI = uri;
}
//set public sale drop size (888)
function setPublicSaleDropSize(uint256 newDropSize) public onlyOwner {
publicSaleDropSize = newDropSize;
}
//set public sale drop phase (1-9)
function setPublicSaleDropPhase(uint256 newDropPhase) public onlyOwner {
require(newDropPhase >= 1 && newDropPhase <= 9, "Drop phase cannot exceed 9.");
publicSaleDropPhase = newDropPhase;
}
//set max mint amount
function setMaxMintAmount(uint256 newMintAmount) public onlyOwner {
maxMintAmount = newMintAmount;
}
//set public token price
function setPricePerPublicToken(uint256 newPrice) public onlyOwner {
pricePerPublicToken = newPrice;
}
//set pause
function setPaused(bool newState) public onlyOwner {
paused = newState;
}
//set whitelist allowed
function setWhitelistAllowed(bool newState) public onlyOwner {
whitelistAllowed = newState;
}
//Set whitelist addresses
function setWhitelist(address[] calldata addresses, uint8 allowedMintAmount) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
_whitelist[addresses[i]] = allowedMintAmount;
}
}
//get curernt token counter value (mintType: PUBLIC_MINT/PRIVATE_MINT)
function getCurrentCounterValue(uint8 mintType) public view returns (uint256){
if(mintType == PUBLIC_MINT){
return _publicMintCounter.current();
}else if(mintType == PRIVATE_MINT){
return _privateMintCounter.current() + privateMintCounterStart;//private mint counter starts from 7905 (reserved items)
}else{
return 0;
}
}
//increment token counter value (mintType: PUBLIC_MINT/PRIVATE_MINT)
function incrementCurrentCounterValue(uint8 mintType) private {
if(mintType == PUBLIC_MINT){
require(getCurrentCounterValue(PUBLIC_MINT) < maxPublicSupply, "counter can not exceed the max public supply");
return _publicMintCounter.increment();
}else if(mintType == PRIVATE_MINT){
require(getCurrentCounterValue(PRIVATE_MINT) < maxSupply, "counter can not exceed the max supply");
return _privateMintCounter.increment();
}else{
return;
}
}
//withdraw all money to specidic wallets
function withdrawAll() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "insufficient funds!");
_widthdraw(actWallet, balance * 35 / 100);
_widthdraw(aiWallet, balance * 20 / 100);
_widthdraw(devWallet, balance * 30 / 100);
_widthdraw(afWallet, address(this).balance);
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
} | we override the _baseURI() method of ERC721 to return our own baseURI | function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
| 219,719 |
./partial_match/1/0xa52c0Bb1b802e9d6A483072d56fd22B58B964455/sources/contracts/mixins/nftDropMarket/NFTDropMarketDutchAuction.sol | Get the price per NFT for sale in a dutch auction if purchased at the given time. nftContract The NFT collection address. time Time in seconds since the Unix epoch to calculate the price for. return price The price per NFT at the time provided. This should not be used for historical prices, once the collection sells out this always returns the final clearing price and not the correct historical value./ All tokens have been minted, so the final clearing price is the last successful sale price. Not all tokens have been minted, so calculate current price based on auction config and the time provided. | function getPriceAtTimeForDutchAuction(address nftContract, uint256 time) public view returns (uint256 price) {
DutchAuctionInfo storage auctionInfo = $collectionToDutchAuctionInfo[nftContract];
if (auctionInfo.totalMintedCount >= auctionInfo.totalAvailableSupply) {
price = auctionInfo.lastSalePrice;
price = AuctionPriceFunctions.getLinearlyDecreasingPriceAtTime(
auctionInfo.maxPrice,
auctionInfo.minPrice,
auctionInfo.startTime,
auctionInfo.endTime,
time
);
}
}
| 2,625,039 |
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
/** @title Know You Customer contract
* @author Chris Ball
* @notice This contract handles basic "white listing" of addresses
*/
contract KycContract is Ownable {
mapping(address => bool) allowed; /** @dev valid kyc addresses */
/** @notice function whitelistis of the incoming address
* @param _addr the address to whitelist
*/
function setKycCompleted(address _addr) public onlyOwner {
allowed[_addr] = true;
}
/** @notice function revokes whitelisting of the incoming address
* @param _addr the address to revoke
*/
function setKycRevoked(address _addr) public onlyOwner {
allowed[_addr] = false;
}
/** @notice function returns true or false as to whether an address is currently whitelisted
* @param _addr address to query
* @return true/false
*/
function IsCustomerValid(address _addr) public view returns (bool) {
return allowed[_addr];
}
} | function revokes whitelisting of the incoming address _addr the address to revoke/ | function setKycRevoked(address _addr) public onlyOwner {
allowed[_addr] = false;
}
| 12,913,556 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Marketplace.sol";
contract MarketplaceAuction is Marketplace {
//currency medamon
struct Listing {
address lister;
uint256 initialPrice;
uint256 endTime;
address highestBidder;
uint256 highestBid;
}
mapping(IERC721 => mapping(uint256 => Listing)) public listings;
uint public minTimeToAddPlus; //Tiempo minimo para a contemplar para agregar mas tiempo a la subasta
uint timePlus;//Tiempo que se agrega tras una puja
event Listed(address lister, IERC721 token, uint256 tokenId, uint256 initialPrice, uint256 endTime);
event Bid(address bidder, IERC721 token, uint256 tokenId, uint256 amount);
event Unlisted(address lister, IERC721 token, uint256 tokenId);
event Claim(address purchaser, address lister, IERC721 token, uint256 tokenId, uint256 endPrice);
constructor(
IERC721[] memory _whitelistedTokens,
IERC20 _currency,
address _feeTo,
uint256 _feePercentage
) Marketplace(_whitelistedTokens, _currency) FeeBeneficiary(_feeTo, _feePercentage) {}
/********************
* PUBLIC FUNCTIONS *
*********************/
function list(
IERC721 _token,
uint256 _tokenId,
uint256 _initialPrice,
uint256 _biddingTime
) public whenNotPaused onlyWhitelistedTokens(_token) {
Listing storage listing = listings[_token][_tokenId];
require(_token.ownerOf(_tokenId) == msg.sender, "MARKETPLACE: Caller is not token owner");
_token.transferFrom(msg.sender, address(this), _tokenId);
Listing memory newListing = Listing({
lister: msg.sender,
initialPrice: _initialPrice,
endTime: block.timestamp + _biddingTime,
highestBidder: msg.sender,
highestBid: 0
});
listings[_token][_tokenId] = newListing;
emit Listed(msg.sender, _token, _tokenId, _initialPrice, listing.endTime);
}
//modificado en linea 75. Agrega suma de tiempo si la subasta esta por terminar
function bid(
IERC721 _token,
uint256 _tokenId,
uint256 _amount
) public whenNotPaused onlyWhitelistedTokens(_token) {
//cambiar a memory
Listing storage listing = listings[_token][_tokenId];
require(listing.lister != address(0), "MARKETPLACE: Token not listed");
require(listing.lister != msg.sender, "MARKETPLACE: Can't bid on your own token");
require(block.timestamp < listing.endTime, "MARKETPLACE: Bid too late");
require(_amount > listing.highestBid, "MARKETPLACE: Bid lower than previous bid");
require(_amount > listing.initialPrice, "MARKETPLACE: Bid lower than initialPrice");
if (listing.highestBid != 0) {
currency.transferFrom(address(this), listing.highestBidder, listing.highestBid);
}
currency.transferFrom(msg.sender, address(this), _amount);
listing.highestBid = _amount;
listing.highestBidder = msg.sender;
if(_getTimeLeft(listing.endTime) < minTimeToAddPlus){
listing.endTime += timePlus;
}
emit Bid(msg.sender, _token, _tokenId, _amount);
}
//Permite reclamar los resultados de una subasta terminada.
function claim(IERC721 _token, uint256 _tokenId) public whenNotPaused{
Listing storage listing = listings[_token][_tokenId];
require(listing.lister != address(0), "MARKETPLACE: Token not listed");
require(_getClaimers(msg.sender,listing), "MARKETPLACE: Can settle only your own token");
require(block.timestamp > listing.endTime, "MARKETPLACE: endTime not reached");
uint256 endPrice = listing.highestBid;
uint256 resultingAmount = _getResultingAmount(endPrice, currency);
currency.transfer(listing.lister, resultingAmount);
_token.transferFrom(address(this), listing.highestBidder, _tokenId);
_unlist(_token, _tokenId);
emit Claim(listing.highestBidder, listing.lister, _token, _tokenId, endPrice);
}
//Permite quitar un nft de subasta solo si, nadie pujo por el.
function unlist(IERC721 _token, uint256 _tokenId) public {
Listing storage listing = listings[_token][_tokenId];
require(listing.lister == msg.sender);
require(listing.highestBidder == listing.lister);
_unlist(_token, _tokenId);
}
//permite cambiar el precio minimo de puja, solo si, nadie pujo por el nft.
function changePrice(IERC721 _token, uint256 _tokenId, uint _initialPrice) public {
Listing storage listing = listings[_token][_tokenId];
require(listing.lister == msg.sender);
require(listing.highestBidder == listing.lister);
listing.initialPrice = _initialPrice;
//emit changePrice
}
/********************
*INTERNAL FUNCTIONS *
*********************/
//Regresa tiempo restante de una subasta, para hacerlo publico modifcar parametreo de entrada
function _getTimeLeft(uint _endTime) internal view returns(uint){
return _endTime - block.timestamp;
}
//Regresa true si quien llama es el listador o el ganador, de una subasta.
function _getClaimers(address _sender, Listing memory _listing) internal returns(bool){
if( (_sender == _listing.lister) || (_sender == _listing.highestBidder)){
return true;
}else{
return false;
}
}
//Quita el nft de una subasta. Borra los datos del mapping
function _unlist(IERC721 _token, uint256 _tokenId) internal {
delete listings[_token][_tokenId];
emit Unlisted(msg.sender, _token, _tokenId);
}
/*TODO:
* Tiempo fijo de suma.
* views.
*/
} | modificado en linea 75. Agrega suma de tiempo si la subasta esta por terminarcambiar a memory | function bid(
IERC721 _token,
uint256 _tokenId,
uint256 _amount
) public whenNotPaused onlyWhitelistedTokens(_token) {
Listing storage listing = listings[_token][_tokenId];
require(listing.lister != address(0), "MARKETPLACE: Token not listed");
require(listing.lister != msg.sender, "MARKETPLACE: Can't bid on your own token");
require(block.timestamp < listing.endTime, "MARKETPLACE: Bid too late");
require(_amount > listing.highestBid, "MARKETPLACE: Bid lower than previous bid");
require(_amount > listing.initialPrice, "MARKETPLACE: Bid lower than initialPrice");
if (listing.highestBid != 0) {
currency.transferFrom(address(this), listing.highestBidder, listing.highestBid);
}
currency.transferFrom(msg.sender, address(this), _amount);
listing.highestBid = _amount;
listing.highestBidder = msg.sender;
if(_getTimeLeft(listing.endTime) < minTimeToAddPlus){
listing.endTime += timePlus;
}
emit Bid(msg.sender, _token, _tokenId, _amount);
}
| 15,860,271 |
./full_match/97/0x309569E6920a78c97d7A4a881D41EB432b565603/sources/contracts/MethodsExposureFacet.sol | Gets reward account information by address | function getRewardAccount(address _account)
public
view
returns (
address account,
int256 index,
int256 numInQueue,
uint256 withdrawableRewards,
uint256 totalRewards,
bool manualClaim
)
{
return (address(0), 0, 0, 0, 0, false);
}
| 5,017,322 |
./partial_match/1/0x99b57Abf76E69E52EfF39a5f876280d4B525119F/sources/contracts/cedar/drop/CedarERC721DropLogic.sol | Interpret empty string as unsetting tokenURI | function setTokenURI(
DropERC721DataTypes.ClaimData storage claimData,
uint256 _tokenId,
string memory _tokenURI
) public {
if (bytes(_tokenURI).length == 0) {
claimData.tokenURIs[_tokenId].sequenceNumber = 0;
return;
}
claimData.tokenURIs[_tokenId].uri = _tokenURI;
claimData.tokenURIs[_tokenId].sequenceNumber = claimData.uriSequenceCounter.current();
}
| 3,659,950 |
./full_match/1/0xd712A863766dE7e7cA13289A97997E01832A6571/sources/@mimic-fi/v2-smart-vaults-base/contracts/actions/OracledAction.sol | Extracts the number of feeds encoded in the extra calldata. This function returns bogus data if there is no extra calldata in place. The number of encoded feeds is encoded in the 4th word from the calldata end./ | function _getFeedsLength() private pure returns (uint256) {
return uint256(_decodeCalldataWord(3));
}
| 2,974,014 |
./full_match/100/0x1Cb33B22118d1e60545A5241fF187f737B21732c/sources/home/didi/src/artis2/artis2-launch-contracts/contracts/Artis2Launch.sol | After the end of the swapping period, the owner can withdraw remaining new tokens to a given address. | function withdrawRemainingNewTokensTo(address receiver)
external
onlyOwner
{
require(block.timestamp > SWAP_DISABLED_AFTER, "withdrawal not yet allowed");
newToken.transfer(receiver, newToken.balanceOf(address(this)));
}
| 14,272,677 |
./full_match/44787/0x5C3847f9CCa301232795CDd4Eb9732928B0CC916/sources/contracts/StarNFTLogic.sol | uint256 _rndCateIndex2; _rndCateIndex = uint256(keccak256(abi.encodePacked(block.coinbase, msg.sender, nonce, block.timestamp))) % (_cate.length -1); _rndCateIndex2 = uint256(keccak256(abi.encodePacked(block.coinbase, msg.sender, nonce, block.timestamp))) % (_cate.length -1) + 1; if (cateId[_cate[_rndCateIndex2]].maxUnit > cateId[_cate[_rndCateIndex2]].usedUnit){ _rndCateIndex = _rndCateIndex2; } | function getRndCateIndex(StarLevel _level) view public returns (uint256) {
uint256[] storage _cate = starCate[_level];
require(_cate.length > 0, "no cate");
uint256 _rndCateIndex;
uint256 nonce;
do {
_rndCateIndex = uint256(keccak256(abi.encodePacked(block.coinbase, msg.sender, nonce, block.timestamp))) % (_cate.length -1);
if (cateId[_cate[_rndCateIndex]].maxUnit > cateId[_cate[_rndCateIndex]].usedUnit) break;
nonce ++;
} while (true);
return _rndCateIndex;
}
| 13,254,395 |
pragma solidity ^0.5.2;
library SafeMath {
function MUL803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV739(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB240(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD649(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD521(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
interface IERC20 {
function TRANSFER940(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE773(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM406(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY323() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF593(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE869(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER104(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL145(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
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 NAME604() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL119() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS999() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY323() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF593(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE869(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER940(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER651(msg.sender, to, value);
return true;
}
function APPROVE773(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE103(msg.sender, spender, value);
return true;
}
function TRANSFERFROM406(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER651(from, to, value);
_APPROVE103(from, msg.sender, _allowed[from][msg.sender].SUB240(value));
return true;
}
function INCREASEALLOWANCE839(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE103(msg.sender, spender, _allowed[msg.sender][spender].ADD649(addedValue));
return true;
}
function DECREASEALLOWANCE280(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE103(msg.sender, spender, _allowed[msg.sender][spender].SUB240(subtractedValue));
return true;
}
function _TRANSFER651(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB240(value);
_balances[to] = _balances[to].ADD649(value);
emit TRANSFER104(from, to, value);
}
function _MINT410(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD649(value);
_balances[account] = _balances[account].ADD649(value);
emit TRANSFER104(address(0), account, value);
}
function _BURN498(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB240(value);
_balances[account] = _balances[account].SUB240(value);
emit TRANSFER104(account, address(0), value);
}
function _APPROVE103(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit APPROVAL145(owner, spender, value);
}
function _BURNFROM661(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_BURN498(account, value);
_APPROVE103(account, msg.sender, _allowed[account][msg.sender].SUB240(value));
}
}
contract EXCHANGE is ERC20, ERC20Detailed {
uint256 public constant initial_supply735 = 500000000000 * (10 ** 18); //inject NONSTANDARD NAMING
constructor () public ERC20Detailed("Safuracoin", "EXCHANGE", 8) {
_MINT410(msg.sender, initial_supply735);
}
} | inject NONSTANDARD NAMING | function TRANSFERFROM406(address from, address to, uint256 value) public returns (bool) { | 14,105,829 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../token/interface/IHN.sol";
import "../pool/interface/IHNPool.sol";
/**
* @title HN Market Contract
* @author HASHLAND-TEAM
* @notice In this contract users can trade HN
*/
contract HNMarket is ERC721Holder, AccessControlEnumerable, ReentrancyGuard {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
IHN public hn;
IHNPool public hnPool;
IERC20 public busd;
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
bytes32 public constant HNPOOL_ROLE = keccak256("HNPOOL_ROLE");
bool public openStatus = false;
address public receivingAddress;
uint256 public feeRatio = 500;
uint256 public totalSellAmount;
uint256 public totalFeeAmount;
uint256 public totalSellCount;
mapping(uint256 => uint256) public hnPrice;
mapping(uint256 => address) public hnSeller;
mapping(uint256 => bool) public hnIsInPool;
mapping(address => uint256) public sellerTotalSellAmount;
mapping(address => uint256) public sellerTotalSellCount;
mapping(address => uint256) public buyerTotalBuyAmount;
mapping(address => uint256) public buyerTotalBuyCount;
EnumerableSet.AddressSet private sellers;
EnumerableSet.AddressSet private buyers;
EnumerableSet.UintSet private hnIds;
mapping(uint256 => EnumerableSet.UintSet) private levelHnIds;
mapping(address => EnumerableSet.UintSet) private sellerHnIds;
mapping(address => mapping(uint256 => EnumerableSet.UintSet))
private sellerLevelHnIds;
event SetOpenStatus(bool status);
event SetFeeRatio(uint256 ratio);
event SetReceivingAddress(address receivingAddr);
event Sell(
address indexed seller,
uint256[] hnIds,
uint256[] prices,
bool[] isInPools
);
event Cancel(address indexed seller, uint256[] hnIds, bool isHnPoolCancel);
event Buy(
address indexed buyer,
address[] sellers,
uint256[] hnIds,
uint256[] prices,
bool[] isInPools
);
/**
* @param hnAddr Initialize HN Address
* @param hnPoolAddr Initialize HNPool Address
* @param busdAddr Initialize BUSD Address
* @param receivingAddr Initialize Receiving Address
* @param manager Initialize Manager Role
*/
constructor(
address hnAddr,
address hnPoolAddr,
address busdAddr,
address receivingAddr,
address manager
) {
hn = IHN(hnAddr);
hnPool = IHNPool(hnPoolAddr);
busd = IERC20(busdAddr);
receivingAddress = receivingAddr;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MANAGER_ROLE, manager);
_setupRole(HNPOOL_ROLE, hnPoolAddr);
}
/**
* @dev Set Open Status
*/
function setOpenStatus(bool status) external onlyRole(MANAGER_ROLE) {
openStatus = status;
emit SetOpenStatus(status);
}
/**
* @dev Set Fee Ratio
*/
function setFeeRatio(uint256 ratio) external onlyRole(MANAGER_ROLE) {
require(ratio <= 2000, "The fee ratio cannot exceed 20%");
feeRatio = ratio;
emit SetFeeRatio(ratio);
}
/**
* @dev Set Receiving Address
*/
function setReceivingAddress(address receivingAddr)
external
onlyRole(MANAGER_ROLE)
{
receivingAddress = receivingAddr;
emit SetReceivingAddress(receivingAddr);
}
/**
* @dev HN Pool Cancel
*/
function hnPoolCancel(address seller, uint256[] calldata _hnIds)
external
onlyRole(HNPOOL_ROLE)
{
for (uint256 i = 0; i < _hnIds.length; i++) {
if (
hnIds.contains(_hnIds[i]) &&
sellerHnIds[seller].contains(_hnIds[i])
) {
uint256 level = hn.level(_hnIds[i]);
hnIds.remove(_hnIds[i]);
levelHnIds[level].remove(_hnIds[i]);
sellerHnIds[seller].remove(_hnIds[i]);
sellerLevelHnIds[seller][level].remove(_hnIds[i]);
}
if (i == _hnIds.length - 1) emit Cancel(seller, _hnIds, true);
}
}
/**
* @dev Sell
*/
function sell(
uint256[] calldata _hnIds,
uint256[] calldata prices,
bool[] calldata isInPools
) external nonReentrant {
require(
_hnIds.length == prices.length && _hnIds.length == isInPools.length,
"Data length mismatch"
);
require(openStatus, "This pool is not opened");
for (uint256 i = 0; i < _hnIds.length; i++) {
if (isInPools[i]) {
require(
hnPool.getUserHnIdExistence(msg.sender, _hnIds[i]),
"This HN is not own"
);
} else {
hn.safeTransferFrom(msg.sender, address(this), _hnIds[i]);
}
uint256 level = hn.level(_hnIds[i]);
hnIds.add(_hnIds[i]);
levelHnIds[level].add(_hnIds[i]);
sellerHnIds[msg.sender].add(_hnIds[i]);
sellerLevelHnIds[msg.sender][level].add(_hnIds[i]);
hnPrice[_hnIds[i]] = prices[i];
hnSeller[_hnIds[i]] = msg.sender;
hnIsInPool[_hnIds[i]] = isInPools[i];
}
emit Sell(msg.sender, _hnIds, prices, isInPools);
}
/**
* @dev Cancel
*/
function cancel(uint256[] calldata _hnIds) external nonReentrant {
for (uint256 i = 0; i < _hnIds.length; i++) {
require(hnIds.contains(_hnIds[i]), "This HN does not exist");
require(
sellerHnIds[msg.sender].contains(_hnIds[i]),
"This HN is not own"
);
uint256 level = hn.level(_hnIds[i]);
hnIds.remove(_hnIds[i]);
levelHnIds[level].remove(_hnIds[i]);
sellerHnIds[msg.sender].remove(_hnIds[i]);
sellerLevelHnIds[msg.sender][level].remove(_hnIds[i]);
if (!hnIsInPool[_hnIds[i]])
hn.safeTransferFrom(address(this), msg.sender, _hnIds[i]);
}
emit Cancel(msg.sender, _hnIds, false);
}
/**
* @dev Buy
*/
function buy(uint256[] calldata _hnIds) external nonReentrant {
address[] memory _sellers = new address[](_hnIds.length);
uint256[] memory prices = new uint256[](_hnIds.length);
bool[] memory isInPools = new bool[](_hnIds.length);
for (uint256 i = 0; i < _hnIds.length; i++) {
require(hnIds.contains(_hnIds[i]), "This HN does not exist");
prices[i] = hnPrice[_hnIds[i]];
uint256 feeAmount = (prices[i] * feeRatio) / 1e4;
uint256 sellAmount = prices[i] - feeAmount;
_sellers[i] = hnSeller[_hnIds[i]];
isInPools[i] = hnIsInPool[_hnIds[i]];
uint256 level = hn.level(_hnIds[i]);
hnIds.remove(_hnIds[i]);
levelHnIds[level].remove(_hnIds[i]);
sellerHnIds[_sellers[i]].remove(_hnIds[i]);
sellerLevelHnIds[_sellers[i]][level].remove(_hnIds[i]);
busd.safeTransferFrom(msg.sender, _sellers[i], sellAmount);
busd.safeTransferFrom(msg.sender, receivingAddress, feeAmount);
if (isInPools[i]) {
hnPool.hnMarketWithdraw(msg.sender, _sellers[i], _hnIds[i]);
} else {
hn.safeTransferFrom(address(this), msg.sender, _hnIds[i]);
}
sellerTotalSellAmount[_sellers[i]] += sellAmount;
sellerTotalSellCount[_sellers[i]]++;
sellers.add(_sellers[i]);
buyerTotalBuyAmount[msg.sender] += sellAmount;
buyerTotalBuyCount[msg.sender]++;
totalSellAmount += sellAmount;
totalFeeAmount += feeAmount;
totalSellCount++;
}
buyers.add(msg.sender);
emit Buy(msg.sender, _sellers, _hnIds, prices, isInPools);
}
/**
* @dev Get Sellers Length
*/
function getSellersLength() external view returns (uint256) {
return sellers.length();
}
/**
* @dev Get Sellers by Size
*/
function getSellersBySize(uint256 cursor, uint256 size)
external
view
returns (address[] memory, uint256)
{
uint256 length = size;
if (length > sellers.length() - cursor) {
length = sellers.length() - cursor;
}
address[] memory values = new address[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = sellers.at(cursor + i);
}
return (values, cursor + length);
}
/**
* @dev Get Buyers Length
*/
function getBuyersLength() external view returns (uint256) {
return buyers.length();
}
/**
* @dev Get Buyers by Size
*/
function getBuyersBySize(uint256 cursor, uint256 size)
external
view
returns (address[] memory, uint256)
{
uint256 length = size;
if (length > buyers.length() - cursor) {
length = buyers.length() - cursor;
}
address[] memory values = new address[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = buyers.at(cursor + i);
}
return (values, cursor + length);
}
/**
* @dev Get HnIds Length
*/
function getHnIdsLength() external view returns (uint256) {
return hnIds.length();
}
/**
* @dev Get HnIds by Size
*/
function getHnIdsBySize(uint256 cursor, uint256 size)
external
view
returns (uint256[] memory, uint256)
{
uint256 length = size;
if (length > hnIds.length() - cursor) {
length = hnIds.length() - cursor;
}
uint256[] memory values = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = hnIds.at(cursor + i);
}
return (values, cursor + length);
}
/**
* @dev Get Each Level HnIds Length
*/
function getEachLevelHnIdsLength(uint256 maxLevel)
external
view
returns (uint256[] memory)
{
uint256[] memory lengths = new uint256[](maxLevel);
for (uint256 i = 0; i < maxLevel; i++) {
lengths[i] = levelHnIds[i + 1].length();
}
return lengths;
}
/**
* @dev Get Level HnIds Length
*/
function getLevelHnIdsLength(uint256 level)
external
view
returns (uint256)
{
return levelHnIds[level].length();
}
/**
* @dev Get Level HnIds by Size
*/
function getLevelHnIdsBySize(
uint256 level,
uint256 cursor,
uint256 size
) external view returns (uint256[] memory, uint256) {
uint256 length = size;
if (length > levelHnIds[level].length() - cursor) {
length = levelHnIds[level].length() - cursor;
}
uint256[] memory values = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = levelHnIds[level].at(cursor + i);
}
return (values, cursor + length);
}
/**
* @dev Get Seller HnId Existence
*/
function getSellerHnIdExistence(address seller, uint256 hnId)
external
view
returns (bool)
{
return sellerHnIds[seller].contains(hnId);
}
/**
* @dev Get Seller HnIds Length
*/
function getSellerHnIdsLength(address seller)
external
view
returns (uint256)
{
return sellerHnIds[seller].length();
}
/**
* @dev Get Seller HnIds by Size
*/
function getSellerHnIdsBySize(
address seller,
uint256 cursor,
uint256 size
) external view returns (uint256[] memory, uint256) {
uint256 length = size;
if (length > sellerHnIds[seller].length() - cursor) {
length = sellerHnIds[seller].length() - cursor;
}
uint256[] memory values = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = sellerHnIds[seller].at(cursor + i);
}
return (values, cursor + length);
}
/**
* @dev Get Seller Each Level HnIds Length
*/
function getSellerEachLevelHnIdsLength(address seller, uint256 maxLevel)
external
view
returns (uint256[] memory)
{
uint256[] memory lengths = new uint256[](maxLevel);
for (uint256 i = 0; i < maxLevel; i++) {
lengths[i] = sellerLevelHnIds[seller][i + 1].length();
}
return lengths;
}
/**
* @dev Get Seller Level HnIds Length
*/
function getSellerLevelHnIdsLength(address seller, uint256 level)
external
view
returns (uint256)
{
return sellerLevelHnIds[seller][level].length();
}
/**
* @dev Get Seller Level HnIds by Size
*/
function getSellerLevelHnIdsBySize(
address seller,
uint256 level,
uint256 cursor,
uint256 size
) external view returns (uint256[] memory, uint256) {
uint256 length = size;
if (length > sellerLevelHnIds[seller][level].length() - cursor) {
length = sellerLevelHnIds[seller][level].length() - cursor;
}
uint256[] memory values = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = sellerLevelHnIds[seller][level].at(cursor + i);
}
return (values, cursor + length);
}
}
| Get Seller Level HnIds Length/ | function getSellerLevelHnIdsLength(address seller, uint256 level)
external
view
returns (uint256)
{
return sellerLevelHnIds[seller][level].length();
}
| 908,918 |
pragma solidity ^0.4.25;
/**
* Kitsune Token Lockup
*/
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 KitsuneLockToken is owned{
using SafeMath for uint256;
/*
* deposit vars
*/
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);
/**
* Constrctor function
*/
constructor() public {
}
/**
*lock tokens
*/
function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 31536000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
//update balance in address
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_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);
}
/**
*withdraw tokens
*/
function withdrawTokens(uint256 _id) public {
require(block.timestamp >= lockedToken[_id].unlockTime, 'Tokens are locked');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'Can withdraw by withdrawal Address only');
require(!lockedToken[_id].withdrawn, 'Tokens already withdrawn');
require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount), 'Transfer of tokens failed');
lockedToken[_id].withdrawn = true;
//update balance in address
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount);
//remove this id from this address
uint256 i; uint256 j;
for(j=0; j<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; j++){
if(depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id){
for (i = j; i<depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length-1; i++){
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][i+1];
}
depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--;
break;
}
}
emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount);
}
/*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 getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256)
{
return walletTokenBalance[_tokenAddress][_walletAddress];
}
/*get allDepositIds*/
function getAllDepositIds() view public returns (uint256[])
{
return allDepositIds;
}
/*get getDepositDetails*/
function getDepositDetails(uint256 _id) view public returns (address, address, uint256, uint256, bool)
{
return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,lockedToken[_id].withdrawn);
}
/*get DepositsByWithdrawalAddress*/
function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[])
{
return depositsByWithdrawalAddress[_withdrawalAddress];
}
} | lock tokens/update balance in address | function lockTokens(address _tokenAddress, uint256 _amount, uint256 _unlockTime) public returns (uint256 _id) {
require(_amount > 0, 'token amount is Zero');
require(_unlockTime < 31536000, 'Enter an unix timestamp in seconds, not miliseconds');
require(Token(_tokenAddress).approve(this, _amount), 'Approve tokens failed');
require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount), 'Transfer of tokens failed');
walletTokenBalance[_tokenAddress][msg.sender] = walletTokenBalance[_tokenAddress][msg.sender].add(_amount);
address _withdrawalAddress = msg.sender;
_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);
}
| 2,302,468 |
./full_match/1/0x23c9ba9A19a4F3Fcc7Fdd3899c79Ea5a1b42dCCE/sources/contracts/interfaces/ICommunityIssuance.sol | --- Events --- --- Functions --- | interface ICommunityIssuance {
event TotalMAHAIssuedUpdated(uint256 _totalMAHAIssued);
event RewardAdded(uint256 reward);
function issueMAHA() external returns (uint256);
function sendMAHA(address _account, uint256 _MAHAamount) external;
function lastTimeRewardApplicable() external view returns (uint256);
function notifyRewardAmount(uint256 reward) external;
function transferOwnership(address who) external;
}
| 4,853,487 |
./full_match/1/0x8940fd30496bD58De8f574919f3A0382c378D842/sources/contracts/interfaces/IMerkleDistributor.sol | Allows anyone to claim a token if they exist in a merkle root. Returns true if the index has been marked claimed. Claim the given amount of the token to the given address. Reverts if the inputs are invalid. This event is triggered whenever a call to claim succeeds. | interface IMerkleDistributor {
function isClaimed(uint256 index) external view returns (bool);
function claim(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external;
event Claimed(uint256 index, address account, uint256 amount);
pragma solidity =0.7.6;
}
| 9,801,234 |
./full_match/43113/0x28F5c190AE9F6E2C08b5C3ebd26b9d8da0E16c92/sources/Certifications.sol | returns the api Link of the dynamic certificate having id = `certificationID`. certificationID Id of the certificate./ | function getDynamicCertificateLink(uint256 certificationID) external view returns(string memory) {
return m_dynamicCertifications[certificationID]._apiLink;
}
| 13,209,220 |
./full_match/5/0x2500439FE503A1b9b51704BD9d8d91a2738150c0/sources/contracts/v7.sol | Function to return all restrictions for all users | function getRestrictions() public onlyOwner view returns (address[] memory, uint8[] memory, uint256[] memory) {
address[] memory accounts = new address[](_restrictedAccounts.length);
uint8[] memory restrictions = new uint8[](_restrictedAccounts.length);
uint256[] memory endDates = new uint256[](_restrictedAccounts.length);
for (uint256 i = 0; i < _restrictedAccounts.length; i++) {
address account = _restrictedAccounts[i];
uint8 restriction = _accountsToRestrictions[account];
uint256 endDate = _accountsToRestrictionsEndDate[account];
accounts[i] = account;
restrictions[i] = restriction;
endDates[i] = endDate;
}
return (accounts, restrictions, endDates);
}
| 1,892,548 |
pragma solidity 0.7.6;
//@dev - Chainlink VRF
import { VRFConsumerBase } from "@chainlink/contracts/src/v0.7/VRFConsumerBase.sol"; // Solidity-v0.7
//import { VRFConsumerBase } from "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; // Solidity-v0.8
//@dev - NFT (ERC721)
import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
/**
* @notice - This is a smart contract that manage the Diploma NFTs using RNG via VRF
*/
//contract DiplomaNFT is ERC721, Ownable {
contract DiplomaNFT is VRFConsumerBase, ERC721, Ownable {
//----------------------------
// RNG via Chainlink VRF
//----------------------------
bytes32 internal keyHash;
uint256 internal fee;
//@dev - Test variable to assign a random number retrieved
bytes32 public requestIdCalledBack;
//@dev - Mappling for storing a random number retrieved
mapping (bytes32 => uint256) public randomNumberStored; // [Param]: requestId -> randomness (random number) that is retrieved from VRF
event RandomResultRetrieved(bytes32 indexed requestId, uint256 indexed randomness);
//--------------------------------
// NFT (ERC721) related method
//--------------------------------
uint256 public tokenCounter; // [NOTE]: TokenID counting is started from "0"
mapping(string => string) public diplomaToDiplomaURI;
event DiplomaNFTMinted (address indexed to, uint indexed tokenId);
/**
* Constructor inherits VRFConsumerBase
*
* Network: Kovan
* Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9
* LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088
* Key Hash: 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311
* Fee: 0.1 LINK *
*/
constructor(
string memory _diplomaNFTName,
string memory _diplomaNFTSymbol,
address _vrfCoordinator,
address _link,
bytes32 _keyHash,
uint _fee
)
VRFConsumerBase(_vrfCoordinator, _link)
ERC721(_diplomaNFTName, _diplomaNFTSymbol)
public
{
keyHash = _keyHash;
fee = _fee;
}
//----------------------------
// RNG via Chainlink VRF
//----------------------------
/**
* Requests randomness
*/
function getRandomNumber() public returns (bytes32 requestId) {
LINK.transferFrom(msg.sender, address(this), fee); // 1 LINK
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
return requestRandomness(keyHash, fee);
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
//@dev - Request ID called back from VRF
requestIdCalledBack = requestId;
//@dev - Store a random number retrieved from VRF with requestId called back
randomNumberStored[requestId] = randomness;
//@dev - Emit event of "RandomResultRetrieved"
emit RandomResultRetrieved(requestId, randomness);
}
//--------------------------------
// NFT (ERC721) related method
//--------------------------------
/**
* @dev - Mint a new Diploma NFT.
* @param graduate - "to" address that NFT minted will be transferred. Eligible address assigned is a new graduate's address
*/
function mintDiplomaNFT(address graduate) public returns (bool) {
_safeMint(graduate, tokenCounter); // [NOTE]: In case of this, a receiver of a new Diploma NFT minted is "graduate" address specified.
//_safeMint(msg.sender, tokenCounter); // [NOTE]: In case of this, mintDiplomaNFT() is called from the GraduatesRegistry.sol and therefore "msg.sender" is the GraduatesRegistry.sol and the GraduatesRegistry.sol will receive a new Diploma NFT minted.
tokenCounter = tokenCounter + 1;
//bytes32 requestId = getRandomNumber(); // [NOTE]: getRandomNumber() method is execute outside of mintDiplomaNFT() method separately
emit DiplomaNFTMinted(msg.sender, tokenCounter);
}
function setDiplomaURI(string memory diploma, string memory tokenUri, uint256 tokenId) public {
diplomaToDiplomaURI[diploma] = tokenUri; // [Todo]: Fix
// overRideTokenIdToWeatherURI[tokenId] = tokenUri;
}
function tokenURI(uint256 tokenId) public view override (ERC721) returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
}
function getCurrentTokenId() public view returns (uint256 _currentTokenId) {
return tokenCounter;
}
/**
* Get a existing random number stored
*/
function getRandomNumberStored(bytes32 requestId) public view returns (uint256 _randomNumberStored) {
return randomNumberStored[requestId];
}
} | overRideTokenIdToWeatherURI[tokenId] = tokenUri; | function setDiplomaURI(string memory diploma, string memory tokenUri, uint256 tokenId) public {
}
| 1,061,561 |
/*
This file is part of the DAO.
The DAO is free software: you can redistribute it and/or modify
it under the terms of the GNU lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The DAO 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 lesser General Public License for more details.
You should have received a copy of the GNU lesser General Public License
along with the DAO. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Token Creation contract, used by the DAO to create its tokens and initialize
* its ether. Feel free to modify the divisor method to implement different
* Token Creation parameters
*/
import "./Token.sol";
import "./ManagedAccount.sol";
pragma solidity ^0.4.26;
contract TokenCreationInterface {
// End of token creation, in Unix time
uint public closingTime;
// Minimum fueling goal of the token creation, denominated in tokens to
// be created
uint public minTokensToCreate;
// True if the DAO reached its minimum fueling goal, false otherwise
bool public isFueled;
// For DAO splits - if parentDAO is 0, then it is a public token
// creation, otherwise only the address stored in parentDAO is
// allowed to create tokens
address public parentDAO;
/// @dev Constructor setting the minimum fueling goal and the
/// end of the Token Creation
/// @param _minTokensToCreate Minimum fueling goal in number of
/// Tokens to be created
/// @param _closingTime Date (in Unix time) of the end of the Token Creation
/// @param _parentDAO Zero means that the creation is public. A
/// non-zero address represents the parentDAO that can buy tokens in the
/// creation phase.
/// (the address can also create Tokens on behalf of other accounts)
// This is the constructor: it can not be overloaded so it is commented out
// function TokenCreation(
// uint _minTokensTocreate,
// uint _closingTime,
// address _parentDAO,
// string _tokenName,
// string _tokenSymbol,
// uint _decimalPlaces
// );
/// @notice Create Token with `_tokenHolder` as the initial owner of the Token
/// @param _tokenHolder The address of the Tokens's recipient
/// @return Whether the token creation was successful
function createTokenProxy(address _tokenHolder) payable returns (bool success);
/// @notice Refund `msg.sender` in the case the Token Creation did
/// not reach its minimum fueling goal
function refund();
event FuelingToDate(uint value);
event CreatedToken(address indexed to, uint amount);
event Refund(address indexed to, uint value);
}
contract TokenCreation is TokenCreationInterface, Token {
function TokenCreation(
uint _minTokensToCreate,
uint _closingTime,
address _parentDAO,
string _tokenName,
string _tokenSymbol,
uint8 _decimalPlaces) {
closingTime = _closingTime;
minTokensToCreate = _minTokensToCreate;
parentDAO = _parentDAO;
name = _tokenName;
symbol = _tokenSymbol;
decimals = _decimalPlaces;
}
function createTokenProxy(address _tokenHolder) payable returns (bool success) {
if (now < closingTime && msg.value > 0
&& (parentDAO == 0 || parentDAO == msg.sender)) {
balances[_tokenHolder] += msg.value;
totalSupply += msg.value;
CreatedToken(_tokenHolder, msg.value);
if (totalSupply >= minTokensToCreate && !isFueled) {
isFueled = true;
FuelingToDate(totalSupply);
}
return true;
}
revert();
}
/// @notice Refund `msg.sender` in the case the Token Creation did
/// not reach its minimum fueling goal
function refund() noEther {
if (now > closingTime && !isFueled) {
// Execute refund
if (msg.sender.send(balances[msg.sender])) {
// its the recipients responsibilty to ensure
// their address does not use too much gas
Refund(msg.sender, balances[msg.sender]);
totalSupply -= balances[msg.sender];
balances[msg.sender] = 0;
}
}
}
}
| Refund `msg.sender` in the case the Token Creation did not reach its minimum fueling goal Execute refund its the recipients responsibilty to ensure their address does not use too much gas | function refund() noEther {
if (now > closingTime && !isFueled) {
if (msg.sender.send(balances[msg.sender])) {
Refund(msg.sender, balances[msg.sender]);
totalSupply -= balances[msg.sender];
balances[msg.sender] = 0;
}
}
}
| 7,212,582 |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------------------------
//Bit Capital Vendor by BitCV Foundation.
// An ERC20 standard
//
// author: BitCV Foundation Team
contract ERC20Interface {
function totalSupply() public constant returns (uint256 _totalSupply);
function balanceOf(address _owner) public constant 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 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 BCV is ERC20Interface {
uint256 public constant decimals = 8;
string public constant symbol = "BCV";
string public constant name = "BitCapitalVendorToken";
uint256 public _totalSupply = 120000000000000000; // total supply is 1.2 billion
// Owner of this contract
address public owner;
// Balances BCV for each account
mapping(address => uint256) private balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) private allowed;
// List of approved investors
mapping(address => bool) private approvedInvestorList;
// deposit
mapping(address => uint256) private deposit;
// totalTokenSold
uint256 public totalTokenSold = 0;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
revert();
}
_;
}
/// @dev Constructor
function BCV()
public {
owner = msg.sender;
balances[owner] = _totalSupply;
}
/// @dev Gets totalSupply
/// @return Total supply
function totalSupply()
public
constant
returns (uint256) {
return _totalSupply;
}
/// @dev Gets account's balance
/// @param _addr Address of the account
/// @return Account balance
function balanceOf(address _addr)
public
constant
returns (uint256) {
return balances[_addr];
}
/// @dev check address is approved investor
/// @param _addr address
function isApprovedInvestor(address _addr)
public
constant
returns (bool) {
return approvedInvestorList[_addr];
}
/// @dev get ETH deposit
/// @param _addr address get deposit
/// @return amount deposit of an buyer
function getDeposit(address _addr)
public
constant
returns(uint256){
return deposit[_addr];
}
/// @dev Transfers the balance from msg.sender to an account
/// @param _to Recipient address
/// @param _amount Transfered amount in unit
/// @return Transfer status
function transfer(address _to, uint256 _amount)
public
returns (bool) {
// if sender's balance has enough unit and amount >= 0,
// and the sum is not overflow,
// then do transfer
if ( (balances[msg.sender] >= _amount) &&
(_amount >= 0) &&
(balances[_to] + _amount > balances[_to]) ) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(
address _from,
address _to,
uint256 _amount
)
public
returns (bool success) {
if (balances[_from] >= _amount && _amount > 0 && allowed[_from][msg.sender] >= _amount) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount)
public
returns (bool success) {
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// get allowance
function allowance(address _owner, address _spender)
public
constant
returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function () public payable{
revert();
}
}
/**
* SafeMath
* 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); // 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;
}
}
/**
* 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);
function Ownable() public {
owner = msg.sender;
}
/**
* Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* 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;
}
}
contract BCVTokenVault is Ownable {
using SafeMath for uint256;
// team 2.4 * 10 ** 8, 3% every month after 2019-3-9
address public teamReserveWallet = 0x7e5C65b899Fb7Cd0c959e5534489B454B7c6c3dF;
// life 1.2 * 10 ** 8, 20% every month after 2018-6-1
address public lifeReserveWallet = 0xaed0363f76e4b906ef818b0f3199c580b5b01a43;
// finance 1.2 * 10 ** 8, 20% every month after 2018-6-1
address public finanReserveWallet = 0xd60A1D84835006499d5E6376Eb7CB9725643E25F;
// economic system 1.2 * 10 ** 8, 1200000 every month in first 6 years, left for last 14 years, release after 2018-6-1
address public econReserveWallet = 0x0C6e75e481cC6Ba8e32d6eF742768fc2273b1Bf0;
// chain development 1.2 * 10 ** 8, release all after 2018-9-30
address public developReserveWallet = 0x11aC32f89e874488890E5444723A644248609C0b;
// Token Allocations
uint256 public teamReserveAllocation = 2.4 * (10 ** 8) * (10 ** 8);
uint256 public lifeReserveAllocation = 1.2 * (10 ** 8) * (10 ** 8);
uint256 public finanReserveAllocation = 1.2 * (10 ** 8) * (10 ** 8);
uint256 public econReserveAllocation = 1.2 * (10 ** 8) * (10 ** 8);
uint256 public developReserveAllocation = 1.2 * (10 ** 8) * (10 ** 8);
// Total Token Allocations
uint256 public totalAllocation = 7.2 * (10 ** 8) * (10 ** 8);
uint256 public teamReserveTimeLock = 1552060800; // 2019-3-9
uint256 public lifeReserveTimeLock = 1527782400; // 2018-6-1
uint256 public finanReserveTimeLock = 1527782400; // 2018-6-1
uint256 public econReserveTimeLock = 1527782400; // 2018-6-1
uint256 public developReserveTimeLock = 1538236800; // 2018-9-30
uint256 public teamVestingStages = 34; // 3% each month; total 34 stages.
uint256 public lifeVestingStages = 5; // 20% each month; total 5 stages.
uint256 public finanVestingStages = 5; // 20% each month; total 5 stages.
uint256 public econVestingStages = 240; // 1200000 each month for first six years and 200000 each month for next forteen years; total 240 stages.
mapping(address => uint256) public allocations;
mapping(address => uint256) public timeLocks;
mapping(address => uint256) public claimed;
uint256 public lockedAt = 0;
BCV public token;
event Allocated(address wallet, uint256 value);
event Distributed(address wallet, uint256 value);
event Locked(uint256 lockTime);
// Any of the five reserve wallets
modifier onlyReserveWallets {
require(allocations[msg.sender] > 0);
_;
}
// Team reserve wallet
modifier onlyTeamReserve {
require(msg.sender == teamReserveWallet);
require(allocations[msg.sender] > 0);
require(allocations[msg.sender] > claimed[msg.sender]);
_;
}
// Life token reserve wallet
modifier onlyTokenReserveLife {
require(msg.sender == lifeReserveWallet);
require(allocations[msg.sender] > 0);
require(allocations[msg.sender] > claimed[msg.sender]);
_;
}
// Finance token reserve wallet
modifier onlyTokenReserveFinance {
require(msg.sender == finanReserveWallet);
require(allocations[msg.sender] > 0);
require(allocations[msg.sender] > claimed[msg.sender]);
_;
}
// Economic token reserve wallet
modifier onlyTokenReserveEcon {
require(msg.sender == econReserveWallet);
require(allocations[msg.sender] > 0);
require(allocations[msg.sender] > claimed[msg.sender]);
_;
}
// Develop token reserve wallet
modifier onlyTokenReserveDevelop {
require(msg.sender == developReserveWallet);
require(allocations[msg.sender] > 0);
require(allocations[msg.sender] > claimed[msg.sender]);
_;
}
// Has not been locked yet
modifier notLocked {
require(lockedAt == 0);
_;
}
// Already locked
modifier locked {
require(lockedAt > 0);
_;
}
// Token allocations have not been set
modifier notAllocated {
require(allocations[teamReserveWallet] == 0);
require(allocations[lifeReserveWallet] == 0);
require(allocations[finanReserveWallet] == 0);
require(allocations[econReserveWallet] == 0);
require(allocations[developReserveWallet] == 0);
_;
}
function BCVTokenVault(ERC20Interface _token) public {
owner = msg.sender;
token = BCV(_token);
}
function allocate() public notLocked notAllocated onlyOwner {
// Makes sure Token Contract has the exact number of tokens
require(token.balanceOf(address(this)) == totalAllocation);
allocations[teamReserveWallet] = teamReserveAllocation;
allocations[lifeReserveWallet] = lifeReserveAllocation;
allocations[finanReserveWallet] = finanReserveAllocation;
allocations[econReserveWallet] = econReserveAllocation;
allocations[developReserveWallet] = developReserveAllocation;
Allocated(teamReserveWallet, teamReserveAllocation);
Allocated(lifeReserveWallet, lifeReserveAllocation);
Allocated(finanReserveWallet, finanReserveAllocation);
Allocated(econReserveWallet, econReserveAllocation);
Allocated(developReserveWallet, developReserveAllocation);
lock();
}
// Lock the vault for the wallets
function lock() internal notLocked onlyOwner {
lockedAt = block.timestamp;
timeLocks[teamReserveWallet] = teamReserveTimeLock;
timeLocks[lifeReserveWallet] = lifeReserveTimeLock;
timeLocks[finanReserveWallet] = finanReserveTimeLock;
timeLocks[econReserveWallet] = econReserveTimeLock;
timeLocks[developReserveWallet] = developReserveTimeLock;
Locked(lockedAt);
}
// Recover Tokens in case incorrect amount was sent to contract.
function recoverFailedLock() external notLocked notAllocated onlyOwner {
// Transfer all tokens on this contract back to the owner
require(token.transfer(owner, token.balanceOf(address(this))));
}
// Total number of tokens currently in the vault
function getTotalBalance() public view returns (uint256 tokensCurrentlyInVault) {
return token.balanceOf(address(this));
}
// Number of tokens that are still locked
function getLockedBalance() public view onlyReserveWallets returns (uint256 tokensLocked) {
return allocations[msg.sender].sub(claimed[msg.sender]);
}
// Claim tokens for team reserve wallet
function claimTeamReserve() onlyTeamReserve locked public {
address reserveWallet = msg.sender;
// Can't claim before Lock ends
require(block.timestamp > timeLocks[reserveWallet]);
uint256 vestingStage = teamVestingStage();
// Amount of tokens the team should have at this vesting stage
uint256 totalUnlocked = vestingStage.mul(7.2 * (10 ** 6) * (10 ** 8));
// For the last vesting stage, we will release all tokens
if (vestingStage == 34) {
totalUnlocked = allocations[teamReserveWallet];
}
// Total unlocked token must be smaller or equal to total locked token
require(totalUnlocked <= allocations[teamReserveWallet]);
// Previously claimed tokens must be less than what is unlocked
require(claimed[teamReserveWallet] < totalUnlocked);
// Number of tokens we can get
uint256 payment = totalUnlocked.sub(claimed[teamReserveWallet]);
// Update the claimed tokens in team wallet
claimed[teamReserveWallet] = totalUnlocked;
// Transfer to team wallet address
require(token.transfer(teamReserveWallet, payment));
Distributed(teamReserveWallet, payment);
}
//Current Vesting stage for team
function teamVestingStage() public view onlyTeamReserve returns(uint256) {
uint256 nowTime = block.timestamp;
// Number of months past our unlock time, which is the stage
uint256 stage = (nowTime.sub(teamReserveTimeLock)).div(2592000);
// Ensures team vesting stage doesn't go past teamVestingStages
if(stage > teamVestingStages) {
stage = teamVestingStages;
}
return stage;
}
// Claim tokens for life reserve wallet
function claimTokenReserveLife() onlyTokenReserveLife locked public {
address reserveWallet = msg.sender;
// Can't claim before Lock ends
require(block.timestamp > timeLocks[reserveWallet]);
// The vesting stage of life wallet
uint256 vestingStage = lifeVestingStage();
// Amount of tokens the life wallet should have at this vesting stage
uint256 totalUnlocked = vestingStage.mul(2.4 * (10 ** 7) * (10 ** 8));
// Total unlocked token must be smaller or equal to total locked token
require(totalUnlocked <= allocations[lifeReserveWallet]);
// Previously claimed tokens must be less than what is unlocked
require(claimed[lifeReserveWallet] < totalUnlocked);
// Number of tokens we can get
uint256 payment = totalUnlocked.sub(claimed[lifeReserveWallet]);
// Update the claimed tokens in finance wallet
claimed[lifeReserveWallet] = totalUnlocked;
// Transfer to life wallet address
require(token.transfer(reserveWallet, payment));
Distributed(reserveWallet, payment);
}
// Current Vesting stage for life wallet
function lifeVestingStage() public view onlyTokenReserveLife returns(uint256) {
uint256 nowTime = block.timestamp;
// Number of months past our unlock time, which is the stage
uint256 stage = (nowTime.sub(lifeReserveTimeLock)).div(2592000);
// Ensures life wallet vesting stage doesn't go past lifeVestingStages
if(stage > lifeVestingStages) {
stage = lifeVestingStages;
}
return stage;
}
// Claim tokens for finance reserve wallet
function claimTokenReserveFinan() onlyTokenReserveFinance locked public {
address reserveWallet = msg.sender;
// Can't claim before Lock ends
require(block.timestamp > timeLocks[reserveWallet]);
// The vesting stage of finance wallet
uint256 vestingStage = finanVestingStage();
// Amount of tokens the finance wallet should have at this vesting stage
uint256 totalUnlocked = vestingStage.mul(2.4 * (10 ** 7) * (10 ** 8));
// Total unlocked token must be smaller or equal to total locked token
require(totalUnlocked <= allocations[finanReserveWallet]);
// Previously claimed tokens must be less than what is unlocked
require(claimed[finanReserveWallet] < totalUnlocked);
// Number of tokens we can get
uint256 payment = totalUnlocked.sub(claimed[finanReserveWallet]);
// Update the claimed tokens in finance wallet
claimed[finanReserveWallet] = totalUnlocked;
// Transfer to finance wallet address
require(token.transfer(reserveWallet, payment));
Distributed(reserveWallet, payment);
}
// Current Vesting stage for finance wallet
function finanVestingStage() public view onlyTokenReserveFinance returns(uint256) {
uint256 nowTime = block.timestamp;
// Number of months past our unlock time, which is the stage
uint256 stage = (nowTime.sub(finanReserveTimeLock)).div(2592000);
// Ensures finance wallet vesting stage doesn't go past finanVestingStages
if(stage > finanVestingStages) {
stage = finanVestingStages;
}
return stage;
}
// Claim tokens for economic reserve wallet
function claimTokenReserveEcon() onlyTokenReserveEcon locked public {
address reserveWallet = msg.sender;
// Can't claim before Lock ends
require(block.timestamp > timeLocks[reserveWallet]);
uint256 vestingStage = econVestingStage();
// Amount of tokens the economic wallet should have at this vesting stage
uint256 totalUnlocked;
// For first 6 years stages
if (vestingStage <= 72) {
totalUnlocked = vestingStage.mul(1200000 * (10 ** 8));
} else { // For the next 14 years stages
totalUnlocked = ((vestingStage.sub(72)).mul(200000 * (10 ** 8))).add(86400000 * (10 ** 8));
}
// Total unlocked token must be smaller or equal to total locked token
require(totalUnlocked <= allocations[econReserveWallet]);
// Previously claimed tokens must be less than what is unlocked
require(claimed[econReserveWallet] < totalUnlocked);
// Number of tokens we can get
uint256 payment = totalUnlocked.sub(claimed[econReserveWallet]);
// Update the claimed tokens in economic wallet
claimed[econReserveWallet] = totalUnlocked;
// Transfer to economic wallet address
require(token.transfer(reserveWallet, payment));
Distributed(reserveWallet, payment);
}
// Current Vesting stage for economic wallet
function econVestingStage() public view onlyTokenReserveEcon returns(uint256) {
uint256 nowTime = block.timestamp;
// Number of months past our unlock time, which is the stage
uint256 stage = (nowTime.sub(timeLocks[econReserveWallet])).div(2592000);
// Ensures economic wallet vesting stage doesn't go past econVestingStages
if(stage > econVestingStages) {
stage = econVestingStages;
}
return stage;
}
// Claim tokens for development reserve wallet
function claimTokenReserveDevelop() onlyTokenReserveDevelop locked public {
address reserveWallet = msg.sender;
// Can't claim before Lock ends
require(block.timestamp > timeLocks[reserveWallet]);
// Must Only claim once
require(claimed[reserveWallet] == 0);
// Number of tokens we can get, which is all tokens in developReserveWallet
uint256 payment = allocations[reserveWallet];
// Update the claimed tokens in development wallet
claimed[reserveWallet] = payment;
// Transfer to development wallet address
require(token.transfer(reserveWallet, payment));
Distributed(reserveWallet, payment);
}
// Checks if msg.sender can collect tokens
function canCollect() public view onlyReserveWallets returns(bool) {
return block.timestamp > timeLocks[msg.sender] && claimed[msg.sender] == 0;
}
} | Recover Tokens in case incorrect amount was sent to contract. Transfer all tokens on this contract back to the owner | function recoverFailedLock() external notLocked notAllocated onlyOwner {
require(token.transfer(owner, token.balanceOf(address(this))));
}
| 12,266,743 |
pragma solidity 0.6.6;
import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/interfaces/AggregatorInterface.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol";
/// @title Manage the backend of the Tetri0n game i.e. leaderboard, high scores, make payouts e.t.c
/// @author Mulili Nzuki [email protected]
/// @notice Create a custom leaderboard and start counting the scores for the Tetri0n game
/// @dev All function calls are currently implement without side effects
/// @dev v0.0.1
contract Tetrion {
using SafeMath for uint256;
struct Player {
address playerAddress;
uint score;
uint score_unconfirmed;
uint isActive;
}
struct Board {
bytes32 boardName;
string boardDescription;
uint numPlayers;
address boardOwner;
uint boardStatus; // 0 if it is closed 1 if it is open
mapping (uint => Player) players;
}
mapping (uint256 => Board) boards;
uint public numBoards;
uint public numOfActiveBoards;
address payable owner = msg.sender;
uint public balance;
uint public playerFee = 1000000000000000;
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
AggregatorInterface internal priceFeed;
/**
* Network: Ropsten
* Aggregator: ETH/USD
* Address: 0x8468b2bDCE073A157E560AA4D9CcF6dB1DB98507
*/
constructor() public {
priceFeed = AggregatorInterface(0x8468b2bDCE073A157E560AA4D9CcF6dB1DB98507);
}
/**
* Returns the latest price
*/
function getLatestPrice() external view returns (int256) {
return priceFeed.latestAnswer();
}
/**
* Returns the timestamp of the latest price update
*/
function getLatestPriceTimestamp() external view returns (uint256) {
return priceFeed.latestTimestamp();
}
/**
Funding Functions
*/
/// @notice change the staking fee for playing the game using the contract
/// @param _playerFee costs for a new player to play game
/// @return true
function setPlayerFee ( uint _playerFee) isOwner public returns(bool) {
playerFee = _playerFee;
return true;
}
/// @notice split the revenue of a new player between boardOwner and contract owner
/// @param boardOwner of the leaderboard
/// @param _amount amount to be split
/// @return true
function split(address payable boardOwner, uint _amount) internal returns(bool) {
emit Withdrawal(owner, _amount/2);
owner.transfer(_amount/2);
//emit Withdrawal(boardOwner, _amount/2);
boardOwner.transfer(_amount/2);
return true;
}
/// @notice Event for Withdrawal
event Withdrawal(address indexed _from, uint _value);
/**
Payout Function
*/
/// @notice payout the top 3 players after each round
/// @param playerAddress the address of the player
/// @param _amount amount to be split
/// @return true
function payoutWinnings(address payable playerAddress, uint _amount) external returns(bool) {
emit Payout(playerAddress, _amount);
playerAddress.transfer(_amount);
return true;
}
/// @notice Event for Payout
event Payout(address indexed _from, uint _value);
/**
Board Functions
*/
/// @notice Add a new leaderboard. Board hash will be created by name and creator
/// @notice a funding is required to create a new leaderboard
/// @param boardId The randomly generated boardId from the chainlink VRF
/// @param name The name of the leaderboard
/// @param boardDescription A subtitle for the leaderboard
/// @return The hash of the newly created leaderboard
function addNewBoard(uint256 boardId, bytes32 name, string memory boardDescription) public returns(bool){
numBoards++;
// add a new board and mark it as active
boards[boardId] = Board(name, boardDescription, 0, msg.sender, 1);
return true;
}
/// @notice Get the metadata of a leaderboard
/// @param boardId The randomly generated boardId from the chainlink VRF
/// @return Leaderboard name, description and number of players
function getBoardByHash(uint256 boardId) view public returns(bytes32,string memory,uint){
return (boards[boardId].boardName, boards[boardId].boardDescription, boards[boardId].numPlayers);
}
/// @notice Overwrite leaderboard name and desctiption as owner only
/// @param boardId The randomly generated boardId from the chainlink VRF
/// @param name The new name of the leaderboard
/// @param boardDescription The new subtitle for the leaderboard
/// @return true
function changeBoardMetadata(uint256 boardId, bytes32 name, string memory boardDescription) public returns(bool) {
require(boards[boardId].boardOwner == msg.sender);
boards[boardId].boardName = name;
boards[boardId].boardDescription = boardDescription;
}
/// @notice Close a board once the payouts have been done as owner only
/// @param boardId The randomly generated boardId from the chainlink VRF
/// @return true
function closeBoard(uint256 boardId) public returns(bool) {
require(boards[boardId].boardOwner == msg.sender);
boards[boardId].boardStatus = 0; // mark board as closed
// reduce the number of active boards
numOfActiveBoards = numOfActiveBoards - 1;
}
/// @notice event for newly created leaderboard
event newBoardCreated(bytes32 boardHash);
/**
Player Functions
*/
/// @notice Add a new player to an existing leaderboard
/// @param boardId The randomly generated boardId from the chainlink VRF
/// @return Player ID
function addPlayerToBoard(uint256 boardId) public payable returns (bool) {
require(msg.value >= playerFee, " The ETH sent is less than the amount required");
Board storage g = boards[boardId];
// split (g.boardOwner, msg.value);
uint newPlayerID = g.numPlayers++;
// init a new player in the board
g.players[newPlayerID] = Player(msg.sender,0,0,1);
return true;
}
/// @notice Get player data by leaderboard hash and player id/index
/// @param boardId The randomly generated boardId from the chainlink VRF
/// @param playerID Index number of the player
/// @return Player name, confirmed score, unconfirmed score
function getPlayerByBoard(uint256 boardId, uint8 playerID) view public returns ( uint, uint){
Player storage p = boards[boardId].players[playerID];
require(p.isActive == 1);
return ( p.score, p.score_unconfirmed);
}
/// @notice Get the player id either by player Name or address
/// @param boardId The randomly generated boardId from the chainlink VRF
/// @param playerAddress The player address
/// @return ID or 999 in case of false
function getPlayerId (uint256 boardId, address playerAddress) view internal returns (uint8) {
Board storage g = boards[boardId];
for (uint8 i = 0; i <= g.numPlayers; i++) {
if ((playerAddress == g.players[i].playerAddress) && g.players[i].isActive == 1) {
return i;
}
}
return 255;
}
/**
Score Functions
*/
/// @notice Add a unconfirmed score to leaderboard/player. Overwrites an existing unconfirmed score
/// @param boardId The randomly generated boardId from the chainlink VRF
/// @param playerAddress The address of the player
/// @param score Integer
/// @return true/false
function addBoardScore(uint256 boardId, address playerAddress, uint score) public returns (bool){
uint8 playerID = getPlayerId (boardId, playerAddress);
require(playerID < 255 );
boards[boardId].players[playerID].score_unconfirmed = score;
return true;
}
/// @notice Confirm an unconfirmed score to leaderboard/player. Adds unconfirmed to existing score. Player can not confirm his own score
/// @param boardId The randomly generated boardId from the chainlink VRF
/// @param playerAddress The name of the player who's score should be confirmed
/// @return true/false
function confirmBoardScore(uint256 boardId, address playerAddress) public returns (bool){
uint8 playerID = getPlayerId (boardId, playerAddress);
uint8 confirmerID = getPlayerId (boardId, msg.sender);
require(playerID < 255); // player needs to be active
require(confirmerID < 255); // confirmer needs to be active
require(boards[boardId].players[playerID].playerAddress != msg.sender); //confirm only other players
boards[boardId].players[playerID].score += boards[boardId].players[playerID].score_unconfirmed;
boards[boardId].players[playerID].score_unconfirmed = 0;
return true;
}
} | Confirm an unconfirmed score to leaderboard/player. Adds unconfirmed to existing score. Player can not confirm his own score boardId The randomly generated boardId from the chainlink VRF playerAddress The name of the player who's score should be confirmed return true/false | function confirmBoardScore(uint256 boardId, address playerAddress) public returns (bool){
uint8 playerID = getPlayerId (boardId, playerAddress);
uint8 confirmerID = getPlayerId (boardId, msg.sender);
boards[boardId].players[playerID].score += boards[boardId].players[playerID].score_unconfirmed;
boards[boardId].players[playerID].score_unconfirmed = 0;
return true;
}
| 6,435,478 |
pragma solidity ^0.4.23;
// For safe math operations
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
assert(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
assert(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ERC223 receiving contract base implementation
contract ContractReceiver {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
// interface ERC223/ERC20
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address _to, uint _value)public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// sets owner of contract, allows for ownership transfer
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// implement base variables and functions
contract StandardToken is ERC20Interface, Owned{
using SafeMath for uint;
string public symbol;
string public name;
// 18 is standard
uint8 public decimals;
// total supply of tokens
uint public _totalSupply;
// mapping of address to balance
mapping(address => uint) balances;
//mapping of address allowing, to adddress allowed and amount allowed for
//transfer
mapping(address => mapping(address => uint)) allowed;
//event to tell when token transferred to a contract
event TokenTransferredToContract(address indexed from, address indexed to, uint value, bytes data);
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// For ERC20 transfer
function transfer(address _to, uint _value)public returns (bool success){
bytes memory empty;
require(_value >= 0);
require(balances[msg.sender] >= _value);
// subtract from senders balance
balances[msg.sender] = balances[msg.sender].sub(_value);
// add to receiving contracts balance
balances[_to] = balances[_to].add(_value);
if(isContract(_to)){
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, empty);
emit TokenTransferredToContract(msg.sender, _to, _value,empty);
emit Transfer(msg.sender, _to, _value, empty);
}else{
emit Transfer(msg.sender, _to, _value);
}
return true;
}
// sender approves withdrawal of tokens. no checks needed
function approve(address _spender, uint _value) public returns (bool success){
require(_value > 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// return tokens allowed to spend from tokenOwner by spender
function allowance(address _tokenOwner, address _spender) public view returns (uint remaining){
return allowed[_tokenOwner][_spender];
}
// transfer tokens approved to spend
function transferFrom(address _from, address _to, uint _tokens) public returns (bool success){
require(_tokens > 0);
balances[_from] = balances[_from].sub(_tokens);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_tokens);
balances[_to] = balances[_to].add(_tokens);
emit Transfer(_from, _to, _tokens);
return true;
}
// function used to check if address is a contract
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
}
// basic interface of contract implementing receiveApproval function
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract OToken2 is StandardToken{
// log when unspent approval is revoked
event RevokeApproval(address _owner, address _spender);
// constructor of contract.
constructor() public{
symbol = "ORST";
name = "OToken2";
decimals = 18;
_totalSupply = 2500000000 * 10**uint(decimals); // 2.5 billion tokens
balances[owner] = _totalSupply; // give owner all supply
emit Transfer(address(0), owner, _totalSupply); // log event
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address _spender, uint _value, bytes _data) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
ApproveAndCallFallBack(_spender).receiveApproval(msg.sender, _value, this, _data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
| transfer tokens approved to spend | function transferFrom(address _from, address _to, uint _tokens) public returns (bool success){
require(_tokens > 0);
balances[_from] = balances[_from].sub(_tokens);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_tokens);
balances[_to] = balances[_to].add(_tokens);
emit Transfer(_from, _to, _tokens);
return true;
}
| 15,788,058 |
./full_match/44787/0x6B21Af6aA0F656A4ea1b2Db85A676cF33E67711E/sources/src/SpiralsStaking.sol | Activates pending votes (if ready) with a given validator group. all pending -> active for this group | function activate() external {
IElection c_election = getElection();
require(
c_election.hasActivatablePendingVotes(
address(this),
validatorGroup
),
"NOT_READY_TO_ACTIVATE"
);
uint256 pendingVotes = getElection().getPendingVotesForGroupByAccount(
validatorGroup,
address(this)
);
require(c_election.activate(validatorGroup), "ACTIVATE_FAILED");
emit VotesActivated(validatorGroup, pendingVotes);
}
| 13,246,279 |
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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/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/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/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. 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/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/interfaces/IERC165.sol
pragma solidity ^0.8.0;
// File: @openzeppelin/contracts/interfaces/IERC2981.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// 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: contracts/FeralfileArtwork.sol
pragma solidity >=0.4.22 <0.9.0;
contract Authorizable is Ownable {
address public trustee;
constructor() {
trustee = address(0x0);
}
modifier onlyAuthorized() {
require(msg.sender == trustee || msg.sender == owner());
_;
}
function setTrustee(address _newTrustee) public onlyOwner {
trustee = _newTrustee;
}
}
contract FeralfileExhibition is ERC721Enumerable, Authorizable, IERC2981 {
using Strings for uint256;
struct Artwork {
string fingerprint;
string title;
string description;
address artist;
string medium;
uint256 editionSize;
}
struct ArtworkEdition {
uint256 editionID;
uint256 editionNumber;
uint256 artworkID;
uint256 bitmarkID;
string prevProvenance;
string ipfsCID;
}
// Exihibition information
string public title;
address public curator;
uint256 public maxEditionPerArtwork;
uint256 public basePrice;
uint256 public secondarySaleRoyaltyBPS = 0;
address public multipleRoyaltySharingPayoutAddress;
uint256 public MaxRoyaltyBPS = 100_00;
string private _tokenBaseURI;
string private _contractURI;
uint256[] private _allArtworks;
mapping(uint256 => Artwork) public artworks; // artworkID => Artwork
mapping(uint256 => ArtworkEdition) public artworkEditions; // artworkEditionID => ArtworkEdition
mapping(uint256 => uint256[]) internal allArtworkEditions; // artworkID => []ArtworkEditionID
mapping(uint256 => bool) internal registeredBitmarks; // bitmarkID => bool
mapping(string => bool) internal registeredIPFSCIDs; // ipfsCID => bool
constructor(
string memory _title,
string memory _symbol,
address _curator,
uint256 _maxEditionPerArtwork,
uint256 _basePrice,
uint256 _secondarySaleRoyaltyBPS,
string memory contractURI_,
string memory tokenBaseURI_
) ERC721(_title, _symbol) {
require(_curator != address(0), "invalid curator address");
require(
_maxEditionPerArtwork > 0,
"maxEdition of each artwork in an exhibition needs to be greater than zero"
);
require(_basePrice > 0, "basePrice needs to be greater than zero");
title = _title;
curator = _curator;
basePrice = _basePrice;
maxEditionPerArtwork = _maxEditionPerArtwork;
secondarySaleRoyaltyBPS = _secondarySaleRoyaltyBPS;
_contractURI = contractURI_;
_tokenBaseURI = tokenBaseURI_;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
// Create an artwork for an exhibition
function createArtwork(
string memory _fingerprint,
string memory _title,
string memory _description,
address _artist,
string memory _medium,
uint256 _editionSize
) public onlyAuthorized {
require(
bytes(_fingerprint).length != 0,
"fingerprint can not be empty"
);
require(bytes(_title).length != 0, "title can not be empty");
require(_artist != address(0), "invalid artist address");
require(bytes(_medium).length != 0, "medium can not be empty");
require(_editionSize > 0, "edition size needs to be at least 1");
require(
_editionSize <= maxEditionPerArtwork,
"artwork edition size exceeds the maximum edition size of the exhibition"
);
uint256 _artworkID = uint256(keccak256(abi.encode(_fingerprint)));
// make sure an artwork have not been registered
require(
artworks[_artworkID].artist == address(0),
"an artwork with the same fingerprint has already registered"
);
Artwork memory _artwork = Artwork(
_fingerprint,
_title,
_description,
_artist,
_medium,
_editionSize
);
_allArtworks.push(_artworkID);
artworks[_artworkID] = _artwork;
emit NewArtwork(_artist, _artworkID);
}
// Return a count of artworks registered in this exhibition
function totalArtworks() public view virtual returns (uint256) {
return _allArtworks.length;
}
// Return the token identifier for the `_index`th artwork
function getArtworkByIndex(uint256 index)
public
view
virtual
returns (uint256)
{
require(
index < totalArtworks(),
"artworks: global index out of bounds"
);
return _allArtworks[index];
}
// Swap an existent artwork from bitmark to ERC721
function swapArtworkFromBitmark(
uint256 _artworkID,
uint256 _bitmarkID,
uint256 _editionNumber,
address _owner,
string memory _prevProvenance,
string memory _ipfsCID
) public onlyAuthorized {
Artwork memory artwork = artworks[_artworkID];
require(artwork.artist != address(0), "artwork is not found");
// The range of _editionNumber should be between 0 (AP) ~ artwork.editionSize
require(
_editionNumber <= artwork.editionSize,
"edition number exceed the edition size of the artwork"
);
require(_owner != address(0), "invalid owner address");
require(!registeredBitmarks[_bitmarkID], "bitmark id has registered");
require(!registeredIPFSCIDs[_ipfsCID], "ipfs id has registered");
uint256 editionID = _artworkID + _editionNumber;
require(
artworkEditions[editionID].editionID == 0,
"the edition is existent"
);
ArtworkEdition memory edition = ArtworkEdition(
editionID,
_editionNumber,
_artworkID,
_bitmarkID,
_prevProvenance,
_ipfsCID
);
artworkEditions[editionID] = edition;
allArtworkEditions[_artworkID].push(editionID);
registeredBitmarks[_bitmarkID] = true;
registeredIPFSCIDs[_ipfsCID] = true;
_safeMint(_owner, editionID);
emit NewArtworkEdition(_owner, _artworkID, editionID);
}
// Update the IPFS cid of an edition to a new value
function updateArtworkEditionIPFSCid(
uint256 _tokenId,
string memory _ipfsCID
) public onlyAuthorized {
ArtworkEdition memory edition = artworkEditions[_tokenId];
require(edition.editionID != 0, "artwork edition is not found");
require(!registeredIPFSCIDs[_ipfsCID], "ipfs id has registered");
delete registeredIPFSCIDs[edition.ipfsCID];
registeredIPFSCIDs[_ipfsCID] = true;
artworkEditions[_tokenId].ipfsCID = _ipfsCID;
}
// setMultipleRoyaltySharingPayoutAddress assigns a payout address so
// that we can split the royalty.
function setMultipleRoyaltySharingPayoutAddress(address payoutAddress)
public
onlyAuthorized
{
multipleRoyaltySharingPayoutAddress = payoutAddress;
}
// Return the edition counts for an artwork
function totalEditionOfArtwork(uint256 artworkID)
public
view
returns (uint256)
{
return allArtworkEditions[artworkID].length;
}
// Return the edition id of an artwork by index
function getArtworkEditionByIndex(uint256 artworkID, uint256 index)
public
view
returns (uint256)
{
require(index < totalEditionOfArtwork(artworkID));
return allArtworkEditions[artworkID][index];
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
if (bytes(baseURI).length == 0) {
return "";
}
string memory ipfsID = artworkEditions[tokenId].ipfsCID;
return string(abi.encodePacked(baseURI, ipfsID, "/metadata.json"));
}
function setArtworkBaseURI(string memory baseURI_) public onlyAuthorized {
_tokenBaseURI = baseURI_;
}
function _baseURI() internal view virtual override returns (string memory) {
return _tokenBaseURI;
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
//////////////
// ERC-2981 //
//////////////
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
override
returns (address _receiver, uint256 _royaltyAmount)
{
ArtworkEdition memory edition = artworkEditions[_tokenId];
require(edition.editionID != 0, "artwork edition is not found");
Artwork memory artwork = artworks[edition.artworkID];
if (multipleRoyaltySharingPayoutAddress == address(0)) {
_receiver = artwork.artist;
} else {
_receiver = multipleRoyaltySharingPayoutAddress;
}
_royaltyAmount = (_value / MaxRoyaltyBPS) * secondarySaleRoyaltyBPS;
}
event NewArtwork(address indexed creator, uint256 indexed artworkID);
event NewArtworkEdition(
address indexed owner,
uint256 indexed artworkID,
uint256 indexed editionID
);
} | Swap an existent artwork from bitmark to ERC721 The range of _editionNumber should be between 0 (AP) ~ artwork.editionSize | function swapArtworkFromBitmark(
uint256 _artworkID,
uint256 _bitmarkID,
uint256 _editionNumber,
address _owner,
string memory _prevProvenance,
string memory _ipfsCID
) public onlyAuthorized {
Artwork memory artwork = artworks[_artworkID];
require(artwork.artist != address(0), "artwork is not found");
require(
_editionNumber <= artwork.editionSize,
"edition number exceed the edition size of the artwork"
);
require(_owner != address(0), "invalid owner address");
require(!registeredBitmarks[_bitmarkID], "bitmark id has registered");
require(!registeredIPFSCIDs[_ipfsCID], "ipfs id has registered");
uint256 editionID = _artworkID + _editionNumber;
require(
artworkEditions[editionID].editionID == 0,
"the edition is existent"
);
ArtworkEdition memory edition = ArtworkEdition(
editionID,
_editionNumber,
_artworkID,
_bitmarkID,
_prevProvenance,
_ipfsCID
);
artworkEditions[editionID] = edition;
allArtworkEditions[_artworkID].push(editionID);
registeredBitmarks[_bitmarkID] = true;
registeredIPFSCIDs[_ipfsCID] = true;
_safeMint(_owner, editionID);
emit NewArtworkEdition(_owner, _artworkID, editionID);
}
| 6,186,755 |
./partial_match/42220/0x9de4171EDc1F69EAD07f7595bD3beD62d9215532/sources/contracts/CToken.sol | Payer supplies assets into the market and receiver receives cTokens in exchange Assumes interest has already been accrued up to the current block payer The address of the account which is paying the underlying token receiver The address of the account which is receiving cToken mintAmount The amount of the underlying asset to supply return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount./ Fail if mint not allowed / Verify market's block number equals current block number / | function mintBehalfFresh(address payer, address receiver, uint mintAmount) internal returns (uint, uint) {
require(receiver != address(0), "receiver is invalid");
uint allowed = comptroller.mintAllowed(address(this), receiver, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[receiver], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
accountTokens[receiver] = vars.accountTokensNew;
emit Transfer(address(this), receiver, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
| 3,495,170 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.